Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> self_stepsize = self_periodreg_value * self_scale
i = 0
if self_progress < self_stepsize:
val = self_shape_buf[self_index]
j = min(self_stepsize - self_progress, self_block_framecount)
while i < j:
self_blockbuf_buf[i] = val
i += 1
if i == self_block_framecount:
self_progress += self_block_framecount
else:
if not self_eager:
self_stepsize = self_periodreg_value * self_scale
n = (self_block_framecount - i) // self_stepsize
while n:
self_index += 1
if self_index == self_shape_size:
self_index = self_shape_introlen
val = self_shape_buf[self_index]
j = i + self_stepsize
while i < j:
self_blockbuf_buf[i] = val
i += 1
n -= 1
if i == self_block_framecount:
self_progress = self_stepsize
else:
self_index += 1
if self_index == self_shape_size:
self_index = self_shape_introlen
<|code_end|>
, generate the next line using the imports in this file:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | val = self_shape_buf[self_index] |
Predict the next line after this snippet: <|code_start|>#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
oscnodepyrbotype = dict(
blockbuf = dict(buf = [signaldtype]),
block = dict(framecount = u4),
index = i4,
shape = Shape.pyrbotype,
)
class ShapeOsc(BufNode):
progressdtype = u4
def __init__(self, scale, periodreg):
super().__init__(BufType.signal)
self.stepsize = 0 # XXX: Move to reset?
self.scale = scale
self.periodreg = periodreg
def reset(self, shape):
self.index = -1
self.progress = np.iinfo(self.progressdtype).max
self.shape = shape
def callimpl(self):
self.index, self.progress, self.stepsize = self.shapeimpl()
<|code_end|>
using the current file's imports:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and any relevant context from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | @turbo( |
Next line prediction: <|code_start|> self.shape = effect.getshape(self.fixedreg)
prescalerornone = self.timer.prescalerornone.value
if prescalerornone is None:
self.blockbuf.fill_same(self.shape.buf[self.index])
self.precounterxmfp = None
else:
if self.precounterxmfp is None:
self.precounterxmfp = prescalerornone * self.chipimplclock
self.repeat, self.index, self.maincounter, self.precounterxmfp = self.rtoneimpl(prescalerornone, self.timer.effectivedata.value)
self.timer.repeat.value = self.repeat
@turbo(
self = dict(
oscnodepyrbotype,
mfpclock = i8, # Signed so j doesn't blow up.
chipimplclock = u8,
maincounter = i4,
precounterxmfp = u4,
repeat = u4,
),
prescaler = u4,
etdr = u4,
chunksizexmfp = u8,
stepsizexmfp = u8,
nextstepxmfp = i8,
i = u4,
j = u4,
val = signaldtype,
numerator = i8,
)
<|code_end|>
. Use current file imports:
(from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | def rtoneimpl(self, prescaler, etdr): |
Predict the next line after this snippet: <|code_start|> eager = u1,
),
i = u4,
j = u4,
n = u4,
val = signaldtype,
)
def shapeimpl(self):
self_blockbuf_buf = self_block_framecount = self_index = self_progress = self_scale = self_periodreg_value = self_shape_buf = self_shape_size = self_shape_introlen = self_eager = LOCAL
if self_eager:
self_stepsize = self_periodreg_value * self_scale
i = 0
if self_progress < self_stepsize:
val = self_shape_buf[self_index]
j = min(self_stepsize - self_progress, self_block_framecount)
while i < j:
self_blockbuf_buf[i] = val
i += 1
if i == self_block_framecount:
self_progress += self_block_framecount
else:
if not self_eager:
self_stepsize = self_periodreg_value * self_scale
n = (self_block_framecount - i) // self_stepsize
while n:
self_index += 1
if self_index == self_shape_size:
self_index = self_shape_introlen
val = self_shape_buf[self_index]
j = i + self_stepsize
<|code_end|>
using the current file's imports:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and any relevant context from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | while i < j: |
Given snippet: <|code_start|> n = u4,
val = signaldtype,
)
def shapeimpl(self):
self_blockbuf_buf = self_block_framecount = self_index = self_progress = self_scale = self_periodreg_value = self_shape_buf = self_shape_size = self_shape_introlen = self_eager = LOCAL
if self_eager:
self_stepsize = self_periodreg_value * self_scale
i = 0
if self_progress < self_stepsize:
val = self_shape_buf[self_index]
j = min(self_stepsize - self_progress, self_block_framecount)
while i < j:
self_blockbuf_buf[i] = val
i += 1
if i == self_block_framecount:
self_progress += self_block_framecount
else:
if not self_eager:
self_stepsize = self_periodreg_value * self_scale
n = (self_block_framecount - i) // self_stepsize
while n:
self_index += 1
if self_index == self_shape_size:
self_index = self_shape_introlen
val = self_shape_buf[self_index]
j = i + self_stepsize
while i < j:
self_blockbuf_buf[i] = val
i += 1
n -= 1
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and context:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
which might include code, classes, or functions. Output only the next line. | if i == self_block_framecount: |
Based on the snippet: <|code_start|> self_blockbuf_buf = self_block_framecount = self_mfpclock = self_chipimplclock = self_repeat = self_index = self_maincounter = self_precounterxmfp = self_shape_buf = self_shape_size = self_shape_introlen = LOCAL
chunksizexmfp = self_chipimplclock * prescaler
stepsizexmfp = chunksizexmfp * etdr
nextstepxmfp = chunksizexmfp * self_maincounter + self_precounterxmfp - chunksizexmfp
i = 0
while True:
numerator = nextstepxmfp + self_mfpclock - 1
if numerator >= 0:
j = min(numerator // self_mfpclock, self_block_framecount)
val = self_shape_buf[self_index]
while i < j:
self_blockbuf_buf[i] = val
i += 1
if j == self_block_framecount:
break
nextstepxmfp += stepsizexmfp
self_index += 1
if self_index == self_shape_size:
self_repeat += 1
self_index = self_shape_introlen
nextstepxmfp -= self_mfpclock * self_block_framecount
self_maincounter = 1
while nextstepxmfp < 0:
nextstepxmfp += chunksizexmfp
self_maincounter -= 1
self_maincounter += nextstepxmfp // chunksizexmfp
return self_repeat, self_index, self_maincounter, nextstepxmfp % chunksizexmfp
class ToneOsc(ShapeOsc):
<|code_end|>
, predict the immediate next line with the help of imports:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | eager = True |
Continue the code snippet: <|code_start|># (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
oscnodepyrbotype = dict(
blockbuf = dict(buf = [signaldtype]),
block = dict(framecount = u4),
index = i4,
shape = Shape.pyrbotype,
)
class ShapeOsc(BufNode):
progressdtype = u4
def __init__(self, scale, periodreg):
super().__init__(BufType.signal)
self.stepsize = 0 # XXX: Move to reset?
self.scale = scale
self.periodreg = periodreg
def reset(self, shape):
self.index = -1
<|code_end|>
. Use current file imports:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and context (classes, functions, or code) from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | self.progress = np.iinfo(self.progressdtype).max |
Predict the next line for this snippet: <|code_start|> self.periodreg = periodreg
def reset(self, shape):
self.index = -1
self.progress = np.iinfo(self.progressdtype).max
self.shape = shape
def callimpl(self):
self.index, self.progress, self.stepsize = self.shapeimpl()
@turbo(
self = dict(
oscnodepyrbotype,
progress = progressdtype,
stepsize = u4,
scale = u4,
periodreg = dict(value = u4),
eager = u1,
),
i = u4,
j = u4,
n = u4,
val = signaldtype,
)
def shapeimpl(self):
self_blockbuf_buf = self_block_framecount = self_index = self_progress = self_scale = self_periodreg_value = self_shape_buf = self_shape_size = self_shape_introlen = self_eager = LOCAL
if self_eager:
self_stepsize = self_periodreg_value * self_scale
i = 0
if self_progress < self_stepsize:
<|code_end|>
with the help of current file imports:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and context from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
, which may contain function names, class names, or code. Output only the next line. | val = self_shape_buf[self_index] |
Continue the code snippet: <|code_start|> val = self_shape_buf[self_index]
j = i + self_stepsize
while i < j:
self_blockbuf_buf[i] = val
i += 1
n -= 1
if i == self_block_framecount:
self_progress = self_stepsize
else:
self_index += 1
if self_index == self_shape_size:
self_index = self_shape_introlen
val = self_shape_buf[self_index]
self_progress = self_block_framecount - i
while i < self_block_framecount:
self_blockbuf_buf[i] = val
i += 1
return self_index, self_progress, self_stepsize
class RToneOsc(BufNode):
effect = None
def __init__(self, mfpclock, chipimplclock, timer, fixedreg):
super().__init__(BufType.signal)
self.mfpclock = mfpclock
self.chipimplclock = chipimplclock
self.timer = timer
self.fixedreg = fixedreg
<|code_end|>
. Use current file imports:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and context (classes, functions, or code) from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | def callimpl(self): |
Given the following code snippet before the placeholder: <|code_start|> oscnodepyrbotype,
mfpclock = i8, # Signed so j doesn't blow up.
chipimplclock = u8,
maincounter = i4,
precounterxmfp = u4,
repeat = u4,
),
prescaler = u4,
etdr = u4,
chunksizexmfp = u8,
stepsizexmfp = u8,
nextstepxmfp = i8,
i = u4,
j = u4,
val = signaldtype,
numerator = i8,
)
def rtoneimpl(self, prescaler, etdr):
self_blockbuf_buf = self_block_framecount = self_mfpclock = self_chipimplclock = self_repeat = self_index = self_maincounter = self_precounterxmfp = self_shape_buf = self_shape_size = self_shape_introlen = LOCAL
chunksizexmfp = self_chipimplclock * prescaler
stepsizexmfp = chunksizexmfp * etdr
nextstepxmfp = chunksizexmfp * self_maincounter + self_precounterxmfp - chunksizexmfp
i = 0
while True:
numerator = nextstepxmfp + self_mfpclock - 1
if numerator >= 0:
j = min(numerator // self_mfpclock, self_block_framecount)
val = self_shape_buf[self_index]
while i < j:
self_blockbuf_buf[i] = val
<|code_end|>
, predict the next line using imports from the current file:
from .buf import BufType
from .const import i4, i8, u1, u4, u8
from .nod import BufNode
from .shapes import Shape, signaldtype, toneshape
from pyrbo import LOCAL, turbo
import itertools, numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
#
# Path: pym2149/const.py
#
# Path: pym2149/nod.py
# class BufNode(Node):
#
# def __init__(self, buftype, channels = 1):
# super().__init__()
# self.masterbuf = buftype()
# self.channels = channels
# self.realcallimpl = self.callimpl
# self.callimpl = self.makeresult
#
# def makeresult(self):
# self.blockbuf = self.masterbuf.ensureandcrop(self.block.framecount * self.channels)
# resultornone = self.realcallimpl()
# if resultornone is not None:
# return resultornone
# return self.blockbuf
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | i += 1 |
Based on the snippet: <|code_start|># along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class PortAudioClient(pac.PortAudioClient, Platform):
@types(Config, StereoInfo)
def __init__(self, config, stereoinfo):
config = config.PortAudio
super().__init__(stereoinfo.getoutchans.size, config.outputrate, config.buffersize, config.ringsize, config.coupling)
class PortAudioStream(Node, Stream, metaclass = AmpScale):
log2maxpeaktopeak = 1
@types(StereoInfo, FloatStream, PortAudioClient)
def __init__(self, stereoinfo, wavs, client):
super().__init__()
self.chancount = stereoinfo.getoutchans.size
self.wavs = wavs
self.client = client
def start(self):
self.client.activate()
self.filler = BufferFiller(self.chancount, self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer)
def callimpl(self):
self.filler([self.chain(wav) for wav in self.wavs])
<|code_end|>
, predict the immediate next line with the help of imports:
from .iface import AmpScale, Config, Platform, Stream
from .jackclient import BufferFiller
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import logging, outjack.portaudioclient as pac
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/jackclient.py
# class BufferFiller:
#
# def __init__(self, portcount, buffersize, init, flip):
# self.portcount = portcount
# self.buffersize = buffersize
# self._newbuf(init)
# self.flip = flip
#
# def __call__(self, outbufs):
# n = len(outbufs[0])
# i = 0
# while i < n:
# m = min(n - i, self.buffersize - self.cursor)
# for portindex in range(self.portcount):
# self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m]
# self.cursor += m
# i += m
# if self.cursor == self.buffersize:
# self._newbuf(self.flip)
#
# def _newbuf(self, factory):
# outbuf = factory().view()
# outbuf.shape = self.portcount, self.buffersize
# self.outbuf = outbuf
# self.cursor = 0
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | def flush(self): |
Given the code snippet: <|code_start|># pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class PortAudioClient(pac.PortAudioClient, Platform):
@types(Config, StereoInfo)
def __init__(self, config, stereoinfo):
config = config.PortAudio
super().__init__(stereoinfo.getoutchans.size, config.outputrate, config.buffersize, config.ringsize, config.coupling)
class PortAudioStream(Node, Stream, metaclass = AmpScale):
log2maxpeaktopeak = 1
@types(StereoInfo, FloatStream, PortAudioClient)
def __init__(self, stereoinfo, wavs, client):
super().__init__()
<|code_end|>
, generate the next line using the imports in this file:
from .iface import AmpScale, Config, Platform, Stream
from .jackclient import BufferFiller
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import logging, outjack.portaudioclient as pac
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/jackclient.py
# class BufferFiller:
#
# def __init__(self, portcount, buffersize, init, flip):
# self.portcount = portcount
# self.buffersize = buffersize
# self._newbuf(init)
# self.flip = flip
#
# def __call__(self, outbufs):
# n = len(outbufs[0])
# i = 0
# while i < n:
# m = min(n - i, self.buffersize - self.cursor)
# for portindex in range(self.portcount):
# self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m]
# self.cursor += m
# i += m
# if self.cursor == self.buffersize:
# self._newbuf(self.flip)
#
# def _newbuf(self, factory):
# outbuf = factory().view()
# outbuf.shape = self.portcount, self.buffersize
# self.outbuf = outbuf
# self.cursor = 0
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | self.chancount = stereoinfo.getoutchans.size |
Given the code snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class PortAudioClient(pac.PortAudioClient, Platform):
@types(Config, StereoInfo)
def __init__(self, config, stereoinfo):
config = config.PortAudio
super().__init__(stereoinfo.getoutchans.size, config.outputrate, config.buffersize, config.ringsize, config.coupling)
class PortAudioStream(Node, Stream, metaclass = AmpScale):
<|code_end|>
, generate the next line using the imports in this file:
from .iface import AmpScale, Config, Platform, Stream
from .jackclient import BufferFiller
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import logging, outjack.portaudioclient as pac
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/jackclient.py
# class BufferFiller:
#
# def __init__(self, portcount, buffersize, init, flip):
# self.portcount = portcount
# self.buffersize = buffersize
# self._newbuf(init)
# self.flip = flip
#
# def __call__(self, outbufs):
# n = len(outbufs[0])
# i = 0
# while i < n:
# m = min(n - i, self.buffersize - self.cursor)
# for portindex in range(self.portcount):
# self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m]
# self.cursor += m
# i += m
# if self.cursor == self.buffersize:
# self._newbuf(self.flip)
#
# def _newbuf(self, factory):
# outbuf = factory().view()
# outbuf.shape = self.portcount, self.buffersize
# self.outbuf = outbuf
# self.cursor = 0
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | log2maxpeaktopeak = 1 |
Here is a snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class PortAudioClient(pac.PortAudioClient, Platform):
@types(Config, StereoInfo)
<|code_end|>
. Write the next line using the current file imports:
from .iface import AmpScale, Config, Platform, Stream
from .jackclient import BufferFiller
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import logging, outjack.portaudioclient as pac
and context from other files:
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/jackclient.py
# class BufferFiller:
#
# def __init__(self, portcount, buffersize, init, flip):
# self.portcount = portcount
# self.buffersize = buffersize
# self._newbuf(init)
# self.flip = flip
#
# def __call__(self, outbufs):
# n = len(outbufs[0])
# i = 0
# while i < n:
# m = min(n - i, self.buffersize - self.cursor)
# for portindex in range(self.portcount):
# self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m]
# self.cursor += m
# i += m
# if self.cursor == self.buffersize:
# self._newbuf(self.flip)
#
# def _newbuf(self, factory):
# outbuf = factory().view()
# outbuf.shape = self.portcount, self.buffersize
# self.outbuf = outbuf
# self.cursor = 0
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
, which may include functions, classes, or code. Output only the next line. | def __init__(self, config, stereoinfo): |
Based on the snippet: <|code_start|>#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class PortAudioClient(pac.PortAudioClient, Platform):
@types(Config, StereoInfo)
def __init__(self, config, stereoinfo):
config = config.PortAudio
super().__init__(stereoinfo.getoutchans.size, config.outputrate, config.buffersize, config.ringsize, config.coupling)
class PortAudioStream(Node, Stream, metaclass = AmpScale):
log2maxpeaktopeak = 1
@types(StereoInfo, FloatStream, PortAudioClient)
def __init__(self, stereoinfo, wavs, client):
<|code_end|>
, predict the immediate next line with the help of imports:
from .iface import AmpScale, Config, Platform, Stream
from .jackclient import BufferFiller
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import logging, outjack.portaudioclient as pac
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/jackclient.py
# class BufferFiller:
#
# def __init__(self, portcount, buffersize, init, flip):
# self.portcount = portcount
# self.buffersize = buffersize
# self._newbuf(init)
# self.flip = flip
#
# def __call__(self, outbufs):
# n = len(outbufs[0])
# i = 0
# while i < n:
# m = min(n - i, self.buffersize - self.cursor)
# for portindex in range(self.portcount):
# self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m]
# self.cursor += m
# i += m
# if self.cursor == self.buffersize:
# self._newbuf(self.flip)
#
# def _newbuf(self, factory):
# outbuf = factory().view()
# outbuf.shape = self.portcount, self.buffersize
# self.outbuf = outbuf
# self.cursor = 0
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | super().__init__() |
Given snippet: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class PortAudioClient(pac.PortAudioClient, Platform):
@types(Config, StereoInfo)
def __init__(self, config, stereoinfo):
config = config.PortAudio
super().__init__(stereoinfo.getoutchans.size, config.outputrate, config.buffersize, config.ringsize, config.coupling)
class PortAudioStream(Node, Stream, metaclass = AmpScale):
log2maxpeaktopeak = 1
@types(StereoInfo, FloatStream, PortAudioClient)
def __init__(self, stereoinfo, wavs, client):
super().__init__()
self.chancount = stereoinfo.getoutchans.size
self.wavs = wavs
self.client = client
def start(self):
self.client.activate()
self.filler = BufferFiller(self.chancount, self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .iface import AmpScale, Config, Platform, Stream
from .jackclient import BufferFiller
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import logging, outjack.portaudioclient as pac
and context:
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/jackclient.py
# class BufferFiller:
#
# def __init__(self, portcount, buffersize, init, flip):
# self.portcount = portcount
# self.buffersize = buffersize
# self._newbuf(init)
# self.flip = flip
#
# def __call__(self, outbufs):
# n = len(outbufs[0])
# i = 0
# while i < n:
# m = min(n - i, self.buffersize - self.cursor)
# for portindex in range(self.portcount):
# self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m]
# self.cursor += m
# i += m
# if self.cursor == self.buffersize:
# self._newbuf(self.flip)
#
# def _newbuf(self, factory):
# outbuf = factory().view()
# outbuf.shape = self.portcount, self.buffersize
# self.outbuf = outbuf
# self.cursor = 0
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
which might include code, classes, or functions. Output only the next line. | def callimpl(self): |
Predict the next line for this snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class TestSimpleTimer(TestCase):
def periodframecount(self, rate):
block, = self.t.blocksforperiod(rate)
return block.framecount
def test_carry(self):
clock = 2000000
t = self.t = SimpleTimer(clock)
self.assertEqual(33333, self.periodframecount(60))
self.assertEqual(20, t.carryticks)
self.assertEqual(33334, self.periodframecount(60))
self.assertEqual(-20, t.carryticks)
self.assertEqual(33333, self.periodframecount(60))
self.assertEqual(0, t.carryticks)
self.assertEqual(clock * 10, self.periodframecount(.1))
self.assertEqual(0, t.carryticks)
def test_fractionalrefreshrates(self):
t = self.t = SimpleTimer(100)
self.assertEqual(200, self.periodframecount(.5))
self.assertEqual(0, t.carryticks)
self.assertEqual(300, self.periodframecount(1 / 3))
self.assertEqual(0, t.carryticks)
self.assertEqual(67, self.periodframecount(1.5))
self.assertEqual(-.5, t.carryticks)
<|code_end|>
with the help of current file imports:
from .timer import SimpleTimer, MinBlockRateTimer
from unittest import TestCase
and context from other files:
# Path: pym2149/timer.py
# class SimpleTimer(Timer):
#
# def __init__(self, clock):
# self.carryticks = 0
# self.clock = clock
#
# def blocksforperiod(self, refreshrate):
# available = self.carryticks + self.clock
# blockticks = int(round(available / refreshrate))
# self.carryticks = available - blockticks * refreshrate
# yield Block(blockticks)
#
# def __del__(self):
# if self.carryticks:
# log.warning("Non-zero carry on dispose: %s", self.carryticks)
#
# class MinBlockRateTimer(SimpleTimer):
#
# def __init__(self, clock, minblockrate):
# # If division not exact, rate will slightly exceed given minimum:
# self.maxblocksize = int(clock // minblockrate)
# if not self.maxblocksize:
# raise Exception(clock, minblockrate)
# super().__init__(clock)
#
# def blocksforperiod(self, refreshrate):
# wholeperiodblock, = super().blocksforperiod(refreshrate)
# blockticks = wholeperiodblock.framecount
# while blockticks:
# size = min(blockticks, self.maxblocksize)
# b = Block(size)
# blockticks -= size
# yield b
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(66, self.periodframecount(1.5)) |
Next line prediction: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class TestSimpleTimer(TestCase):
def periodframecount(self, rate):
block, = self.t.blocksforperiod(rate)
<|code_end|>
. Use current file imports:
(from .timer import SimpleTimer, MinBlockRateTimer
from unittest import TestCase)
and context including class names, function names, or small code snippets from other files:
# Path: pym2149/timer.py
# class SimpleTimer(Timer):
#
# def __init__(self, clock):
# self.carryticks = 0
# self.clock = clock
#
# def blocksforperiod(self, refreshrate):
# available = self.carryticks + self.clock
# blockticks = int(round(available / refreshrate))
# self.carryticks = available - blockticks * refreshrate
# yield Block(blockticks)
#
# def __del__(self):
# if self.carryticks:
# log.warning("Non-zero carry on dispose: %s", self.carryticks)
#
# class MinBlockRateTimer(SimpleTimer):
#
# def __init__(self, clock, minblockrate):
# # If division not exact, rate will slightly exceed given minimum:
# self.maxblocksize = int(clock // minblockrate)
# if not self.maxblocksize:
# raise Exception(clock, minblockrate)
# super().__init__(clock)
#
# def blocksforperiod(self, refreshrate):
# wholeperiodblock, = super().blocksforperiod(refreshrate)
# blockticks = wholeperiodblock.framecount
# while blockticks:
# size = min(blockticks, self.maxblocksize)
# b = Block(size)
# blockticks -= size
# yield b
. Output only the next line. | return block.framecount |
Here is a snippet: <|code_start|>class LogicalBundle(Bundle):
@types(Prerecorded, [Chip])
def __init__(self, prerecorded, chips):
super().__init__(prerecorded, {chip.param: chip.channels for chip in chips})
class PhysicalBundle(Bundle):
@types(Prerecorded, PhysicalRegisters)
def __init__(self, prerecorded, registers):
super().__init__(prerecorded, registers)
class Player(MainBackground):
@types(Config, Bundle, Roll, Timer, Stream)
def __init__(self, config, bundle, roll, timer, stream):
super().__init__(config)
self.updaterate = config.updaterate
self.bundle = bundle
self.roll = roll
self.timer = timer
self.stream = stream
def __call__(self):
for _ in self.bundle:
if self.quit:
break
self.roll.update()
for b in self.timer.blocksforperiod(self.updaterate):
self.stream.call(b)
<|code_end|>
. Write the next line using the current file imports:
from .iface import Chip, Config, Prerecorded, Roll, Stream, Timer
from .ym2149 import PhysicalRegisters
from diapyr import types
from splut.bg import MainBackground
and context from other files:
# Path: pym2149/iface.py
# class Chip: pass
#
# class Config(lurlene.iface.Config): pass
#
# class Prerecorded: pass
#
# class Roll: pass
#
# class Stream: pass
#
# class Timer: pass
#
# Path: pym2149/ym2149.py
# class PhysicalRegisters:
#
# supportedchannels = 3
# timers = property(lambda self: self.logical.timers)
# levelbase = 0x8
#
# @types(Config, LogicalRegisters)
# def __init__(self, config, logical):
# # XXX: Add reverse wiring?
# # Like the real thing we have 16 registers, this impl ignores the last 2:
# self.R = tuple(Reg() for _ in range(16)) # Assume all incoming values are in [0, 255].
# # We only have registers for the authentic number of channels:
# for c in range(min(self.supportedchannels, config.chipchannels)):
# logical.toneperiods[c].link(TP, self.R[c * 2], self.R[c * 2 + 1])
# logical.toneflags[c].link(MixerFlag(c), self.R[0x7])
# logical.noiseflags[c].link(MixerFlag(self.supportedchannels + c), self.R[0x7])
# logical.fixedlevels[c].link(lambda l: l & 0x0f, self.R[self.levelbase + c])
# logical.levelmodes[c].link(getlevelmode, self.R[self.levelbase + c])
# logical.noiseperiod.link(NP, self.R[0x6])
# logical.envperiod.link(EP, self.R[0xB], self.R[0xC])
# logical.envshape.link(lambda s: s & 0x0f, self.R[0xD])
# for r in self.R:
# r.value = 0
# self.logical = logical
, which may include functions, classes, or code. Output only the next line. | self.stream.flush() |
Using the snippet: <|code_start|> self.prerecorded = prerecorded
self.registers = registers
def __iter__(self):
yield from self.prerecorded.frames(self.registers)
class LogicalBundle(Bundle):
@types(Prerecorded, [Chip])
def __init__(self, prerecorded, chips):
super().__init__(prerecorded, {chip.param: chip.channels for chip in chips})
class PhysicalBundle(Bundle):
@types(Prerecorded, PhysicalRegisters)
def __init__(self, prerecorded, registers):
super().__init__(prerecorded, registers)
class Player(MainBackground):
@types(Config, Bundle, Roll, Timer, Stream)
def __init__(self, config, bundle, roll, timer, stream):
super().__init__(config)
self.updaterate = config.updaterate
self.bundle = bundle
self.roll = roll
self.timer = timer
self.stream = stream
def __call__(self):
<|code_end|>
, determine the next line of code. You have imports:
from .iface import Chip, Config, Prerecorded, Roll, Stream, Timer
from .ym2149 import PhysicalRegisters
from diapyr import types
from splut.bg import MainBackground
and context (class names, function names, or code) available:
# Path: pym2149/iface.py
# class Chip: pass
#
# class Config(lurlene.iface.Config): pass
#
# class Prerecorded: pass
#
# class Roll: pass
#
# class Stream: pass
#
# class Timer: pass
#
# Path: pym2149/ym2149.py
# class PhysicalRegisters:
#
# supportedchannels = 3
# timers = property(lambda self: self.logical.timers)
# levelbase = 0x8
#
# @types(Config, LogicalRegisters)
# def __init__(self, config, logical):
# # XXX: Add reverse wiring?
# # Like the real thing we have 16 registers, this impl ignores the last 2:
# self.R = tuple(Reg() for _ in range(16)) # Assume all incoming values are in [0, 255].
# # We only have registers for the authentic number of channels:
# for c in range(min(self.supportedchannels, config.chipchannels)):
# logical.toneperiods[c].link(TP, self.R[c * 2], self.R[c * 2 + 1])
# logical.toneflags[c].link(MixerFlag(c), self.R[0x7])
# logical.noiseflags[c].link(MixerFlag(self.supportedchannels + c), self.R[0x7])
# logical.fixedlevels[c].link(lambda l: l & 0x0f, self.R[self.levelbase + c])
# logical.levelmodes[c].link(getlevelmode, self.R[self.levelbase + c])
# logical.noiseperiod.link(NP, self.R[0x6])
# logical.envperiod.link(EP, self.R[0xB], self.R[0xC])
# logical.envshape.link(lambda s: s & 0x0f, self.R[0xD])
# for r in self.R:
# r.value = 0
# self.logical = logical
. Output only the next line. | for _ in self.bundle: |
Given snippet: <|code_start|> self.registers = registers
def __iter__(self):
yield from self.prerecorded.frames(self.registers)
class LogicalBundle(Bundle):
@types(Prerecorded, [Chip])
def __init__(self, prerecorded, chips):
super().__init__(prerecorded, {chip.param: chip.channels for chip in chips})
class PhysicalBundle(Bundle):
@types(Prerecorded, PhysicalRegisters)
def __init__(self, prerecorded, registers):
super().__init__(prerecorded, registers)
class Player(MainBackground):
@types(Config, Bundle, Roll, Timer, Stream)
def __init__(self, config, bundle, roll, timer, stream):
super().__init__(config)
self.updaterate = config.updaterate
self.bundle = bundle
self.roll = roll
self.timer = timer
self.stream = stream
def __call__(self):
for _ in self.bundle:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .iface import Chip, Config, Prerecorded, Roll, Stream, Timer
from .ym2149 import PhysicalRegisters
from diapyr import types
from splut.bg import MainBackground
and context:
# Path: pym2149/iface.py
# class Chip: pass
#
# class Config(lurlene.iface.Config): pass
#
# class Prerecorded: pass
#
# class Roll: pass
#
# class Stream: pass
#
# class Timer: pass
#
# Path: pym2149/ym2149.py
# class PhysicalRegisters:
#
# supportedchannels = 3
# timers = property(lambda self: self.logical.timers)
# levelbase = 0x8
#
# @types(Config, LogicalRegisters)
# def __init__(self, config, logical):
# # XXX: Add reverse wiring?
# # Like the real thing we have 16 registers, this impl ignores the last 2:
# self.R = tuple(Reg() for _ in range(16)) # Assume all incoming values are in [0, 255].
# # We only have registers for the authentic number of channels:
# for c in range(min(self.supportedchannels, config.chipchannels)):
# logical.toneperiods[c].link(TP, self.R[c * 2], self.R[c * 2 + 1])
# logical.toneflags[c].link(MixerFlag(c), self.R[0x7])
# logical.noiseflags[c].link(MixerFlag(self.supportedchannels + c), self.R[0x7])
# logical.fixedlevels[c].link(lambda l: l & 0x0f, self.R[self.levelbase + c])
# logical.levelmodes[c].link(getlevelmode, self.R[self.levelbase + c])
# logical.noiseperiod.link(NP, self.R[0x6])
# logical.envperiod.link(EP, self.R[0xB], self.R[0xC])
# logical.envshape.link(lambda s: s & 0x0f, self.R[0xD])
# for r in self.R:
# r.value = 0
# self.logical = logical
which might include code, classes, or functions. Output only the next line. | if self.quit: |
Given the code snippet: <|code_start|>class Bundle:
def __init__(self, prerecorded, registers):
self.prerecorded = prerecorded
self.registers = registers
def __iter__(self):
yield from self.prerecorded.frames(self.registers)
class LogicalBundle(Bundle):
@types(Prerecorded, [Chip])
def __init__(self, prerecorded, chips):
super().__init__(prerecorded, {chip.param: chip.channels for chip in chips})
class PhysicalBundle(Bundle):
@types(Prerecorded, PhysicalRegisters)
def __init__(self, prerecorded, registers):
super().__init__(prerecorded, registers)
class Player(MainBackground):
@types(Config, Bundle, Roll, Timer, Stream)
def __init__(self, config, bundle, roll, timer, stream):
super().__init__(config)
self.updaterate = config.updaterate
self.bundle = bundle
self.roll = roll
self.timer = timer
<|code_end|>
, generate the next line using the imports in this file:
from .iface import Chip, Config, Prerecorded, Roll, Stream, Timer
from .ym2149 import PhysicalRegisters
from diapyr import types
from splut.bg import MainBackground
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/iface.py
# class Chip: pass
#
# class Config(lurlene.iface.Config): pass
#
# class Prerecorded: pass
#
# class Roll: pass
#
# class Stream: pass
#
# class Timer: pass
#
# Path: pym2149/ym2149.py
# class PhysicalRegisters:
#
# supportedchannels = 3
# timers = property(lambda self: self.logical.timers)
# levelbase = 0x8
#
# @types(Config, LogicalRegisters)
# def __init__(self, config, logical):
# # XXX: Add reverse wiring?
# # Like the real thing we have 16 registers, this impl ignores the last 2:
# self.R = tuple(Reg() for _ in range(16)) # Assume all incoming values are in [0, 255].
# # We only have registers for the authentic number of channels:
# for c in range(min(self.supportedchannels, config.chipchannels)):
# logical.toneperiods[c].link(TP, self.R[c * 2], self.R[c * 2 + 1])
# logical.toneflags[c].link(MixerFlag(c), self.R[0x7])
# logical.noiseflags[c].link(MixerFlag(self.supportedchannels + c), self.R[0x7])
# logical.fixedlevels[c].link(lambda l: l & 0x0f, self.R[self.levelbase + c])
# logical.levelmodes[c].link(getlevelmode, self.R[self.levelbase + c])
# logical.noiseperiod.link(NP, self.R[0x6])
# logical.envperiod.link(EP, self.R[0xB], self.R[0xC])
# logical.envshape.link(lambda s: s & 0x0f, self.R[0xD])
# for r in self.R:
# r.value = 0
# self.logical = logical
. Output only the next line. | self.stream = stream |
Given the following code snippet before the placeholder: <|code_start|>
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class Bundle:
def __init__(self, prerecorded, registers):
self.prerecorded = prerecorded
self.registers = registers
def __iter__(self):
yield from self.prerecorded.frames(self.registers)
class LogicalBundle(Bundle):
@types(Prerecorded, [Chip])
def __init__(self, prerecorded, chips):
<|code_end|>
, predict the next line using imports from the current file:
from .iface import Chip, Config, Prerecorded, Roll, Stream, Timer
from .ym2149 import PhysicalRegisters
from diapyr import types
from splut.bg import MainBackground
and context including class names, function names, and sometimes code from other files:
# Path: pym2149/iface.py
# class Chip: pass
#
# class Config(lurlene.iface.Config): pass
#
# class Prerecorded: pass
#
# class Roll: pass
#
# class Stream: pass
#
# class Timer: pass
#
# Path: pym2149/ym2149.py
# class PhysicalRegisters:
#
# supportedchannels = 3
# timers = property(lambda self: self.logical.timers)
# levelbase = 0x8
#
# @types(Config, LogicalRegisters)
# def __init__(self, config, logical):
# # XXX: Add reverse wiring?
# # Like the real thing we have 16 registers, this impl ignores the last 2:
# self.R = tuple(Reg() for _ in range(16)) # Assume all incoming values are in [0, 255].
# # We only have registers for the authentic number of channels:
# for c in range(min(self.supportedchannels, config.chipchannels)):
# logical.toneperiods[c].link(TP, self.R[c * 2], self.R[c * 2 + 1])
# logical.toneflags[c].link(MixerFlag(c), self.R[0x7])
# logical.noiseflags[c].link(MixerFlag(self.supportedchannels + c), self.R[0x7])
# logical.fixedlevels[c].link(lambda l: l & 0x0f, self.R[self.levelbase + c])
# logical.levelmodes[c].link(getlevelmode, self.R[self.levelbase + c])
# logical.noiseperiod.link(NP, self.R[0x6])
# logical.envperiod.link(EP, self.R[0xB], self.R[0xC])
# logical.envshape.link(lambda s: s & 0x0f, self.R[0xD])
# for r in self.R:
# r.value = 0
# self.logical = logical
. Output only the next line. | super().__init__(prerecorded, {chip.param: chip.channels for chip in chips}) |
Based on the snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class TestReg(TestCase):
def test_anim(self):
d = Data()
r = d.reg()
d.setprev(0)
self.assertEqual(0, d.totalticks)
<|code_end|>
, predict the immediate next line with the help of imports:
from .mkdsd import Data
from unittest import TestCase
and context (classes, functions, sometimes code) from other files:
# Path: ymtests/mkdsd.py
# class Data:
#
# def __init__(self):
# self.index = 0
# self.totalticks = 0
# self.bytecode = []
#
# def reg(self, xform = lambda x: x):
# r = Reg(self, self.index, xform)
# self.index += 1
# return r
#
# def setprev(self, prev):
# self.bytecode.extend([0x80, prev])
# self.prev = prev
#
# def sleep(self, ticks):
# if ticks < 2:
# raise UnsupportedTicksException(ticks)
# while ticks:
# part = min(256, ticks)
# self.bytecode.extend([0x82, part - 1])
# self.totalticks += part
# ticks -= part
#
# def save(self, f):
# w = lambda v: f.write(bytes(v))
# w([self.totalticks >> 8, self.totalticks & 0xff])
# w(self.bytecode)
# w([0x82, 0])
. Output only the next line. | r.anim(2, 5) |
Next line prediction: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class TestMakeSample5Shape(TestCase):
def test_happypath(self):
s = makesample5shape([0x00, 0x7f, 0x80, 0xff], False, False)
self.assertEqual(4, s.size)
self.assertEqual(3, s.introlen)
self.assertEqual([1, 27, 27, 31], list(s.buf))
def test_signed(self):
s = makesample5shape([0x80, 0xff, 0x00, 0x7f], True, False)
self.assertEqual(4, s.size)
self.assertEqual(3, s.introlen)
<|code_end|>
. Use current file imports:
(from .shapes import makesample5shape
from unittest import TestCase)
and context including class names, function names, or small code snippets from other files:
# Path: pym2149/shapes.py
# def makesample5shape(data, signed, is4bit):
# if is4bit:
# data4 = data
# else:
# if signed:
# data = [(d + 0x80) & 0xff for d in data]
# d0 = min(data)
# data4 = (_amptolevel4(((d - d0) + .5) / 0x100) for d in data)
# return Shape.level4to5(data4, len(data) - 1)
. Output only the next line. | self.assertEqual([1, 27, 27, 31], list(s.buf)) |
Predict the next line for this snippet: <|code_start|> def test_diamond(self):
self.spectator = Reg(value = -1)
self.lhs = Reg()
self.rhs = Reg()
self.pair = Reg()
self.leaf = Reg().link(lambda l, r, s: (l, r, s), self.lhs, self.rhs, self.spectator)
self.lhs.link(lambda p: p[0], self.pair)
self.rhs.link(lambda p: p[1], self.pair)
self.pair.value = 1, 2
self.assertEqual((1, 2, -1), self.leaf.value)
self.pair.value = 3, 4
self.assertEqual((3, 4, -1), self.leaf.value)
def test_multipath(self):
source = Reg()
middle = Reg().link(lambda x: x * 2, source)
target1 = Reg().link(lambda x: x * 3, source).link(lambda x: x * 5, middle)
target2 = Reg().link(lambda x: x * 7, middle).link(lambda x: x * 11, source)
source.value = 1
# These values have overwritten via-middle values:
self.assertEqual(3, target1.value)
self.assertEqual(11, target2.value)
def test_initversionreg(self):
self.assertEqual(0, VersionReg().version)
self.assertEqual(1, VersionReg(value = 123).version)
def test_minval(self):
r = Reg(minval = 1, value = 0)
self.assertEqual(1, r.value) # Check minval applied to passed-in value.
<|code_end|>
with the help of current file imports:
from .reg import Reg, VersionReg
from unittest import TestCase
and context from other files:
# Path: pym2149/reg.py
# class Reg:
#
# undefined = object()
#
# def __init__(self, value = undefined, *, maxval = None, minval = None):
# self.links = []
# self.idle = True
# self.maxval = maxval # Friendlier than a mask.
# self.minval = minval # Typically to avoid 0 period.
# if value is not self.undefined:
# self.value = value
#
# def link(self, xform, *upstream):
# link = Link(self, xform, upstream)
# for r in upstream:
# r.links.append(link)
# return self
#
# def mlink(self, mask, xform, *upstream):
# negmask = ~mask
# self.link(lambda *args: (negmask & self.value) | (mask & xform(*args)), *upstream)
#
# def set(self, value):
# if self.maxval is not None:
# value = min(self.maxval, value)
# if self.minval is not None:
# value = max(self.minval, value)
# self._value = value
# self.idle = False
# try:
# for link in self.links:
# link.update()
# finally:
# self.idle = True
#
# value = property(lambda self: self._value, lambda self, value: self.set(value))
#
# class VersionReg(Reg):
#
# version = 0
#
# def set(self, value):
# super().set(value)
# self.version += 1
, which may contain function names, class names, or code. Output only the next line. | r.value = 2 |
Given the code snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class TestReg(TestCase):
def test_bidi(self):
high = Reg()
low = Reg()
value = Reg().link(lambda h, l: (h << 8) | l, high, low)
high.link(lambda v: (v >> 8), value)
low.link(lambda v: v & 0xff, value)
vr = VersionReg().link(lambda v: v, value)
value.link(lambda v: v, vr)
self.assertEqual(0, vr.version)
high.value = 0x87
<|code_end|>
, generate the next line using the imports in this file:
from .reg import Reg, VersionReg
from unittest import TestCase
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/reg.py
# class Reg:
#
# undefined = object()
#
# def __init__(self, value = undefined, *, maxval = None, minval = None):
# self.links = []
# self.idle = True
# self.maxval = maxval # Friendlier than a mask.
# self.minval = minval # Typically to avoid 0 period.
# if value is not self.undefined:
# self.value = value
#
# def link(self, xform, *upstream):
# link = Link(self, xform, upstream)
# for r in upstream:
# r.links.append(link)
# return self
#
# def mlink(self, mask, xform, *upstream):
# negmask = ~mask
# self.link(lambda *args: (negmask & self.value) | (mask & xform(*args)), *upstream)
#
# def set(self, value):
# if self.maxval is not None:
# value = min(self.maxval, value)
# if self.minval is not None:
# value = max(self.minval, value)
# self._value = value
# self.idle = False
# try:
# for link in self.links:
# link.update()
# finally:
# self.idle = True
#
# value = property(lambda self: self._value, lambda self, value: self.set(value))
#
# class VersionReg(Reg):
#
# version = 0
#
# def set(self, value):
# super().set(value)
# self.version += 1
. Output only the next line. | self.assertEqual(0x87, high.value) |
Based on the snippet: <|code_start|> chanindex = syschanindex % stream.chancount
self.client.connect(f"{clientname}:{stream.streamname}_{1 + chanindex}", f"system:playback_{1 + syschanindex}")
self.filler = BufferFiller(sum(s.chancount for s in self.streams), self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer)
def callimpl(self):
self.filler([self.chain(wav) for stream in self.streams for wav in stream])
def flush(self):
pass # Nothing to be done.
def stop(self):
self.client.deactivate()
class BufferFiller:
def __init__(self, portcount, buffersize, init, flip):
self.portcount = portcount
self.buffersize = buffersize
self._newbuf(init)
self.flip = flip
def __call__(self, outbufs):
n = len(outbufs[0])
i = 0
while i < n:
m = min(n - i, self.buffersize - self.cursor)
for portindex in range(self.portcount):
self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m]
self.cursor += m
i += m
<|code_end|>
, predict the immediate next line with the help of imports:
from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | if self.cursor == self.buffersize: |
Given snippet: <|code_start|> super().__init__(clientname, portcount, config.jackringsize, config.jackcoupling)
def start(self):
super().start()
log.debug(
"JACK block size: %s or %.3f seconds",
self.buffersize,
self.buffersize / self.outputrate)
class JackStream(Stream, Node, metaclass = AmpScale):
log2maxpeaktopeak = 1
@types(Config, [FloatStream], JackClient)
def __init__(self, config, streams, client):
super().__init__()
self.systemchannelcount = config.systemchannelcount
for stream in streams:
for chanindex in range(stream.chancount):
client.port_register_output(f"{stream.streamname}_{1 + chanindex}")
self.streams = streams
self.client = client
def start(self):
self.client.activate()
for stream in self.streams:
# Connect all system channels, cycling over our streams if necessary:
for syschanindex in range(self.systemchannelcount):
chanindex = syschanindex % stream.chancount
self.client.connect(f"{clientname}:{stream.streamname}_{1 + chanindex}", f"system:playback_{1 + syschanindex}")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging
and context:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
which might include code, classes, or functions. Output only the next line. | self.filler = BufferFiller(sum(s.chancount for s in self.streams), self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer) |
Given the following code snippet before the placeholder: <|code_start|> for stream in self.streams:
# Connect all system channels, cycling over our streams if necessary:
for syschanindex in range(self.systemchannelcount):
chanindex = syschanindex % stream.chancount
self.client.connect(f"{clientname}:{stream.streamname}_{1 + chanindex}", f"system:playback_{1 + syschanindex}")
self.filler = BufferFiller(sum(s.chancount for s in self.streams), self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer)
def callimpl(self):
self.filler([self.chain(wav) for stream in self.streams for wav in stream])
def flush(self):
pass # Nothing to be done.
def stop(self):
self.client.deactivate()
class BufferFiller:
def __init__(self, portcount, buffersize, init, flip):
self.portcount = portcount
self.buffersize = buffersize
self._newbuf(init)
self.flip = flip
def __call__(self, outbufs):
n = len(outbufs[0])
i = 0
while i < n:
m = min(n - i, self.buffersize - self.cursor)
for portindex in range(self.portcount):
<|code_end|>
, predict the next line using imports from the current file:
from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging
and context including class names, function names, and sometimes code from other files:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | self.outbuf[portindex, self.cursor:self.cursor + m] = outbufs[portindex].buf[i:i + m] |
Continue the code snippet: <|code_start|> super().start()
log.debug(
"JACK block size: %s or %.3f seconds",
self.buffersize,
self.buffersize / self.outputrate)
class JackStream(Stream, Node, metaclass = AmpScale):
log2maxpeaktopeak = 1
@types(Config, [FloatStream], JackClient)
def __init__(self, config, streams, client):
super().__init__()
self.systemchannelcount = config.systemchannelcount
for stream in streams:
for chanindex in range(stream.chancount):
client.port_register_output(f"{stream.streamname}_{1 + chanindex}")
self.streams = streams
self.client = client
def start(self):
self.client.activate()
for stream in self.streams:
# Connect all system channels, cycling over our streams if necessary:
for syschanindex in range(self.systemchannelcount):
chanindex = syschanindex % stream.chancount
self.client.connect(f"{clientname}:{stream.streamname}_{1 + chanindex}", f"system:playback_{1 + syschanindex}")
self.filler = BufferFiller(sum(s.chancount for s in self.streams), self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer)
def callimpl(self):
<|code_end|>
. Use current file imports:
from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging
and context (classes, functions, or code) from other files:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | self.filler([self.chain(wav) for stream in self.streams for wav in stream]) |
Given the code snippet: <|code_start|># This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class JackClient(jc.JackClient, Platform):
@types(Config, StereoInfo)
def __init__(self, config, stereoinfo):
portcount = stereoinfo.getoutchans.size + config.SID.enabled # FIXME: This is a hack.
super().__init__(clientname, portcount, config.jackringsize, config.jackcoupling)
def start(self):
super().start()
log.debug(
"JACK block size: %s or %.3f seconds",
self.buffersize,
<|code_end|>
, generate the next line using the imports in this file:
from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | self.buffersize / self.outputrate) |
Based on the snippet: <|code_start|> self.client = client
def start(self):
self.client.activate()
for stream in self.streams:
# Connect all system channels, cycling over our streams if necessary:
for syschanindex in range(self.systemchannelcount):
chanindex = syschanindex % stream.chancount
self.client.connect(f"{clientname}:{stream.streamname}_{1 + chanindex}", f"system:playback_{1 + syschanindex}")
self.filler = BufferFiller(sum(s.chancount for s in self.streams), self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer)
def callimpl(self):
self.filler([self.chain(wav) for stream in self.streams for wav in stream])
def flush(self):
pass # Nothing to be done.
def stop(self):
self.client.deactivate()
class BufferFiller:
def __init__(self, portcount, buffersize, init, flip):
self.portcount = portcount
self.buffersize = buffersize
self._newbuf(init)
self.flip = flip
def __call__(self, outbufs):
n = len(outbufs[0])
<|code_end|>
, predict the immediate next line with the help of imports:
from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | i = 0 |
Next line prediction: <|code_start|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
class JackClient(jc.JackClient, Platform):
@types(Config, StereoInfo)
def __init__(self, config, stereoinfo):
portcount = stereoinfo.getoutchans.size + config.SID.enabled # FIXME: This is a hack.
super().__init__(clientname, portcount, config.jackringsize, config.jackcoupling)
def start(self):
super().start()
log.debug(
"JACK block size: %s or %.3f seconds",
self.buffersize,
self.buffersize / self.outputrate)
class JackStream(Stream, Node, metaclass = AmpScale):
log2maxpeaktopeak = 1
@types(Config, [FloatStream], JackClient)
def __init__(self, config, streams, client):
super().__init__()
self.systemchannelcount = config.systemchannelcount
<|code_end|>
. Use current file imports:
(from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging)
and context including class names, function names, or small code snippets from other files:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | for stream in streams: |
Predict the next line after this snippet: <|code_start|> self.client = client
def start(self):
self.client.activate()
for stream in self.streams:
# Connect all system channels, cycling over our streams if necessary:
for syschanindex in range(self.systemchannelcount):
chanindex = syschanindex % stream.chancount
self.client.connect(f"{clientname}:{stream.streamname}_{1 + chanindex}", f"system:playback_{1 + syschanindex}")
self.filler = BufferFiller(sum(s.chancount for s in self.streams), self.client.buffersize, self.client.current_output_buffer, self.client.send_and_get_output_buffer)
def callimpl(self):
self.filler([self.chain(wav) for stream in self.streams for wav in stream])
def flush(self):
pass # Nothing to be done.
def stop(self):
self.client.deactivate()
class BufferFiller:
def __init__(self, portcount, buffersize, init, flip):
self.portcount = portcount
self.buffersize = buffersize
self._newbuf(init)
self.flip = flip
def __call__(self, outbufs):
n = len(outbufs[0])
<|code_end|>
using the current file's imports:
from .const import clientname
from .iface import AmpScale, Config, Platform, Stream
from .nod import Node
from .out import FloatStream, StereoInfo
from diapyr import types
import outjack.jackclient as jc, logging
and any relevant context from other files:
# Path: pym2149/const.py
#
# Path: pym2149/iface.py
# class AmpScale(type): pass
#
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class Stream: pass
#
# Path: pym2149/nod.py
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
#
# Path: pym2149/out.py
# class FloatStream(list):
#
# chancount = property(len)
#
# class StereoInfo:
#
# @types(Config)
# def __init__(self, config):
# self.n = config.chipchannels
# if config.stereo:
# self.panlaw = config.panlaw
# self.maxpan = float(config.maxpan)
# self.getoutchans = self.getstaticoutchans
# else:
# self.getoutchans = self.gettrivialoutchans
#
# def pantoamp(self, outchan, pan):
# return ((1 + (outchan * 2 - 1) * pan) / 2) ** (self.panlaw / 6)
#
# def staticamp(self, outchan, chipchan):
# return self.pantoamp(outchan, (chipchan * 2 - (self.n - 1)) / (self.n - 1) * self.maxpan)
#
# def gettrivialoutchans(self):
# return [TrivialOutChannel]
# gettrivialoutchans.size = 1
#
# def getstaticoutchans(self):
# return [StaticOutChannel([self.staticamp(oc, cc) for cc in range(self.n)]) for oc in range(2)]
# getstaticoutchans.size = 2
. Output only the next line. | i = 0 |
Here is a snippet: <|code_start|> return Pitch(self.refmidi + 12 * math.log(freq / self.reffreq, 2))
class Unequal:
def __init__(self, refpitch, freqs):
self.factors = [math.log(g / f, 2) for f, g in zip(freqs, freqs[1:] + [freqs[0] * 2])]
self.refpitch = refpitch
self.freqs = freqs
def freq(self, pitch):
pitch -= self.refpitch
pitchindex = math.floor(pitch) % 12
return self.freqs[pitchindex] * 2 ** (self.factors[pitchindex] * (pitch % 1) + pitch // 12)
def pitch(self, freq):
octave = math.floor(math.log(freq / self.freqs[0], 2))
freq /= 2 ** octave
pitchindex = bisect.bisect(self.freqs, freq) - 1 # FIXME LATER: Handle out of range.
x = math.log(freq / self.freqs[pitchindex], 2) / self.factors[pitchindex]
return Pitch(self.refpitch + octave * 12 + pitchindex + x)
class Meantone(Unequal):
'Including Pythagorean as a special case when meantonecomma is zero.'
syntonic = 81 / 80
@types(Config)
def __init__(self, config):
reffreq = float(config.referencefrequency)
refpitch = float(config.referencemidinote)
<|code_end|>
. Write the next line using the current file imports:
from .iface import Config, Tuning
from diapyr import DI, types
from lurlene.context import Context
import bisect, logging, math
and context from other files:
# Path: pym2149/iface.py
# class Config(lurlene.iface.Config): pass
#
# class Tuning: pass
, which may include functions, classes, or code. Output only the next line. | flats = config.meantoneflats |
Given the code snippet: <|code_start|> self.freqs = freqs
def freq(self, pitch):
pitch -= self.refpitch
pitchindex = math.floor(pitch) % 12
return self.freqs[pitchindex] * 2 ** (self.factors[pitchindex] * (pitch % 1) + pitch // 12)
def pitch(self, freq):
octave = math.floor(math.log(freq / self.freqs[0], 2))
freq /= 2 ** octave
pitchindex = bisect.bisect(self.freqs, freq) - 1 # FIXME LATER: Handle out of range.
x = math.log(freq / self.freqs[pitchindex], 2) / self.factors[pitchindex]
return Pitch(self.refpitch + octave * 12 + pitchindex + x)
class Meantone(Unequal):
'Including Pythagorean as a special case when meantonecomma is zero.'
syntonic = 81 / 80
@types(Config)
def __init__(self, config):
reffreq = float(config.referencefrequency)
refpitch = float(config.referencemidinote)
flats = config.meantoneflats
fifthratio = 1.5 / self.syntonic ** float(config.meantonecomma)
freqs = [None] * 12
for fifth in range(-flats, 12 - flats):
pitch = fifth * 7
freqs[pitch % 12] = reffreq * fifthratio ** fifth / 2 ** (pitch // 12)
super().__init__(refpitch, freqs)
<|code_end|>
, generate the next line using the imports in this file:
from .iface import Config, Tuning
from diapyr import DI, types
from lurlene.context import Context
import bisect, logging, math
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/iface.py
# class Config(lurlene.iface.Config): pass
#
# class Tuning: pass
. Output only the next line. | wolfpitch = Pitch(refpitch + 11 - flats) |
Predict the next line after this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
prescalers = {1 + i: v for i, v in enumerate([4, 10, 16, 50, 64, 100, 200])}
mfpclock = 2457600
class MFPTimer:
def __init__(self):
self.control = Reg()
self.data = Reg()
# TODO LATER: Verify that TDR 0 indeed behaves like 0x100.
self.effectivedata = Reg().link(lambda tdr: tdr if tdr else 0x100, self.data)
self.control.value = 0
self.data.value = 0
self.effect = Reg(NullEffect)
self.control_data = Reg()
self.control.link(lambda cd: cd[0], self.control_data)
self.data.link(lambda cd: cd[1], self.control_data)
self.freq = Reg()
# XXX: Should change of wavelength trigger this link?
self.control_data.link(self._findtcrtdr, self.freq)
self.prescalerornone = Reg().link(lambda tcr: prescalers.get(tcr), self.control)
self.repeat = Reg().link(lambda _: None, self.effect)
<|code_end|>
using the current file's imports:
from .dac import NullEffect
from .reg import Reg
and any relevant context from other files:
# Path: pym2149/dac.py
# class NullEffect:
# 'All registers are non-virtual and write directly to chip, the timer does not interfere.'
#
# def putlevel5(self, node):
# node.blockbuf.copybuf(node.chain(node.signal))
# if node.levelmodereg.value:
# node.blockbuf.mulbuf(node.chain(node.env))
# else:
# # According to block diagram, the level is already 5-bit when combining with binary signal:
# node.blockbuf.mul(level4to5(node.fixedreg.value))
#
# Path: pym2149/reg.py
# class Reg:
#
# undefined = object()
#
# def __init__(self, value = undefined, *, maxval = None, minval = None):
# self.links = []
# self.idle = True
# self.maxval = maxval # Friendlier than a mask.
# self.minval = minval # Typically to avoid 0 period.
# if value is not self.undefined:
# self.value = value
#
# def link(self, xform, *upstream):
# link = Link(self, xform, upstream)
# for r in upstream:
# r.links.append(link)
# return self
#
# def mlink(self, mask, xform, *upstream):
# negmask = ~mask
# self.link(lambda *args: (negmask & self.value) | (mask & xform(*args)), *upstream)
#
# def set(self, value):
# if self.maxval is not None:
# value = min(self.maxval, value)
# if self.minval is not None:
# value = max(self.minval, value)
# self._value = value
# self.idle = False
# try:
# for link in self.links:
# link.update()
# finally:
# self.idle = True
#
# value = property(lambda self: self._value, lambda self, value: self.set(value))
. Output only the next line. | def update(self, tcr, tdr, effect): |
Based on the snippet: <|code_start|>class MFPTimer:
def __init__(self):
self.control = Reg()
self.data = Reg()
# TODO LATER: Verify that TDR 0 indeed behaves like 0x100.
self.effectivedata = Reg().link(lambda tdr: tdr if tdr else 0x100, self.data)
self.control.value = 0
self.data.value = 0
self.effect = Reg(NullEffect)
self.control_data = Reg()
self.control.link(lambda cd: cd[0], self.control_data)
self.data.link(lambda cd: cd[1], self.control_data)
self.freq = Reg()
# XXX: Should change of wavelength trigger this link?
self.control_data.link(self._findtcrtdr, self.freq)
self.prescalerornone = Reg().link(lambda tcr: prescalers.get(tcr), self.control)
self.repeat = Reg().link(lambda _: None, self.effect)
def update(self, tcr, tdr, effect):
self.control_data.value = tcr, tdr
self.effect.value = effect
def _findtcrtdr(self, freq):
if not freq:
return 0, self.data.value # Stop timer.
diff = float('inf')
for tcr, prescaler in prescalers.items():
prescaler *= self.effect.value.wavelength # Avoid having to multiply twice.
etdr = int(round(mfpclock / (freq * prescaler)))
<|code_end|>
, predict the immediate next line with the help of imports:
from .dac import NullEffect
from .reg import Reg
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/dac.py
# class NullEffect:
# 'All registers are non-virtual and write directly to chip, the timer does not interfere.'
#
# def putlevel5(self, node):
# node.blockbuf.copybuf(node.chain(node.signal))
# if node.levelmodereg.value:
# node.blockbuf.mulbuf(node.chain(node.env))
# else:
# # According to block diagram, the level is already 5-bit when combining with binary signal:
# node.blockbuf.mul(level4to5(node.fixedreg.value))
#
# Path: pym2149/reg.py
# class Reg:
#
# undefined = object()
#
# def __init__(self, value = undefined, *, maxval = None, minval = None):
# self.links = []
# self.idle = True
# self.maxval = maxval # Friendlier than a mask.
# self.minval = minval # Typically to avoid 0 period.
# if value is not self.undefined:
# self.value = value
#
# def link(self, xform, *upstream):
# link = Link(self, xform, upstream)
# for r in upstream:
# r.links.append(link)
# return self
#
# def mlink(self, mask, xform, *upstream):
# negmask = ~mask
# self.link(lambda *args: (negmask & self.value) | (mask & xform(*args)), *upstream)
#
# def set(self, value):
# if self.maxval is not None:
# value = min(self.maxval, value)
# if self.minval is not None:
# value = max(self.minval, value)
# self._value = value
# self.idle = False
# try:
# for link in self.links:
# link.update()
# finally:
# self.idle = True
#
# value = property(lambda self: self._value, lambda self, value: self.set(value))
. Output only the next line. | if 1 <= etdr and etdr <= 0x100: |
Based on the snippet: <|code_start|># pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class SyncTimer(SimpleTimer):
'Fill platform buffer most efficiently.'
@types(Platform, MinBleps, ClockInfo)
def __init__(self, platform, minbleps, clockinfo):
self.naiverate = clockinfo.implclock
super().__init__(self.naiverate)
self.buffersize = platform.buffersize
self.naivex = 0
self.bufferx = 0
self.minbleps = minbleps
def blocksforperiod(self, refreshrate):
wholeperiodblock, = super().blocksforperiod(refreshrate)
naiveN = wholeperiodblock.framecount
while naiveN:
<|code_end|>
, predict the immediate next line with the help of imports:
from .clock import ClockInfo
from .iface import Platform
from .minblep import MinBleps
from .nod import Block
from .timer import MinBlockRateTimer, SimpleTimer
from diapyr import types
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/clock.py
# class ClockInfo:
#
# trishapes = frozenset([0xa, 0xe])
# tonescale = 16
#
# @classmethod
# def _shapescale(cls, shape):
# # Musically, the triangular shapes have twice the scale:
# return 512 if shape in cls.trishapes else 256
#
# @types(Config, Platform, YMFile)
# def __init__(self, config, platform, ymfile = None):
# self.nomclock = config.nominalclock
# if self.nomclock % config.underclock:
# raise Exception(f"Clock {self.nomclock} not divisible by underclock {config.underclock}.")
# self.implclock = self.nomclock // config.underclock
# if ymfile is not None and self.nomclock != ymfile.nominalclock:
# log.info("Context clock %s overridden to: %s", ymfile.nominalclock, self.nomclock)
# if self.implclock != self.nomclock:
# log.debug("Clock adjusted to %s to take advantage of non-trivial underclock.", self.implclock)
# if config.underclock < 1 or defaultscale % config.underclock:
# raise Exception(f"underclock must be a factor of {defaultscale}.")
# self.scale = defaultscale // config.underclock
# if config.freqclamp:
# # The 0 case just means that 1 is audible:
# self.mintoneperiod = max(1, self._toneperiodclampor0(platform.outputrate))
# log.debug("Minimum tone period: %s", self.mintoneperiod)
# else:
# self.mintoneperiod = 1
#
# def _toneperiodclampor0(self, outrate):
# # Largest period with frequency strictly greater than Nyquist, or 0 if there isn't one:
# return (self.implclock - 1) // (self.scale * outrate)
#
# def _convert(self, freqorperiod, scale):
# return self.nomclock / (scale * freqorperiod)
#
# def toneperiod(self, freq):
# return self._convert(freq, self.tonescale)
#
# def noiseperiod(self, freq):
# return self._convert(freq, 16) # First notch at freq.
#
# def envperiod(self, freq, shape):
# return self._convert(freq, self._shapescale(shape))
#
# def tonefreq(self, period):
# return self._convert(period, self.tonescale)
#
# def envfreq(self, period, shape):
# return self._convert(period, self._shapescale(shape))
#
# Path: pym2149/iface.py
# class Platform: pass
#
# Path: pym2149/minblep.py
# def loadorcreate(platform, clockinfo):
#
# Path: pym2149/nod.py
# class Block:
#
# def __init__(self, framecount):
# # If it's a numpy type it can cause overflow in osc module, so ensure arbitrary precision:
# self.framecount = int(framecount)
#
# def __repr__(self):
# return f"{type(self).__name__}({self.framecount!r})"
#
# Path: pym2149/timer.py
# class MinBlockRateTimer(SimpleTimer):
#
# def __init__(self, clock, minblockrate):
# # If division not exact, rate will slightly exceed given minimum:
# self.maxblocksize = int(clock // minblockrate)
# if not self.maxblocksize:
# raise Exception(clock, minblockrate)
# super().__init__(clock)
#
# def blocksforperiod(self, refreshrate):
# wholeperiodblock, = super().blocksforperiod(refreshrate)
# blockticks = wholeperiodblock.framecount
# while blockticks:
# size = min(blockticks, self.maxblocksize)
# b = Block(size)
# blockticks -= size
# yield b
#
# class SimpleTimer(Timer):
#
# def __init__(self, clock):
# self.carryticks = 0
# self.clock = clock
#
# def blocksforperiod(self, refreshrate):
# available = self.carryticks + self.clock
# blockticks = int(round(available / refreshrate))
# self.carryticks = available - blockticks * refreshrate
# yield Block(blockticks)
#
# def __del__(self):
# if self.carryticks:
# log.warning("Non-zero carry on dispose: %s", self.carryticks)
. Output only the next line. | naiven = min(naiveN, self.minbleps.getminnaiven(self.naivex, self.buffersize - self.bufferx)) |
Based on the snippet: <|code_start|>
@types(Platform, MinBleps, ClockInfo)
def __init__(self, platform, minbleps, clockinfo):
self.naiverate = clockinfo.implclock
super().__init__(self.naiverate)
self.buffersize = platform.buffersize
self.naivex = 0
self.bufferx = 0
self.minbleps = minbleps
def blocksforperiod(self, refreshrate):
wholeperiodblock, = super().blocksforperiod(refreshrate)
naiveN = wholeperiodblock.framecount
while naiveN:
naiven = min(naiveN, self.minbleps.getminnaiven(self.naivex, self.buffersize - self.bufferx))
yield Block(naiven)
self.bufferx = (self.bufferx + self.minbleps.getoutcount(self.naivex, naiven)) % self.buffersize
self.naivex = (self.naivex + naiven) % self.naiverate
naiveN -= naiven
class ChipTimer(MinBlockRateTimer):
@types(ClockInfo)
def __init__(self, clockinfo):
super().__init__(clockinfo.implclock, 100)
class SimpleChipTimer(SimpleTimer):
'One block per update.'
@types(ClockInfo)
<|code_end|>
, predict the immediate next line with the help of imports:
from .clock import ClockInfo
from .iface import Platform
from .minblep import MinBleps
from .nod import Block
from .timer import MinBlockRateTimer, SimpleTimer
from diapyr import types
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/clock.py
# class ClockInfo:
#
# trishapes = frozenset([0xa, 0xe])
# tonescale = 16
#
# @classmethod
# def _shapescale(cls, shape):
# # Musically, the triangular shapes have twice the scale:
# return 512 if shape in cls.trishapes else 256
#
# @types(Config, Platform, YMFile)
# def __init__(self, config, platform, ymfile = None):
# self.nomclock = config.nominalclock
# if self.nomclock % config.underclock:
# raise Exception(f"Clock {self.nomclock} not divisible by underclock {config.underclock}.")
# self.implclock = self.nomclock // config.underclock
# if ymfile is not None and self.nomclock != ymfile.nominalclock:
# log.info("Context clock %s overridden to: %s", ymfile.nominalclock, self.nomclock)
# if self.implclock != self.nomclock:
# log.debug("Clock adjusted to %s to take advantage of non-trivial underclock.", self.implclock)
# if config.underclock < 1 or defaultscale % config.underclock:
# raise Exception(f"underclock must be a factor of {defaultscale}.")
# self.scale = defaultscale // config.underclock
# if config.freqclamp:
# # The 0 case just means that 1 is audible:
# self.mintoneperiod = max(1, self._toneperiodclampor0(platform.outputrate))
# log.debug("Minimum tone period: %s", self.mintoneperiod)
# else:
# self.mintoneperiod = 1
#
# def _toneperiodclampor0(self, outrate):
# # Largest period with frequency strictly greater than Nyquist, or 0 if there isn't one:
# return (self.implclock - 1) // (self.scale * outrate)
#
# def _convert(self, freqorperiod, scale):
# return self.nomclock / (scale * freqorperiod)
#
# def toneperiod(self, freq):
# return self._convert(freq, self.tonescale)
#
# def noiseperiod(self, freq):
# return self._convert(freq, 16) # First notch at freq.
#
# def envperiod(self, freq, shape):
# return self._convert(freq, self._shapescale(shape))
#
# def tonefreq(self, period):
# return self._convert(period, self.tonescale)
#
# def envfreq(self, period, shape):
# return self._convert(period, self._shapescale(shape))
#
# Path: pym2149/iface.py
# class Platform: pass
#
# Path: pym2149/minblep.py
# def loadorcreate(platform, clockinfo):
#
# Path: pym2149/nod.py
# class Block:
#
# def __init__(self, framecount):
# # If it's a numpy type it can cause overflow in osc module, so ensure arbitrary precision:
# self.framecount = int(framecount)
#
# def __repr__(self):
# return f"{type(self).__name__}({self.framecount!r})"
#
# Path: pym2149/timer.py
# class MinBlockRateTimer(SimpleTimer):
#
# def __init__(self, clock, minblockrate):
# # If division not exact, rate will slightly exceed given minimum:
# self.maxblocksize = int(clock // minblockrate)
# if not self.maxblocksize:
# raise Exception(clock, minblockrate)
# super().__init__(clock)
#
# def blocksforperiod(self, refreshrate):
# wholeperiodblock, = super().blocksforperiod(refreshrate)
# blockticks = wholeperiodblock.framecount
# while blockticks:
# size = min(blockticks, self.maxblocksize)
# b = Block(size)
# blockticks -= size
# yield b
#
# class SimpleTimer(Timer):
#
# def __init__(self, clock):
# self.carryticks = 0
# self.clock = clock
#
# def blocksforperiod(self, refreshrate):
# available = self.carryticks + self.clock
# blockticks = int(round(available / refreshrate))
# self.carryticks = available - blockticks * refreshrate
# yield Block(blockticks)
#
# def __del__(self):
# if self.carryticks:
# log.warning("Non-zero carry on dispose: %s", self.carryticks)
. Output only the next line. | def __init__(self, clockinfo): |
Here is a snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class SyncTimer(SimpleTimer):
'Fill platform buffer most efficiently.'
@types(Platform, MinBleps, ClockInfo)
def __init__(self, platform, minbleps, clockinfo):
self.naiverate = clockinfo.implclock
super().__init__(self.naiverate)
self.buffersize = platform.buffersize
self.naivex = 0
self.bufferx = 0
<|code_end|>
. Write the next line using the current file imports:
from .clock import ClockInfo
from .iface import Platform
from .minblep import MinBleps
from .nod import Block
from .timer import MinBlockRateTimer, SimpleTimer
from diapyr import types
and context from other files:
# Path: pym2149/clock.py
# class ClockInfo:
#
# trishapes = frozenset([0xa, 0xe])
# tonescale = 16
#
# @classmethod
# def _shapescale(cls, shape):
# # Musically, the triangular shapes have twice the scale:
# return 512 if shape in cls.trishapes else 256
#
# @types(Config, Platform, YMFile)
# def __init__(self, config, platform, ymfile = None):
# self.nomclock = config.nominalclock
# if self.nomclock % config.underclock:
# raise Exception(f"Clock {self.nomclock} not divisible by underclock {config.underclock}.")
# self.implclock = self.nomclock // config.underclock
# if ymfile is not None and self.nomclock != ymfile.nominalclock:
# log.info("Context clock %s overridden to: %s", ymfile.nominalclock, self.nomclock)
# if self.implclock != self.nomclock:
# log.debug("Clock adjusted to %s to take advantage of non-trivial underclock.", self.implclock)
# if config.underclock < 1 or defaultscale % config.underclock:
# raise Exception(f"underclock must be a factor of {defaultscale}.")
# self.scale = defaultscale // config.underclock
# if config.freqclamp:
# # The 0 case just means that 1 is audible:
# self.mintoneperiod = max(1, self._toneperiodclampor0(platform.outputrate))
# log.debug("Minimum tone period: %s", self.mintoneperiod)
# else:
# self.mintoneperiod = 1
#
# def _toneperiodclampor0(self, outrate):
# # Largest period with frequency strictly greater than Nyquist, or 0 if there isn't one:
# return (self.implclock - 1) // (self.scale * outrate)
#
# def _convert(self, freqorperiod, scale):
# return self.nomclock / (scale * freqorperiod)
#
# def toneperiod(self, freq):
# return self._convert(freq, self.tonescale)
#
# def noiseperiod(self, freq):
# return self._convert(freq, 16) # First notch at freq.
#
# def envperiod(self, freq, shape):
# return self._convert(freq, self._shapescale(shape))
#
# def tonefreq(self, period):
# return self._convert(period, self.tonescale)
#
# def envfreq(self, period, shape):
# return self._convert(period, self._shapescale(shape))
#
# Path: pym2149/iface.py
# class Platform: pass
#
# Path: pym2149/minblep.py
# def loadorcreate(platform, clockinfo):
#
# Path: pym2149/nod.py
# class Block:
#
# def __init__(self, framecount):
# # If it's a numpy type it can cause overflow in osc module, so ensure arbitrary precision:
# self.framecount = int(framecount)
#
# def __repr__(self):
# return f"{type(self).__name__}({self.framecount!r})"
#
# Path: pym2149/timer.py
# class MinBlockRateTimer(SimpleTimer):
#
# def __init__(self, clock, minblockrate):
# # If division not exact, rate will slightly exceed given minimum:
# self.maxblocksize = int(clock // minblockrate)
# if not self.maxblocksize:
# raise Exception(clock, minblockrate)
# super().__init__(clock)
#
# def blocksforperiod(self, refreshrate):
# wholeperiodblock, = super().blocksforperiod(refreshrate)
# blockticks = wholeperiodblock.framecount
# while blockticks:
# size = min(blockticks, self.maxblocksize)
# b = Block(size)
# blockticks -= size
# yield b
#
# class SimpleTimer(Timer):
#
# def __init__(self, clock):
# self.carryticks = 0
# self.clock = clock
#
# def blocksforperiod(self, refreshrate):
# available = self.carryticks + self.clock
# blockticks = int(round(available / refreshrate))
# self.carryticks = available - blockticks * refreshrate
# yield Block(blockticks)
#
# def __del__(self):
# if self.carryticks:
# log.warning("Non-zero carry on dispose: %s", self.carryticks)
, which may include functions, classes, or code. Output only the next line. | self.minbleps = minbleps |
Given the following code snippet before the placeholder: <|code_start|># You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class SyncTimer(SimpleTimer):
'Fill platform buffer most efficiently.'
@types(Platform, MinBleps, ClockInfo)
def __init__(self, platform, minbleps, clockinfo):
self.naiverate = clockinfo.implclock
super().__init__(self.naiverate)
self.buffersize = platform.buffersize
self.naivex = 0
self.bufferx = 0
self.minbleps = minbleps
def blocksforperiod(self, refreshrate):
wholeperiodblock, = super().blocksforperiod(refreshrate)
naiveN = wholeperiodblock.framecount
while naiveN:
naiven = min(naiveN, self.minbleps.getminnaiven(self.naivex, self.buffersize - self.bufferx))
yield Block(naiven)
self.bufferx = (self.bufferx + self.minbleps.getoutcount(self.naivex, naiven)) % self.buffersize
self.naivex = (self.naivex + naiven) % self.naiverate
naiveN -= naiven
class ChipTimer(MinBlockRateTimer):
@types(ClockInfo)
def __init__(self, clockinfo):
<|code_end|>
, predict the next line using imports from the current file:
from .clock import ClockInfo
from .iface import Platform
from .minblep import MinBleps
from .nod import Block
from .timer import MinBlockRateTimer, SimpleTimer
from diapyr import types
and context including class names, function names, and sometimes code from other files:
# Path: pym2149/clock.py
# class ClockInfo:
#
# trishapes = frozenset([0xa, 0xe])
# tonescale = 16
#
# @classmethod
# def _shapescale(cls, shape):
# # Musically, the triangular shapes have twice the scale:
# return 512 if shape in cls.trishapes else 256
#
# @types(Config, Platform, YMFile)
# def __init__(self, config, platform, ymfile = None):
# self.nomclock = config.nominalclock
# if self.nomclock % config.underclock:
# raise Exception(f"Clock {self.nomclock} not divisible by underclock {config.underclock}.")
# self.implclock = self.nomclock // config.underclock
# if ymfile is not None and self.nomclock != ymfile.nominalclock:
# log.info("Context clock %s overridden to: %s", ymfile.nominalclock, self.nomclock)
# if self.implclock != self.nomclock:
# log.debug("Clock adjusted to %s to take advantage of non-trivial underclock.", self.implclock)
# if config.underclock < 1 or defaultscale % config.underclock:
# raise Exception(f"underclock must be a factor of {defaultscale}.")
# self.scale = defaultscale // config.underclock
# if config.freqclamp:
# # The 0 case just means that 1 is audible:
# self.mintoneperiod = max(1, self._toneperiodclampor0(platform.outputrate))
# log.debug("Minimum tone period: %s", self.mintoneperiod)
# else:
# self.mintoneperiod = 1
#
# def _toneperiodclampor0(self, outrate):
# # Largest period with frequency strictly greater than Nyquist, or 0 if there isn't one:
# return (self.implclock - 1) // (self.scale * outrate)
#
# def _convert(self, freqorperiod, scale):
# return self.nomclock / (scale * freqorperiod)
#
# def toneperiod(self, freq):
# return self._convert(freq, self.tonescale)
#
# def noiseperiod(self, freq):
# return self._convert(freq, 16) # First notch at freq.
#
# def envperiod(self, freq, shape):
# return self._convert(freq, self._shapescale(shape))
#
# def tonefreq(self, period):
# return self._convert(period, self.tonescale)
#
# def envfreq(self, period, shape):
# return self._convert(period, self._shapescale(shape))
#
# Path: pym2149/iface.py
# class Platform: pass
#
# Path: pym2149/minblep.py
# def loadorcreate(platform, clockinfo):
#
# Path: pym2149/nod.py
# class Block:
#
# def __init__(self, framecount):
# # If it's a numpy type it can cause overflow in osc module, so ensure arbitrary precision:
# self.framecount = int(framecount)
#
# def __repr__(self):
# return f"{type(self).__name__}({self.framecount!r})"
#
# Path: pym2149/timer.py
# class MinBlockRateTimer(SimpleTimer):
#
# def __init__(self, clock, minblockrate):
# # If division not exact, rate will slightly exceed given minimum:
# self.maxblocksize = int(clock // minblockrate)
# if not self.maxblocksize:
# raise Exception(clock, minblockrate)
# super().__init__(clock)
#
# def blocksforperiod(self, refreshrate):
# wholeperiodblock, = super().blocksforperiod(refreshrate)
# blockticks = wholeperiodblock.framecount
# while blockticks:
# size = min(blockticks, self.maxblocksize)
# b = Block(size)
# blockticks -= size
# yield b
#
# class SimpleTimer(Timer):
#
# def __init__(self, clock):
# self.carryticks = 0
# self.clock = clock
#
# def blocksforperiod(self, refreshrate):
# available = self.carryticks + self.clock
# blockticks = int(round(available / refreshrate))
# self.carryticks = available - blockticks * refreshrate
# yield Block(blockticks)
#
# def __del__(self):
# if self.carryticks:
# log.warning("Non-zero carry on dispose: %s", self.carryticks)
. Output only the next line. | super().__init__(clockinfo.implclock, 100) |
Based on the snippet: <|code_start|># pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class SyncTimer(SimpleTimer):
'Fill platform buffer most efficiently.'
@types(Platform, MinBleps, ClockInfo)
def __init__(self, platform, minbleps, clockinfo):
self.naiverate = clockinfo.implclock
super().__init__(self.naiverate)
self.buffersize = platform.buffersize
self.naivex = 0
self.bufferx = 0
self.minbleps = minbleps
def blocksforperiod(self, refreshrate):
wholeperiodblock, = super().blocksforperiod(refreshrate)
naiveN = wholeperiodblock.framecount
while naiveN:
<|code_end|>
, predict the immediate next line with the help of imports:
from .clock import ClockInfo
from .iface import Platform
from .minblep import MinBleps
from .nod import Block
from .timer import MinBlockRateTimer, SimpleTimer
from diapyr import types
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/clock.py
# class ClockInfo:
#
# trishapes = frozenset([0xa, 0xe])
# tonescale = 16
#
# @classmethod
# def _shapescale(cls, shape):
# # Musically, the triangular shapes have twice the scale:
# return 512 if shape in cls.trishapes else 256
#
# @types(Config, Platform, YMFile)
# def __init__(self, config, platform, ymfile = None):
# self.nomclock = config.nominalclock
# if self.nomclock % config.underclock:
# raise Exception(f"Clock {self.nomclock} not divisible by underclock {config.underclock}.")
# self.implclock = self.nomclock // config.underclock
# if ymfile is not None and self.nomclock != ymfile.nominalclock:
# log.info("Context clock %s overridden to: %s", ymfile.nominalclock, self.nomclock)
# if self.implclock != self.nomclock:
# log.debug("Clock adjusted to %s to take advantage of non-trivial underclock.", self.implclock)
# if config.underclock < 1 or defaultscale % config.underclock:
# raise Exception(f"underclock must be a factor of {defaultscale}.")
# self.scale = defaultscale // config.underclock
# if config.freqclamp:
# # The 0 case just means that 1 is audible:
# self.mintoneperiod = max(1, self._toneperiodclampor0(platform.outputrate))
# log.debug("Minimum tone period: %s", self.mintoneperiod)
# else:
# self.mintoneperiod = 1
#
# def _toneperiodclampor0(self, outrate):
# # Largest period with frequency strictly greater than Nyquist, or 0 if there isn't one:
# return (self.implclock - 1) // (self.scale * outrate)
#
# def _convert(self, freqorperiod, scale):
# return self.nomclock / (scale * freqorperiod)
#
# def toneperiod(self, freq):
# return self._convert(freq, self.tonescale)
#
# def noiseperiod(self, freq):
# return self._convert(freq, 16) # First notch at freq.
#
# def envperiod(self, freq, shape):
# return self._convert(freq, self._shapescale(shape))
#
# def tonefreq(self, period):
# return self._convert(period, self.tonescale)
#
# def envfreq(self, period, shape):
# return self._convert(period, self._shapescale(shape))
#
# Path: pym2149/iface.py
# class Platform: pass
#
# Path: pym2149/minblep.py
# def loadorcreate(platform, clockinfo):
#
# Path: pym2149/nod.py
# class Block:
#
# def __init__(self, framecount):
# # If it's a numpy type it can cause overflow in osc module, so ensure arbitrary precision:
# self.framecount = int(framecount)
#
# def __repr__(self):
# return f"{type(self).__name__}({self.framecount!r})"
#
# Path: pym2149/timer.py
# class MinBlockRateTimer(SimpleTimer):
#
# def __init__(self, clock, minblockrate):
# # If division not exact, rate will slightly exceed given minimum:
# self.maxblocksize = int(clock // minblockrate)
# if not self.maxblocksize:
# raise Exception(clock, minblockrate)
# super().__init__(clock)
#
# def blocksforperiod(self, refreshrate):
# wholeperiodblock, = super().blocksforperiod(refreshrate)
# blockticks = wholeperiodblock.framecount
# while blockticks:
# size = min(blockticks, self.maxblocksize)
# b = Block(size)
# blockticks -= size
# yield b
#
# class SimpleTimer(Timer):
#
# def __init__(self, clock):
# self.carryticks = 0
# self.clock = clock
#
# def blocksforperiod(self, refreshrate):
# available = self.carryticks + self.clock
# blockticks = int(round(available / refreshrate))
# self.carryticks = available - blockticks * refreshrate
# yield Block(blockticks)
#
# def __del__(self):
# if self.carryticks:
# log.warning("Non-zero carry on dispose: %s", self.carryticks)
. Output only the next line. | naiven = min(naiveN, self.minbleps.getminnaiven(self.naivex, self.buffersize - self.bufferx)) |
Given the following code snippet before the placeholder: <|code_start|> self.writen(rate)
bytesperframe = self.bytespersample * channels
self.writen(rate * bytesperframe) # Bytes per second.
self.writen(bytesperframe, 2)
self.writen(self.bytespersample * 8, 2) # Bits per sample.
self.f.write(b'data')
self.datasizeoff = 40
self.writedatasize(self.hugefilesize)
self.adjustsizes()
def writeriffsize(self, filesize):
self.writen(filesize - (self.riffsizeoff + 4))
def writedatasize(self, filesize):
self.writen(filesize - (self.datasizeoff + 4))
def writen(self, n, size = 4):
self.f.write(struct.pack(self.formats[size], n))
def block(self, buf):
buf.tofile(self.f)
self.adjustsizes()
def adjustsizes(self):
try:
filesize = self.f.tell()
if not filesize:
return # It's probably /dev/null so give up.
except IOError as e:
if errno.ESPIPE != e.errno:
<|code_end|>
, predict the next line using imports from the current file:
from .buf import BufType
import errno, struct, sys
and context including class names, function names, and sometimes code from other files:
# Path: pym2149/buf.py
# class BufType:
#
# def __init__(self, _, dtype):
# self.dtype = dtype
#
# def __call__(self):
# return MasterBuf(self.dtype)
. Output only the next line. | raise |
Predict the next line for this snippet: <|code_start|> @_turbo(startframe = u4, endframe = u4, thatnp = [T], j = u4)
def partcopyintonp(self, startframe, endframe, thatnp):
self_buf = LOCAL
for j in range(endframe - startframe):
thatnp[j] = self_buf[startframe]
startframe += 1
@_turbo(value = np.int8, i = u4, v = T)
def fill_i1(self, value):
self_buf = py_self_buf = LOCAL
v = value # Cast once.
for i in range(py_self_buf.size):
self_buf[i] = v
@_turbo(value = T, i = u4)
def fill_same(self, value):
self_buf = py_self_buf = LOCAL
for i in range(py_self_buf.size):
self_buf[i] = value
@_turbo(start = u4, end = u4, step = u4, data = [T], j = u4)
def putstrided(self, start, end, step, data):
self_buf = LOCAL
j = 0
while start < end:
self_buf[start] = data[j]
start += step
j += 1
def ceildiv(self, divisor, alreadynegated = False):
<|code_end|>
with the help of current file imports:
from .const import u4
from .shapes import floatdtype, signaldtype
from diapyr.util import enum
from pyrbo import generic, LOCAL, turbo, T
import numpy as np
and context from other files:
# Path: pym2149/const.py
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
, which may contain function names, class names, or code. Output only the next line. | if not alreadynegated: |
Predict the next line for this snippet: <|code_start|>
def subbuf(self, that):
self.buf -= that.buf
def andbuf(self, that):
self.buf &= that.buf
def copybuf(self, that):
self.buf[:] = that.buf
def tofile(self, fileobj):
# TODO LATER: Reinstate tofile when fixed upstream, see https://github.com/numpy/numpy/issues/7380 for details.
fileobj.write(self.buf.tobytes())
def differentiate(self, lastofprev, that):
self.copybuf(that)
self.buf[0] -= lastofprev
self.buf[1:] -= that.buf[:-1]
def tolist(self): # For tests.
return list(self.buf)
class MasterBuf:
def __init__(self, dtype):
self.bufcls = Buf[T, dtype]
self.dtype = dtype
self.setsize(0)
def setsize(self, size):
<|code_end|>
with the help of current file imports:
from .const import u4
from .shapes import floatdtype, signaldtype
from diapyr.util import enum
from pyrbo import generic, LOCAL, turbo, T
import numpy as np
and context from other files:
# Path: pym2149/const.py
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
, which may contain function names, class names, or code. Output only the next line. | self.buf = np.empty(size, self.dtype) |
Given the code snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
@enum(
['float', floatdtype],
['int16', np.int16],
['short', np.short],
['signal', signaldtype],
)
<|code_end|>
, generate the next line using the imports in this file:
from .const import u4
from .shapes import floatdtype, signaldtype
from diapyr.util import enum
from pyrbo import generic, LOCAL, turbo, T
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/const.py
#
# Path: pym2149/shapes.py
# def level5toamp(level):
# def _amptolevel4(amp):
# def level4to5(level4):
# def level4to5(cls, data4, introlen = defaultintrolen):
# def __init__(self, g, introlen = defaultintrolen):
# def wavelength(self):
# def _meansin(x1, x2):
# def _sinsliceamp(i, n, skew):
# def _sinuslevel4(steps, maxlevel4, skew):
# def makesample5shape(data, signed, is4bit):
# class Shape:
. Output only the next line. | class BufType: |
Next line prediction: <|code_start|> self.assertEqual(1.5, m.freq(22.25) / m.freq(15.25))
self.assertEqual(1.5, m.freq(23.25) / m.freq(16.25))
self.assertEqual(1.5, m.freq(24.25) / m.freq(17.25))
self.assertEqual(2 ** 18 / 3 ** 11, m.freq(25.25) / m.freq(18.25)) # Comma.
self.assertEqual(1.5, m.freq(26.25) / m.freq(19.25))
self.assertEqual(1.5, m.freq(27.25) / m.freq(20.25))
self.assertEqual(1.5, m.freq(28.25) / m.freq(21.25))
self.assertEqual(1.5, m.freq(29.25) / m.freq(22.25))
self.assertEqual(1.5, m.freq(30.25) / m.freq(23.25))
def test_pythagoreanclassic(self):
'This is the classic Eb x G# tuning.'
m = Meantone(SimpleNamespace(referencefrequency = 200, referencemidinote = 53, meantoneflats = 2, meantonecomma = 0))
self.assertEqual(2 ** 18 / 3 ** 11, m.freq(63) / m.freq(56))
def test_meantonemajor(self):
m = Meantone(SimpleNamespace(referencefrequency = 440, referencemidinote = 69, meantoneflats = 2, meantonecomma = .25))
self.assertEqual(8, sum(1 for p in range(60, 72) if math.isclose(5 / 4, m.freq(p + 4) / m.freq(p))))
def test_meantoneminor(self):
m = Meantone(SimpleNamespace(referencefrequency = 440, referencemidinote = 69, meantoneflats = 2, meantonecomma = 1 / 3))
self.assertEqual(9, sum(1 for p in range(60, 72) if math.isclose(6 / 5, m.freq(p + 3) / m.freq(p))))
class TestFiveLimit(TestCase):
def test_asymmetric(self):
t = FiveLimit(SimpleNamespace(referencefrequency = 440, referencemidinote = 69))
self.assertAlmostEqual(440, t.freq(69))
self.assertAlmostEqual(440 * 16 / 15, t.freq(70))
self.assertAlmostEqual(440 * 9 / 8, t.freq(71))
<|code_end|>
. Use current file imports:
(from .pitch import FiveLimit, Meantone, Pitch
from types import SimpleNamespace
from unittest import TestCase
import math)
and context including class names, function names, or small code snippets from other files:
# Path: pym2149/pitch.py
# class FiveLimit(Unequal):
# 'Asymmetric variant.'
#
# @types(Config)
# def __init__(self, config):
# reffreq = float(config.referencefrequency)
# refpitch = float(config.referencemidinote)
# freqs = [None] * 12
# for p5 in range(-1, 2):
# for p3 in range(-1, 3): # Skip first column for asymmetric.
# ratio = 3 ** p3 * 5 ** p5
# ratio /= 2 ** math.floor(math.log(ratio, 2))
# index = round(math.log(ratio, 2) * 12)
# freqs[index] = reffreq * ratio
# super().__init__(refpitch, freqs)
#
# class Meantone(Unequal):
# 'Including Pythagorean as a special case when meantonecomma is zero.'
#
# syntonic = 81 / 80
#
# @types(Config)
# def __init__(self, config):
# reffreq = float(config.referencefrequency)
# refpitch = float(config.referencemidinote)
# flats = config.meantoneflats
# fifthratio = 1.5 / self.syntonic ** float(config.meantonecomma)
# freqs = [None] * 12
# for fifth in range(-flats, 12 - flats):
# pitch = fifth * 7
# freqs[pitch % 12] = reffreq * fifthratio ** fifth / 2 ** (pitch // 12)
# super().__init__(refpitch, freqs)
# wolfpitch = Pitch(refpitch + 11 - flats)
# log.debug("The fifth %s to %s is a wolf interval.", wolfpitch, wolfpitch + 7)
#
# class Pitch(float):
#
# names = ('C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B')
#
# def __add__(self, that):
# return type(self)(float.__add__(self, that))
#
# def __sub__(self, that):
# return type(self)(float.__sub__(self, that))
#
# def __str__(self):
# return self.str(10)
#
# def str(self, mincents):
# nearest = int(math.ceil(self - .5))
# octave = nearest // 12
# note = nearest % 12
# cents = int(round((self - nearest) * 100))
# octave -= 1
# notestr = self.names[note]
# if len(notestr) < 2:
# notestr += '.'
# octavestr = str(octave)
# if len(octavestr) < 2:
# octavestr = '.' + octavestr
# if abs(cents) < mincents:
# centsstr = ' ' * 3
# else:
# centsstr = f"{cents:+3d}"
# return notestr + octavestr + centsstr
. Output only the next line. | self.assertAlmostEqual(440 * 6 / 5, t.freq(72)) |
Using the snippet: <|code_start|> def freqpitch(a):
# Pitches:
a(2048, 25.25)
a(3072, 32.25)
a(4608, 39.25)
a(6912, 46.25)
a(10368, 53.25)
a(15552, 60.25)
a(23328, 67.25)
a(34992, 74.25)
a(52488, 81.25)
a(78732, 88.25)
a(118098, 95.25)
a(177147, 102.25)
# Octaves:
a(1024, 13.25)
a(4096, 37.25)
a(88573.5, 90.25)
a(354294, 114.25)
# Extremes:
a(486, .25)
a(746496, 127.25)
# Interpolation:
a(13824 * 2 ** (math.log(14762.25 / 13824, 2) * .75), 59)
a(14762.25 * 2 ** (math.log(15552 / 14762.25, 2) * .75), 60)
freqpitch(lambda freq, pitch: self.assertEqual(freq, m.freq(pitch)))
freqpitch(lambda freq, pitch: self.assertEqual(pitch, m.pitch(freq)))
# Fifths:
self.assertEqual(1.5, m.freq(19.25) / m.freq(12.25))
self.assertEqual(1.5, m.freq(20.25) / m.freq(13.25))
<|code_end|>
, determine the next line of code. You have imports:
from .pitch import FiveLimit, Meantone, Pitch
from types import SimpleNamespace
from unittest import TestCase
import math
and context (class names, function names, or code) available:
# Path: pym2149/pitch.py
# class FiveLimit(Unequal):
# 'Asymmetric variant.'
#
# @types(Config)
# def __init__(self, config):
# reffreq = float(config.referencefrequency)
# refpitch = float(config.referencemidinote)
# freqs = [None] * 12
# for p5 in range(-1, 2):
# for p3 in range(-1, 3): # Skip first column for asymmetric.
# ratio = 3 ** p3 * 5 ** p5
# ratio /= 2 ** math.floor(math.log(ratio, 2))
# index = round(math.log(ratio, 2) * 12)
# freqs[index] = reffreq * ratio
# super().__init__(refpitch, freqs)
#
# class Meantone(Unequal):
# 'Including Pythagorean as a special case when meantonecomma is zero.'
#
# syntonic = 81 / 80
#
# @types(Config)
# def __init__(self, config):
# reffreq = float(config.referencefrequency)
# refpitch = float(config.referencemidinote)
# flats = config.meantoneflats
# fifthratio = 1.5 / self.syntonic ** float(config.meantonecomma)
# freqs = [None] * 12
# for fifth in range(-flats, 12 - flats):
# pitch = fifth * 7
# freqs[pitch % 12] = reffreq * fifthratio ** fifth / 2 ** (pitch // 12)
# super().__init__(refpitch, freqs)
# wolfpitch = Pitch(refpitch + 11 - flats)
# log.debug("The fifth %s to %s is a wolf interval.", wolfpitch, wolfpitch + 7)
#
# class Pitch(float):
#
# names = ('C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B')
#
# def __add__(self, that):
# return type(self)(float.__add__(self, that))
#
# def __sub__(self, that):
# return type(self)(float.__sub__(self, that))
#
# def __str__(self):
# return self.str(10)
#
# def str(self, mincents):
# nearest = int(math.ceil(self - .5))
# octave = nearest // 12
# note = nearest % 12
# cents = int(round((self - nearest) * 100))
# octave -= 1
# notestr = self.names[note]
# if len(notestr) < 2:
# notestr += '.'
# octavestr = str(octave)
# if len(octavestr) < 2:
# octavestr = '.' + octavestr
# if abs(cents) < mincents:
# centsstr = ' ' * 3
# else:
# centsstr = f"{cents:+3d}"
# return notestr + octavestr + centsstr
. Output only the next line. | self.assertEqual(1.5, m.freq(21.25) / m.freq(14.25)) |
Given the code snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class TestMeantone(TestCase):
def test_pythagoreanmodified(self):
m = Meantone(SimpleNamespace(referencefrequency = 15552, referencemidinote = 60.25, meantoneflats = 5, meantonecomma = 0))
def freqpitch(a):
# Pitches:
a(2048, 25.25)
a(3072, 32.25)
a(4608, 39.25)
a(6912, 46.25)
a(10368, 53.25)
<|code_end|>
, generate the next line using the imports in this file:
from .pitch import FiveLimit, Meantone, Pitch
from types import SimpleNamespace
from unittest import TestCase
import math
and context (functions, classes, or occasionally code) from other files:
# Path: pym2149/pitch.py
# class FiveLimit(Unequal):
# 'Asymmetric variant.'
#
# @types(Config)
# def __init__(self, config):
# reffreq = float(config.referencefrequency)
# refpitch = float(config.referencemidinote)
# freqs = [None] * 12
# for p5 in range(-1, 2):
# for p3 in range(-1, 3): # Skip first column for asymmetric.
# ratio = 3 ** p3 * 5 ** p5
# ratio /= 2 ** math.floor(math.log(ratio, 2))
# index = round(math.log(ratio, 2) * 12)
# freqs[index] = reffreq * ratio
# super().__init__(refpitch, freqs)
#
# class Meantone(Unequal):
# 'Including Pythagorean as a special case when meantonecomma is zero.'
#
# syntonic = 81 / 80
#
# @types(Config)
# def __init__(self, config):
# reffreq = float(config.referencefrequency)
# refpitch = float(config.referencemidinote)
# flats = config.meantoneflats
# fifthratio = 1.5 / self.syntonic ** float(config.meantonecomma)
# freqs = [None] * 12
# for fifth in range(-flats, 12 - flats):
# pitch = fifth * 7
# freqs[pitch % 12] = reffreq * fifthratio ** fifth / 2 ** (pitch // 12)
# super().__init__(refpitch, freqs)
# wolfpitch = Pitch(refpitch + 11 - flats)
# log.debug("The fifth %s to %s is a wolf interval.", wolfpitch, wolfpitch + 7)
#
# class Pitch(float):
#
# names = ('C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B')
#
# def __add__(self, that):
# return type(self)(float.__add__(self, that))
#
# def __sub__(self, that):
# return type(self)(float.__sub__(self, that))
#
# def __str__(self):
# return self.str(10)
#
# def str(self, mincents):
# nearest = int(math.ceil(self - .5))
# octave = nearest // 12
# note = nearest % 12
# cents = int(round((self - nearest) * 100))
# octave -= 1
# notestr = self.names[note]
# if len(notestr) < 2:
# notestr += '.'
# octavestr = str(octave)
# if len(octavestr) < 2:
# octavestr = '.' + octavestr
# if abs(cents) < mincents:
# centsstr = ' ' * 3
# else:
# centsstr = f"{cents:+3d}"
# return notestr + octavestr + centsstr
. Output only the next line. | a(15552, 60.25) |
Continue the code snippet: <|code_start|>
log = logging.getLogger(__name__)
stclock = 2000000
spectrum128crystal = 17734470 # Correct according to service manual.
spectrumclock = spectrum128crystal // 10
defaultscale = 8
class ClockInfo:
trishapes = frozenset([0xa, 0xe])
tonescale = 16
@classmethod
def _shapescale(cls, shape):
# Musically, the triangular shapes have twice the scale:
return 512 if shape in cls.trishapes else 256
@types(Config, Platform, YMFile)
def __init__(self, config, platform, ymfile = None):
self.nomclock = config.nominalclock
if self.nomclock % config.underclock:
raise Exception(f"Clock {self.nomclock} not divisible by underclock {config.underclock}.")
self.implclock = self.nomclock // config.underclock
if ymfile is not None and self.nomclock != ymfile.nominalclock:
log.info("Context clock %s overridden to: %s", ymfile.nominalclock, self.nomclock)
if self.implclock != self.nomclock:
log.debug("Clock adjusted to %s to take advantage of non-trivial underclock.", self.implclock)
if config.underclock < 1 or defaultscale % config.underclock:
raise Exception(f"underclock must be a factor of {defaultscale}.")
<|code_end|>
. Use current file imports:
from .iface import Config, Platform, YMFile
from diapyr import types
import logging
and context (classes, functions, or code) from other files:
# Path: pym2149/iface.py
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class YMFile(Prerecorded): pass
. Output only the next line. | self.scale = defaultscale // config.underclock |
Continue the code snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
stclock = 2000000
spectrum128crystal = 17734470 # Correct according to service manual.
spectrumclock = spectrum128crystal // 10
defaultscale = 8
class ClockInfo:
trishapes = frozenset([0xa, 0xe])
tonescale = 16
@classmethod
def _shapescale(cls, shape):
# Musically, the triangular shapes have twice the scale:
return 512 if shape in cls.trishapes else 256
@types(Config, Platform, YMFile)
<|code_end|>
. Use current file imports:
from .iface import Config, Platform, YMFile
from diapyr import types
import logging
and context (classes, functions, or code) from other files:
# Path: pym2149/iface.py
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class YMFile(Prerecorded): pass
. Output only the next line. | def __init__(self, config, platform, ymfile = None): |
Using the snippet: <|code_start|># along with pym2149. If not, see <http://www.gnu.org/licenses/>.
log = logging.getLogger(__name__)
stclock = 2000000
spectrum128crystal = 17734470 # Correct according to service manual.
spectrumclock = spectrum128crystal // 10
defaultscale = 8
class ClockInfo:
trishapes = frozenset([0xa, 0xe])
tonescale = 16
@classmethod
def _shapescale(cls, shape):
# Musically, the triangular shapes have twice the scale:
return 512 if shape in cls.trishapes else 256
@types(Config, Platform, YMFile)
def __init__(self, config, platform, ymfile = None):
self.nomclock = config.nominalclock
if self.nomclock % config.underclock:
raise Exception(f"Clock {self.nomclock} not divisible by underclock {config.underclock}.")
self.implclock = self.nomclock // config.underclock
if ymfile is not None and self.nomclock != ymfile.nominalclock:
log.info("Context clock %s overridden to: %s", ymfile.nominalclock, self.nomclock)
if self.implclock != self.nomclock:
log.debug("Clock adjusted to %s to take advantage of non-trivial underclock.", self.implclock)
if config.underclock < 1 or defaultscale % config.underclock:
<|code_end|>
, determine the next line of code. You have imports:
from .iface import Config, Platform, YMFile
from diapyr import types
import logging
and context (class names, function names, or code) available:
# Path: pym2149/iface.py
# class Config(lurlene.iface.Config): pass
#
# class Platform: pass
#
# class YMFile(Prerecorded): pass
. Output only the next line. | raise Exception(f"underclock must be a factor of {defaultscale}.") |
Based on the snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class MyNode(Node):
def __init__(self):
super().__init__()
self.x = 0
def callimpl(self):
x = self.block.framecount + self.x
self.x += 1
return x
<|code_end|>
, predict the immediate next line with the help of imports:
from .nod import Block, Node
from unittest import TestCase
and context (classes, functions, sometimes code) from other files:
# Path: pym2149/nod.py
# class Block:
#
# def __init__(self, framecount):
# # If it's a numpy type it can cause overflow in osc module, so ensure arbitrary precision:
# self.framecount = int(framecount)
#
# def __repr__(self):
# return f"{type(self).__name__}({self.framecount!r})"
#
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
. Output only the next line. | class TestNode(TestCase): |
Here is a snippet: <|code_start|># Copyright 2014, 2018, 2019, 2020 Andrzej Cichocki
# This file is part of pym2149.
#
# pym2149 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pym2149 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pym2149. If not, see <http://www.gnu.org/licenses/>.
class MyNode(Node):
def __init__(self):
super().__init__()
self.x = 0
def callimpl(self):
x = self.block.framecount + self.x
<|code_end|>
. Write the next line using the current file imports:
from .nod import Block, Node
from unittest import TestCase
and context from other files:
# Path: pym2149/nod.py
# class Block:
#
# def __init__(self, framecount):
# # If it's a numpy type it can cause overflow in osc module, so ensure arbitrary precision:
# self.framecount = int(framecount)
#
# def __repr__(self):
# return f"{type(self).__name__}({self.framecount!r})"
#
# class Node:
#
# def __init__(self):
# self.block = None
#
# def call(self, block): # I think we don't default masked to False to ensure it is propagated.
# return self(block, False)
#
# def __call__(self, block, masked):
# if self.block != block:
# self.block = block
# self.masked = masked
# self.result = self.callimpl()
# elif not masked and self.masked:
# log.warning("This node has already executed masked: %s", self)
# return self.result
#
# def chain(self, node):
# return node(self.block, self.masked)
, which may include functions, classes, or code. Output only the next line. | self.x += 1 |
Given snippet: <|code_start|> assert repr(group) == "ContextGroup(bar, foo)"
assert len(group) == 2
assert set(group) == {'foo', 'bar'}
assert group['bar'] is thing
assert 'foo' in group
del group.foo
assert len(group) == 1
assert set(group) == {'bar'}
del group['bar']
assert len(group) == 0
def test_context_group_initial_arguments():
group = ContextGroup(foo=Thing(), bar=Thing())
assert repr(group) == "ContextGroup(bar, foo)"
assert len(group) == 2
assert set(group) == {'foo', 'bar'}
def test_context_group_default():
inner = ContextGroup()
group = ContextGroup(inner)
thing = group.foo = Thing()
assert inner.foo is thing
assert group.foo is thing
del group.foo
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from web.core.context import Context, ContextGroup
and context:
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# class ContextGroup(Context):
# """A managed group of related context additions.
#
# This proxies most attribute access through to the "default" group member.
#
# Because of the possibility of conflicts, all attributes are accessible through dict-like subscripting.
#
# Register new group members through dict-like subscript assignment as attribute assignment is passed through to the
# default handler if assigned.
# """
#
# default = None
#
# def __init__(self, default=None, **kw):
# if default is not None:
# self.default = default
# default.__name__ = 'default'
#
# for name in kw:
# kw[name].__name__ = name
# self.__dict__[name] = kw[name]
#
# def __repr__(self):
# return "{0.__class__.__name__}({1})".format(self, ', '.join(sorted(self)))
#
# def __len__(self):
# return len(self.__dict__)
#
# def __iter__(self):
# return iter(set(dir(self)) - self._STANDARD_ATTRS)
#
# def __getitem__(self, name):
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# raise KeyError()
#
# def __setitem__(self, name, value):
# self.__dict__[name] = value
#
# def __delitem__(self, name):
# del self.__dict__[name]
#
# def __getattr__(self, name):
# if self.default is None:
# raise AttributeError()
#
# return getattr(self.default, name)
#
# def __setattr__(self, name, value):
# if self.default is not None:
# return setattr(self.default, name, value)
#
# self.__dict__[name] = value
#
# def __delattr__(self, name):
# if self.default is not None:
# return delattr(self.default, name)
#
# self.__dict__[name] = None
# del self.__dict__[name]
which might include code, classes, or functions. Output only the next line. | assert 'foo' not in inner, list(inner) |
Predict the next line for this snippet: <|code_start|>
class Thing(object):
def __init__(self):
self.__name__ = None
def test_basic_context_operations():
sample = Context(foo=1, bar=2, _baz=3)
assert sorted(sample) == ['bar', 'foo']
assert len(sample) == 2
assert sample['foo'] == 1
del sample['bar']
with pytest.raises(KeyError):
sample['bar']
with pytest.raises(KeyError):
del sample['bar']
def test_context_group_basics():
group = ContextGroup()
assert repr(group) == "ContextGroup()"
assert len(group) == 0
assert list(group) == []
thing = group.foo = Thing()
assert repr(group) == "ContextGroup(foo)"
<|code_end|>
with the help of current file imports:
import pytest
from web.core.context import Context, ContextGroup
and context from other files:
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# class ContextGroup(Context):
# """A managed group of related context additions.
#
# This proxies most attribute access through to the "default" group member.
#
# Because of the possibility of conflicts, all attributes are accessible through dict-like subscripting.
#
# Register new group members through dict-like subscript assignment as attribute assignment is passed through to the
# default handler if assigned.
# """
#
# default = None
#
# def __init__(self, default=None, **kw):
# if default is not None:
# self.default = default
# default.__name__ = 'default'
#
# for name in kw:
# kw[name].__name__ = name
# self.__dict__[name] = kw[name]
#
# def __repr__(self):
# return "{0.__class__.__name__}({1})".format(self, ', '.join(sorted(self)))
#
# def __len__(self):
# return len(self.__dict__)
#
# def __iter__(self):
# return iter(set(dir(self)) - self._STANDARD_ATTRS)
#
# def __getitem__(self, name):
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# raise KeyError()
#
# def __setitem__(self, name, value):
# self.__dict__[name] = value
#
# def __delitem__(self, name):
# del self.__dict__[name]
#
# def __getattr__(self, name):
# if self.default is None:
# raise AttributeError()
#
# return getattr(self.default, name)
#
# def __setattr__(self, name, value):
# if self.default is not None:
# return setattr(self.default, name, value)
#
# self.__dict__[name] = value
#
# def __delattr__(self, name):
# if self.default is not None:
# return delattr(self.default, name)
#
# self.__dict__[name] = None
# del self.__dict__[name]
, which may contain function names, class names, or code. Output only the next line. | assert len(group) == 1 |
Using the snippet: <|code_start|>class Sample(object):
ep = static(HERE)
epm = static(HERE, dict(html='mako'))
dev = static('/dev')
far = static(HERE, far=('txt'))
sample = Sample()
def test_base_path_policy():
with pytest.raises(HTTPForbidden):
sample.ep(None, '..', 'foo')
with pytest.raises(HTTPForbidden):
sample.ep(None, '/', 'foo')
def test_non_extant():
with pytest.raises(HTTPNotFound):
sample.ep(None, 'noex')
def test_non_file():
with pytest.raises(HTTPForbidden):
sample.ep(None)
def test_mapping():
template, data = sample.epm(None, 'foo.html')
<|code_end|>
, determine the next line of code. You have imports:
import os.path
import pytest
from webob.exc import HTTPForbidden, HTTPNotFound
from web.core.context import Context
from web.app.static import static
and context (class names, function names, or code) available:
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# Path: web/app/static.py
# def static(base, mapping=None, far=('js', 'css', 'gif', 'jpg', 'jpeg', 'png', 'ttf', 'woff')):
# """Serve files from disk.
#
# This utility endpoint factory is meant primarily for use in development environments; in production environments
# it is better (more efficient, secure, etc.) to serve your static content using a front end load balancer such as
# Nginx.
#
# The first argument, `base`, represents the base path to serve files from. Paths below the attachment point for
# the generated endpoint will combine this base path with the remaining path elements to determine the file to
# serve.
#
# The second argument is an optional dictionary mapping filename extensions to template engines, for cooperation
# with the TemplateExtension. (See: https://github.com/marrow/template) The result of attempting to serve a
# mapped path is a 2-tuple of `("{mapping}:{path}", dict())`. For example, to render all `.html` files as Mako
# templates, you would attach something like the following:
#
# class Root:
# page = static('/path/to/static/pages', dict(html='mako'))
#
# By default the "usual culprits" are served with far-futures cache expiry headers. If you wish to change the
# extensions searched just assign a new `far` iterable. To disable, assign any falsy value.
# """
#
# base = abspath(base)
#
# @staticmethod
# def static_handler(context, *parts, **kw):
# path = normpath(pathjoin(base, *parts))
#
# if __debug__:
# log.debug("Attempting to serve static file.", extra=dict(
# request = id(context),
# base = base,
# path = path
# ))
#
# if not path.startswith(base): # Ensure we only serve files from the allowed path.
# raise HTTPForbidden("Cowardly refusing to violate base path policy." if __debug__ else None)
#
# if not exists(path): # Do the right thing if the file doesn't actually exist.
# raise HTTPNotFound()
#
# if not isfile(path): # Only serve normal files; no UNIX domain sockets, FIFOs, etc., etc.
# raise HTTPForbidden("Cowardly refusing to open a non-file." if __debug__ else None)
#
# if far and path.rpartition('.')[2] in far:
# context.response.cache_expires = 60*60*24*365
#
# if mapping: # Handle the mapping of filename extensions to 2-tuples. 'Cause why not?
# _, _, extension = basename(path).partition('.')
# if extension in mapping:
# return mapping[extension] + ':' + path, dict()
#
# return open(path, 'rb')
#
# return static_handler
. Output only the next line. | assert data == dict() |
Given the code snippet: <|code_start|>
from __future__ import unicode_literals
HERE = os.path.dirname(__file__)
class Sample(object):
ep = static(HERE)
epm = static(HERE, dict(html='mako'))
dev = static('/dev')
far = static(HERE, far=('txt'))
sample = Sample()
def test_base_path_policy():
with pytest.raises(HTTPForbidden):
sample.ep(None, '..', 'foo')
with pytest.raises(HTTPForbidden):
sample.ep(None, '/', 'foo')
def test_non_extant():
with pytest.raises(HTTPNotFound):
sample.ep(None, 'noex')
<|code_end|>
, generate the next line using the imports in this file:
import os.path
import pytest
from webob.exc import HTTPForbidden, HTTPNotFound
from web.core.context import Context
from web.app.static import static
and context (functions, classes, or occasionally code) from other files:
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# Path: web/app/static.py
# def static(base, mapping=None, far=('js', 'css', 'gif', 'jpg', 'jpeg', 'png', 'ttf', 'woff')):
# """Serve files from disk.
#
# This utility endpoint factory is meant primarily for use in development environments; in production environments
# it is better (more efficient, secure, etc.) to serve your static content using a front end load balancer such as
# Nginx.
#
# The first argument, `base`, represents the base path to serve files from. Paths below the attachment point for
# the generated endpoint will combine this base path with the remaining path elements to determine the file to
# serve.
#
# The second argument is an optional dictionary mapping filename extensions to template engines, for cooperation
# with the TemplateExtension. (See: https://github.com/marrow/template) The result of attempting to serve a
# mapped path is a 2-tuple of `("{mapping}:{path}", dict())`. For example, to render all `.html` files as Mako
# templates, you would attach something like the following:
#
# class Root:
# page = static('/path/to/static/pages', dict(html='mako'))
#
# By default the "usual culprits" are served with far-futures cache expiry headers. If you wish to change the
# extensions searched just assign a new `far` iterable. To disable, assign any falsy value.
# """
#
# base = abspath(base)
#
# @staticmethod
# def static_handler(context, *parts, **kw):
# path = normpath(pathjoin(base, *parts))
#
# if __debug__:
# log.debug("Attempting to serve static file.", extra=dict(
# request = id(context),
# base = base,
# path = path
# ))
#
# if not path.startswith(base): # Ensure we only serve files from the allowed path.
# raise HTTPForbidden("Cowardly refusing to violate base path policy." if __debug__ else None)
#
# if not exists(path): # Do the right thing if the file doesn't actually exist.
# raise HTTPNotFound()
#
# if not isfile(path): # Only serve normal files; no UNIX domain sockets, FIFOs, etc., etc.
# raise HTTPForbidden("Cowardly refusing to open a non-file." if __debug__ else None)
#
# if far and path.rpartition('.')[2] in far:
# context.response.cache_expires = 60*60*24*365
#
# if mapping: # Handle the mapping of filename extensions to 2-tuples. 'Cause why not?
# _, _, extension = basename(path).partition('.')
# if extension in mapping:
# return mapping[extension] + ':' + path, dict()
#
# return open(path, 'rb')
#
# return static_handler
. Output only the next line. | def test_non_file(): |
Given snippet: <|code_start|>
ext.mutate(ctx, endpoint, args, kwargs)
assert args == [27, 42]
assert kwargs == {}
def test_annotation_transformation():
ext = AnnotationExtension()
ctx = Context()
result = ext.transform(ctx, endpoint, 1134)
assert result == ('int', 1134)
def test_annotation_failure():
ext = AnnotationExtension()
ctx = Context()
args = []
kwargs = {'a': 'xyzzy'}
with pytest.raises(ValueError):
ext.mutate(ctx, endpoint, args, kwargs)
try:
ext.mutate(ctx, endpoint, args, kwargs)
except ValueError as e:
s = str(e)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from web.core.compat import py3
from web.core.context import Context
from web.ext.annotation import AnnotationExtension
and context:
# Path: web/core/compat.py
#
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
which might include code, classes, or functions. Output only the next line. | assert 'xyzzy' in s |
Given the code snippet: <|code_start|>
def test_annotation_method():
ext = AnnotationExtension()
ctx = Context()
args = []
kwargs = {'a': '27', 'b': '42'}
ext.mutate(ctx, Endpoint().endpoint, args, kwargs)
assert kwargs == {'a': 27, 'b': 42}
def test_annotation_positional():
ext = AnnotationExtension()
ctx = Context()
args = ['27', '42']
kwargs = {}
ext.mutate(ctx, endpoint, args, kwargs)
assert args == [27, 42]
assert kwargs == {}
def test_annotation_transformation():
ext = AnnotationExtension()
ctx = Context()
result = ext.transform(ctx, endpoint, 1134)
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from web.core.compat import py3
from web.core.context import Context
from web.ext.annotation import AnnotationExtension
and context (functions, classes, or occasionally code) from other files:
# Path: web/core/compat.py
#
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
. Output only the next line. | assert result == ('int', 1134) |
Here is a snippet: <|code_start|># encoding: utf-8
def mock_lazy_value(context):
context.ran = True
context.count += 1
return 42
<|code_end|>
. Write the next line using the current file imports:
from web.core.context import Context
from web.core.util import lazy
and context from other files:
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# Path: web/core/util.py
# class lazy(object):
# """Lazily record the result of evaluating a function and cache the result.
#
# This is a non-data descriptor which tells Python to allow the instance __dict__ to override. Intended to be used
# by extensions to add zero-overhead (if un-accessed) values to the context.
# """
#
# def __init__(self, func, name=None, doc=None):
# self.__name__ = name or func.__name__
# self.__module__ = func.__module__
# self.__doc__ = func.__doc__
# self.lock = RLock()
# self.func = func
#
# def __get__(self, instance, type=None):
# if instance is None: # Allow direct access to the non-data descriptor via the class.
# return self
#
# with self.lock: # Try to avoid situations with parallel thread access hammering the function.
# value = instance.__dict__.get(self.__name__, sentinel)
#
# if value is sentinel:
# value = instance.__dict__[self.__name__] = self.func(instance)
#
# return value
, which may include functions, classes, or code. Output only the next line. | def test_lazy_context_value(): |
Based on the snippet: <|code_start|># encoding: utf-8
def mock_lazy_value(context):
context.ran = True
context.count += 1
return 42
def test_lazy_context_value():
Ctx = Context(sample=lazy(mock_lazy_value, 'sample'))._promote('MockContext', False)
ctx = Ctx(count=0, ran=False)
assert isinstance(Ctx.sample, lazy)
<|code_end|>
, predict the immediate next line with the help of imports:
from web.core.context import Context
from web.core.util import lazy
and context (classes, functions, sometimes code) from other files:
# Path: web/core/context.py
# class Context(MutableMapping):
# """An attribute access dictionary, of a kind.
#
# This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
# from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
# the use of descriptor protocol attributes; without promotion the protocol would not be utilized.
# """
#
# # M-Morty! We're, *belch*, gonna have to go in deep, Morty! Elbow deep!
# def _promote(self, name, instantiate=True):
# """Create a new subclass of Context which incorporates instance attributes and new descriptors.
#
# This promotes an instance and its instance attributes up to being a class with class attributes, then
# returns an instance of that class.
# """
#
# metaclass = type(self.__class__)
# contents = self.__dict__.copy()
# cls = metaclass(str(name), (self.__class__, ), contents)
#
# if instantiate:
# return cls()
#
# return cls
#
# def __init__(self, **kw):
# """Construct a new Context instance.
#
# All keyword arguments are applied to the instance as attributes through direct assignment to `__dict__`.
# """
# self.__dict__.update(kw)
# super(Context, self).__init__()
#
# def __len__(self):
# """Get a list of the public data attributes."""
# return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
#
# def __iter__(self):
# """Iterate all valid (public) attributes/keys."""
# return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')
#
# def __getitem__(self, name):
# """Retrieve an attribute through dictionary access."""
# try:
# return getattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# def __setitem__(self, name, value):
# """Assign an attribute through dictionary access."""
# setattr(self, name, value)
#
# def __delitem__(self, name):
# """Delete an attribute through dictionary access."""
# try:
# return delattr(self, name)
# except AttributeError:
# pass
#
# # We do this here to avoid Python 3's nested exception support.
# raise KeyError(name)
#
# Path: web/core/util.py
# class lazy(object):
# """Lazily record the result of evaluating a function and cache the result.
#
# This is a non-data descriptor which tells Python to allow the instance __dict__ to override. Intended to be used
# by extensions to add zero-overhead (if un-accessed) values to the context.
# """
#
# def __init__(self, func, name=None, doc=None):
# self.__name__ = name or func.__name__
# self.__module__ = func.__module__
# self.__doc__ = func.__doc__
# self.lock = RLock()
# self.func = func
#
# def __get__(self, instance, type=None):
# if instance is None: # Allow direct access to the non-data descriptor via the class.
# return self
#
# with self.lock: # Try to avoid situations with parallel thread access hammering the function.
# value = instance.__dict__.get(self.__name__, sentinel)
#
# if value is sentinel:
# value = instance.__dict__[self.__name__] = self.func(instance)
#
# return value
. Output only the next line. | assert 'sample' not in ctx.__dict__ |
Continue the code snippet: <|code_start|>
# -----------------------------------------------------------------------------
class WorkfileEntity(SetBasedWorkfileEntity):
category = "workfile"
# -------------------------------------------------------------------------
@staticmethod
def _name_from_context(session):
ptask = session.ptask
type_lookup = ptask.types
# hardcoding knowledge of the pipeline hierarchy here which is, in
# general, a bad idea. However, it makes things much cleaner/easier to
# read as far as the output products, so we'll go with it for now.
if 'build' in type_lookup and 'stage' in type_lookup:
base_name = type_lookup['build'] + "_" + type_lookup['stage']
elif 'shot' in type_lookup and 'stage' in type_lookup:
base_name = type_lookup['shot'] + "_" + type_lookup['stage']
# fall back to the file name
else:
file_path = session.cmds.file(q=True, sceneName=True)
(base_name, file_ext) = os.path.splitext(
<|code_end|>
. Use current file imports:
import os
import re
from dpa.app.entity import EntityRegistry, EntityError
from dpa.maya.entity.base import SetBasedWorkfileEntity
and context (classes, functions, or code) from other files:
# Path: dpa/app/entity.py
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# class EntityError(Exception):
# pass
#
# Path: dpa/maya/entity/base.py
# class SetBasedWorkfileEntity(SetBasedEntity):
#
# # -------------------------------------------------------------------------
# @classmethod
# def import_product_representation(cls, session, representation, *args,
# **kwargs):
#
# product = representation.product_version.product
#
# if representation.type != "ma":
# raise EntityError(
# "Don't know how to import {cat} of type {typ}".format(
# cat=cls.category, type=representation.type)
# )
#
# repr_path = cls.get_import_file(session, product.name,
# product.category, representation)
#
# name = product.name
# instances = kwargs.get('instances', 1)
# instance_start = kwargs.get('instance_start', 0)
# exportable = kwargs.get('exportable', True)
# group_reference = kwargs.get('group_reference', False)
#
# entities_to_create = []
#
# if instances == 1 and instance_start == 0:
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((name, name, None))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, None))
# else:
# for inst in range(instance_start, instance_start + instances):
# inst_name = name + "_" + str(inst)
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=inst_name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((inst_name, name, inst))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, inst))
#
# entities = []
#
# if exportable:
# for (obj_name, name, inst) in entities_to_create:
# set_name = cls.get_set_name(name, inst)
# session.cmds.sets(obj_name, name=set_name)
#
# entities.append(cls.get(name, session, instance=inst))
#
# return entities
#
# # -------------------------------------------------------------------------
# @classmethod
# def _get_top_level_ref_objs(cls, session, ref_node):
#
# ref_objs = session.cmds.referenceQuery(ref_node, nodes=True)
# top_level_objs = session.cmds.ls(references=True, assemblies=True)
# top_level_ref_objs= []
# for top_level_obj in top_level_objs:
# if top_level_obj in ref_objs:
# top_level_ref_objs.append(top_level_obj)
#
# return top_level_ref_objs
. Output only the next line. | os.path.split(file_path)[-1]) |
Given the code snippet: <|code_start|>
# -----------------------------------------------------------------------------
class WorkfileEntity(SetBasedWorkfileEntity):
category = "workfile"
# -------------------------------------------------------------------------
@staticmethod
def _name_from_context(session):
ptask = session.ptask
type_lookup = ptask.types
# hardcoding knowledge of the pipeline hierarchy here which is, in
# general, a bad idea. However, it makes things much cleaner/easier to
# read as far as the output products, so we'll go with it for now.
if 'build' in type_lookup and 'stage' in type_lookup:
base_name = type_lookup['build'] + "_" + type_lookup['stage']
elif 'shot' in type_lookup and 'stage' in type_lookup:
base_name = type_lookup['shot'] + "_" + type_lookup['stage']
# fall back to the file name
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
from dpa.app.entity import EntityRegistry, EntityError
from dpa.maya.entity.base import SetBasedWorkfileEntity
and context (functions, classes, or occasionally code) from other files:
# Path: dpa/app/entity.py
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# class EntityError(Exception):
# pass
#
# Path: dpa/maya/entity/base.py
# class SetBasedWorkfileEntity(SetBasedEntity):
#
# # -------------------------------------------------------------------------
# @classmethod
# def import_product_representation(cls, session, representation, *args,
# **kwargs):
#
# product = representation.product_version.product
#
# if representation.type != "ma":
# raise EntityError(
# "Don't know how to import {cat} of type {typ}".format(
# cat=cls.category, type=representation.type)
# )
#
# repr_path = cls.get_import_file(session, product.name,
# product.category, representation)
#
# name = product.name
# instances = kwargs.get('instances', 1)
# instance_start = kwargs.get('instance_start', 0)
# exportable = kwargs.get('exportable', True)
# group_reference = kwargs.get('group_reference', False)
#
# entities_to_create = []
#
# if instances == 1 and instance_start == 0:
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((name, name, None))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, None))
# else:
# for inst in range(instance_start, instance_start + instances):
# inst_name = name + "_" + str(inst)
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=inst_name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((inst_name, name, inst))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, inst))
#
# entities = []
#
# if exportable:
# for (obj_name, name, inst) in entities_to_create:
# set_name = cls.get_set_name(name, inst)
# session.cmds.sets(obj_name, name=set_name)
#
# entities.append(cls.get(name, session, instance=inst))
#
# return entities
#
# # -------------------------------------------------------------------------
# @classmethod
# def _get_top_level_ref_objs(cls, session, ref_node):
#
# ref_objs = session.cmds.referenceQuery(ref_node, nodes=True)
# top_level_objs = session.cmds.ls(references=True, assemblies=True)
# top_level_ref_objs= []
# for top_level_obj in top_level_objs:
# if top_level_obj in ref_objs:
# top_level_ref_objs.append(top_level_obj)
#
# return top_level_ref_objs
. Output only the next line. | else: |
Predict the next line after this snippet: <|code_start|>
cls._fbx_import(session, representation, *args, **kwargs)
# -------------------------------------------------------------------------
def export(self, product_desc=None, version_note=None, fbx_export=False,
fbx_options=None, ma_export=False, ma_options=None):
product_reprs = []
if fbx_export:
product_reprs.extend(
self._fbx_export(fbx_options, product_desc, version_note)
)
if ma_export:
product_reprs.extend(
self._ma_export(ma_options, product_desc, version_note)
)
return product_reprs
# -------------------------------------------------------------------------
def _fbx_export(self, options, product_desc, version_note):
self.session.require_plugin('fbxmaya')
file_type = 'fbx'
product_repr = self._create_product(product_desc, version_note,
file_type)
<|code_end|>
using the current file's imports:
import os.path
import re
from dpa.app.entity import EntityRegistry, EntityError
from dpa.maya.entity.base import SetBasedWorkfileEntity
and any relevant context from other files:
# Path: dpa/app/entity.py
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# class EntityError(Exception):
# pass
#
# Path: dpa/maya/entity/base.py
# class SetBasedWorkfileEntity(SetBasedEntity):
#
# # -------------------------------------------------------------------------
# @classmethod
# def import_product_representation(cls, session, representation, *args,
# **kwargs):
#
# product = representation.product_version.product
#
# if representation.type != "ma":
# raise EntityError(
# "Don't know how to import {cat} of type {typ}".format(
# cat=cls.category, type=representation.type)
# )
#
# repr_path = cls.get_import_file(session, product.name,
# product.category, representation)
#
# name = product.name
# instances = kwargs.get('instances', 1)
# instance_start = kwargs.get('instance_start', 0)
# exportable = kwargs.get('exportable', True)
# group_reference = kwargs.get('group_reference', False)
#
# entities_to_create = []
#
# if instances == 1 and instance_start == 0:
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((name, name, None))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, None))
# else:
# for inst in range(instance_start, instance_start + instances):
# inst_name = name + "_" + str(inst)
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=inst_name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((inst_name, name, inst))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, inst))
#
# entities = []
#
# if exportable:
# for (obj_name, name, inst) in entities_to_create:
# set_name = cls.get_set_name(name, inst)
# session.cmds.sets(obj_name, name=set_name)
#
# entities.append(cls.get(name, session, instance=inst))
#
# return entities
#
# # -------------------------------------------------------------------------
# @classmethod
# def _get_top_level_ref_objs(cls, session, ref_node):
#
# ref_objs = session.cmds.referenceQuery(ref_node, nodes=True)
# top_level_objs = session.cmds.ls(references=True, assemblies=True)
# top_level_ref_objs= []
# for top_level_obj in top_level_objs:
# if top_level_obj in ref_objs:
# top_level_ref_objs.append(top_level_obj)
#
# return top_level_ref_objs
. Output only the next line. | product_repr_dir = product_repr.directory |
Based on the snippet: <|code_start|> category = "camera"
# -------------------------------------------------------------------------
@classmethod
def import_product_representation(cls, session, representation, *args,
**kwargs):
if representation.type == 'ma':
super(CameraEntity, cls).import_product_representation(
session, representation, *args, **kwargs)
else:
if representation.type != 'fbx':
raise EntityError(
"Unknown type for {cat} import: {typ}".format(
cls=cls.category, typ=representation.type))
cls._fbx_import(session, representation, *args, **kwargs)
# -------------------------------------------------------------------------
def export(self, product_desc=None, version_note=None, fbx_export=False,
fbx_options=None, ma_export=False, ma_options=None):
product_reprs = []
if fbx_export:
product_reprs.extend(
self._fbx_export(fbx_options, product_desc, version_note)
)
if ma_export:
<|code_end|>
, predict the immediate next line with the help of imports:
import os.path
import re
from dpa.app.entity import EntityRegistry, EntityError
from dpa.maya.entity.base import SetBasedWorkfileEntity
and context (classes, functions, sometimes code) from other files:
# Path: dpa/app/entity.py
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# class EntityError(Exception):
# pass
#
# Path: dpa/maya/entity/base.py
# class SetBasedWorkfileEntity(SetBasedEntity):
#
# # -------------------------------------------------------------------------
# @classmethod
# def import_product_representation(cls, session, representation, *args,
# **kwargs):
#
# product = representation.product_version.product
#
# if representation.type != "ma":
# raise EntityError(
# "Don't know how to import {cat} of type {typ}".format(
# cat=cls.category, type=representation.type)
# )
#
# repr_path = cls.get_import_file(session, product.name,
# product.category, representation)
#
# name = product.name
# instances = kwargs.get('instances', 1)
# instance_start = kwargs.get('instance_start', 0)
# exportable = kwargs.get('exportable', True)
# group_reference = kwargs.get('group_reference', False)
#
# entities_to_create = []
#
# if instances == 1 and instance_start == 0:
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((name, name, None))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, None))
# else:
# for inst in range(instance_start, instance_start + instances):
# inst_name = name + "_" + str(inst)
# session.cmds.file(
# repr_path,
# reference=True,
# groupReference=group_reference,
# groupName=inst_name,
# mergeNamespacesOnClash=True,
# namespace=":"
# )
# if exportable:
# if group_reference:
# entities_to_create.append((inst_name, name, inst))
# else:
# ref_node = session.cmds.file(
# repr_path, referenceNode=True, query=True)
# if not ref_node:
# Logger.get().warning(
# "No reference node found for " + repr_path)
# else:
# entities_to_create.append(
# (cls._get_top_level_ref_objs(session, ref_node),
# name, inst))
#
# entities = []
#
# if exportable:
# for (obj_name, name, inst) in entities_to_create:
# set_name = cls.get_set_name(name, inst)
# session.cmds.sets(obj_name, name=set_name)
#
# entities.append(cls.get(name, session, instance=inst))
#
# return entities
#
# # -------------------------------------------------------------------------
# @classmethod
# def _get_top_level_ref_objs(cls, session, ref_node):
#
# ref_objs = session.cmds.referenceQuery(ref_node, nodes=True)
# top_level_objs = session.cmds.ls(references=True, assemblies=True)
# top_level_ref_objs= []
# for top_level_obj in top_level_objs:
# if top_level_obj in ref_objs:
# top_level_ref_objs.append(top_level_obj)
#
# return top_level_ref_objs
. Output only the next line. | product_reprs.extend( |
Given the following code snippet before the placeholder: <|code_start|> raise SessionError(
"Can not open '{f}'. File does not exist.".format(f=file_path))
self.nuke.scriptOpen(file_path)
# -------------------------------------------------------------------------
def save(self, file_path=None):
self.nuke.scriptSave(file_path)
# -------------------------------------------------------------------------
@property
def nuke(self):
return self._nuke
# -------------------------------------------------------------------------
@property
def in_session(self):
return NUKE_IMPORTED
# -------------------------------------------------------------------------
@property
def main_window(self):
if not NUKE_HAS_UI:
return None
return QtGui.QApplication.activeWindow()
# -------------------------------------------------------------------------
<|code_end|>
, predict the next line using imports from the current file:
import os
import nuke
from PySide import QtCore, QtGui
from dpa.app.session import Session, SessionRegistry, SessionError
and context including class names, function names, and sometimes code from other files:
# Path: dpa/app/session.py
# class Session(object):
#
# __metaclass__ = ABCMeta
#
# app_name = None
#
# # -------------------------------------------------------------------------
# @classmethod
# def current(cls):
# return None
#
# # -------------------------------------------------------------------------
# def __init__(self):
# pass
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def close(self):
# """Close the current file."""
#
# # -------------------------------------------------------------------------
# def list_entities(self, categories=None):
# """List entities in the session."""
#
# entities = []
# entity_classes = EntityRegistry().get_entity_classes(
# self.__class__.app_name)
# for entity_class in entity_classes:
# entities.extend(entity_class.list(self))
#
# if categories:
# filtered = [e for e in entities if e.category in categories]
# else:
# filtered = entities
#
# return filtered
#
# # -------------------------------------------------------------------------
# @classmethod
# def open_file(self, filepath):
# """Open a new session with the supplied file."""
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def save(self, filepath=None):
# """Save the current session. Save to the file path if provided."""
#
# # -------------------------------------------------------------------------
# @abstractproperty
# def in_session(self):
# """Returns True if inside a current app session."""
#
# # -------------------------------------------------------------------------
# def init_module(self, module_path):
#
# _module = None
#
# if self.in_session:
# try:
# _module = importlib.import_module(module_path)
# except ImportError:
# pass # will raise below
#
# if not _module:
# raise SessionError(
# "Failed to initialize session. " + \
# "'{mod}' module could not be imported.".format(mod=module_path)
# )
#
# return _module
#
# # -------------------------------------------------------------------------
# def require_executable(self, executable):
# """Returns the full path for the supplied executable name."""
#
# (path, file_name) = os.path.split(executable)
#
# # path already included
# if path:
# if not os.path.isfile(executable):
# raise SessionError("Unable to locate executable: " + executable)
# elif not os.access(executable, os.X_OK):
# raise SessionError("File is not executable: " + executable)
# else:
# return executable
# else:
# bin_paths = DpaVars.path()
# bin_paths.get()
# for path in bin_paths.list:
# executable_path = os.path.join(path, executable)
# if (os.path.isfile(executable_path) and
# os.access(executable_path, os.X_OK)):
# return executable_path
#
# raise SessionError("Unable to locate executable: " + executable)
#
# # -------------------------------------------------------------------------
# @property
# def app_name(self):
# return self.__class__.app_name
#
# # -------------------------------------------------------------------------
# @property
# def ptask_area(self):
# """Return the current ptask area for this session."""
#
# if not hasattr(self, '_ptask_area'):
# self._ptask_area = PTaskArea.current()
#
# return self._ptask_area
#
# # -------------------------------------------------------------------------
# @property
# def ptask(self):
#
# if not hasattr(self, '_ptask'):
# ptask_area = self.ptask_area
# if not ptask_area.spec:
# self._ptask = None
# else:
# try:
# self._ptask = PTask.get(ptask_area.spec)
# except PTaskError as e:
# raise SessionError("Unable to determine ptask.")
#
# return self._ptask
#
# # -------------------------------------------------------------------------
# @property
# def ptask_version(self):
# """Return the current ptask version for this session."""
#
# if not hasattr(self, '_ptask_version'):
#
# ptask = self.ptask
# if not ptask:
# self._ptask_version = None
# else:
# self._ptask_version = ptask.latest_version
#
# return self._ptask_version
#
# class SessionRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
#
# self._registry = {}
#
# # -------------------------------------------------------------------------
# def current(self):
#
# for registered_cls in self._registry.values():
# if registered_cls.current():
# return registered_cls()
#
# return None
#
# # -------------------------------------------------------------------------
# def register(self, cls):
# self._registry[cls.app_name] = cls
#
# class SessionError(Exception):
# pass
. Output only the next line. | @property |
Predict the next line after this snippet: <|code_start|>
# -----------------------------------------------------------------------------
try:
except ImportError:
NUKE_IMPORTED = False
NUKE_HAS_UI = False
else:
<|code_end|>
using the current file's imports:
import os
import nuke
from PySide import QtCore, QtGui
from dpa.app.session import Session, SessionRegistry, SessionError
and any relevant context from other files:
# Path: dpa/app/session.py
# class Session(object):
#
# __metaclass__ = ABCMeta
#
# app_name = None
#
# # -------------------------------------------------------------------------
# @classmethod
# def current(cls):
# return None
#
# # -------------------------------------------------------------------------
# def __init__(self):
# pass
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def close(self):
# """Close the current file."""
#
# # -------------------------------------------------------------------------
# def list_entities(self, categories=None):
# """List entities in the session."""
#
# entities = []
# entity_classes = EntityRegistry().get_entity_classes(
# self.__class__.app_name)
# for entity_class in entity_classes:
# entities.extend(entity_class.list(self))
#
# if categories:
# filtered = [e for e in entities if e.category in categories]
# else:
# filtered = entities
#
# return filtered
#
# # -------------------------------------------------------------------------
# @classmethod
# def open_file(self, filepath):
# """Open a new session with the supplied file."""
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def save(self, filepath=None):
# """Save the current session. Save to the file path if provided."""
#
# # -------------------------------------------------------------------------
# @abstractproperty
# def in_session(self):
# """Returns True if inside a current app session."""
#
# # -------------------------------------------------------------------------
# def init_module(self, module_path):
#
# _module = None
#
# if self.in_session:
# try:
# _module = importlib.import_module(module_path)
# except ImportError:
# pass # will raise below
#
# if not _module:
# raise SessionError(
# "Failed to initialize session. " + \
# "'{mod}' module could not be imported.".format(mod=module_path)
# )
#
# return _module
#
# # -------------------------------------------------------------------------
# def require_executable(self, executable):
# """Returns the full path for the supplied executable name."""
#
# (path, file_name) = os.path.split(executable)
#
# # path already included
# if path:
# if not os.path.isfile(executable):
# raise SessionError("Unable to locate executable: " + executable)
# elif not os.access(executable, os.X_OK):
# raise SessionError("File is not executable: " + executable)
# else:
# return executable
# else:
# bin_paths = DpaVars.path()
# bin_paths.get()
# for path in bin_paths.list:
# executable_path = os.path.join(path, executable)
# if (os.path.isfile(executable_path) and
# os.access(executable_path, os.X_OK)):
# return executable_path
#
# raise SessionError("Unable to locate executable: " + executable)
#
# # -------------------------------------------------------------------------
# @property
# def app_name(self):
# return self.__class__.app_name
#
# # -------------------------------------------------------------------------
# @property
# def ptask_area(self):
# """Return the current ptask area for this session."""
#
# if not hasattr(self, '_ptask_area'):
# self._ptask_area = PTaskArea.current()
#
# return self._ptask_area
#
# # -------------------------------------------------------------------------
# @property
# def ptask(self):
#
# if not hasattr(self, '_ptask'):
# ptask_area = self.ptask_area
# if not ptask_area.spec:
# self._ptask = None
# else:
# try:
# self._ptask = PTask.get(ptask_area.spec)
# except PTaskError as e:
# raise SessionError("Unable to determine ptask.")
#
# return self._ptask
#
# # -------------------------------------------------------------------------
# @property
# def ptask_version(self):
# """Return the current ptask version for this session."""
#
# if not hasattr(self, '_ptask_version'):
#
# ptask = self.ptask
# if not ptask:
# self._ptask_version = None
# else:
# self._ptask_version = ptask.latest_version
#
# return self._ptask_version
#
# class SessionRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
#
# self._registry = {}
#
# # -------------------------------------------------------------------------
# def current(self):
#
# for registered_cls in self._registry.values():
# if registered_cls.current():
# return registered_cls()
#
# return None
#
# # -------------------------------------------------------------------------
# def register(self, cls):
# self._registry[cls.app_name] = cls
#
# class SessionError(Exception):
# pass
. Output only the next line. | NUKE_IMPORTED = True |
Based on the snippet: <|code_start|>
# -----------------------------------------------------------------------------
try:
except ImportError:
NUKE_IMPORTED = False
NUKE_HAS_UI = False
else:
NUKE_IMPORTED = True
NUKE_HAS_UI = nuke.GUI
# -----------------------------------------------------------------------------
class NukeSession(Session):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import nuke
from PySide import QtCore, QtGui
from dpa.app.session import Session, SessionRegistry, SessionError
and context (classes, functions, sometimes code) from other files:
# Path: dpa/app/session.py
# class Session(object):
#
# __metaclass__ = ABCMeta
#
# app_name = None
#
# # -------------------------------------------------------------------------
# @classmethod
# def current(cls):
# return None
#
# # -------------------------------------------------------------------------
# def __init__(self):
# pass
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def close(self):
# """Close the current file."""
#
# # -------------------------------------------------------------------------
# def list_entities(self, categories=None):
# """List entities in the session."""
#
# entities = []
# entity_classes = EntityRegistry().get_entity_classes(
# self.__class__.app_name)
# for entity_class in entity_classes:
# entities.extend(entity_class.list(self))
#
# if categories:
# filtered = [e for e in entities if e.category in categories]
# else:
# filtered = entities
#
# return filtered
#
# # -------------------------------------------------------------------------
# @classmethod
# def open_file(self, filepath):
# """Open a new session with the supplied file."""
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def save(self, filepath=None):
# """Save the current session. Save to the file path if provided."""
#
# # -------------------------------------------------------------------------
# @abstractproperty
# def in_session(self):
# """Returns True if inside a current app session."""
#
# # -------------------------------------------------------------------------
# def init_module(self, module_path):
#
# _module = None
#
# if self.in_session:
# try:
# _module = importlib.import_module(module_path)
# except ImportError:
# pass # will raise below
#
# if not _module:
# raise SessionError(
# "Failed to initialize session. " + \
# "'{mod}' module could not be imported.".format(mod=module_path)
# )
#
# return _module
#
# # -------------------------------------------------------------------------
# def require_executable(self, executable):
# """Returns the full path for the supplied executable name."""
#
# (path, file_name) = os.path.split(executable)
#
# # path already included
# if path:
# if not os.path.isfile(executable):
# raise SessionError("Unable to locate executable: " + executable)
# elif not os.access(executable, os.X_OK):
# raise SessionError("File is not executable: " + executable)
# else:
# return executable
# else:
# bin_paths = DpaVars.path()
# bin_paths.get()
# for path in bin_paths.list:
# executable_path = os.path.join(path, executable)
# if (os.path.isfile(executable_path) and
# os.access(executable_path, os.X_OK)):
# return executable_path
#
# raise SessionError("Unable to locate executable: " + executable)
#
# # -------------------------------------------------------------------------
# @property
# def app_name(self):
# return self.__class__.app_name
#
# # -------------------------------------------------------------------------
# @property
# def ptask_area(self):
# """Return the current ptask area for this session."""
#
# if not hasattr(self, '_ptask_area'):
# self._ptask_area = PTaskArea.current()
#
# return self._ptask_area
#
# # -------------------------------------------------------------------------
# @property
# def ptask(self):
#
# if not hasattr(self, '_ptask'):
# ptask_area = self.ptask_area
# if not ptask_area.spec:
# self._ptask = None
# else:
# try:
# self._ptask = PTask.get(ptask_area.spec)
# except PTaskError as e:
# raise SessionError("Unable to determine ptask.")
#
# return self._ptask
#
# # -------------------------------------------------------------------------
# @property
# def ptask_version(self):
# """Return the current ptask version for this session."""
#
# if not hasattr(self, '_ptask_version'):
#
# ptask = self.ptask
# if not ptask:
# self._ptask_version = None
# else:
# self._ptask_version = ptask.latest_version
#
# return self._ptask_version
#
# class SessionRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
#
# self._registry = {}
#
# # -------------------------------------------------------------------------
# def current(self):
#
# for registered_cls in self._registry.values():
# if registered_cls.current():
# return registered_cls()
#
# return None
#
# # -------------------------------------------------------------------------
# def register(self, cls):
# self._registry[cls.app_name] = cls
#
# class SessionError(Exception):
# pass
. Output only the next line. | app_name = 'nuke' |
Based on the snippet: <|code_start|>
# -----------------------------------------------------------------------------
class MariShelf(object):
# -------------------------------------------------------------------------
def __init__(self, name, layout=None, widget=None, palette=None):
self._name = name
if not layout:
layout = QtGui.QHBoxLayout()
self._layout = layout
if not widget:
widget = QtGui.QWidget()
widget.setLayout(self.layout)
self._widget = widget
if not palette:
palette = mari.palettes.create(name, widget)
self._palette = palette
self._palette.show()
# -------------------------------------------------------------------------
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
import mari
from dpa.ui.icon.factory import IconFactory
from PySide import QtGui, QtCore
and context (classes, functions, sometimes code) from other files:
# Path: dpa/ui/icon/factory.py
# class IconFactory(object):
#
# ICON_SCHEME = "icon:///"
#
# # -------------------------------------------------------------------------
# @classmethod
# def is_icon_path(cls, path):
# return path.startswith(cls.ICON_SCHEME)
#
# # -------------------------------------------------------------------------
# def disk_path(self, uri):
#
# if not uri:
# return ""
#
# # XXX need to properly parse uri
# rel_path = uri.replace(self.__class__.ICON_SCHEME, "")
#
# image_paths = self.ptask_area.ancestor_paths(
# relative_file=rel_path, include_install=True)
#
# for image_path in image_paths:
# if os.path.exists(image_path):
# return image_path
#
# return rel_path
#
# # -------------------------------------------------------------------------
# @property
# def ptask_area(self):
#
# if not hasattr(self, '_ptask_area'):
# self._ptask_area = PTaskArea.current()
#
# return self._ptask_area
. Output only the next line. | def add_button(self, **kwargs): |
Continue the code snippet: <|code_start|>
# -----------------------------------------------------------------------------
class GeomcacheEntity(SetBasedEntity):
category = "geomcache"
# -------------------------------------------------------------------------
@classmethod
def import_product_representation(cls, session, representation, *args,
**kwargs):
if representation.type == 'fbx':
<|code_end|>
. Use current file imports:
import os.path
import re
from dpa.app.entity import EntityRegistry, EntityError
from dpa.maya.entity.base import SetBasedEntity
and context (classes, functions, or code) from other files:
# Path: dpa/app/entity.py
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# class EntityError(Exception):
# pass
#
# Path: dpa/maya/entity/base.py
# class SetBasedEntity(MayaEntity):
#
# category = None
#
# # -------------------------------------------------------------------------
# @classmethod
# def set_regex(cls):
#
# return re.compile(
# "^export_{cat}_([\w]+)_?(\d+)?$".format(cat=cls.category),
# re.IGNORECASE
# )
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_set_name(cls, name, inst=None):
#
# if inst is not None:
# set_name = "export_{cat}_{name}_{inst}".format(
# cat=cls.category,
# name=name,
# inst=inst,
# )
# else:
# set_name = "export_{cat}_{name}".format(
# cat=cls.category,
# name=name,
# )
#
# return set_name
#
# # -------------------------------------------------------------------------
# @classmethod
# def get(cls, name, session, instance=None):
# """Retrieve an entity instance from the supplied session."""
#
# # make sure the name exists.
# set_names = cls.get_export_sets(session)
#
# fullname = name
# if instance:
# fullname += "_" + str(instance)
#
# matches = [s for s in set_names if s.endswith(fullname)]
#
# if not matches and len(matches) != 1:
# raise EntityError(
# "Could not find unique {cat} {name} instance in session.".\
# format(cat=cls.category, name=fullname)
# )
#
# return cls(name, session, instance)
#
# # -------------------------------------------------------------------------
# @classmethod
# def list(cls, session):
# """Retrieve all entities of this type from the supplied session."""
#
# entities = []
#
# set_names = cls.get_export_sets(session)
#
# for set_name in set_names:
#
# name_parts = cls.set_regex().match(set_name)
# if not name_parts:
# continue
#
# (name, instance) = name_parts.groups()
#
# if not instance:
# instance=None
#
# entities.append(cls(name, session, instance))
#
# return entities
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_export_sets(cls, session):
#
# export_sets = []
# maya_sets = session.cmds.ls(sets=True)
# for maya_set in maya_sets:
# match = cls.set_regex().match(maya_set)
# if match:
# export_sets.append(maya_set)
#
# return export_sets
#
# # -------------------------------------------------------------------------
# def get_export_objects(self):
#
# export_set = self._get_export_set()
# return self.session.cmds.sets(export_set, query=True)
#
# # -----------------------------------------------------------------------------
# def _get_export_set(self):
#
# # make sure the name exists.
# set_names = self.__class__.get_export_sets(self.session)
# matches = [s for s in set_names if s.endswith(self.display_name)]
#
# if not matches and len(matches) != 1:
# raise EntityError("Unable to identify export set for entity!")
#
# return matches[0]
. Output only the next line. | cls._fbx_import(session, representation, *args, **kwargs) |
Given the following code snippet before the placeholder: <|code_start|>
# -----------------------------------------------------------------------------
class GeomcacheEntity(SetBasedEntity):
category = "geomcache"
# -------------------------------------------------------------------------
@classmethod
def import_product_representation(cls, session, representation, *args,
**kwargs):
if representation.type == 'fbx':
cls._fbx_import(session, representation, *args, **kwargs)
elif representation.type == 'abc':
cls._abc_import(session, representation, *args, **kwargs)
<|code_end|>
, predict the next line using imports from the current file:
import os.path
import re
from dpa.app.entity import EntityRegistry, EntityError
from dpa.maya.entity.base import SetBasedEntity
and context including class names, function names, and sometimes code from other files:
# Path: dpa/app/entity.py
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# class EntityError(Exception):
# pass
#
# Path: dpa/maya/entity/base.py
# class SetBasedEntity(MayaEntity):
#
# category = None
#
# # -------------------------------------------------------------------------
# @classmethod
# def set_regex(cls):
#
# return re.compile(
# "^export_{cat}_([\w]+)_?(\d+)?$".format(cat=cls.category),
# re.IGNORECASE
# )
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_set_name(cls, name, inst=None):
#
# if inst is not None:
# set_name = "export_{cat}_{name}_{inst}".format(
# cat=cls.category,
# name=name,
# inst=inst,
# )
# else:
# set_name = "export_{cat}_{name}".format(
# cat=cls.category,
# name=name,
# )
#
# return set_name
#
# # -------------------------------------------------------------------------
# @classmethod
# def get(cls, name, session, instance=None):
# """Retrieve an entity instance from the supplied session."""
#
# # make sure the name exists.
# set_names = cls.get_export_sets(session)
#
# fullname = name
# if instance:
# fullname += "_" + str(instance)
#
# matches = [s for s in set_names if s.endswith(fullname)]
#
# if not matches and len(matches) != 1:
# raise EntityError(
# "Could not find unique {cat} {name} instance in session.".\
# format(cat=cls.category, name=fullname)
# )
#
# return cls(name, session, instance)
#
# # -------------------------------------------------------------------------
# @classmethod
# def list(cls, session):
# """Retrieve all entities of this type from the supplied session."""
#
# entities = []
#
# set_names = cls.get_export_sets(session)
#
# for set_name in set_names:
#
# name_parts = cls.set_regex().match(set_name)
# if not name_parts:
# continue
#
# (name, instance) = name_parts.groups()
#
# if not instance:
# instance=None
#
# entities.append(cls(name, session, instance))
#
# return entities
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_export_sets(cls, session):
#
# export_sets = []
# maya_sets = session.cmds.ls(sets=True)
# for maya_set in maya_sets:
# match = cls.set_regex().match(maya_set)
# if match:
# export_sets.append(maya_set)
#
# return export_sets
#
# # -------------------------------------------------------------------------
# def get_export_objects(self):
#
# export_set = self._get_export_set()
# return self.session.cmds.sets(export_set, query=True)
#
# # -----------------------------------------------------------------------------
# def _get_export_set(self):
#
# # make sure the name exists.
# set_names = self.__class__.get_export_sets(self.session)
# matches = [s for s in set_names if s.endswith(self.display_name)]
#
# if not matches and len(matches) != 1:
# raise EntityError("Unable to identify export set for entity!")
#
# return matches[0]
. Output only the next line. | else: |
Using the snippet: <|code_start|> raise SessionError("Unable to determine current app session.")
if not parent:
parent = self._session.main_window
super(SessionDialog, self).__init__(parent=parent)
# -------------------------------------------------------------------------
@property
def session(self):
return self._session
# -----------------------------------------------------------------------------
class SessionActionDialog(SessionDialog):
# -------------------------------------------------------------------------
def __init__(self, title, options_config, icon_path=None,
action_button_text=None, modal=False):
super(SessionActionDialog, self).__init__()
self.setModal(modal)
self.setWindowTitle(title)
icon_lbl = QtGui.QLabel()
icon_lbl.setPixmap(QtGui.QPixmap(icon_path))
icon_lbl.setAlignment(QtCore.Qt.AlignRight)
title = QtGui.QLabel(title)
title.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
<|code_end|>
, determine the next line of code. You have imports:
from PySide import QtCore, QtGui
from dpa.app.session import Session, SessionRegistry, SessionError
from dpa.ui.action.options import ActionOptionWidget
and context (class names, function names, or code) available:
# Path: dpa/app/session.py
# class Session(object):
#
# __metaclass__ = ABCMeta
#
# app_name = None
#
# # -------------------------------------------------------------------------
# @classmethod
# def current(cls):
# return None
#
# # -------------------------------------------------------------------------
# def __init__(self):
# pass
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def close(self):
# """Close the current file."""
#
# # -------------------------------------------------------------------------
# def list_entities(self, categories=None):
# """List entities in the session."""
#
# entities = []
# entity_classes = EntityRegistry().get_entity_classes(
# self.__class__.app_name)
# for entity_class in entity_classes:
# entities.extend(entity_class.list(self))
#
# if categories:
# filtered = [e for e in entities if e.category in categories]
# else:
# filtered = entities
#
# return filtered
#
# # -------------------------------------------------------------------------
# @classmethod
# def open_file(self, filepath):
# """Open a new session with the supplied file."""
#
# # -------------------------------------------------------------------------
# @abstractmethod
# def save(self, filepath=None):
# """Save the current session. Save to the file path if provided."""
#
# # -------------------------------------------------------------------------
# @abstractproperty
# def in_session(self):
# """Returns True if inside a current app session."""
#
# # -------------------------------------------------------------------------
# def init_module(self, module_path):
#
# _module = None
#
# if self.in_session:
# try:
# _module = importlib.import_module(module_path)
# except ImportError:
# pass # will raise below
#
# if not _module:
# raise SessionError(
# "Failed to initialize session. " + \
# "'{mod}' module could not be imported.".format(mod=module_path)
# )
#
# return _module
#
# # -------------------------------------------------------------------------
# def require_executable(self, executable):
# """Returns the full path for the supplied executable name."""
#
# (path, file_name) = os.path.split(executable)
#
# # path already included
# if path:
# if not os.path.isfile(executable):
# raise SessionError("Unable to locate executable: " + executable)
# elif not os.access(executable, os.X_OK):
# raise SessionError("File is not executable: " + executable)
# else:
# return executable
# else:
# bin_paths = DpaVars.path()
# bin_paths.get()
# for path in bin_paths.list:
# executable_path = os.path.join(path, executable)
# if (os.path.isfile(executable_path) and
# os.access(executable_path, os.X_OK)):
# return executable_path
#
# raise SessionError("Unable to locate executable: " + executable)
#
# # -------------------------------------------------------------------------
# @property
# def app_name(self):
# return self.__class__.app_name
#
# # -------------------------------------------------------------------------
# @property
# def ptask_area(self):
# """Return the current ptask area for this session."""
#
# if not hasattr(self, '_ptask_area'):
# self._ptask_area = PTaskArea.current()
#
# return self._ptask_area
#
# # -------------------------------------------------------------------------
# @property
# def ptask(self):
#
# if not hasattr(self, '_ptask'):
# ptask_area = self.ptask_area
# if not ptask_area.spec:
# self._ptask = None
# else:
# try:
# self._ptask = PTask.get(ptask_area.spec)
# except PTaskError as e:
# raise SessionError("Unable to determine ptask.")
#
# return self._ptask
#
# # -------------------------------------------------------------------------
# @property
# def ptask_version(self):
# """Return the current ptask version for this session."""
#
# if not hasattr(self, '_ptask_version'):
#
# ptask = self.ptask
# if not ptask:
# self._ptask_version = None
# else:
# self._ptask_version = ptask.latest_version
#
# return self._ptask_version
#
# class SessionRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
#
# self._registry = {}
#
# # -------------------------------------------------------------------------
# def current(self):
#
# for registered_cls in self._registry.values():
# if registered_cls.current():
# return registered_cls()
#
# return None
#
# # -------------------------------------------------------------------------
# def register(self, cls):
# self._registry[cls.app_name] = cls
#
# class SessionError(Exception):
# pass
#
# Path: dpa/ui/action/options.py
# class ActionOptionWidget(ActionOptionGroup):
#
# # -------------------------------------------------------------------------
# def __init__(self, config, name='root', parent=None):
#
# super(ActionOptionWidget, self).__init__(name, config)
#
# show_required_label = False
# for widget in self.widgets:
# if widget.required:
# show_required_label = True
# break
#
# if show_required_label:
# required_label = QtGui.QLabel(REQUIRED + ' required options')
# required_label.setAlignment(QtCore.Qt.AlignRight)
# self._main_layout.addWidget(required_label)
. Output only the next line. | font = title.font() |
Next line prediction: <|code_start|> def delete(self):
cmds.deleteUI("|".join([self.layout, self.name]))
self._shelf_error_fix()
# -------------------------------------------------------------------------
@property
def exists(self):
cmds.setParent(self.layout)
return cmds.shelfLayout(self.name, q=True, exists=True)
# -------------------------------------------------------------------------
@property
def icon_factory(self):
if not hasattr(self, '_icon_factory'):
self._icon_factory = IconFactory()
return self._icon_factory
# -------------------------------------------------------------------------
@property
def layout(self):
return self._layout
# -------------------------------------------------------------------------
@property
def name(self):
return self._name
# -------------------------------------------------------------------------
<|code_end|>
. Use current file imports:
(from maya import cmds, mel
from dpa.ui.icon.factory import IconFactory
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: dpa/ui/icon/factory.py
# class IconFactory(object):
#
# ICON_SCHEME = "icon:///"
#
# # -------------------------------------------------------------------------
# @classmethod
# def is_icon_path(cls, path):
# return path.startswith(cls.ICON_SCHEME)
#
# # -------------------------------------------------------------------------
# def disk_path(self, uri):
#
# if not uri:
# return ""
#
# # XXX need to properly parse uri
# rel_path = uri.replace(self.__class__.ICON_SCHEME, "")
#
# image_paths = self.ptask_area.ancestor_paths(
# relative_file=rel_path, include_install=True)
#
# for image_path in image_paths:
# if os.path.exists(image_path):
# return image_path
#
# return rel_path
#
# # -------------------------------------------------------------------------
# @property
# def ptask_area(self):
#
# if not hasattr(self, '_ptask_area'):
# self._ptask_area = PTaskArea.current()
#
# return self._ptask_area
. Output only the next line. | def _shelf_error_fix(self): |
Next line prediction: <|code_start|>
# -----------------------------------------------------------------------------
class MapsEntity(MayaEntity):
category = 'maps'
# -------------------------------------------------------------------------
@classmethod
def import_product_representation(cls, session, representation, *args,
**kwargs):
<|code_end|>
. Use current file imports:
(from dpa.app.entity import EntityError, EntityRegistry
from dpa.maya.entity.base import MayaEntity)
and context including class names, function names, or small code snippets from other files:
# Path: dpa/app/entity.py
# class EntityError(Exception):
# pass
#
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# Path: dpa/maya/entity/base.py
# class MayaEntity(Entity):
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_import_file(cls, session, name, category, representation,
# relative=True):
#
# session_file_path = session.cmds.file(q=True, sceneName=True)
#
# if relative:
# relative_to = os.path.dirname(session_file_path)
# else:
# relative_to = None
#
# return super(MayaEntity, cls).get_import_file(session, name, category,
# representation, relative_to=relative_to)
#
# # -------------------------------------------------------------------------
# @classmethod
# def _abc_import(cls, session, representation, *args, **kwargs):
#
# # XXX
# product = representation.product_version.product
#
# merge_under_selection = kwargs.pop('merge_under_selection', True)
#
# # AbcImport, for some ridiculous reason, treats imports as being
# # relative to the project rather than the actual file that you're
# # working in. This may bite us depending on how alembics are loaded
# # from disk, but just to get something working, don't use a relative
# # path.
# abc_file = cls.get_import_file(session, product.name,
# product.category, representation, relative=False)
#
# if merge_under_selection:
# session.mel.eval('AbcImport -m "import" -connect "/" "{path}"'.\
# format(path=abc_file))
# else:
# session.mel.eval('AbcImport -m "import" "{path}"'.format(
# path=abc_file))
#
# # -------------------------------------------------------------------------
# @classmethod
# def _fbx_import(cls, session, representation, *args, **kwargs):
#
# reference = kwargs.pop('reference', True)
#
# product = representation.product_version.product
# fbx_file = cls.get_import_file(session, product.name,
# product.category, representation)
#
# if reference:
# # -options "v=0;" "/home/arizeak/Desktop/fake.fbx";
# session.cmds.file(fbx_file, reference=True, type="FBX",
# ignoreVersion=True, groupLocator=True,
# mergeNamespacesOnClash=True, namespace=":", options="v=0;")
# else:
# session.mel.eval('FBXImport -f "{path}" -s'.format(path=fbx_file))
. Output only the next line. | shader_name = kwargs.get('shader', False)[0] |
Predict the next line after this snippet: <|code_start|>
# -----------------------------------------------------------------------------
class MapsEntity(MayaEntity):
category = 'maps'
# -------------------------------------------------------------------------
@classmethod
<|code_end|>
using the current file's imports:
from dpa.app.entity import EntityError, EntityRegistry
from dpa.maya.entity.base import MayaEntity
and any relevant context from other files:
# Path: dpa/app/entity.py
# class EntityError(Exception):
# pass
#
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# Path: dpa/maya/entity/base.py
# class MayaEntity(Entity):
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_import_file(cls, session, name, category, representation,
# relative=True):
#
# session_file_path = session.cmds.file(q=True, sceneName=True)
#
# if relative:
# relative_to = os.path.dirname(session_file_path)
# else:
# relative_to = None
#
# return super(MayaEntity, cls).get_import_file(session, name, category,
# representation, relative_to=relative_to)
#
# # -------------------------------------------------------------------------
# @classmethod
# def _abc_import(cls, session, representation, *args, **kwargs):
#
# # XXX
# product = representation.product_version.product
#
# merge_under_selection = kwargs.pop('merge_under_selection', True)
#
# # AbcImport, for some ridiculous reason, treats imports as being
# # relative to the project rather than the actual file that you're
# # working in. This may bite us depending on how alembics are loaded
# # from disk, but just to get something working, don't use a relative
# # path.
# abc_file = cls.get_import_file(session, product.name,
# product.category, representation, relative=False)
#
# if merge_under_selection:
# session.mel.eval('AbcImport -m "import" -connect "/" "{path}"'.\
# format(path=abc_file))
# else:
# session.mel.eval('AbcImport -m "import" "{path}"'.format(
# path=abc_file))
#
# # -------------------------------------------------------------------------
# @classmethod
# def _fbx_import(cls, session, representation, *args, **kwargs):
#
# reference = kwargs.pop('reference', True)
#
# product = representation.product_version.product
# fbx_file = cls.get_import_file(session, product.name,
# product.category, representation)
#
# if reference:
# # -options "v=0;" "/home/arizeak/Desktop/fake.fbx";
# session.cmds.file(fbx_file, reference=True, type="FBX",
# ignoreVersion=True, groupLocator=True,
# mergeNamespacesOnClash=True, namespace=":", options="v=0;")
# else:
# session.mel.eval('FBXImport -f "{path}" -s'.format(path=fbx_file))
. Output only the next line. | def import_product_representation(cls, session, representation, *args, |
Continue the code snippet: <|code_start|>
# -----------------------------------------------------------------------------
class MapsEntity(MayaEntity):
category = 'maps'
# -------------------------------------------------------------------------
@classmethod
def import_product_representation(cls, session, representation, *args,
**kwargs):
shader_name = kwargs.get('shader', False)[0]
if( shader_name == 'PxrSurface' ):
MapsEntity.rendermanImport(session, representation, kwargs)
elif( shader_name == 'aiStandard' ):
MapsEntity.arnoldImport(session, representation, kwargs)
elif( shader_name == 'aiStandardSurface' ):
MapsEntity.arnold5Import(session, representation, kwargs)
elif( shader_name == 'PtexSurface'):
<|code_end|>
. Use current file imports:
from dpa.app.entity import EntityError, EntityRegistry
from dpa.maya.entity.base import MayaEntity
and context (classes, functions, or code) from other files:
# Path: dpa/app/entity.py
# class EntityError(Exception):
# pass
#
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# Path: dpa/maya/entity/base.py
# class MayaEntity(Entity):
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_import_file(cls, session, name, category, representation,
# relative=True):
#
# session_file_path = session.cmds.file(q=True, sceneName=True)
#
# if relative:
# relative_to = os.path.dirname(session_file_path)
# else:
# relative_to = None
#
# return super(MayaEntity, cls).get_import_file(session, name, category,
# representation, relative_to=relative_to)
#
# # -------------------------------------------------------------------------
# @classmethod
# def _abc_import(cls, session, representation, *args, **kwargs):
#
# # XXX
# product = representation.product_version.product
#
# merge_under_selection = kwargs.pop('merge_under_selection', True)
#
# # AbcImport, for some ridiculous reason, treats imports as being
# # relative to the project rather than the actual file that you're
# # working in. This may bite us depending on how alembics are loaded
# # from disk, but just to get something working, don't use a relative
# # path.
# abc_file = cls.get_import_file(session, product.name,
# product.category, representation, relative=False)
#
# if merge_under_selection:
# session.mel.eval('AbcImport -m "import" -connect "/" "{path}"'.\
# format(path=abc_file))
# else:
# session.mel.eval('AbcImport -m "import" "{path}"'.format(
# path=abc_file))
#
# # -------------------------------------------------------------------------
# @classmethod
# def _fbx_import(cls, session, representation, *args, **kwargs):
#
# reference = kwargs.pop('reference', True)
#
# product = representation.product_version.product
# fbx_file = cls.get_import_file(session, product.name,
# product.category, representation)
#
# if reference:
# # -options "v=0;" "/home/arizeak/Desktop/fake.fbx";
# session.cmds.file(fbx_file, reference=True, type="FBX",
# ignoreVersion=True, groupLocator=True,
# mergeNamespacesOnClash=True, namespace=":", options="v=0;")
# else:
# session.mel.eval('FBXImport -f "{path}" -s'.format(path=fbx_file))
. Output only the next line. | MapsEntity.ptexImport(session, representation, kwargs) |
Next line prediction: <|code_start|>
# options:
# export types: obj
# -----------------------------------------------------------------------------
class GeomEntity(SetBasedEntity):
category = "geom"
# -------------------------------------------------------------------------
def export(self, product_desc=None, version_note=None, obj_export=False,
<|code_end|>
. Use current file imports:
(import os.path
import re
from dpa.app.entity import EntityRegistry, EntityError
from dpa.maya.entity.base import SetBasedEntity)
and context including class names, function names, or small code snippets from other files:
# Path: dpa/app/entity.py
# class EntityRegistry(Singleton):
#
# # -------------------------------------------------------------------------
# def init(self):
# self._registry = defaultdict(list)
#
# # -------------------------------------------------------------------------
# def get_entity_classes(self, app_name):
#
# # XXX should be filtered based on current ptask.
# # for example, anim stages may want to expose different entity types
# # than modeling or lighting
#
# return self._registry.get(app_name, [])
#
# # -------------------------------------------------------------------------
# def register(self, app_name, cls):
# self._registry[app_name].append(cls)
#
# class EntityError(Exception):
# pass
#
# Path: dpa/maya/entity/base.py
# class SetBasedEntity(MayaEntity):
#
# category = None
#
# # -------------------------------------------------------------------------
# @classmethod
# def set_regex(cls):
#
# return re.compile(
# "^export_{cat}_([\w]+)_?(\d+)?$".format(cat=cls.category),
# re.IGNORECASE
# )
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_set_name(cls, name, inst=None):
#
# if inst is not None:
# set_name = "export_{cat}_{name}_{inst}".format(
# cat=cls.category,
# name=name,
# inst=inst,
# )
# else:
# set_name = "export_{cat}_{name}".format(
# cat=cls.category,
# name=name,
# )
#
# return set_name
#
# # -------------------------------------------------------------------------
# @classmethod
# def get(cls, name, session, instance=None):
# """Retrieve an entity instance from the supplied session."""
#
# # make sure the name exists.
# set_names = cls.get_export_sets(session)
#
# fullname = name
# if instance:
# fullname += "_" + str(instance)
#
# matches = [s for s in set_names if s.endswith(fullname)]
#
# if not matches and len(matches) != 1:
# raise EntityError(
# "Could not find unique {cat} {name} instance in session.".\
# format(cat=cls.category, name=fullname)
# )
#
# return cls(name, session, instance)
#
# # -------------------------------------------------------------------------
# @classmethod
# def list(cls, session):
# """Retrieve all entities of this type from the supplied session."""
#
# entities = []
#
# set_names = cls.get_export_sets(session)
#
# for set_name in set_names:
#
# name_parts = cls.set_regex().match(set_name)
# if not name_parts:
# continue
#
# (name, instance) = name_parts.groups()
#
# if not instance:
# instance=None
#
# entities.append(cls(name, session, instance))
#
# return entities
#
# # -------------------------------------------------------------------------
# @classmethod
# def get_export_sets(cls, session):
#
# export_sets = []
# maya_sets = session.cmds.ls(sets=True)
# for maya_set in maya_sets:
# match = cls.set_regex().match(maya_set)
# if match:
# export_sets.append(maya_set)
#
# return export_sets
#
# # -------------------------------------------------------------------------
# def get_export_objects(self):
#
# export_set = self._get_export_set()
# return self.session.cmds.sets(export_set, query=True)
#
# # -----------------------------------------------------------------------------
# def _get_export_set(self):
#
# # make sure the name exists.
# set_names = self.__class__.get_export_sets(self.session)
# matches = [s for s in set_names if s.endswith(self.display_name)]
#
# if not matches and len(matches) != 1:
# raise EntityError("Unable to identify export set for entity!")
#
# return matches[0]
. Output only the next line. | obj_options=None): |
Given snippet: <|code_start|> print 'Encrypting...'
enc = c.encrypt(msg, 'user1')
#print enc
print len(enc)
assert enc != msg
assert len(enc) > len(msg)
print 'Decrypting...'
txt = c.decrypt(enc, 'user1')
#print txt
assert txt == msg
print 'OK'
def bench():
msg = """{ "foo": "baaaaaaaaaaaaaaaaaaaaaaaaaaaaaar" }\n"""
msg = msg * 50
c = CMSTool(TestStore())
#c = CMSTool(KeyStore('./keys', './keys'))
print 'msg len', len(msg)
count = 5000
print 'Signing...'
start = time.time()
for i in range(count):
sgn = c.sign(msg, 'user1')
now = time.time()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os.path
import time
import skytools
import time
from hashlib import sha1
from M2Crypto import SMIME, BIO, X509
from cc.json import Struct
from cc.message import CCMessage
from M2Crypto import m2, Err
and context:
# Path: cc/json.py
# class Struct(dbdict):
# """Base class. All structure components must inherit or
# instantiate Struct. Magic happens in metaclass.
# """
# __metaclass__ = _MetaStruct
#
# @classmethod
# def from_json(cls, jsonstr):
# """creates object from json string"""
# return cls(loads(jsonstr))
#
# def dump_json(self):
# """dumps object to json string"""
# return dumps(self)
#
# def getas(self, name, cast = None, default = None):
# """get value by name with optional casting and default"""
# value = self.get(name, default)
# if cast:
# value = cast(value)
# return value
#
# Path: cc/message.py
# class CCMessage(object):
# """CC multipart message.
#
# Format is similar to usual REQ+REP sockets:
#
# - id_hopX
# - id_hop2
# - id_hop1
# - id_req (optional)
# - empty part
# - cc dest
# - cc payload (json)
# - cc signature
# - cc blob data
# """
# __slots__ = ('zmsg', 'rpos', 'parsed', 'signature')
#
# def __init__(self, zmsg):
# assert isinstance(zmsg, list)
# self.zmsg = zmsg
# self.rpos = zmsg.index('')
# self.parsed = None
# self.signature = None
# assert_msg_req (self.get_dest())
#
# def get_route(self):
# """Route parts"""
# return self.zmsg[ : self.rpos]
#
# def get_non_route(self):
# """Payload parts"""
# return self.zmsg[ self.rpos + 1 : ]
#
# def get_dest(self):
# """Return destination part"""
# return self.zmsg[self.rpos + 1]
#
# def get_part1(self):
# """Return body (json) as string"""
# return self.zmsg[self.rpos + 2]
#
# def get_part2(self):
# """Return signature"""
# if self.rpos + 3 >= len(self.zmsg):
# return ''
# return self.zmsg[self.rpos + 3]
#
# def get_part3(self):
# """Return blob"""
# if self.rpos + 4 >= len(self.zmsg):
# return None
# return self.zmsg[self.rpos + 4]
#
# def get_size(self):
# return zmsg_size (self.zmsg)
#
# def __repr__(self):
# x = repr(self.zmsg)
# if len(x) > 300:
# x = x[:300] + '...'
# return 'CCMessage(%s)' % x
#
# def __str__(self):
# x = repr(self.get_non_route())
# if len(x) > 300:
# x = x[:300] + '...'
# return 'CCMessage(%s)' % x
#
# def set_route (self, route):
# """Fill local route with another route."""
# self.zmsg[:self.rpos] = route
# self.rpos = len(route)
#
# def take_route(self, cmsg):
# """Fill local route with route from another message."""
# r = cmsg.get_route()
# self.set_route(r)
#
# def get_payload(self, xtx):
# if self.parsed:
# return self.parsed
# msg, sgn = xtx.parse_cmsg(self)
# if not msg:
# return None
# self.parsed = msg
# self.signature = sgn
# return msg
#
# def get_signature(self, xtx):
# self.get_payload(xtx)
# return self.signature
#
# def send_to (self, sock):
# sock.send_multipart (self.zmsg)
which might include code, classes, or functions. Output only the next line. | if count > 1 and now > start: |
Next line prediction: <|code_start|>
__all__ = ['LogMessage', 'InfofileMessage', 'JobRequestMessage', 'JobConfigReplyMessage', 'TaskRegisterMessage', 'TaskSendMessage']
class BaseMessage(Struct):
# needs default as json.py seems to get inheritance wrong
req = Field(str, '?')
time = Field(float, default = time.time)
hostname = Field(str, default = socket.gethostname())
blob_hash = Field(str, default = '')
class ReplyMessage (BaseMessage):
req = Field(str, "reply")
class ErrorMessage (ReplyMessage):
req = Field(str, "error")
msg = Field(str)
class EchoRequestMessage (BaseMessage):
req = Field(str, "echo.request")
target = Field(str)
<|code_end|>
. Use current file imports:
(import socket
import time
from cc.json import Struct, Field
from cc.message import CCMessage)
and context including class names, function names, or small code snippets from other files:
# Path: cc/json.py
# class Struct(dbdict):
# """Base class. All structure components must inherit or
# instantiate Struct. Magic happens in metaclass.
# """
# __metaclass__ = _MetaStruct
#
# @classmethod
# def from_json(cls, jsonstr):
# """creates object from json string"""
# return cls(loads(jsonstr))
#
# def dump_json(self):
# """dumps object to json string"""
# return dumps(self)
#
# def getas(self, name, cast = None, default = None):
# """get value by name with optional casting and default"""
# value = self.get(name, default)
# if cast:
# value = cast(value)
# return value
#
# class Field(object):
# """Struct field definition"""
#
# def __init__(self, type = None, default = None):
# self.type = type
# self.default = default
#
# def __call__(self, name, value = None):
# _value = value
# _default = self.default
# if _value is None:
# if _default is None:
# raise Exception('Field "%s" not set' % name)
# if callable(_default):
# _default = _default()
# _value = _default
# if self.type is not None and type(_value) != self.type:
# _args = [_value] if _value else []
# _value = self.type(*_args)
# return _value
#
# Path: cc/message.py
# class CCMessage(object):
# """CC multipart message.
#
# Format is similar to usual REQ+REP sockets:
#
# - id_hopX
# - id_hop2
# - id_hop1
# - id_req (optional)
# - empty part
# - cc dest
# - cc payload (json)
# - cc signature
# - cc blob data
# """
# __slots__ = ('zmsg', 'rpos', 'parsed', 'signature')
#
# def __init__(self, zmsg):
# assert isinstance(zmsg, list)
# self.zmsg = zmsg
# self.rpos = zmsg.index('')
# self.parsed = None
# self.signature = None
# assert_msg_req (self.get_dest())
#
# def get_route(self):
# """Route parts"""
# return self.zmsg[ : self.rpos]
#
# def get_non_route(self):
# """Payload parts"""
# return self.zmsg[ self.rpos + 1 : ]
#
# def get_dest(self):
# """Return destination part"""
# return self.zmsg[self.rpos + 1]
#
# def get_part1(self):
# """Return body (json) as string"""
# return self.zmsg[self.rpos + 2]
#
# def get_part2(self):
# """Return signature"""
# if self.rpos + 3 >= len(self.zmsg):
# return ''
# return self.zmsg[self.rpos + 3]
#
# def get_part3(self):
# """Return blob"""
# if self.rpos + 4 >= len(self.zmsg):
# return None
# return self.zmsg[self.rpos + 4]
#
# def get_size(self):
# return zmsg_size (self.zmsg)
#
# def __repr__(self):
# x = repr(self.zmsg)
# if len(x) > 300:
# x = x[:300] + '...'
# return 'CCMessage(%s)' % x
#
# def __str__(self):
# x = repr(self.get_non_route())
# if len(x) > 300:
# x = x[:300] + '...'
# return 'CCMessage(%s)' % x
#
# def set_route (self, route):
# """Fill local route with another route."""
# self.zmsg[:self.rpos] = route
# self.rpos = len(route)
#
# def take_route(self, cmsg):
# """Fill local route with route from another message."""
# r = cmsg.get_route()
# self.set_route(r)
#
# def get_payload(self, xtx):
# if self.parsed:
# return self.parsed
# msg, sgn = xtx.parse_cmsg(self)
# if not msg:
# return None
# self.parsed = msg
# self.signature = sgn
# return msg
#
# def get_signature(self, xtx):
# self.get_payload(xtx)
# return self.signature
#
# def send_to (self, sock):
# sock.send_multipart (self.zmsg)
. Output only the next line. | class EchoResponseMessage (BaseMessage): |
Predict the next line after this snippet: <|code_start|> log_function = Field(str)
class DatabaseMessage (BaseMessage):
req = Field (str, "db")
function = Field (str)
params = Field (str)
class InfofileMessage(BaseMessage):
req = Field(str, "pub.infofile")
mtime = Field(float) # last modification time of file
filename = Field(str)
data = Field(str) # file contents (data fork)
comp = Field(str) # compression method used
mode = Field(str, 'b') # file mode to use for fopen
class LogtailMessage (BaseMessage):
req = Field(str, "pub.logtail")
filename = Field(str)
data = Field(str) # file contents (data fork)
comp = Field(str) # compression method used
mode = Field(str, 'b') # file mode to use for fopen
fpos = Field(int)
op_mode = Field(str) # classic, rotated
st_dev = Field(long) # device number
st_ino = Field(int) # inode number
class JobConfigRequestMessage(BaseMessage):
req = Field(str, "job.config")
job_name = Field(str)
<|code_end|>
using the current file's imports:
import socket
import time
from cc.json import Struct, Field
from cc.message import CCMessage
and any relevant context from other files:
# Path: cc/json.py
# class Struct(dbdict):
# """Base class. All structure components must inherit or
# instantiate Struct. Magic happens in metaclass.
# """
# __metaclass__ = _MetaStruct
#
# @classmethod
# def from_json(cls, jsonstr):
# """creates object from json string"""
# return cls(loads(jsonstr))
#
# def dump_json(self):
# """dumps object to json string"""
# return dumps(self)
#
# def getas(self, name, cast = None, default = None):
# """get value by name with optional casting and default"""
# value = self.get(name, default)
# if cast:
# value = cast(value)
# return value
#
# class Field(object):
# """Struct field definition"""
#
# def __init__(self, type = None, default = None):
# self.type = type
# self.default = default
#
# def __call__(self, name, value = None):
# _value = value
# _default = self.default
# if _value is None:
# if _default is None:
# raise Exception('Field "%s" not set' % name)
# if callable(_default):
# _default = _default()
# _value = _default
# if self.type is not None and type(_value) != self.type:
# _args = [_value] if _value else []
# _value = self.type(*_args)
# return _value
#
# Path: cc/message.py
# class CCMessage(object):
# """CC multipart message.
#
# Format is similar to usual REQ+REP sockets:
#
# - id_hopX
# - id_hop2
# - id_hop1
# - id_req (optional)
# - empty part
# - cc dest
# - cc payload (json)
# - cc signature
# - cc blob data
# """
# __slots__ = ('zmsg', 'rpos', 'parsed', 'signature')
#
# def __init__(self, zmsg):
# assert isinstance(zmsg, list)
# self.zmsg = zmsg
# self.rpos = zmsg.index('')
# self.parsed = None
# self.signature = None
# assert_msg_req (self.get_dest())
#
# def get_route(self):
# """Route parts"""
# return self.zmsg[ : self.rpos]
#
# def get_non_route(self):
# """Payload parts"""
# return self.zmsg[ self.rpos + 1 : ]
#
# def get_dest(self):
# """Return destination part"""
# return self.zmsg[self.rpos + 1]
#
# def get_part1(self):
# """Return body (json) as string"""
# return self.zmsg[self.rpos + 2]
#
# def get_part2(self):
# """Return signature"""
# if self.rpos + 3 >= len(self.zmsg):
# return ''
# return self.zmsg[self.rpos + 3]
#
# def get_part3(self):
# """Return blob"""
# if self.rpos + 4 >= len(self.zmsg):
# return None
# return self.zmsg[self.rpos + 4]
#
# def get_size(self):
# return zmsg_size (self.zmsg)
#
# def __repr__(self):
# x = repr(self.zmsg)
# if len(x) > 300:
# x = x[:300] + '...'
# return 'CCMessage(%s)' % x
#
# def __str__(self):
# x = repr(self.get_non_route())
# if len(x) > 300:
# x = x[:300] + '...'
# return 'CCMessage(%s)' % x
#
# def set_route (self, route):
# """Fill local route with another route."""
# self.zmsg[:self.rpos] = route
# self.rpos = len(route)
#
# def take_route(self, cmsg):
# """Fill local route with route from another message."""
# r = cmsg.get_route()
# self.set_route(r)
#
# def get_payload(self, xtx):
# if self.parsed:
# return self.parsed
# msg, sgn = xtx.parse_cmsg(self)
# if not msg:
# return None
# self.parsed = msg
# self.signature = sgn
# return msg
#
# def get_signature(self, xtx):
# self.get_payload(xtx)
# return self.signature
#
# def send_to (self, sock):
# sock.send_multipart (self.zmsg)
. Output only the next line. | class JobConfigReplyMessage(BaseMessage): |
Using the snippet: <|code_start|># coding: utf8
# in all modules that use pubsub
class WxStripWindow(wx.Frame):
def __init__(self, parent, title,weh):
super(WxStripWindow, self).__init__(parent, title=title,
size=(500, 500))
self.weh = weh
self.panel = wx.Panel(self, wx.ID_ANY)
self.panel.Bind(wx.EVT_KEY_DOWN, self.onKeyPress)
<|code_end|>
, determine the next line of code. You have imports:
import threading
import os
import sys
import wx
from wordclock_interfaces import event_handler as weh
from wordclock_tools.wordclock_colors import Color
from wx.lib.pubsub import pub as Publisher
and context (class names, function names, or code) available:
# Path: wordclock_interfaces/event_handler.py
# class event_handler:
# EVENT_INVALID = -1
#
# EVENT_BUTTON_LEFT = 0
# EVENT_BUTTON_RIGHT = 1
# EVENT_BUTTON_RETURN = 2
# EVENT_EXIT_PLUGIN = 3
# EVENT_NEXT_PLUGIN_REQUESTED = 4
#
# BUTTONS = {'left': EVENT_BUTTON_LEFT, 'right': EVENT_BUTTON_RIGHT, 'return': EVENT_BUTTON_RETURN}
#
# def __init__(self):
# self.condition = threading.Condition()
# self.event = self.EVENT_INVALID
# self.lock_time = 0.1
# self.nextAction = next_action.RUN_DEFAULT_PLUGIN
#
# def getNextAction(self, evt):
# if evt == self.EVENT_NEXT_PLUGIN_REQUESTED:
# self.nextAction = next_action.NEXT_PLUGIN
# elif evt == self.EVENT_BUTTON_RETURN:
# self.nextAction = next_action.GOTO_MENU
# else:
# self.nextAction = next_action.RUN_DEFAULT_PLUGIN
#
# def waitForEvent(self, seconds=None):
# self.condition.acquire()
# self.__wait_for(lambda: self.event != self.EVENT_INVALID, seconds)
# evt = self.event
# self.getNextAction(evt)
# self.event = self.EVENT_INVALID
# self.condition.release()
# return evt
#
# def setEvent(self, evt):
# self.condition.acquire()
# if self.event != self.EVENT_EXIT_PLUGIN and self.event != self.EVENT_NEXT_PLUGIN_REQUESTED:
# self.event = evt
# self.condition.notifyAll()
# self.condition.release()
#
# def waitForExit(self, seconds=None):
# self.condition.acquire()
# exitWasTriggered = self.__wait_for(
# lambda: self.event == self.EVENT_EXIT_PLUGIN or self.event == self.EVENT_NEXT_PLUGIN_REQUESTED, seconds)
# self.getNextAction(self.event)
# self.event = self.EVENT_INVALID
# self.condition.release()
# return True if exitWasTriggered else False
#
# def __wait_for(self, predicate, timeout=None):
# """
# Wait until a condition evaluates to True.
#
# predicate should be a callable which result will be interpreted as a
# boolean value. A timeout may be provided giving the maximum time to
# wait.
#
# """
# endtime = None
# waittime = timeout
# result = predicate()
# while not result:
# if waittime is not None:
# if endtime is None:
# endtime = _time() + waittime
# else:
# waittime = endtime - _time()
# if waittime <= 0:
# break
# self.condition.wait(waittime)
# result = predicate()
# return result
#
# Path: wordclock_tools/wordclock_colors.py
# class Color:
#
# def __init__(self, r, g, b):
# self.r = r
# self.g = g
# self.b = b
#
# def __sub__(self, other):
# if not isinstance(other, int):
# raise TypeError
#
# self.r = max(self.r - other, 0)
# self.g = max(self.g - other, 0)
# self.b = max(self.b - other, 0)
#
# return self
#
# def brightness(self):
# return int((self.r + self.g + self.b)/3)
. Output only the next line. | self.SetBackgroundColour('#000000') |
Continue the code snippet: <|code_start|> if file_path.match(no_flags_pattern):
log.debug(f"removing flags from {file_path} because it matches pattern {no_flags_pattern}")
break
else:
retVal = False
return retVal
def remove_extraneous_files(self, dst: Path, src_item_names):
""" remove files in destination that are not in source.
files in the ignore list are not removed even if they do not
appear in the source.
"""
for dst_item in os.scandir(dst):
if dst_item.name not in src_item_names and not self.should_ignore_file(dst_item.path):
self.last_step, self.last_src, self.last_dst = "remove redundant file", "", os.fspath(dst_item)
log.info(f"delete {dst_item.path}")
if not self.dry_run:
with RmFileOrDir(dst_item, report_own_progress=False, resolve_path=not dst_item.is_symlink()) as rfod:
rfod()
def copy_symlink(self, src_path: Path, dst_path: Path):
self.last_src, self.last_dst = os.fspath(src_path), os.fspath(dst_path)
self.doing = f"""copy symlink '{self.last_src}' to '{self.last_dst}'"""
link_to = os.readlink(src_path)
if self.symlinks_as_symlinks:
self.dry_run or os.symlink(link_to, dst_path)
self.dry_run or shutil.copystat(src_path, dst_path, follow_symlinks=False)
log.debug(f"create symlink '{dst_path}'")
<|code_end|>
. Use current file imports:
import os
import shutil
import utils
from collections import defaultdict
from pathlib import Path
from typing import List
from .fileSystemBatchCommands import *
from .removeBatchCommands import RmFileOrDir
and context (classes, functions, or code) from other files:
# Path: pybatch/removeBatchCommands.py
# class RmFileOrDir(PythonBatchCommandBase):
# """ remove a file or directory.
# - it's OK if the path does not exist.
# - all files and directory under path will be removed recursively
# """
# def __init__(self, path: os.PathLike, **kwargs):
# super().__init__(**kwargs)
# self.path: os.PathLike = path
# self.exceptions_to_ignore.append(FileNotFoundError)
#
# def repr_own_args(self, all_args: List[str]) -> None:
# all_args.append(self.unnamed__init__param(self.path))
#
# def progress_msg_self(self):
# return f"""Remove '{self.path}'"""
#
# def __call__(self, *args, **kwargs):
# resolved_path = None
# retry = kwargs.get("retry", True)
# try:
# PythonBatchCommandBase.__call__(self, *args, **kwargs)
# resolved_path = utils.ExpandAndResolvePath(self.path)
# if resolved_path.is_symlink() or resolved_path.is_file():
# self.doing = f"""removing file'{resolved_path}'"""
# resolved_path.unlink()
# elif resolved_path.is_dir():
# self.doing = f"""removing folder'{resolved_path}'"""
# shutil.rmtree(resolved_path, onerror=self.who_locks_file_error_dict)
# except Exception as ex:
# if retry and resolved_path is not None:
# kwargs["retry"] = False
# log.info(f"Fixing permission for removing {resolved_path}")
# from pybatch import FixAllPermissions
# with FixAllPermissions(resolved_path, recursive=True, report_own_progress=False) as allower:
# allower()
# self.__call__(*args, **kwargs)
# else:
# raise
. Output only the next line. | else: |
Using the snippet: <|code_start|>
def find_file_log_handler(log_file_path):
retVal = None
top_logger = logging.getLogger()
for handler in top_logger.handlers:
if hasattr(handler, 'stream'):
if handler.stream.name == os.fspath(log_file_path):
retVal = handler
break
return retVal
def get_hdlrs(hdlr_cls=logging.FileHandler, hdlr_name=None):
'''Returning a list of all logger handlers, based on the requested handler class type.
The default type is FileHandlerPlus. hdlr_name is an optional argument to be able to fetch specific handler'''
root_logger = logging.getLogger()
return [hdlr for hdlr in root_logger.handlers if isinstance(hdlr, hdlr_cls) and (not hdlr_name or hdlr_name == hdlr.baseFilename)]
def teardown_file_logging(log_file_path):
return
top_logger = logging.getLogger()
fileLogHandler = find_file_log_handler(log_file_path)
if fileLogHandler:
top_logger.setLevel(fileLogHandler.previous_level)
fileLogHandler.close()
top_logger.removeHandler(fileLogHandler)
del fileLogHandler
global debug_logging_started
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import sys
import json
import inspect
import multiprocessing
import threading
import traceback
import queue
import logging
import logging.handlers
from pathlib import Path
from utils import misc_utils as utils
and context (class names, function names, or code) available:
# Path: utils/misc_utils.py
# def Is64Windows():
# def Is64Mac():
# def Is32Windows():
# def GetProgramFiles32():
# def GetProgramFiles64():
# def get_current_os_names() -> Tuple[str, ...]:
# def __init__(self) -> None:
# def write(self, text: Any):
# def list(self) -> List:
# def __init__(self, initial_list=()) -> None:
# def __setitem__(self, index, item):
# def __delitem__(self, index):
# def __contains__(self, item):
# def append(self, item):
# def extend(self, items=()):
# def insert(self, index, item):
# def remove(self, item):
# def pop(self, index=-1):
# def count(self, item):
# def sort(self, key=None, reverse=False):
# def empty(self):
# def clear(self):
# def __init__(self, initial_list=()) -> None:
# def print_var(var_name):
# def deprecated(deprecated_func):
# def raise_deprecation(*unused_args, **unused_kwargs):
# def max_widths(list_of_lists, string_align='<', numbers_align='>'):
# def gen_col_format(width_list, align_list=None, sep=' '):
# def format_by_width(list_of_lists, string_align='<', numbers_align='>'):
# def ContinuationIter(the_iter, continuation_value=None):
# def ParallelContinuationIter(*iterables):
# def get_buffer_checksum(buff):
# def compare_checksums(_1st_checksum, _2nd_checksum):
# def check_buffer_checksum(buff, expected_checksum):
# def check_file_checksum(file_path, expected_checksum):
# def get_file_checksum(file_path, follow_symlinks=True):
# def compare_files_by_checksum(_1st_file_path, _2nd_file_path, follow_symlinks=False):
# def need_to_download_file(file_path, file_checksum):
# def separate_guids_from_iids(items_list):
# def make_one_list(*things):
# def P4GetPathFromDepotPath(depot_path):
# def replace_all_from_dict(in_text, *in_replace_only_these, **in_replacement_dic):
# def find_sequences(in_sorted_list, is_next_func=lambda a, b: int(a) + 1 == int(b), return_string=True):
# def timing(f):
# def wrap(*args, **kwargs):
# def time_it(message):
# def compile_regex_list_ORed(regex_list, verbose=False):
# def unix_permissions_to_str(the_mod):
# def __init__(self, current_dict, past_dict) -> None:
# def added(self):
# def removed(self):
# def changed(self):
# def unchanged(self):
# def find_mount_point(path):
# def __init__(self, name, print_results=True) -> None:
# def __enter__(self):
# def __exit__(self, *_):
# def child(self, name):
# def start(self):
# def stop(self):
# def print_results(self):
# def _format_results(self, indent=' '):
# def _get_time(self):
# def is_wtar_file(in_possible_wtar) -> bool:
# def is_first_wtar_file(in_possible_wtar):
# def original_name_from_wtar_name(wtar_name):
# def original_names_from_wtars_names(original_list):
# def get_recursive_checksums(some_path, ignore=None):
# def obj_memory_size(obj, seen=None):
# def get_wtar_total_checksum(wtar_file_path):
# def extra_json_serializer(obj):
# def default(self, obj):
# def get_system_log_folder_path():
# def get_system_log_file_path():
# def iter_complete_to_longest(*list_of_lists):
# def clock(func):
# def clocked(*args, **kwargs):
# def partition_list(in_list, partition_condition):
# def iter_grouper(n, iterable):
# def get_os_description():
# def add_to_actions_stack(action: str):
# def get_latest_action_from_stack():
# def get_curl_err_msg(key: int) -> str:
# class write_to_list(object):
# class unique_list(list):
# class set_with_order(unique_list):
# class DictDiffer(object):
# class Timer_CM(object):
# class JsonExtraTypesDecoder(json.JSONDecoder):
. Output only the next line. | debug_logging_started = False |
Next line prediction: <|code_start|>
blueprint = Blueprint("statistics", __name__, url_prefix="/statistics", static_folder="../static")
@blueprint.route("/")
@cache.cached(timeout=3600, key_prefix="statistics")
<|code_end|>
. Use current file imports:
(from flask import Blueprint, render_template
from solarpi.extensions import db, cache)
and context including class names, function names, or small code snippets from other files:
# Path: solarpi/extensions.py
. Output only the next line. | def statistics(): |
Predict the next line for this snippet: <|code_start|>
blueprint = Blueprint("statistics", __name__, url_prefix="/statistics", static_folder="../static")
@blueprint.route("/")
@cache.cached(timeout=3600, key_prefix="statistics")
def statistics():
"""Renders a page with statistics for the last 12 months
:return: a page with statistics for the last 12 months
"""
data = list(
db.engine.execute(
"""SELECT
Strftime('%Y-%m', created_at) AS month,
Min(daily_yield) AS min_yield,
Max(daily_yield) AS max_yield,
Avg(daily_yield) AS avg_yield
FROM (
SELECT
Strftime('%Y-%m-%d', created_at) AS created_at,
Max(total_energy) - Min(total_energy) AS daily_yield
FROM pvdata
GROUP BY Strftime('%Y-%m-%d', created_at))
GROUP BY Strftime('%Y-%m', created_at) ORDER BY month DESC LIMIT 12 """
)
<|code_end|>
with the help of current file imports:
from flask import Blueprint, render_template
from solarpi.extensions import db, cache
and context from other files:
# Path: solarpi/extensions.py
, which may contain function names, class names, or code. Output only the next line. | ) |
Here is a snippet: <|code_start|>
class Weather(SurrogatePK, Model):
__tablename__ = "weather_data"
id = Column(db.Integer(), nullable=False, primary_key=True)
created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow)
temp = Column(db.Float(), nullable=True)
pressure = Column(db.Integer(), nullable=True)
temp_min = Column(db.Float(), nullable=True)
temp_max = Column(db.Float(), nullable=True)
humidity = Column(db.Integer(), nullable=True)
wind_speed = Column(db.Float(), nullable=True)
wind_gust = Column(db.Float(), nullable=True)
wind_deg = Column(db.Integer(), nullable=True)
clouds = Column(db.Integer(), nullable=True)
rain = Column(db.Integer(), nullable=True)
snow = Column(db.Integer(), nullable=True)
weather_id = Column(db.Integer(), nullable=True)
<|code_end|>
. Write the next line using the current file imports:
import datetime as dt
from solarpi.database import (
Column,
db,
Model,
SurrogatePK,
)
and context from other files:
# Path: solarpi/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
# def create(cls, **kwargs):
# def update(self, commit=True, **kwargs):
# def save(self, commit=True):
# def delete(self, commit=True):
# def get_by_id(cls, _id):
# def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs):
, which may include functions, classes, or code. Output only the next line. | def __init__(self): |
Based on the snippet: <|code_start|>
class Weather(SurrogatePK, Model):
__tablename__ = "weather_data"
id = Column(db.Integer(), nullable=False, primary_key=True)
created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow)
temp = Column(db.Float(), nullable=True)
pressure = Column(db.Integer(), nullable=True)
temp_min = Column(db.Float(), nullable=True)
temp_max = Column(db.Float(), nullable=True)
humidity = Column(db.Integer(), nullable=True)
wind_speed = Column(db.Float(), nullable=True)
wind_gust = Column(db.Float(), nullable=True)
wind_deg = Column(db.Integer(), nullable=True)
clouds = Column(db.Integer(), nullable=True)
rain = Column(db.Integer(), nullable=True)
snow = Column(db.Integer(), nullable=True)
weather_id = Column(db.Integer(), nullable=True)
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime as dt
from solarpi.database import (
Column,
db,
Model,
SurrogatePK,
)
and context (classes, functions, sometimes code) from other files:
# Path: solarpi/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
# def create(cls, **kwargs):
# def update(self, commit=True, **kwargs):
# def save(self, commit=True):
# def delete(self, commit=True):
# def get_by_id(cls, _id):
# def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs):
. Output only the next line. | def __init__(self): |
Predict the next line for this snippet: <|code_start|>
class Weather(SurrogatePK, Model):
__tablename__ = "weather_data"
id = Column(db.Integer(), nullable=False, primary_key=True)
created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow)
temp = Column(db.Float(), nullable=True)
pressure = Column(db.Integer(), nullable=True)
temp_min = Column(db.Float(), nullable=True)
temp_max = Column(db.Float(), nullable=True)
humidity = Column(db.Integer(), nullable=True)
wind_speed = Column(db.Float(), nullable=True)
wind_gust = Column(db.Float(), nullable=True)
wind_deg = Column(db.Integer(), nullable=True)
clouds = Column(db.Integer(), nullable=True)
rain = Column(db.Integer(), nullable=True)
snow = Column(db.Integer(), nullable=True)
weather_id = Column(db.Integer(), nullable=True)
<|code_end|>
with the help of current file imports:
import datetime as dt
from solarpi.database import (
Column,
db,
Model,
SurrogatePK,
)
and context from other files:
# Path: solarpi/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
# def create(cls, **kwargs):
# def update(self, commit=True, **kwargs):
# def save(self, commit=True):
# def delete(self, commit=True):
# def get_by_id(cls, _id):
# def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs):
, which may contain function names, class names, or code. Output only the next line. | def __init__(self): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
WEATHER_ICONS = {
211: "wi-storm-showers",
300: "wi-showers",
301: "wi-showers",
310: "wi-showers",
500: "wi-showers",
501: "wi-showers",
502: "wi-rain",
520: "wi-rain",
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime, timedelta
from solarpi.extensions import cache
from solarpi.weather.models import Weather
and context (class names, function names, or code) available:
# Path: solarpi/extensions.py
#
# Path: solarpi/weather/models.py
# class Weather(SurrogatePK, Model):
# __tablename__ = "weather_data"
#
# id = Column(db.Integer(), nullable=False, primary_key=True)
# created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow)
# temp = Column(db.Float(), nullable=True)
# pressure = Column(db.Integer(), nullable=True)
# temp_min = Column(db.Float(), nullable=True)
# temp_max = Column(db.Float(), nullable=True)
# humidity = Column(db.Integer(), nullable=True)
# wind_speed = Column(db.Float(), nullable=True)
# wind_gust = Column(db.Float(), nullable=True)
# wind_deg = Column(db.Integer(), nullable=True)
# clouds = Column(db.Integer(), nullable=True)
# rain = Column(db.Integer(), nullable=True)
# snow = Column(db.Integer(), nullable=True)
# weather_id = Column(db.Integer(), nullable=True)
. Output only the next line. | 521: "wi-rain", |
Predict the next line for this snippet: <|code_start|>
blueprint = Blueprint("tables", __name__, url_prefix="/tables", static_folder="../static")
@blueprint.route("/")
@cache.cached(timeout=3600, key_prefix="tables")
<|code_end|>
with the help of current file imports:
from datetime import timedelta, datetime
from flask import Blueprint, render_template
from solarpi.extensions import db, cache
and context from other files:
# Path: solarpi/extensions.py
, which may contain function names, class names, or code. Output only the next line. | def tables(): |
Predict the next line for this snippet: <|code_start|>
blueprint = Blueprint("tables", __name__, url_prefix="/tables", static_folder="../static")
@blueprint.route("/")
@cache.cached(timeout=3600, key_prefix="tables")
<|code_end|>
with the help of current file imports:
from datetime import timedelta, datetime
from flask import Blueprint, render_template
from solarpi.extensions import db, cache
and context from other files:
# Path: solarpi/extensions.py
, which may contain function names, class names, or code. Output only the next line. | def tables(): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
if os.environ.get("SOLARPI_ENV") == "prod":
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
import subprocess
from flask_script import Manager, Shell, Server
from flask_migrate import MigrateCommand
from solarpi.app import create_app
from solarpi.settings import DevConfig, ProdConfig
from solarpi.database import db
and context (functions, classes, or occasionally code) from other files:
# Path: solarpi/app.py
# def create_app(config_object=ProdConfig):
# """An application factory, as explained here:
# http://flask.pocoo.org/docs/patterns/appfactories/
#
# :param config_object: The configuration object to use.
# """
# app = Flask(__name__)
# app.config.from_object(config_object)
# register_extensions(app)
# register_blueprints(app)
# register_errorhandlers(app)
# return app
#
# Path: solarpi/settings.py
# class DevConfig(Config):
# """Development configuration."""
#
# ENV = "dev"
# DEBUG = True
# DB_NAME = "dev.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = True
# ASSETS_DEBUG = True # Don't bundle/minify static assets
# CACHE_TYPE = "simple" # Can be "memcached", "redis", etc.
#
# class ProdConfig(Config):
# """Production configuration."""
#
# ENV = "prod"
# DEBUG = False
# DB_NAME = "app.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = False # Disable Debug toolbar
# SENTRY_DNS = os_env.get("SENTRY_DNS", None)
#
# Path: solarpi/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
# def create(cls, **kwargs):
# def update(self, commit=True, **kwargs):
# def save(self, commit=True):
# def delete(self, commit=True):
# def get_by_id(cls, _id):
# def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs):
. Output only the next line. | manager = Manager(app) |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
if os.environ.get("SOLARPI_ENV") == "prod":
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
import subprocess
from flask_script import Manager, Shell, Server
from flask_migrate import MigrateCommand
from solarpi.app import create_app
from solarpi.settings import DevConfig, ProdConfig
from solarpi.database import db
and context (class names, function names, or code) available:
# Path: solarpi/app.py
# def create_app(config_object=ProdConfig):
# """An application factory, as explained here:
# http://flask.pocoo.org/docs/patterns/appfactories/
#
# :param config_object: The configuration object to use.
# """
# app = Flask(__name__)
# app.config.from_object(config_object)
# register_extensions(app)
# register_blueprints(app)
# register_errorhandlers(app)
# return app
#
# Path: solarpi/settings.py
# class DevConfig(Config):
# """Development configuration."""
#
# ENV = "dev"
# DEBUG = True
# DB_NAME = "dev.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = True
# ASSETS_DEBUG = True # Don't bundle/minify static assets
# CACHE_TYPE = "simple" # Can be "memcached", "redis", etc.
#
# class ProdConfig(Config):
# """Production configuration."""
#
# ENV = "prod"
# DEBUG = False
# DB_NAME = "app.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = False # Disable Debug toolbar
# SENTRY_DNS = os_env.get("SENTRY_DNS", None)
#
# Path: solarpi/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
# def create(cls, **kwargs):
# def update(self, commit=True, **kwargs):
# def save(self, commit=True):
# def delete(self, commit=True):
# def get_by_id(cls, _id):
# def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs):
. Output only the next line. | manager = Manager(app) |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
if os.environ.get("SOLARPI_ENV") == "prod":
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
manager = Manager(app)
TEST_CMD = "py.test tests"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
import subprocess
from flask_script import Manager, Shell, Server
from flask_migrate import MigrateCommand
from solarpi.app import create_app
from solarpi.settings import DevConfig, ProdConfig
from solarpi.database import db
and context:
# Path: solarpi/app.py
# def create_app(config_object=ProdConfig):
# """An application factory, as explained here:
# http://flask.pocoo.org/docs/patterns/appfactories/
#
# :param config_object: The configuration object to use.
# """
# app = Flask(__name__)
# app.config.from_object(config_object)
# register_extensions(app)
# register_blueprints(app)
# register_errorhandlers(app)
# return app
#
# Path: solarpi/settings.py
# class DevConfig(Config):
# """Development configuration."""
#
# ENV = "dev"
# DEBUG = True
# DB_NAME = "dev.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = True
# ASSETS_DEBUG = True # Don't bundle/minify static assets
# CACHE_TYPE = "simple" # Can be "memcached", "redis", etc.
#
# class ProdConfig(Config):
# """Production configuration."""
#
# ENV = "prod"
# DEBUG = False
# DB_NAME = "app.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = False # Disable Debug toolbar
# SENTRY_DNS = os_env.get("SENTRY_DNS", None)
#
# Path: solarpi/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
# def create(cls, **kwargs):
# def update(self, commit=True, **kwargs):
# def save(self, commit=True):
# def delete(self, commit=True):
# def get_by_id(cls, _id):
# def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs):
which might include code, classes, or functions. Output only the next line. | def _make_context(): |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
def test_production_config():
app = create_app(ProdConfig)
assert app.config["ENV"] == "prod"
assert app.config["DEBUG"] is False
assert app.config["DEBUG_TB_ENABLED"] is False
assert app.config["ASSETS_DEBUG"] is False
def test_dev_config():
app = create_app(DevConfig)
assert app.config["ENV"] == "dev"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from solarpi.app import create_app
from solarpi.settings import ProdConfig, DevConfig
and context:
# Path: solarpi/app.py
# def create_app(config_object=ProdConfig):
# """An application factory, as explained here:
# http://flask.pocoo.org/docs/patterns/appfactories/
#
# :param config_object: The configuration object to use.
# """
# app = Flask(__name__)
# app.config.from_object(config_object)
# register_extensions(app)
# register_blueprints(app)
# register_errorhandlers(app)
# return app
#
# Path: solarpi/settings.py
# class ProdConfig(Config):
# """Production configuration."""
#
# ENV = "prod"
# DEBUG = False
# DB_NAME = "app.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = False # Disable Debug toolbar
# SENTRY_DNS = os_env.get("SENTRY_DNS", None)
#
# class DevConfig(Config):
# """Development configuration."""
#
# ENV = "dev"
# DEBUG = True
# DB_NAME = "dev.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = True
# ASSETS_DEBUG = True # Don't bundle/minify static assets
# CACHE_TYPE = "simple" # Can be "memcached", "redis", etc.
which might include code, classes, or functions. Output only the next line. | assert app.config["DEBUG"] is True |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def test_production_config():
app = create_app(ProdConfig)
assert app.config["ENV"] == "prod"
assert app.config["DEBUG"] is False
assert app.config["DEBUG_TB_ENABLED"] is False
assert app.config["ASSETS_DEBUG"] is False
def test_dev_config():
app = create_app(DevConfig)
<|code_end|>
. Use current file imports:
(from solarpi.app import create_app
from solarpi.settings import ProdConfig, DevConfig)
and context including class names, function names, or small code snippets from other files:
# Path: solarpi/app.py
# def create_app(config_object=ProdConfig):
# """An application factory, as explained here:
# http://flask.pocoo.org/docs/patterns/appfactories/
#
# :param config_object: The configuration object to use.
# """
# app = Flask(__name__)
# app.config.from_object(config_object)
# register_extensions(app)
# register_blueprints(app)
# register_errorhandlers(app)
# return app
#
# Path: solarpi/settings.py
# class ProdConfig(Config):
# """Production configuration."""
#
# ENV = "prod"
# DEBUG = False
# DB_NAME = "app.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = False # Disable Debug toolbar
# SENTRY_DNS = os_env.get("SENTRY_DNS", None)
#
# class DevConfig(Config):
# """Development configuration."""
#
# ENV = "dev"
# DEBUG = True
# DB_NAME = "dev.db"
# DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
# SQLALCHEMY_DATABASE_URI = "sqlite:///{0}".format(DB_PATH)
# DEBUG_TB_ENABLED = True
# ASSETS_DEBUG = True # Don't bundle/minify static assets
# CACHE_TYPE = "simple" # Can be "memcached", "redis", etc.
. Output only the next line. | assert app.config["ENV"] == "dev" |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class PVData(SurrogatePK, Model):
__tablename__ = "pvdata"
id = Column(db.Integer(), nullable=False, primary_key=True)
created_at = Column(db.Text(), nullable=False, default=dt.datetime.utcnow)
dc_1_u = Column(db.Integer(), nullable=True)
dc_1_i = Column(db.Float(), nullable=True)
ac_1_u = Column(db.Integer(), nullable=True)
ac_1_p = Column(db.Integer(), nullable=True)
dc_2_u = Column(db.Integer(), nullable=True)
dc_2_i = Column(db.Float(), nullable=True)
ac_2_u = Column(db.Integer(), nullable=True)
ac_2_p = Column(db.Integer(), nullable=True)
dc_3_u = Column(db.Integer(), nullable=True)
dc_3_i = Column(db.Float(), nullable=True)
ac_3_u = Column(db.Integer(), nullable=True)
ac_3_p = Column(db.Integer(), nullable=True)
current_power = Column(db.Integer(), nullable=True)
daily_energy = Column(db.Float(), nullable=True)
total_energy = Column(db.Integer(), nullable=True)
<|code_end|>
. Use current file imports:
(import datetime as dt
from solarpi.database import (
Column,
db,
Model,
SurrogatePK,
))
and context including class names, function names, or small code snippets from other files:
# Path: solarpi/database.py
# class CRUDMixin(object):
# class Model(CRUDMixin, db.Model):
# class SurrogatePK(object):
# def create(cls, **kwargs):
# def update(self, commit=True, **kwargs):
# def save(self, commit=True):
# def delete(self, commit=True):
# def get_by_id(cls, _id):
# def ReferenceCol(tablename, nullable=False, pk_name="id", **kwargs):
. Output only the next line. | def __init__(self): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.