Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> class ScrollText(ArtBaseClass): description = "Scroll text across the display" fg = None bg = None def __init__(self, matrix, config): self.config = config self._initText() self.thisMessage = self._getText() self.nextMessage = self._getText() <|code_end|> , continue by predicting the next line. Consider current file imports: from .. _baseclass import ArtBaseClass from opc.text import OPCText, typeface_bbc and context: # Path: opc/text.py # class WidthCache(object): # class OPCText(object): # def __init__(self, space): # def add(self, char, width): # def get(self, char): # def __init__(self, typeface): # def drawHalfChar(self, matrix, x, y, char, offset, fg, bg): # def drawChar(self, matrix, x, y, c, fg, bg): # def drawText(self, matrix, x, y, string, fg, bg): which might include code, classes, or functions. Output only the next line.
self.typeface = OPCText(typeface_bbc)
Based on the snippet: <|code_start|> self.amp = 0 self.mult = 1+sqrt(matrix.numpix/32)/90 self.train = ClearTrain(TRAIN_LEN) def start(self, matrix): matrix.clear() def refresh(self, matrix): # this relies on the fact that the pixels we seed get multiplied and # overfow the uint8 in intresting ways matrix.blur(3) matrix.buf.buf = (self.mult*matrix.buf.buf).astype(np.uint8) self.amp += DELTA_AMP if self.amp >= 1 and False: self.amp = 0 self.hue += DELTA_HUE self.ang += DELTA_ANG xcenter = matrix.width / 2.0 ycenter = matrix.height / 2.0 amp = sin(self.amp) tx = amp * sin(self.ang) ty = amp * cos(self.ang) x = xcenter + xcenter * tx y = ycenter + ycenter * ty <|code_end|> , predict the immediate next line with the help of imports: from ._baseclass import ArtBaseClass from opc.colors import BLACK from opc.hue import hsvToRgb from math import fmod, sin, cos, sqrt import numpy as np and context (classes, functions, sometimes code) from other files: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] . Output only the next line.
color = hsvToRgb(fmod(self.hue, 1), 1, 1)
Based on the snippet: <|code_start|> PENS = 4 SCALE = 3 SIZE = 6 class Blobs(ArtBaseClass): def __init__(self, matrix, config): <|code_end|> , predict the immediate next line with the help of imports: from .. _baseclass import ArtBaseClass from random import random, uniform from opc.matrix import HQ from .. utils.pen import Pen and context (classes, functions, sometimes code) from other files: # Path: opc/matrix/hq.py # class HQ(object): # # """ # use the HQ class to savely wrap art init blocks when you need to # switch on HQ for set-up purposes. For example: # # from opc.matrix import HQ # # # class Art(object): # # def __init__(self, matrix): # # with HQ(matrix): # initialization stuff... # """ # # def __init__(self, matrix): # self.matrix = matrix # # def __enter__(self): # self.matrix.hq() # # def __exit__(self, type, value, traceback): # self.matrix.hq(False) . Output only the next line.
with HQ(matrix):
Given the following code snippet before the placeholder: <|code_start|> class Art(ArtBaseClass): description = "Dense Balistics" def __init__(self, matrix, config): <|code_end|> , predict the next line using imports from the current file: from ._baseclass import ArtBaseClass from .utils.fire import Gun and context including class names, function names, and sometimes code from other files: # Path: art/utils/fire.py # class Gun(object): # # def __init__(self, matrix): # self.points = [] # self.expires = int(matrix.numpix/2) # self.location = self._locationGenerator(matrix) # self.hue = getHueGen(step=0.05, hue=randint(0, 100)/100.0) # # def _locationGenerator(self, matrix): # x, y = 0, 0 # # while True: # for x in range(matrix.width-1): # yield x, y, -1, 1 # # for y in range(0, matrix.height-1): # yield matrix.width-1, y, -1, -1 # # for x in range(matrix.width-1, 0, -1): # yield x, matrix.height-1, 1, -1 # # for y in range(matrix.height-1, 0, -1): # yield 0, y, 1, 1 # # def fire(self, matrix): # x, y, dx, dy = next(self.location) # # point = Point(x, y, dx, dy, next(self.hue)) # self.points.append(point) # # if len(self.points) > self.expires: # point = self.points.pop(0) # point.expire(matrix) # # for point in self.points: # point.update(matrix, self.expires) . Output only the next line.
self.gun = Gun(matrix)
Given the following code snippet before the placeholder: <|code_start|> def start(self, matrix): matrix.clear() def _weightedAverage(self, v0, v1, percent): return v0 + (v1-v0)*percent def _bilinearInterp(self, gun, px, py): xi0 = self._weightedAverage(gun[0], gun[1], px) xi1 = self._weightedAverage(gun[2], gun[3], px) return self._weightedAverage(xi0, xi1, py) def _percent(self, v, max): return (v+1.0)/max def _interpolate(self, rgb, px, py): return tuple([self._bilinearInterp(gun, px, py) for gun in rgb]) def _rotate(self, array): return list(zip(*array[::-1])) def refresh(self, matrix): """ For any pair of colors represented as a hue, we need to calculate the distance between those two hues for each of the rgb components of the color. For the set of four corners, we have to interpolate each gun independently. """ <|code_end|> , predict the next line using imports from the current file: from .. _baseclass import ArtBaseClass from math import fmod from random import random from opc.hue import hsvToRgb and context including class names, function names, and sometimes code from other files: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] . Output only the next line.
rgbs = self._rotate([hsvToRgb(self.cornerValues[i]) for i in range(4)])
Here is a snippet: <|code_start|> def _reset(self, matrix): self.color = random() self.y = matrix.height - 1 - self.radius self.dy = -1.3 def refresh(self, matrix): matrix.shift(ds=0.75, dv=0.9) self.x = self.x + self.dx*self.dt self.y = self.y + self.dy*self.dt absdx, absdy = fabs(self.dx), fabs(self.dy) if self.x < self.radius: self.dx = absdx elif self.x >= (matrix.width-self.radius-1): self.dx = -absdx if self.y < self.radius: self.dy = absdy elif self.dy < 0.2 and self.dy > 0: self.dy = -absdy self.dy = self.dy - self.accel*self.dt if self.dy < 0 and self.y < self.radius: self._reset(matrix) else: matrix.fillCircle(self.x, self.y, self.radius, <|code_end|> . Write the next line using the current file imports: from ._baseclass import ArtBaseClass from opc.hue import hsvToRgb from random import random from math import fabs, sqrt and context from other files: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] , which may include functions, classes, or code. Output only the next line.
hsvToRgb(self.color))
Continue the code snippet: <|code_start|> w = matrix.width*16 h = matrix.height*16 self.url = "http://lorempixel.com/%s/%d/" % (w, h) self.image_active = None self._load() def start(self, matrix): matrix.clear() def _load(self): self.image_loaded = None start_new_thread(Art._loadthread, (self,)) def _consume(self, matrix): if not self.image_loaded: return False self.image_active = self.image_loaded self._load() self.position = position(matrix, self.image_active) return True def _loadthread(self): logging.info("_loadthread begin") try: r = requests.get(self.url) if r.status_code == 200: <|code_end|> . Use current file imports: from ._baseclass import ArtBaseClass from thread import start_new_thread, allocate_lock from _thread import start_new_thread, allocate_lock from opc.image import Image import requests import logging and context (classes, functions, or code) from other files: # Path: opc/image.py # class Image(object): # # def __init__(self, filename=None, bytestream=None): # if filename is not None: # image = PI.open(filename).rotate(-90, PI.BICUBIC).convert('RGB') # self.image = image # # if bytestream is not None: # self.image = PI.open(BytesIO(bytestream)) # # self.width, self.height = self.image.size # # @timefunc # def translate(self, matrix, scale=0, x=0, y=0): # i = self.image.copy() # if scale == 0: # i = self.image.resize((matrix.height, matrix.width), PI.ANTIALIAS) # else: # i = self.image.resize((int(self.height/scale), # int(self.width/scale)), PI.ANTIALIAS) # # return np.asarray(i.crop((y, x, y+matrix.height, x+matrix.width))) . Output only the next line.
self.image_loaded = Image(bytestream=r.content)
Here is a snippet: <|code_start|> GRIDSIZE = 8 C_BACKGROUND = (96, 64, 24) C_BORDER = (128, 128, 128) class Art(ArtBaseClass): description = "A silly chess board" def __init__(self, matrix, config): <|code_end|> . Write the next line using the current file imports: from ._baseclass import ArtBaseClass from opc.hue import getHueGen, hsvToRgb from math import sqrt and context from other files: # Path: opc/hue.py # def getHueGen(step=0.05, hue=0): # """ # Generator that returns a stream of shades as hues # """ # while True: # hue = fmod(hue + step, 1) # yield hue # # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] , which may include functions, classes, or code. Output only the next line.
self.hue = getHueGen(0.0005)
Given the following code snippet before the placeholder: <|code_start|>C_BACKGROUND = (96, 64, 24) C_BORDER = (128, 128, 128) class Art(ArtBaseClass): description = "A silly chess board" def __init__(self, matrix, config): self.hue = getHueGen(0.0005) def start(self, matrix): matrix.clear(C_BACKGROUND) def refresh(self, matrix): hue = next(self.hue) # pixels per squre pps = int((sqrt(matrix.numpix)-1)/GRIDSIZE) xcorner = matrix.midWidth - pps*(GRIDSIZE/2) ycorner = matrix.midHeight - pps*(GRIDSIZE/2) matrix.drawRect(xcorner-1, ycorner-1, pps*GRIDSIZE+1, pps*GRIDSIZE+1, C_BORDER) for x in range(GRIDSIZE): for y in range(GRIDSIZE): black = (x & 1) ^ (y & 1) if black: <|code_end|> , predict the next line using imports from the current file: from ._baseclass import ArtBaseClass from opc.hue import getHueGen, hsvToRgb from math import sqrt and context including class names, function names, and sometimes code from other files: # Path: opc/hue.py # def getHueGen(step=0.05, hue=0): # """ # Generator that returns a stream of shades as hues # """ # while True: # hue = fmod(hue + step, 1) # yield hue # # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] . Output only the next line.
color = hsvToRgb(hue, s=0.7, v=0.5)
Predict the next line after this snippet: <|code_start|> class Art(Barber): description = "Barber-pole-esque (dirty)" def _line(self, matrix, x1, x2, hue): for x in range(x1, x2): val = 0.8 + 0.2*random() <|code_end|> using the current file's imports: from .baseclasses.barber import Barber from random import random from opc.hue import hsvToRgb and any relevant context from other files: # Path: art/baseclasses/barber.py # class Barber(ArtBaseClass): # # def __init__(self, matrix, config): # self.width = int(matrix.width/SEGMENTS) # self.hue = getHueGen(step=0.01) # # def start(self, matrix): # pass # # def _line(self, matrix, x1, x2, hue): # raise NotImplementedError # # def refresh(self, matrix): # matrix.scroll("up") # matrix.scroll("right") # # hue = next(self.hue) # for segment in range(SEGMENTS): # self._line( # matrix, # self.width*segment, # self.width*(segment+1), # hue+(HUEDELTA*segment) # ) # # def interval(self): # return 120 # # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] . Output only the next line.
matrix.drawPixel(x, 0, hsvToRgb(hue, 1, val))
Predict the next line for this snippet: <|code_start|> class Art(ArtBaseClass): description = "Churning candy" def __init__(self, matrix, config): with HQ(matrix): self.pieces = int(sqrt(matrix.numpix/2)) cycles = int(sqrt(matrix.numpix)*2) <|code_end|> with the help of current file imports: from ._baseclass import ArtBaseClass from .utils.shrapnel import Shrapnel from math import sqrt from random import random from opc.matrix import HQ and context from other files: # Path: art/utils/shrapnel.py # class Shrapnel(Pen): # def __init__(self, matrix, motion_cycles, huedelta=0.001, saturation=1, # radius=0, decelerate=False): # self.centerx = matrix.width/2.0 # self.centery = matrix.height/2.0 # self.cycles = motion_cycles # self.decelerate = decelerate # # # we will reset some params to sensible values in a minute, so let's # # not fuss with x, y, dx, dy now # super(Shrapnel, self).__init__( # matrix.width, # matrix.height, # 0, 0, 0, 0, # huedelta=huedelta, # saturation=saturation, # radius=radius # ) # # super(Shrapnel, self).setBumpStrategy(self._pause, x=True, y=True) # # self.reset(matrix) # # def _pause(self, x=None, y=None): # self.paused = True # # def reset(self, matrix): # # the furthest distance any pen will have to travel is on the diagonal # w, h = matrix.width, matrix.height # maxDimension = sqrt(w*w + h*h) # # # slowest pens need to cover the distance in cycles time, but there may # # be some that go faster # velocity = maxDimension/(2.0*self.cycles) + 0.05*random()*maxDimension # # angle = random()*2*pi # self.dx = velocity * sin(angle) # self.dy = velocity * cos(angle) # # self.x = self.centerx # self.y = self.centery # self.paused = False # # def clock(self, matrix): # super(Shrapnel, self).clock(matrix) # # # optionally slow over time # # XXX: this may cause problems for larger spans? # if self.decelerate: # self.dx *= 0.99 # self.dy *= 0.99 # # return self.paused # # Path: opc/matrix/hq.py # class HQ(object): # # """ # use the HQ class to savely wrap art init blocks when you need to # switch on HQ for set-up purposes. For example: # # from opc.matrix import HQ # # # class Art(object): # # def __init__(self, matrix): # # with HQ(matrix): # initialization stuff... # """ # # def __init__(self, matrix): # self.matrix = matrix # # def __enter__(self): # self.matrix.hq() # # def __exit__(self, type, value, traceback): # self.matrix.hq(False) , which may contain function names, class names, or code. Output only the next line.
self.shrapnel = [Shrapnel(matrix, cycles, saturation=random(),
Given snippet: <|code_start|> class Art(ArtBaseClass): description = "Churning candy" def __init__(self, matrix, config): <|code_end|> , continue by predicting the next line. Consider current file imports: from ._baseclass import ArtBaseClass from .utils.shrapnel import Shrapnel from math import sqrt from random import random from opc.matrix import HQ and context: # Path: art/utils/shrapnel.py # class Shrapnel(Pen): # def __init__(self, matrix, motion_cycles, huedelta=0.001, saturation=1, # radius=0, decelerate=False): # self.centerx = matrix.width/2.0 # self.centery = matrix.height/2.0 # self.cycles = motion_cycles # self.decelerate = decelerate # # # we will reset some params to sensible values in a minute, so let's # # not fuss with x, y, dx, dy now # super(Shrapnel, self).__init__( # matrix.width, # matrix.height, # 0, 0, 0, 0, # huedelta=huedelta, # saturation=saturation, # radius=radius # ) # # super(Shrapnel, self).setBumpStrategy(self._pause, x=True, y=True) # # self.reset(matrix) # # def _pause(self, x=None, y=None): # self.paused = True # # def reset(self, matrix): # # the furthest distance any pen will have to travel is on the diagonal # w, h = matrix.width, matrix.height # maxDimension = sqrt(w*w + h*h) # # # slowest pens need to cover the distance in cycles time, but there may # # be some that go faster # velocity = maxDimension/(2.0*self.cycles) + 0.05*random()*maxDimension # # angle = random()*2*pi # self.dx = velocity * sin(angle) # self.dy = velocity * cos(angle) # # self.x = self.centerx # self.y = self.centery # self.paused = False # # def clock(self, matrix): # super(Shrapnel, self).clock(matrix) # # # optionally slow over time # # XXX: this may cause problems for larger spans? # if self.decelerate: # self.dx *= 0.99 # self.dy *= 0.99 # # return self.paused # # Path: opc/matrix/hq.py # class HQ(object): # # """ # use the HQ class to savely wrap art init blocks when you need to # switch on HQ for set-up purposes. For example: # # from opc.matrix import HQ # # # class Art(object): # # def __init__(self, matrix): # # with HQ(matrix): # initialization stuff... # """ # # def __init__(self, matrix): # self.matrix = matrix # # def __enter__(self): # self.matrix.hq() # # def __exit__(self, type, value, traceback): # self.matrix.hq(False) which might include code, classes, or functions. Output only the next line.
with HQ(matrix):
Given snippet: <|code_start|> self.y += self.dy if self.y <= 0 or self.y >= (matrix.height-1): self.dy = -self.dy return self class Vector(object): def __init__(self, bases, color): self.points = [Point(base.x, base.y, base.dx, base.dy) for base in bases] self.color = color def clock(self, matrix): for point in self.points: point.clock(matrix) p = self.points matrix.drawLine(p[0].x, p[0].y, p[1].x, p[1].y, self.color) class Vectors(object): DELTA = 0.41 def __init__(self, matrix, count): pointgen = self.positionGenerator(matrix) <|code_end|> , continue by predicting the next line. Consider current file imports: from opc.hue import getColorGen from math import sqrt from random import random and context: # Path: opc/hue.py # def getColorGen(step=0.05, hue=0, sat=1, val=1): # """ # Generator that returns a stream of shades as colors # """ # hue = getHueGen(step, hue) # while True: # yield hsvToRgb(next(hue), sat, val) which might include code, classes, or functions. Output only the next line.
huegen = getColorGen(step=0.15, hue=random())
Continue the code snippet: <|code_start|>class Art(ArtBaseClass): description = "Loop the loop" def __init__(self, matrix, config): with HQ(matrix): self.hue = 0 self.ang = 0 self.amp = 0 self.radius = sqrt(matrix.numpix)/16 def start(self, matrix): matrix.hq() matrix.clear() def refresh(self, matrix): matrix.fade(0.97) self.amp += DELTA_AMP self.hue += DELTA_HUE self.ang += DELTA_ANG amp = sin(self.amp) tx = amp * sin(self.ang) ty = amp * cos(self.ang) x = matrix.midWidth + matrix.midWidth * tx y = matrix.midHeight + matrix.midHeight * ty <|code_end|> . Use current file imports: from ._baseclass import ArtBaseClass from opc.hue import hsvToRgb from opc.matrix import HQ from math import fmod, sin, cos, sqrt and context (classes, functions, or code) from other files: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # Path: opc/matrix/hq.py # class HQ(object): # # """ # use the HQ class to savely wrap art init blocks when you need to # switch on HQ for set-up purposes. For example: # # from opc.matrix import HQ # # # class Art(object): # # def __init__(self, matrix): # # with HQ(matrix): # initialization stuff... # """ # # def __init__(self, matrix): # self.matrix = matrix # # def __enter__(self): # self.matrix.hq() # # def __exit__(self, type, value, traceback): # self.matrix.hq(False) . Output only the next line.
color = hsvToRgb(fmod(self.hue, 1), 1, 1)
Given the code snippet: <|code_start|> DELTA_AMP = 0.09 DELTA_ANG = 0.033 DELTA_HUE = 0.006 class Art(ArtBaseClass): description = "Loop the loop" def __init__(self, matrix, config): <|code_end|> , generate the next line using the imports in this file: from ._baseclass import ArtBaseClass from opc.hue import hsvToRgb from opc.matrix import HQ from math import fmod, sin, cos, sqrt and context (functions, classes, or occasionally code) from other files: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # Path: opc/matrix/hq.py # class HQ(object): # # """ # use the HQ class to savely wrap art init blocks when you need to # switch on HQ for set-up purposes. For example: # # from opc.matrix import HQ # # # class Art(object): # # def __init__(self, matrix): # # with HQ(matrix): # initialization stuff... # """ # # def __init__(self, matrix): # self.matrix = matrix # # def __enter__(self): # self.matrix.hq() # # def __exit__(self, type, value, traceback): # self.matrix.hq(False) . Output only the next line.
with HQ(matrix):
Predict the next line after this snippet: <|code_start|>class Art(ArtBaseClass): description = "Classic plasma (almost)" def __init__(self, matrix, config): ones = np.ones(matrix.numpix).reshape((matrix.height, matrix.width)) self.x = ones*np.arange(matrix.width) self.y = np.flipud(np.rot90(np.rot90(ones)*np.arange(matrix.height))) self.base = 128000 def start(self, matrix): pass def _dist(self, a, b, c, d): return np.sqrt((c-a)*(c-a)+(d-b)*(d-b)) def refresh(self, matrix): xb = self.x + self.base yb = self.y + self.base c1 = self._dist(xb, self.y, 128.0, 128.0) / (matrix.smallest/2) c2 = self._dist(self.y, self.y, 64.0, 64.0) / (matrix.smallest/2) c3 = self._dist(self.x, yb / 7, 192.0, 64) / (matrix.smallest/2) c4 = self._dist(self.y, self.x, 192.0, 100.0) / (matrix.smallest/2) hue = np.sum(np.sin(c) for c in (c1, c2, c3, c4)) hue = np.fmod(np.fabs(1+hue/2), 1.0) <|code_end|> using the current file's imports: from ._baseclass import ArtBaseClass from opc.nphue import h_to_rgb import numpy as np and any relevant context from other files: # Path: opc/nphue.py # @timefunc # def h_to_rgb(h, sat=1, val=255.0): # # Local variation of hsv_to_rgb that only cares about a variable # # hue, with (s,v) assumed to be constant # # h should be a numpy array with values between 0.0 and 1.0 # # hsv_to_rgb returns an array of uints between 0 and 255. # s = np.full_like(h, sat) # v = np.full_like(h, val) # hsv = np.dstack((h, s, v)) # # return hsv_to_rgb(hsv) . Output only the next line.
rgb = h_to_rgb(hue)
Predict the next line for this snippet: <|code_start|> class Image(object): def __init__(self, filename=None, bytestream=None): if filename is not None: image = PI.open(filename).rotate(-90, PI.BICUBIC).convert('RGB') self.image = image if bytestream is not None: self.image = PI.open(BytesIO(bytestream)) self.width, self.height = self.image.size <|code_end|> with the help of current file imports: import numpy as np from PIL import Image as PI from io import BytesIO from .utils.prof import timefunc and context from other files: # Path: opc/utils/prof.py # def timefunc(f, reference=False): # global records # # records[f.__name__] = Record(f.__name__, reference) # # @wraps(f) # def f_timer(*args, **kwargs): # global active # # if not active: # return f(*args, **kwargs) # # start = time.time() # result = f(*args, **kwargs) # end = time.time() # # records[f.__name__].addTime(end-start) # # return result # # return f_timer , which may contain function names, class names, or code. Output only the next line.
@timefunc
Predict the next line after this snippet: <|code_start|> HUEINCYCLES = 8 class Art(ArtBaseClass): description = "Use an LFSR to 'randomly' fill the display" def __init__(self, matrix, config): pass def start(self, matrix): # we could probably shuffle() up a range, but that sounds like # it'd be less of a challenge :) self.random = compoundLfsr(matrix.numpix) self.hue = random() matrix.clear() def refresh(self, matrix): try: pos = next(self.random) except: self.random = compoundLfsr(matrix.numpix) pos = next(self.random) # gently transition through all hues over HUEINCYCLES fills self.hue += 1.0/(matrix.numpix*HUEINCYCLES) <|code_end|> using the current file's imports: from ._baseclass import ArtBaseClass from opc.hue import hsvToRgb from random import random from .utils.lfsr import compoundLfsr and any relevant context from other files: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # Path: art/utils/lfsr.py # @timefunc # def compoundLfsr(slots): # """ # Combine a number of LFSRs to support an arbitary range of # once-visit values, most of the heavy lifting is done in a # class. # # figure out largest power of two that is smaller than places # add as many of these to the pool that fit, this is a bucket. # take the remainder and repeat until there is nothing left. # # while generating visit each bucket in round-robin sequence, # until all of the buckets report empty. # """ # pool = LfsrBucket(slots) # while True: # failures = 0 # while True: # value = pool.get() # if value is not None: # yield value # break # # failures += 1 # if failures == pool.buckets(): # # nome of the buckets have anything left, the # # supply of values is exhausted # return . Output only the next line.
color = hsvToRgb(self.hue, 1, 0.2+0.8*random())
Using the snippet: <|code_start|> HUEINCYCLES = 8 class Art(ArtBaseClass): description = "Use an LFSR to 'randomly' fill the display" def __init__(self, matrix, config): pass def start(self, matrix): # we could probably shuffle() up a range, but that sounds like # it'd be less of a challenge :) <|code_end|> , determine the next line of code. You have imports: from ._baseclass import ArtBaseClass from opc.hue import hsvToRgb from random import random from .utils.lfsr import compoundLfsr and context (class names, function names, or code) available: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # Path: art/utils/lfsr.py # @timefunc # def compoundLfsr(slots): # """ # Combine a number of LFSRs to support an arbitary range of # once-visit values, most of the heavy lifting is done in a # class. # # figure out largest power of two that is smaller than places # add as many of these to the pool that fit, this is a bucket. # take the remainder and repeat until there is nothing left. # # while generating visit each bucket in round-robin sequence, # until all of the buckets report empty. # """ # pool = LfsrBucket(slots) # while True: # failures = 0 # while True: # value = pool.get() # if value is not None: # yield value # break # # failures += 1 # if failures == pool.buckets(): # # nome of the buckets have anything left, the # # supply of values is exhausted # return . Output only the next line.
self.random = compoundLfsr(matrix.numpix)
Continue the code snippet: <|code_start|>from __future__ import division stdscr = None # for flake8 def initCurses(): global stdscr stdscr = curses.initscr() curses.start_color() curses.use_default_colors() def exitCurses(): curses.endwin() <|code_end|> . Use current file imports: import curses import numpy as np from opc.drivers.baseclass import RopDriver from opc.error import TtyTooSmall from opc.utils.prof import timefunc and context (classes, functions, or code) from other files: # Path: opc/drivers/baseclass.py # class RopDriver(object): # # def __init__(self, width, height, address): # raise NotImplementedError # # def send(self, packet): # raise NotImplementedError # # def putPixels(self, channel, *sources): # raise NotImplementedError # # def setFirmwareConfig(self, nodither=False, nointerp=False, # manualled=False, ledonoff=True): # raise NotImplementedError # # def setGlobalColorCorrection(self, gamma, r, g, b): # raise NotImplementedError # # def terminate(self): # raise NotImplementedError # # Path: opc/utils/prof.py # def timefunc(f, reference=False): # global records # # records[f.__name__] = Record(f.__name__, reference) # # @wraps(f) # def f_timer(*args, **kwargs): # global active # # if not active: # return f(*args, **kwargs) # # start = time.time() # result = f(*args, **kwargs) # end = time.time() # # records[f.__name__].addTime(end-start) # # return result # # return f_timer . Output only the next line.
class Driver(RopDriver):
Based on the snippet: <|code_start|> # lines that end 'ax' are approximations curses.color_pair(curses.COLOR_BLACK), curses.color_pair(curses.COLOR_BLUE), curses.color_pair(curses.COLOR_BLUE)+curses.A_BOLD, curses.color_pair(curses.COLOR_GREEN), curses.color_pair(curses.COLOR_CYAN), curses.color_pair(curses.COLOR_CYAN), # ax curses.color_pair(curses.COLOR_GREEN)+curses.A_BOLD, curses.color_pair(curses.COLOR_CYAN), # ax curses.color_pair(curses.COLOR_CYAN)+curses.A_BOLD, curses.color_pair(curses.COLOR_RED), curses.color_pair(curses.COLOR_MAGENTA), curses.color_pair(curses.COLOR_MAGENTA), # ax curses.color_pair(curses.COLOR_YELLOW), curses.color_pair(curses.COLOR_WHITE), curses.color_pair(curses.COLOR_BLUE)+curses.A_BOLD, # ax curses.color_pair(curses.COLOR_YELLOW), # ax curses.color_pair(curses.COLOR_GREEN)+curses.A_BOLD, # ax curses.color_pair(curses.COLOR_CYAN)+curses.A_BOLD, # ax curses.color_pair(curses.COLOR_RED)+curses.A_BOLD, curses.color_pair(curses.COLOR_RED)+curses.A_BOLD, # ax curses.color_pair(curses.COLOR_MAGENTA)+curses.A_BOLD, curses.color_pair(curses.COLOR_YELLOW), # ax curses.color_pair(curses.COLOR_RED)+curses.A_BOLD, # ax curses.color_pair(curses.COLOR_MAGENTA)+curses.A_BOLD, # ax curses.color_pair(curses.COLOR_YELLOW)+curses.A_BOLD, curses.color_pair(curses.COLOR_YELLOW)+curses.A_BOLD, # ax curses.color_pair(curses.COLOR_WHITE)+curses.A_BOLD, ] <|code_end|> , predict the immediate next line with the help of imports: import curses import numpy as np from opc.drivers.baseclass import RopDriver from opc.error import TtyTooSmall from opc.utils.prof import timefunc and context (classes, functions, sometimes code) from other files: # Path: opc/drivers/baseclass.py # class RopDriver(object): # # def __init__(self, width, height, address): # raise NotImplementedError # # def send(self, packet): # raise NotImplementedError # # def putPixels(self, channel, *sources): # raise NotImplementedError # # def setFirmwareConfig(self, nodither=False, nointerp=False, # manualled=False, ledonoff=True): # raise NotImplementedError # # def setGlobalColorCorrection(self, gamma, r, g, b): # raise NotImplementedError # # def terminate(self): # raise NotImplementedError # # Path: opc/utils/prof.py # def timefunc(f, reference=False): # global records # # records[f.__name__] = Record(f.__name__, reference) # # @wraps(f) # def f_timer(*args, **kwargs): # global active # # if not active: # return f(*args, **kwargs) # # start = time.time() # result = f(*args, **kwargs) # end = time.time() # # records[f.__name__].addTime(end-start) # # return result # # return f_timer . Output only the next line.
@timefunc
Given the code snippet: <|code_start|> DTYPE = np.uint8 class OPCBuffer(object): """ Provdes primitive buffer-level storage and operations. """ <|code_end|> , generate the next line using the imports in this file: from PIL import Image, ImageFilter from .colors import BLACK from .utils.prof import timefunc import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: opc/utils/prof.py # def timefunc(f, reference=False): # global records # # records[f.__name__] = Record(f.__name__, reference) # # @wraps(f) # def f_timer(*args, **kwargs): # global active # # if not active: # return f(*args, **kwargs) # # start = time.time() # result = f(*args, **kwargs) # end = time.time() # # records[f.__name__].addTime(end-start) # # return result # # return f_timer . Output only the next line.
@timefunc
Given the code snippet: <|code_start|> self.astep = pi/48 self.hstep = pi/1024 self.radius = min(matrix.width, matrix.height)/2.2 self.x0 = matrix.width/2 self.y0 = matrix.height/2 def start(self, matrix): matrix.clear() def refresh(self, matrix): matrix.fade(0.995) y0 = matrix.height/2 x0 = matrix.width/2 if self.angle >= pi: x0 -= 1 if self.angle > (0.5*pi) and self.angle < (1.5*pi): y0 -= 1 x1 = int(self.x0 + self.radius * sin(self.angle-self.astep)) y1 = int(self.y0 + self.radius * cos(self.angle+self.astep)) x2 = int(self.x0 + self.radius * sin(self.angle)) y2 = int(self.y0 + self.radius * cos(self.angle)) matrix.drawPoly( [(self.x0, self.y0), (x1, y1), (x2, y2)], <|code_end|> , generate the next line using the imports in this file: from ._baseclass import ArtBaseClass from opc.hue import hsvToRgb from math import sin, cos, fmod, pi and context (functions, classes, or occasionally code) from other files: # Path: opc/hue.py # @mwt(timeout=20) # @timefunc # def hsvToRgb(h, s=1.0, v=1.0, rainbow=True): # """ # Convert a (h, s, v) value to the (r, g, b) color space. By default, # we use a more cpu-intense method to curve the hue ramps above the # typical linear, with a view to evening out the visible range of yellow, # cyan, and purple. # # This method takes h, s, and v values in range 0..1 and returns r, g, # and b values in range 0..255. # """ # if rainbow: # return [sin(c*pi/2)*255 for c in colorsys.hsv_to_rgb(h, s, v)] # # return [c*255 for c in colorsys.hsv_to_rgb(h, s, v)] . Output only the next line.
hsvToRgb(self.hue)
Continue the code snippet: <|code_start|> class Art(DiamondSquare): description = "Thin plasma using DiamondSquare and colormap rotation" def __init__(self, matrix, config): super(Art, self).__init__(matrix, self.generate, maxticks=20, interpolate=False) <|code_end|> . Use current file imports: from opc.colormap import Colormap from opc.colors import BLACK, BLUE, YELLOW, RED, GREEN from .baseclasses.diamondsquare import DiamondSquare and context (classes, functions, or code) from other files: # Path: opc/colormap.py # class Colormap(object): # # """ # Colormap management class # """ # # def __init__(self, size=None, palette=None): # if size is not None: # self.size = size # self.cmap = np.empty((self.size, 3), dtype=np.uint8) # elif palette is not None: # self._buildPalette(palette) # else: # raise AttributeError("Invalid Colormap Initializer") # # def __len__(self): # return self.size # # def flat(self, index0, index1, color): # """ # initialize a block of colormap entries with a particular color # """ # self.cmap[index0:index1] = color # # def _buildPalette(self, palette): # index = 0 # oldcolor = None # self.size = sum(palette.values()) # self.cmap = np.empty((self.size, 3), dtype=np.uint8) # # for color, count in palette.items(): # if oldcolor is None: # oldcolor = color # # self.gradient(index, index+count, oldcolor, color) # oldcolor = color # index += count # # def gradient(self, index0, index1, color0, color1): # """ # apply a linear gradient from color0 to color1 across a range of # colormap cells # """ # steps = float(index1) - index0 # delta = [(color1[gun] - color0[gun]) / steps for gun in range(3)] # # for index in range(index0, index1): # c = [color0[gun] + delta[gun] * (index-index0) for gun in range(3)] # self.cmap[index] = c # # def convert(self, point, scale=None): # """ # Get the color associated with the given index. This method allows for # scaling up or down, in the case where the desired range is either # bigger or smaller than the colormap # """ # if scale: # point = point * self.size/scale # # index = int(min(self.size-1, max(0, point))) # return self.cmap[index] # # def apply(self, data, scale=None): # scale = self.size-1 if scale is None else scale # return self.cmap[(data*scale).astype(np.int)] # # def soften(self, neighbors=1): # """ # Use inverse distance weighting to soften the transitions between colors # in the map, looking out by NEIGHBORS entries left and right. # """ # self.cmap = idw.soften_2d(self.cmap, neighbors) # # def rotate(self, stepsize=1): # """ # Rotate the colormap up or down by STEPSIZE places # """ # # # x3 since we have three colors to work with # self.cmap = np.roll(self.cmap, stepsize*3) . Output only the next line.
self.colormap = Colormap(130)
Predict the next line for this snippet: <|code_start|> # if not getattr(f, 'editable', False): # continue if fields and not f.name in fields: continue if exclude and f.name in exclude: continue if isinstance(f, ManyToManyField): # If the object doesn't have a primary key yet, just use an empty # list for its m2m fields. Calling f.value_from_object will raise # an exception. if instance.pk is None: data[f.name] = [] else: # MultipleChoiceWidget needs a list of pks, not object instances. data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True)) else: data[f.name] = f.value_from_object(instance) return data def gravatar_url(email, width, height, gravatar_default): digest = md5(email.lower()).hexdigest() size = max(width, height) url = '//www.gravatar.com/avatar/%s?size=%s&default=%s' % (digest, size, gravatar_default) return url def format_user(user): user_dict = model_to_dict(user, fields=['id', 'username', 'name', 'first_name', 'last_name']) user_dict.update({ <|code_end|> with the help of current file imports: import time from collections import deque from hashlib import md5 from .settings import AVATAR_HEIGHT, AVATAR_WIDTH, GRAVATAR_DEFAULT from django.db.models.fields.related import ManyToManyField and context from other files: # Path: chant/settings.py # AVATAR_HEIGHT = getattr(settings, 'CHANT_AVATAR_HEIGHT', 32) # # AVATAR_WIDTH = getattr(settings, 'CHANT_AVATAR_WIDTH', 32) # # GRAVATAR_DEFAULT = getattr(settings, 'CHANT_GRAVATAR_DEFAULT', 'identicon') , which may contain function names, class names, or code. Output only the next line.
'avatar': gravatar_url(user.email, AVATAR_WIDTH, AVATAR_HEIGHT, GRAVATAR_DEFAULT)
Using the snippet: <|code_start|> # if not getattr(f, 'editable', False): # continue if fields and not f.name in fields: continue if exclude and f.name in exclude: continue if isinstance(f, ManyToManyField): # If the object doesn't have a primary key yet, just use an empty # list for its m2m fields. Calling f.value_from_object will raise # an exception. if instance.pk is None: data[f.name] = [] else: # MultipleChoiceWidget needs a list of pks, not object instances. data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True)) else: data[f.name] = f.value_from_object(instance) return data def gravatar_url(email, width, height, gravatar_default): digest = md5(email.lower()).hexdigest() size = max(width, height) url = '//www.gravatar.com/avatar/%s?size=%s&default=%s' % (digest, size, gravatar_default) return url def format_user(user): user_dict = model_to_dict(user, fields=['id', 'username', 'name', 'first_name', 'last_name']) user_dict.update({ <|code_end|> , determine the next line of code. You have imports: import time from collections import deque from hashlib import md5 from .settings import AVATAR_HEIGHT, AVATAR_WIDTH, GRAVATAR_DEFAULT from django.db.models.fields.related import ManyToManyField and context (class names, function names, or code) available: # Path: chant/settings.py # AVATAR_HEIGHT = getattr(settings, 'CHANT_AVATAR_HEIGHT', 32) # # AVATAR_WIDTH = getattr(settings, 'CHANT_AVATAR_WIDTH', 32) # # GRAVATAR_DEFAULT = getattr(settings, 'CHANT_GRAVATAR_DEFAULT', 'identicon') . Output only the next line.
'avatar': gravatar_url(user.email, AVATAR_WIDTH, AVATAR_HEIGHT, GRAVATAR_DEFAULT)
Given snippet: <|code_start|> # if not getattr(f, 'editable', False): # continue if fields and not f.name in fields: continue if exclude and f.name in exclude: continue if isinstance(f, ManyToManyField): # If the object doesn't have a primary key yet, just use an empty # list for its m2m fields. Calling f.value_from_object will raise # an exception. if instance.pk is None: data[f.name] = [] else: # MultipleChoiceWidget needs a list of pks, not object instances. data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True)) else: data[f.name] = f.value_from_object(instance) return data def gravatar_url(email, width, height, gravatar_default): digest = md5(email.lower()).hexdigest() size = max(width, height) url = '//www.gravatar.com/avatar/%s?size=%s&default=%s' % (digest, size, gravatar_default) return url def format_user(user): user_dict = model_to_dict(user, fields=['id', 'username', 'name', 'first_name', 'last_name']) user_dict.update({ <|code_end|> , continue by predicting the next line. Consider current file imports: import time from collections import deque from hashlib import md5 from .settings import AVATAR_HEIGHT, AVATAR_WIDTH, GRAVATAR_DEFAULT from django.db.models.fields.related import ManyToManyField and context: # Path: chant/settings.py # AVATAR_HEIGHT = getattr(settings, 'CHANT_AVATAR_HEIGHT', 32) # # AVATAR_WIDTH = getattr(settings, 'CHANT_AVATAR_WIDTH', 32) # # GRAVATAR_DEFAULT = getattr(settings, 'CHANT_GRAVATAR_DEFAULT', 'identicon') which might include code, classes, or functions. Output only the next line.
'avatar': gravatar_url(user.email, AVATAR_WIDTH, AVATAR_HEIGHT, GRAVATAR_DEFAULT)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- class Command(BaseCommand): args = '[port_number]' help = 'Starts the Tornado application for message handling.' def sig_handler(self, sig, frame): """Catch signal and init callback""" tornado.ioloop.IOLoop.instance().add_callback(self.shutdown) def shutdown(self): """Stop server and add callback to stop i/o loop""" self.http_server.stop() io_loop = tornado.ioloop.IOLoop.instance() io_loop.add_timeout(time.time() + 1, io_loop.stop) def handle(self, *args, **options): if len(args) == 1: try: port = int(args[0]) except ValueError: raise CommandError('Invalid port number specified') else: port = 8888 <|code_end|> using the current file's imports: import signal import time import tornado.httpserver import tornado.ioloop from django.core.management.base import BaseCommand, CommandError from chant.tornado_chant import application and any relevant context from other files: # Path: chant/tornado_chant.py # def run_async(func): # def async_func(*args, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, **kwargs): # def __init__(self, *args, **kwargs): # def open(self): # def on_close(self): # def json_response(self, data): # def error_response(self, msg): # def on_message(self, client_data): # def get_current_user(self): # def subscribed_rooms(self, values=False): # def chant_authenticate(self, session_key, callback=None): # def chant_post(self, data, callback=None): # def chant_rooms(self, data, callback=None): # def chant_typing(self, data, callback=None): # def chant_history(self, data, callback=None): # def chant_notify(self, data, callback=None): # def chant_blacklist(self, data, callback=None): # def __init__(self): # class DummyRequest(object): # class ResponseDict(dict): # class ErrorResponse(ResponseDict): # class CommandNotAllowedResponse(ErrorResponse): # class RateLimitExceededResponse(ErrorResponse): # class ServerFullResponse(ErrorResponse): # class UnauthenticatedResponse(ErrorResponse): # class SuccessResponse(ResponseDict): # class RoomsResponse(SuccessResponse): # class AuthResponseAccept(SuccessResponse): # class AuthResponseDecline(ErrorResponse): # class MessageResponse(SuccessResponse): # class HistoryResponse(SuccessResponse): # class TypingResponse(SuccessResponse): # class NotifyResponse(SuccessResponse): # class BlacklistResponse(SuccessResponse): # class MessagesHandler(WebSocketHandler): # class ChantApplication(Application): . Output only the next line.
self.http_server = tornado.httpserver.HTTPServer(application)
Predict the next line after this snippet: <|code_start|># test_io.py # # Author: R. Booth # Date: 22 - May - 2018 # # Test input / output routines ############################################################################### def test_event_controller(): """Tests that event controller correctly generates events""" t0 = [0, 2, 4, 6, 8 ] t1 = [0, 3, 6, 9] # Label for the next possible events next_event = [ 'et', 'e', 'e', 't', 'e', 'et', 'et', 'e', 'e', 't'] <|code_end|> using the current file's imports: from DiscEvolution.io import Event_Controller and any relevant context from other files: # Path: DiscEvolution/io.py # class Event_Controller(object): # """Handles booking keeping for events that occur at the specified times. # # Event types are specified through key word arguments, e.g. # Event_Controller(save=output_times, plot=plot_times) # where the values passed must be iterable lists of times. # """ # def __init__(self, **events): # # self._events = {} # self._event_number = {} # for key in events: # self._events[key] = sorted(events[key]) # self._event_number[key] = 0 # # def event_types(self): # return self._events.keys() # # def event_times(self, event_type): # """Return the times of the specified event type""" # return self._events[event_type] # # def next_event_time(self, event_type=None): # """Time of next event. # # If no event type is specified, the next event of any time is returned # """ # if event_type is not None: # return self._next_event_time(event_type) # else: # # All events: # t_next = np.inf # for event in self._events: # t_next = min(t_next, self._next_event_time(event)) # return t_next # # def _next_event_time(self, event): # try: # return self._events[event][0] # except IndexError: # return np.inf # # def next_event(self): # """The type of the next event""" # t_next = self.next_event_time() # for event in self._events: # if self._next_event_time(event) == t_next: # return event # return None # # def check_event(self, t, event): # """Has the next occurance of a specified event occured?""" # try: # return self._events[event][0] <= t # except IndexError: # return False # # def events_passed(self, t): # """Returns a list of event types that have passed since last pop""" # return [ e for e in self._events if self.check_event(t, e) ] # # def event_number(self, key): # """The number of times the specified event has occurred""" # return self._event_number[key] # # def pop_events(self, t, event_type=None): # """Remove events that have passed. # # If no event type is specified, pop all event types # """ # if event_type is not None: # self._pop(t, event_type) # else: # for event in self._events: # self._pop(t, event) # # def _pop(self, t, event): # try: # while self.check_event(t, event): # self._events[event].pop(0) # self._event_number[event] += 1 # except IndexError: # pass # # def finished(self): # """Returns True all events have been popped""" # for event in self._events: # if len(self._events[event]) > 0: # return False # else: # return True . Output only the next line.
EC = Event_Controller(evens=t0, threes=t1)
Predict the next line for this snippet: <|code_start|> def read(self, filename): """Read disc data from file""" # read the header head = '' vars = False count = 0 with open(filename) as f: for line in f: if not vars: if not line.startswith('# time'): head += line else: vars = True # Get the time self._t = float(line.strip().split(':')[1][:-2]) count += 1 continue # Get data variables stored vars = line[2:].split(' ') assert(len(vars) % 2 == 0) # Get the number of dust species Nchem = (len(vars) - 4) / 2 iChem = 4 chem_spec = vars[iChem:iChem + Nchem] break # Parse the actual data: data = np.genfromtxt(filename, skip_header=count, names=True) <|code_end|> with the help of current file imports: import sys, os import re import numpy as np import DiscEvolution.chemistry as chem from DiscEvolution.planet_formation import Planets and context from other files: # Path: DiscEvolution/planet_formation.py # class Planets(object): # """Data for growing planets. # # Holds the location, core & envelope mass, and composition of growing # planets. # # args: # Nchem : number of chemical species to track, default = None # """ # def __init__(self, Nchem=None): # self.R = np.array([], dtype='f4') # self.M_core = np.array([], dtype='f4') # self.M_env = np.array([], dtype='f4') # self.t_form = np.array([], dtype='f4') # # self._N = 0 # # if Nchem: # self.X_core = np.array([[] for _ in range(Nchem)], dtype='f4') # self.X_env = np.array([[] for _ in range(Nchem)], dtype='f4') # else: # self.X_core = None # self.X_env = None # self._Nchem = Nchem # # def add_planet(self, t, R, Mcore, Menv, X_core=None, X_env=None): # """Add a new planet""" # if self._Nchem: # self.X_core = np.c_[self.X_core, X_core] # self.X_env = np.c_[self.X_env, X_env] # # self.R = np.append(self.R, R) # self.M_core = np.append(self.M_core, Mcore) # self.M_env = np.append(self.M_env, Menv) # # self.t_form = np.append(self.t_form, np.ones_like(Menv)*t) # # self._N += 1 # # def append(self, planets): # """Add a list of planets from another planet object""" # self.add_planet(planets.t_form, planets.R, # planets.M_core, planets.M_env, # planets.X_core, planets.X_env) # # @property # def M(self): # return self.M_core + self.M_env # # @property # def N(self): # """Number of planets""" # return self._N # # @property # def chem(self): # return self._Nchem > 0 # # def __getitem__(self, idx): # """Get a sub-set of the planets""" # sub = Planets(self._Nchem) # # sub.R = self.R[idx] # sub.M_core = self.M_core[idx] # sub.M_env = self.M_env[idx] # sub.t_form = self.t_form[idx] # if self.chem: # sub.X_core = self.X_core[...,idx] # sub.X_env = self.X_env[...,idx] # # try: # sub._N = len(sub.R) # except TypeError: # sub._N = 1 # # return sub # # def __iter__(self): # for i in range(self.N): # yield self[i] , which may contain function names, class names, or code. Output only the next line.
planets = Planets(Nchem)
Given snippet: <|code_start|> f_max : maximum accretion rate relative to disc accretion rate, default=0.8 Piso & Youdin parameters: f_py : accretion rate fitting factor, default=0.2 kappa_env : envelope opacity [cm^2/g], default=0.06 rho_core : core density [g cm^-3], default=5.5 """ def __init__(self, disc, f_max=0.8, f_py=0.2, kappa_env=0.05, rho_core=5.5): # General properties self._fmax = f_max self._disc = disc # Piso & Youdin parameters self._fPiso = 0.1 * 1.75e-3 / f_py**2 self._fPiso /= kappa_env * (rho_core/5.5)**(1/6.) # Convert Mearth / M_yr to M_E Omega0**-1 self._fPiso *= 1e-6 / (2*np.pi) head = {"f_max" : "{}".format(f_max), "f_py" : "{}".format(f_py), "kappa_env" : "{} cm^2 g^-1".format(kappa_env), "rho_core" : "{} g cm^-1".format(rho_core), } self._head = (self.__class__.__name__, head) def ASCII_header(self): """Get header details""" <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import InterpolatedUnivariateSpline as ispline from scipy.interpolate import UnivariateSpline as spline from scipy.integrate import ode from .constants import * from .disc_utils import make_ASCII_header from .eos import LocallyIsothermalEOS, IrradiatedEOS from .star import SimpleStar from .grid import Grid from .dust import FixedSizeDust and context: # Path: DiscEvolution/disc_utils.py # def make_ASCII_header(HDF5_attributes): # """Generates header in ASCII format from the HDF5 format.""" # # Class name # head = "# {}".format(HDF5_attributes[0]) # # # Add dictionary of attributes # def make_item(item): # key, value = item # return "{}: {}".format(key, value) # # return head + ", ".join(map(make_item, HDF5_attributes[1].items())) which might include code, classes, or functions. Output only the next line.
return make_ASCII_header(self.HDF5_attributes())
Based on the snippet: <|code_start|> self._Mdot_ext = restartdata['M_ext'] except ValueError: pass try: self._Mdot_int = restartdata['M_int'] except ValueError: pass try: self._Mcum_gas = restartdata['M_wg'] except ValueError: pass # Dust-Only Parameters if self._dust: for threshold in self._dthresholds: try: self._Rdust[threshold] = restartdata['R_{}'.format(int(float(threshold)*100))] except ValueError: pass try: self._Mdust = restartdata['M_d'] except ValueError: pass try: self._Mcum_dust = restartdata['M_wd'] except ValueError: pass """Call""" def __call__(self, driver): <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from .constants import yr and context (classes, functions, sometimes code) from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 . Output only the next line.
self._times = np.append(self._times,[driver.t / yr])
Here is a snippet: <|code_start|># star.py # # Author: R. Booth # Date: 8 - Nov - 2016 # # Contains stellar properties classes ################################################################################ # Base class for all stars, implements general properties that should be # common to all stars class StarBase(object): """Wrapper class for stellar properties. args: M : mass, Msun. default = 1 R : radius, Rsun. default = 1 T_eff : effective temperature, K. default = 5770 age : Stellar age, yr. default = 0 """ def __init__(self, M=1,R=1,T_eff=5770, age=0): self._M = M self._Rs = R <|code_end|> . Write the next line using the current file imports: import numpy as np from .constants import Msun, Rsun, AU and context from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 , which may include functions, classes, or code. Output only the next line.
self._Rau = R*Rsun/AU
Next line prediction: <|code_start|># star.py # # Author: R. Booth # Date: 8 - Nov - 2016 # # Contains stellar properties classes ################################################################################ # Base class for all stars, implements general properties that should be # common to all stars class StarBase(object): """Wrapper class for stellar properties. args: M : mass, Msun. default = 1 R : radius, Rsun. default = 1 T_eff : effective temperature, K. default = 5770 age : Stellar age, yr. default = 0 """ def __init__(self, M=1,R=1,T_eff=5770, age=0): self._M = M self._Rs = R <|code_end|> . Use current file imports: (import numpy as np from .constants import Msun, Rsun, AU) and context including class names, function names, or small code snippets from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 . Output only the next line.
self._Rau = R*Rsun/AU
Based on the snippet: <|code_start|> sys.path.append(KROME_PATH) except KeyError: raise ImportError("krome_chem module requires KROME_PATH environment " "variable to be set") # Alias for ctypes by reference def byref(x): return ctypes.byref(ctypes.c_double(x)) # Setup the KROME Library _krome = PyKROME(path_to_lib=KROME_PATH) _krome.lib.krome_init() # Here we setup the species loaded from KROME. # Note: # - KROME distinguishes between gas and ice phase species through the "_DUST" # tail on the names, so we use that to seperate the phases. # - KROME does not explicitly include refractory dust, so we add that those # to the end of the array. For now we hard code a single dust species. # Number of species _nmols = _krome.krome_nmols _ngrain = 1 # Load the names / masses from the KROME library and convert mass to internal # units (Hydrogen masses) _krome_names = np.array(_krome.krome_names[:_nmols]) _krome_masses = np.empty(_nmols, dtype='f8') _krome.lib.krome_get_mass(_krome_masses) <|code_end|> , predict the immediate next line with the help of imports: from ..constants import m_H from multiprocessing import Pool from .base_chem import ChemicalAbund from pykrome import PyKROME from ..eos import LocallyIsothermalEOS from ..star import SimpleStar from ..grid import Grid from ..constants import Msun, AU import sys, os import numpy as np import ctypes import matplotlib.pyplot as plt import time and context (classes, functions, sometimes code) from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 # # Path: DiscEvolution/chemistry/base_chem.py # class ChemicalAbund(object): # """Simple wrapper class to hold chemical species data. # # Holds the mass abundance (g) of the chemical species relative to Hydrogen. # # args: # species : list, maps species name to location in data array # masses : array, molecular masses in atomic mass units # size : Number of data points to hold chemistry for # """ # def __init__(self, species, masses,*sizes): # # Sizes is dimension zero if not specified # sizes = sizes if sizes else (0,) # if len(masses) != len(species): # raise AttributeError("Number of masses must match the number of" # "species") # # self._indexes = dict([(name, i) for i, name in enumerate(species)]) # self._names = species # self._mass = masses # self._Nspec = len(self._names) # # self._data = np.zeros((self.Nspec,) + sizes, dtype='f8') # # def __getitem__(self, k): # return self._data[self._indexes[k]] # # def __setitem__(self, k, val): # self._data[self._indexes[k]] = val # # def __iadd__(self, other): # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data += other._data # return self # # def __iter__(self): # return iter(self._names) # # def copy(self): # return copy.deepcopy(self) # # def number_abund(self, k): # """Number abundance of species k, n_k= rho_k / m_k""" # return self[k]/self.mass(k) # # @property # def total_abund(self): # return self._data.sum(0) # # def set_number_abund(self, k, n_k): # """Set the mass abundance from the number abundance""" # self[k] = n_k * self.mass(k) # # def to_array(self): # """Get the raw data""" # return self.data # # def from_array(self, data): # """Set the raw data""" # if data.shape[0] == self.Nspec: # raise AttributeError("Error: shape must be [Nspec, *]") # self._data = data # # #def resize(self, n): # # '''Resize the data array, keeping any elements that we already have''' # # dn = n - self.size # # if dn < 0: # # self._data = self._data[:,:n].copy() # # else: # # self._data = np.concatenate([self._data, # # np.empty([self.Nspec,dn],dtype='f8')]) # def resize(self, shape): # '''Resize the data array, keeping any elements that we already have''' # try: # shape = (self.Nspec, ) + tuple(shape) # except TypeError: # if type(shape) != type(1): # raise TypeError("shape must be int, or array of int") # shape = (self.Nspec, shape) # # new_data = np.zeros(shape, dtype='f8') # # idx = [ slice(0, min(ni)) for ni in zip(shape, self._data.shape)] # # # Copy accross the old data # new_data[idx] = self._data[idx] # # self._data = new_data # # def append(self, other): # """Append chemistry data from another container""" # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data = np.append(self._data, other.data) # # def mass(self, k): # """Mass of species in atomic mass units""" # return self._mass[self._indexes[k]] # # def mu(self): # '''Mean molecular weight''' # return self._data.sum(0) / (self._data.T / self._mass).sum(1) # # @property # def masses(self): # """Masses of all species in amu""" # return self._mass # # @property # def names(self): # """Names of the species in order""" # return self._names # # @property # def Nspec(self): # return self._Nspec # # @property # def species(self): # """Names of the chemical species held.""" # return self._indexes.keys() # # @property # def data(self): # return self._data # # @property # def size(self): # return self._data.shape[1] . Output only the next line.
_krome_masses /= m_H
Predict the next line for this snippet: <|code_start|># Load the names / masses from the KROME library and convert mass to internal # units (Hydrogen masses) _krome_names = np.array(_krome.krome_names[:_nmols]) _krome_masses = np.empty(_nmols, dtype='f8') _krome.lib.krome_get_mass(_krome_masses) _krome_masses /= m_H #if "M" in _krome_names: # _krome_masses[_krome_names == "M"] = 1.0 # Add grains to the end of the names, with an arbitrary mass _krome_names = np.append(_krome_names, "grain") _krome_masses = np.append(_krome_masses, 100.) # Seperate solid / gas species def is_solid(species): return species.endswith("_DUST") or species.endswith("grain") def to_ice_name(species): if species.endswith("_DUST"): return species[:-5] elif species.endswith("grain"): return species else: raise ValueError("Expect name ending in '_DUST' or 'grain'") _krome_ice = np.array([is_solid(n) for n in _krome_names]) _krome_gas = ~_krome_ice _krome_ice_names = np.array([to_ice_name(n) for n in _krome_names[_krome_ice]]) <|code_end|> with the help of current file imports: from ..constants import m_H from multiprocessing import Pool from .base_chem import ChemicalAbund from pykrome import PyKROME from ..eos import LocallyIsothermalEOS from ..star import SimpleStar from ..grid import Grid from ..constants import Msun, AU import sys, os import numpy as np import ctypes import matplotlib.pyplot as plt import time and context from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 # # Path: DiscEvolution/chemistry/base_chem.py # class ChemicalAbund(object): # """Simple wrapper class to hold chemical species data. # # Holds the mass abundance (g) of the chemical species relative to Hydrogen. # # args: # species : list, maps species name to location in data array # masses : array, molecular masses in atomic mass units # size : Number of data points to hold chemistry for # """ # def __init__(self, species, masses,*sizes): # # Sizes is dimension zero if not specified # sizes = sizes if sizes else (0,) # if len(masses) != len(species): # raise AttributeError("Number of masses must match the number of" # "species") # # self._indexes = dict([(name, i) for i, name in enumerate(species)]) # self._names = species # self._mass = masses # self._Nspec = len(self._names) # # self._data = np.zeros((self.Nspec,) + sizes, dtype='f8') # # def __getitem__(self, k): # return self._data[self._indexes[k]] # # def __setitem__(self, k, val): # self._data[self._indexes[k]] = val # # def __iadd__(self, other): # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data += other._data # return self # # def __iter__(self): # return iter(self._names) # # def copy(self): # return copy.deepcopy(self) # # def number_abund(self, k): # """Number abundance of species k, n_k= rho_k / m_k""" # return self[k]/self.mass(k) # # @property # def total_abund(self): # return self._data.sum(0) # # def set_number_abund(self, k, n_k): # """Set the mass abundance from the number abundance""" # self[k] = n_k * self.mass(k) # # def to_array(self): # """Get the raw data""" # return self.data # # def from_array(self, data): # """Set the raw data""" # if data.shape[0] == self.Nspec: # raise AttributeError("Error: shape must be [Nspec, *]") # self._data = data # # #def resize(self, n): # # '''Resize the data array, keeping any elements that we already have''' # # dn = n - self.size # # if dn < 0: # # self._data = self._data[:,:n].copy() # # else: # # self._data = np.concatenate([self._data, # # np.empty([self.Nspec,dn],dtype='f8')]) # def resize(self, shape): # '''Resize the data array, keeping any elements that we already have''' # try: # shape = (self.Nspec, ) + tuple(shape) # except TypeError: # if type(shape) != type(1): # raise TypeError("shape must be int, or array of int") # shape = (self.Nspec, shape) # # new_data = np.zeros(shape, dtype='f8') # # idx = [ slice(0, min(ni)) for ni in zip(shape, self._data.shape)] # # # Copy accross the old data # new_data[idx] = self._data[idx] # # self._data = new_data # # def append(self, other): # """Append chemistry data from another container""" # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data = np.append(self._data, other.data) # # def mass(self, k): # """Mass of species in atomic mass units""" # return self._mass[self._indexes[k]] # # def mu(self): # '''Mean molecular weight''' # return self._data.sum(0) / (self._data.T / self._mass).sum(1) # # @property # def masses(self): # """Masses of all species in amu""" # return self._mass # # @property # def names(self): # """Names of the species in order""" # return self._names # # @property # def Nspec(self): # return self._Nspec # # @property # def species(self): # """Names of the chemical species held.""" # return self._indexes.keys() # # @property # def data(self): # return self._data # # @property # def size(self): # return self._data.shape[1] , which may contain function names, class names, or code. Output only the next line.
class KromeAbund(ChemicalAbund):
Predict the next line for this snippet: <|code_start|># # Check behaviour of simple chemistry functions ############################################################################### # CO chemistry # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]: <|code_end|> with the help of current file imports: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) , which may contain function names, class names, or code. Output only the next line.
_test_chemical_model(Chem, SimpleCOAtomAbund)
Given the following code snippet before the placeholder: <|code_start|># Author: R. Booth # Date: 22 - May - 2018 # # Check behaviour of simple chemistry functions ############################################################################### # CO chemistry # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): <|code_end|> , predict the next line using imports from the current file: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context including class names, function names, and sometimes code from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg,
Continue the code snippet: <|code_start|># Date: 22 - May - 2018 # # Check behaviour of simple chemistry functions ############################################################################### # CO chemistry # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, <|code_end|> . Use current file imports: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (classes, functions, or code) from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]:
Using the snippet: <|code_start|># Author: R. Booth # Date: 22 - May - 2018 # # Check behaviour of simple chemistry functions ############################################################################### # CO chemistry # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): <|code_end|> , determine the next line of code. You have imports: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (class names, function names, or code) available: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg,
Given the code snippet: <|code_start|># Date: 22 - May - 2018 # # Check behaviour of simple chemistry functions ############################################################################### # CO chemistry # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, <|code_end|> , generate the next line using the imports in this file: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (functions, classes, or occasionally code) from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]:
Given the code snippet: <|code_start|># CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]: _test_chemical_model(Chem, SimpleCOAtomAbund) def test_CNO_chemistry(): for Chem in [ SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg,]: <|code_end|> , generate the next line using the imports in this file: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (functions, classes, or occasionally code) from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
_test_chemical_model(Chem, SimpleCNOAtomAbund)
Using the snippet: <|code_start|># CO chemistry # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]: _test_chemical_model(Chem, SimpleCOAtomAbund) def test_CNO_chemistry(): <|code_end|> , determine the next line of code. You have imports: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (class names, function names, or code) available: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
for Chem in [ SimpleCNOChemMadhu, SimpleCNOChemOberg,
Based on the snippet: <|code_start|> # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]: _test_chemical_model(Chem, SimpleCOAtomAbund) def test_CNO_chemistry(): for Chem in [ SimpleCNOChemMadhu, SimpleCNOChemOberg, <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (classes, functions, sometimes code) from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg,]:
Continue the code snippet: <|code_start|># CO chemistry # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]: _test_chemical_model(Chem, SimpleCOAtomAbund) def test_CNO_chemistry(): <|code_end|> . Use current file imports: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (classes, functions, or code) from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
for Chem in [ SimpleCNOChemMadhu, SimpleCNOChemOberg,
Continue the code snippet: <|code_start|> # CNO chemistry def _test_chemical_model(ChemModel, Abundances): T = np.logspace(0.5, 3, 6) Xi = Abundances(len(T)) Xi.set_solar_abundances() Chem = ChemModel() mol = Chem.equilibrium_chem(T, 1e-10, 0.01, Xi) T *= 3 Chem.update(0, T, 1e-10, 0.01, mol) atom = mol.gas.atomic_abundance() atom += mol.ice.atomic_abundance() for X in atom: assert(np.allclose(Xi[X], atom[X], rtol=1e-12)) def test_CO_chemistry(): for Chem in [ SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg,]: _test_chemical_model(Chem, SimpleCOAtomAbund) def test_CNO_chemistry(): for Chem in [ SimpleCNOChemMadhu, SimpleCNOChemOberg, <|code_end|> . Use current file imports: import numpy as np from DiscEvolution.chemistry import ( SimpleCOAtomAbund, SimpleCOChemMadhu, SimpleCOChemOberg, EquilibriumCOChemMadhu, EquilibriumCOChemOberg ) from DiscEvolution.chemistry import ( SimpleCNOAtomAbund, SimpleCNOChemMadhu, SimpleCNOChemOberg, EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg ) and context (classes, functions, or code) from other files: # Path: DiscEvolution/chemistry/CO_chem.py # class SimpleCOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CO chemistry""" # def __init__(self, *sizes): # atom_ids = ['C', 'O', 'Si'] # masses = [ 12., 16., 28. ] # # super(SimpleCOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # self._data[:] = np.outer(np.array([12*2.7e-4, 16*4.9e-4, 28*3.2e-5]), # np.ones(self.size)) / muH # # class SimpleCOChemOberg(COChemOberg, StaticChem): # def __init__(self, **kwargs): # COChemOberg.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemOberg(COChemOberg, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemOberg.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCOChemMadhu(COChemMadhu, StaticChem): # def __init__(self, **kwargs): # COChemMadhu.__init__(self) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCOChemMadhu(COChemMadhu, EquilibriumChem): # def __init__(self, fix_ratios=False, fix_grains=True, **kwargs): # COChemMadhu.__init__(self, fix_grains) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # Path: DiscEvolution/chemistry/CNO_chem.py # class SimpleCNOAtomAbund(ChemicalAbund): # """Class to hold the raw atomic abundaces of C/O/Si for the CNO chemistry""" # # def __init__(self, *sizes): # atom_ids = ['C', 'N', 'O', 'Si'] # masses = [12., 14., 16., 28.] # # super(SimpleCNOAtomAbund, self).__init__(atom_ids, masses, *sizes) # # def set_solar_abundances(self, muH=1.28): # """Solar mass fractions of C, O and Si. # # args: # muH : mean atomic mass, default = 1.28 # """ # m_abund = np.array([12 * 2.7e-4, 14 * 6.8e-5, 16 * 4.9e-4, 28 * 3.2e-5]) # self._data[:] = np.outer(m_abund, np.ones(self.size)) / muH # # class SimpleCNOChemOberg(CNOChemOberg, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemOberg.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemOberg(CNOChemOberg, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemOberg.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) # # class SimpleCNOChemMadhu(CNOChemMadhu, StaticChem): # def __init__(self, fNH3=None, **kwargs): # CNOChemMadhu.__init__(self, fNH3) # StaticChem.__init__(self, **kwargs) # # class EquilibriumCNOChemMadhu(CNOChemMadhu, EquilibriumChem): # def __init__(self, fNH3=None, fix_ratios=False, fix_grains=True, # fix_N=False, **kwargs): # CNOChemMadhu.__init__(self, fNH3, fix_grains, fix_N) # EquilibriumChem.__init__(self, # fix_ratios=fix_ratios, # **kwargs) . Output only the next line.
EquilibriumCNOChemMadhu, EquilibriumCNOChemOberg,]:
Based on the snippet: <|code_start|> __all__ = [ "atomic_mass", "molecular_mass", "atomic_composition", "atomic_abundances" ] ATOMIC_MASSES = { <|code_end|> , predict the immediate next line with the help of imports: from collections import defaultdict from ..constants import m_H, m_n, m_e from .base_chem import ChemicalAbund import re import numpy as np and context (classes, functions, sometimes code) from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 # # Path: DiscEvolution/chemistry/base_chem.py # class ChemicalAbund(object): # """Simple wrapper class to hold chemical species data. # # Holds the mass abundance (g) of the chemical species relative to Hydrogen. # # args: # species : list, maps species name to location in data array # masses : array, molecular masses in atomic mass units # size : Number of data points to hold chemistry for # """ # def __init__(self, species, masses,*sizes): # # Sizes is dimension zero if not specified # sizes = sizes if sizes else (0,) # if len(masses) != len(species): # raise AttributeError("Number of masses must match the number of" # "species") # # self._indexes = dict([(name, i) for i, name in enumerate(species)]) # self._names = species # self._mass = masses # self._Nspec = len(self._names) # # self._data = np.zeros((self.Nspec,) + sizes, dtype='f8') # # def __getitem__(self, k): # return self._data[self._indexes[k]] # # def __setitem__(self, k, val): # self._data[self._indexes[k]] = val # # def __iadd__(self, other): # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data += other._data # return self # # def __iter__(self): # return iter(self._names) # # def copy(self): # return copy.deepcopy(self) # # def number_abund(self, k): # """Number abundance of species k, n_k= rho_k / m_k""" # return self[k]/self.mass(k) # # @property # def total_abund(self): # return self._data.sum(0) # # def set_number_abund(self, k, n_k): # """Set the mass abundance from the number abundance""" # self[k] = n_k * self.mass(k) # # def to_array(self): # """Get the raw data""" # return self.data # # def from_array(self, data): # """Set the raw data""" # if data.shape[0] == self.Nspec: # raise AttributeError("Error: shape must be [Nspec, *]") # self._data = data # # #def resize(self, n): # # '''Resize the data array, keeping any elements that we already have''' # # dn = n - self.size # # if dn < 0: # # self._data = self._data[:,:n].copy() # # else: # # self._data = np.concatenate([self._data, # # np.empty([self.Nspec,dn],dtype='f8')]) # def resize(self, shape): # '''Resize the data array, keeping any elements that we already have''' # try: # shape = (self.Nspec, ) + tuple(shape) # except TypeError: # if type(shape) != type(1): # raise TypeError("shape must be int, or array of int") # shape = (self.Nspec, shape) # # new_data = np.zeros(shape, dtype='f8') # # idx = [ slice(0, min(ni)) for ni in zip(shape, self._data.shape)] # # # Copy accross the old data # new_data[idx] = self._data[idx] # # self._data = new_data # # def append(self, other): # """Append chemistry data from another container""" # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data = np.append(self._data, other.data) # # def mass(self, k): # """Mass of species in atomic mass units""" # return self._mass[self._indexes[k]] # # def mu(self): # '''Mean molecular weight''' # return self._data.sum(0) / (self._data.T / self._mass).sum(1) # # @property # def masses(self): # """Masses of all species in amu""" # return self._mass # # @property # def names(self): # """Names of the species in order""" # return self._names # # @property # def Nspec(self): # return self._Nspec # # @property # def species(self): # """Names of the chemical species held.""" # return self._indexes.keys() # # @property # def data(self): # return self._data # # @property # def size(self): # return self._data.shape[1] . Output only the next line.
'H' : m_H, 'He' : 2*(m_H + m_n),
Using the snippet: <|code_start|> __all__ = [ "atomic_mass", "molecular_mass", "atomic_composition", "atomic_abundances" ] ATOMIC_MASSES = { <|code_end|> , determine the next line of code. You have imports: from collections import defaultdict from ..constants import m_H, m_n, m_e from .base_chem import ChemicalAbund import re import numpy as np and context (class names, function names, or code) available: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 # # Path: DiscEvolution/chemistry/base_chem.py # class ChemicalAbund(object): # """Simple wrapper class to hold chemical species data. # # Holds the mass abundance (g) of the chemical species relative to Hydrogen. # # args: # species : list, maps species name to location in data array # masses : array, molecular masses in atomic mass units # size : Number of data points to hold chemistry for # """ # def __init__(self, species, masses,*sizes): # # Sizes is dimension zero if not specified # sizes = sizes if sizes else (0,) # if len(masses) != len(species): # raise AttributeError("Number of masses must match the number of" # "species") # # self._indexes = dict([(name, i) for i, name in enumerate(species)]) # self._names = species # self._mass = masses # self._Nspec = len(self._names) # # self._data = np.zeros((self.Nspec,) + sizes, dtype='f8') # # def __getitem__(self, k): # return self._data[self._indexes[k]] # # def __setitem__(self, k, val): # self._data[self._indexes[k]] = val # # def __iadd__(self, other): # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data += other._data # return self # # def __iter__(self): # return iter(self._names) # # def copy(self): # return copy.deepcopy(self) # # def number_abund(self, k): # """Number abundance of species k, n_k= rho_k / m_k""" # return self[k]/self.mass(k) # # @property # def total_abund(self): # return self._data.sum(0) # # def set_number_abund(self, k, n_k): # """Set the mass abundance from the number abundance""" # self[k] = n_k * self.mass(k) # # def to_array(self): # """Get the raw data""" # return self.data # # def from_array(self, data): # """Set the raw data""" # if data.shape[0] == self.Nspec: # raise AttributeError("Error: shape must be [Nspec, *]") # self._data = data # # #def resize(self, n): # # '''Resize the data array, keeping any elements that we already have''' # # dn = n - self.size # # if dn < 0: # # self._data = self._data[:,:n].copy() # # else: # # self._data = np.concatenate([self._data, # # np.empty([self.Nspec,dn],dtype='f8')]) # def resize(self, shape): # '''Resize the data array, keeping any elements that we already have''' # try: # shape = (self.Nspec, ) + tuple(shape) # except TypeError: # if type(shape) != type(1): # raise TypeError("shape must be int, or array of int") # shape = (self.Nspec, shape) # # new_data = np.zeros(shape, dtype='f8') # # idx = [ slice(0, min(ni)) for ni in zip(shape, self._data.shape)] # # # Copy accross the old data # new_data[idx] = self._data[idx] # # self._data = new_data # # def append(self, other): # """Append chemistry data from another container""" # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data = np.append(self._data, other.data) # # def mass(self, k): # """Mass of species in atomic mass units""" # return self._mass[self._indexes[k]] # # def mu(self): # '''Mean molecular weight''' # return self._data.sum(0) / (self._data.T / self._mass).sum(1) # # @property # def masses(self): # """Masses of all species in amu""" # return self._mass # # @property # def names(self): # """Names of the species in order""" # return self._names # # @property # def Nspec(self): # return self._Nspec # # @property # def species(self): # """Names of the chemical species held.""" # return self._indexes.keys() # # @property # def data(self): # return self._data # # @property # def size(self): # return self._data.shape[1] . Output only the next line.
'H' : m_H, 'He' : 2*(m_H + m_n),
Given the following code snippet before the placeholder: <|code_start|> __all__ = [ "atomic_mass", "molecular_mass", "atomic_composition", "atomic_abundances" ] ATOMIC_MASSES = { 'H' : m_H, 'He' : 2*(m_H + m_n), 'C' : 6*(m_H + m_n), 'N' : 7*(m_H + m_n), 'O' : 8*(m_H + m_n), 'Ne' : 10*(m_H + m_n), 'Na' : 11*m_H + 12*m_n, 'Mg' : 12*(m_H + m_n), 'Al' : 13*m_H + 14*m_n, 'Si' : 14*(m_H + m_n), 'P' : 15*m_H + 16*m_n, 'S' : 16*(m_H + m_n), 'Cl' : 17*m_H + 18*m_n, 'Ar' : 18*(m_H + m_n), 'K' : 19*m_H + 20*m_n, 'Ca' : 20*(m_H + m_n), 'Fe' : 26*m_H + 29*m_n, } def atomic_mass(atom): '''Mass of the atom in hydrogen masses''' if atom == 'E': <|code_end|> , predict the next line using imports from the current file: from collections import defaultdict from ..constants import m_H, m_n, m_e from .base_chem import ChemicalAbund import re import numpy as np and context including class names, function names, and sometimes code from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 # # Path: DiscEvolution/chemistry/base_chem.py # class ChemicalAbund(object): # """Simple wrapper class to hold chemical species data. # # Holds the mass abundance (g) of the chemical species relative to Hydrogen. # # args: # species : list, maps species name to location in data array # masses : array, molecular masses in atomic mass units # size : Number of data points to hold chemistry for # """ # def __init__(self, species, masses,*sizes): # # Sizes is dimension zero if not specified # sizes = sizes if sizes else (0,) # if len(masses) != len(species): # raise AttributeError("Number of masses must match the number of" # "species") # # self._indexes = dict([(name, i) for i, name in enumerate(species)]) # self._names = species # self._mass = masses # self._Nspec = len(self._names) # # self._data = np.zeros((self.Nspec,) + sizes, dtype='f8') # # def __getitem__(self, k): # return self._data[self._indexes[k]] # # def __setitem__(self, k, val): # self._data[self._indexes[k]] = val # # def __iadd__(self, other): # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data += other._data # return self # # def __iter__(self): # return iter(self._names) # # def copy(self): # return copy.deepcopy(self) # # def number_abund(self, k): # """Number abundance of species k, n_k= rho_k / m_k""" # return self[k]/self.mass(k) # # @property # def total_abund(self): # return self._data.sum(0) # # def set_number_abund(self, k, n_k): # """Set the mass abundance from the number abundance""" # self[k] = n_k * self.mass(k) # # def to_array(self): # """Get the raw data""" # return self.data # # def from_array(self, data): # """Set the raw data""" # if data.shape[0] == self.Nspec: # raise AttributeError("Error: shape must be [Nspec, *]") # self._data = data # # #def resize(self, n): # # '''Resize the data array, keeping any elements that we already have''' # # dn = n - self.size # # if dn < 0: # # self._data = self._data[:,:n].copy() # # else: # # self._data = np.concatenate([self._data, # # np.empty([self.Nspec,dn],dtype='f8')]) # def resize(self, shape): # '''Resize the data array, keeping any elements that we already have''' # try: # shape = (self.Nspec, ) + tuple(shape) # except TypeError: # if type(shape) != type(1): # raise TypeError("shape must be int, or array of int") # shape = (self.Nspec, shape) # # new_data = np.zeros(shape, dtype='f8') # # idx = [ slice(0, min(ni)) for ni in zip(shape, self._data.shape)] # # # Copy accross the old data # new_data[idx] = self._data[idx] # # self._data = new_data # # def append(self, other): # """Append chemistry data from another container""" # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data = np.append(self._data, other.data) # # def mass(self, k): # """Mass of species in atomic mass units""" # return self._mass[self._indexes[k]] # # def mu(self): # '''Mean molecular weight''' # return self._data.sum(0) / (self._data.T / self._mass).sum(1) # # @property # def masses(self): # """Masses of all species in amu""" # return self._mass # # @property # def names(self): # """Names of the species in order""" # return self._names # # @property # def Nspec(self): # return self._Nspec # # @property # def species(self): # """Names of the chemical species held.""" # return self._indexes.keys() # # @property # def data(self): # return self._data # # @property # def size(self): # return self._data.shape[1] . Output only the next line.
return m_e / m_H
Given the following code snippet before the placeholder: <|code_start|> Whether to track the net charge, i.e. the abundance of electrons ignore_grains : bool, optional Whether to ignore the contribution from dust species. returns: atom_abund : ChemicalAbund object Abundance of the constituent atomic species """ # Break down each molecule into atoms atoms = {} for mol in mol_abund.species: if mol.endswith('grain') and ignore_grains: continue composition = atomic_composition(mol, charge) for atom, count in composition.items(): nmol = mol_abund.number_abund(mol) if atom not in atoms: atoms[atom] = np.zeros_like(nmol) atoms[atom] += nmol * count # Rename charge to E: try: atoms['E'] = -atoms['charge'] del atoms['charge'] except KeyError: pass # Create the ChemicalAbund object species = np.array(list(atoms.keys())) masses = np.array([atomic_mass(s) for s in species]) <|code_end|> , predict the next line using imports from the current file: from collections import defaultdict from ..constants import m_H, m_n, m_e from .base_chem import ChemicalAbund import re import numpy as np and context including class names, function names, and sometimes code from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 # # Path: DiscEvolution/chemistry/base_chem.py # class ChemicalAbund(object): # """Simple wrapper class to hold chemical species data. # # Holds the mass abundance (g) of the chemical species relative to Hydrogen. # # args: # species : list, maps species name to location in data array # masses : array, molecular masses in atomic mass units # size : Number of data points to hold chemistry for # """ # def __init__(self, species, masses,*sizes): # # Sizes is dimension zero if not specified # sizes = sizes if sizes else (0,) # if len(masses) != len(species): # raise AttributeError("Number of masses must match the number of" # "species") # # self._indexes = dict([(name, i) for i, name in enumerate(species)]) # self._names = species # self._mass = masses # self._Nspec = len(self._names) # # self._data = np.zeros((self.Nspec,) + sizes, dtype='f8') # # def __getitem__(self, k): # return self._data[self._indexes[k]] # # def __setitem__(self, k, val): # self._data[self._indexes[k]] = val # # def __iadd__(self, other): # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data += other._data # return self # # def __iter__(self): # return iter(self._names) # # def copy(self): # return copy.deepcopy(self) # # def number_abund(self, k): # """Number abundance of species k, n_k= rho_k / m_k""" # return self[k]/self.mass(k) # # @property # def total_abund(self): # return self._data.sum(0) # # def set_number_abund(self, k, n_k): # """Set the mass abundance from the number abundance""" # self[k] = n_k * self.mass(k) # # def to_array(self): # """Get the raw data""" # return self.data # # def from_array(self, data): # """Set the raw data""" # if data.shape[0] == self.Nspec: # raise AttributeError("Error: shape must be [Nspec, *]") # self._data = data # # #def resize(self, n): # # '''Resize the data array, keeping any elements that we already have''' # # dn = n - self.size # # if dn < 0: # # self._data = self._data[:,:n].copy() # # else: # # self._data = np.concatenate([self._data, # # np.empty([self.Nspec,dn],dtype='f8')]) # def resize(self, shape): # '''Resize the data array, keeping any elements that we already have''' # try: # shape = (self.Nspec, ) + tuple(shape) # except TypeError: # if type(shape) != type(1): # raise TypeError("shape must be int, or array of int") # shape = (self.Nspec, shape) # # new_data = np.zeros(shape, dtype='f8') # # idx = [ slice(0, min(ni)) for ni in zip(shape, self._data.shape)] # # # Copy accross the old data # new_data[idx] = self._data[idx] # # self._data = new_data # # def append(self, other): # """Append chemistry data from another container""" # if self.names != other.names: # raise AttributeError("Chemical species must be the same") # # self._data = np.append(self._data, other.data) # # def mass(self, k): # """Mass of species in atomic mass units""" # return self._mass[self._indexes[k]] # # def mu(self): # '''Mean molecular weight''' # return self._data.sum(0) / (self._data.T / self._mass).sum(1) # # @property # def masses(self): # """Masses of all species in amu""" # return self._mass # # @property # def names(self): # """Names of the species in order""" # return self._names # # @property # def Nspec(self): # return self._Nspec # # @property # def species(self): # """Names of the chemical species held.""" # return self._indexes.keys() # # @property # def data(self): # return self._data # # @property # def size(self): # return self._data.shape[1] . Output only the next line.
atom_abund = ChemicalAbund(species, masses, len(atoms[species[0]]))
Based on the snippet: <|code_start|> @property def T(self): """Temperature""" return self._eos.T @property def mu(self): return self._eos.mu @property def H(self): """Scale-height""" return self._eos.H @property def h(self): """Aspect ratio""" return self.H/self.R @property def H_edge(self): """Scale-height at cell edge""" return self._eos.H_edge @property def P(self): return self.midplane_gas_density * self.cs**2 @property def midplane_gas_density(self): <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from scipy import optimize from .constants import AU, sig_H2, m_H, yr, Msun and context (classes, functions, sometimes code) from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 . Output only the next line.
return self.Sigma_G / (np.sqrt(2*np.pi) * self.H * AU)
Predict the next line for this snippet: <|code_start|> def midplane_gas_density(self): return self.Sigma_G / (np.sqrt(2*np.pi) * self.H * AU) @property def midplane_density(self): return self.Sigma / (np.sqrt(2*np.pi) * self.H * AU) @property def column_density(self): n = self.midplane_gas_density / (self._eos._mu * m_H) Re = self.R_edge * AU ndR = n * (Re[1:] - Re[:-1]) N = np.cumsum(ndR) return N @property def Ncells(self): return self._grid.Ncells @property def alpha(self): return self._eos.alpha @property def nu(self): return self._eos.nu @property def Re(self): """Reynolds number""" <|code_end|> with the help of current file imports: import numpy as np from scipy import optimize from .constants import AU, sig_H2, m_H, yr, Msun and context from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 , which may contain function names, class names, or code. Output only the next line.
return (self.alpha*self.Sigma_G*sig_H2) / (2*self._eos.mu*m_H)
Predict the next line for this snippet: <|code_start|> @property def H(self): """Scale-height""" return self._eos.H @property def h(self): """Aspect ratio""" return self.H/self.R @property def H_edge(self): """Scale-height at cell edge""" return self._eos.H_edge @property def P(self): return self.midplane_gas_density * self.cs**2 @property def midplane_gas_density(self): return self.Sigma_G / (np.sqrt(2*np.pi) * self.H * AU) @property def midplane_density(self): return self.Sigma / (np.sqrt(2*np.pi) * self.H * AU) @property def column_density(self): <|code_end|> with the help of current file imports: import numpy as np from scipy import optimize from .constants import AU, sig_H2, m_H, yr, Msun and context from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 , which may contain function names, class names, or code. Output only the next line.
n = self.midplane_gas_density / (self._eos._mu * m_H)
Here is a snippet: <|code_start|> """Methods to determine global properties of a viscous accretion disc""" def Rout(self, thresh=1e-5): """Determine the outer radius via density threshold""" notempty = self.Sigma_G > thresh notempty_cells = self.R_edge[1:][notempty] if np.size(notempty_cells>0): R_outer = notempty_cells[-1] else: R_outer = 0.0 return R_outer def RC(self): """Fit an LBP profile to the disc and return the scale radius""" not_empty = (self.R < self.Rout()) popt,pcov = optimize.curve_fit(LBP_profile,self.R[not_empty],np.log(self.Sigma_G[not_empty]),p0=[100,0.01],maxfev=5000) return popt[0] def Mtot(self): """Determine the total mass""" Re = self.R_edge * AU dA = np.pi * (Re[1:] ** 2 - Re[:-1] ** 2) dM_tot = self.Sigma * dA M_tot = np.sum(dM_tot) return M_tot def Mdot(self,viscous_velocity): """Determine the viscous accretion rate""" M_visc_out = 2*np.pi * self.R[0] * self.Sigma[0] * viscous_velocity * (AU**2) <|code_end|> . Write the next line using the current file imports: import numpy as np from scipy import optimize from .constants import AU, sig_H2, m_H, yr, Msun and context from other files: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 , which may include functions, classes, or code. Output only the next line.
Mdot = -M_visc_out*(yr/Msun)
Using the snippet: <|code_start|> """Methods to determine global properties of a viscous accretion disc""" def Rout(self, thresh=1e-5): """Determine the outer radius via density threshold""" notempty = self.Sigma_G > thresh notempty_cells = self.R_edge[1:][notempty] if np.size(notempty_cells>0): R_outer = notempty_cells[-1] else: R_outer = 0.0 return R_outer def RC(self): """Fit an LBP profile to the disc and return the scale radius""" not_empty = (self.R < self.Rout()) popt,pcov = optimize.curve_fit(LBP_profile,self.R[not_empty],np.log(self.Sigma_G[not_empty]),p0=[100,0.01],maxfev=5000) return popt[0] def Mtot(self): """Determine the total mass""" Re = self.R_edge * AU dA = np.pi * (Re[1:] ** 2 - Re[:-1] ** 2) dM_tot = self.Sigma * dA M_tot = np.sum(dM_tot) return M_tot def Mdot(self,viscous_velocity): """Determine the viscous accretion rate""" M_visc_out = 2*np.pi * self.R[0] * self.Sigma[0] * viscous_velocity * (AU**2) <|code_end|> , determine the next line of code. You have imports: import numpy as np from scipy import optimize from .constants import AU, sig_H2, m_H, yr, Msun and context (class names, function names, or code) available: # Path: DiscEvolution/constants.py # G = 1. # AU = 1.496e13 . Output only the next line.
Mdot = -M_visc_out*(yr/Msun)
Given the code snippet: <|code_start|>Designed for plotting to test things out """"""""" ################################################################################# class DummyDisc(object): def __init__(self, R, star, MD=10, RC=100): self._M = MD * Mjup self.Rc = RC self.R_edge = R self.R = 0.5*(self.R_edge[1:]+self.R_edge[:-1]) self._Sigma = self._M / (2 * np.pi * self.Rc * self.R * AU**2) * np.exp(-self.R/self.Rc) self.star = star def Rout(self, thresh=None): return max(self.R_edge) @property def Sigma(self): return self._Sigma @property def Sigma_G(self): return self._Sigma def main(): Sigma_dot_plot() Test_Removal() def Test_Removal(): """Removes gas fom a power law disc in regular timesteps without viscous evolution etc""" <|code_end|> , generate the next line using the imports in this file: import numpy as np import argparse import json import matplotlib.pyplot as plt from DiscEvolution.constants import * from DiscEvolution.star import PhotoStar from scipy.signal import argrelmin from control_scripts import run_model and context (functions, classes, or occasionally code) from other files: # Path: DiscEvolution/star.py # class PhotoStar(SimpleStar): # def __init__(self, LX=1e30, Phi=0, **kwargs): # super().__init__(**kwargs) # self._L_X = LX # self._Phi = Phi # # @property # def L_X(self): # """X-ray Luminosity""" # return self._L_X # # @property # def Phi(self): # """EUV Photon Luminosity""" # return self._Phi . Output only the next line.
star1 = PhotoStar(LX=1e30, M=1.0, R=2.5, T_eff=4000)
Predict the next line for this snippet: <|code_start|>class DonorCell(object): '''First-order upwind reconstruction args: xe : Cell edge locations m : Index of radial scaling giving volume, V = x^{m+1} / m+1. ''' STENCIL = 1 def __init__(self, xe, m): pass def __call__(self, v_edge, Q, dt=0.): '''Compute the upwinded face value''' Qp = Qm = Q return np.where(v_edge > 0, Qp[...,:-1], Qm[...,1:]) class VanLeer(object): '''Second-order upwind reconstruction with Van Leer limiting. Uses the geometrically consistent formulation of Mignone (2014). args: xe : Cell edge locations m : Index of radial scaling giving volume, V = x^{m+1} / m+1. ''' STENCIL = 2 def __init__(self, xe, m): self._xe = xe <|code_end|> with the help of current file imports: import numpy as np import matplotlib.pyplot as plt from scipy.special import erf from .FV_interpolation import compute_centroids, construct_FV_edge_weights and context from other files: # Path: DiscEvolution/FV_interpolation.py # def compute_centroids(xe, m): # '''First order upwind reconstruction # # args: # xe : Cell edge locations # m : Index of radial scaling giving volume, V = x^{m+1} / m+1. # ''' # return ((m + 1) * np.diff(xe**(m+2))) / ((m + 2) * np.diff(xe**(m+1))) # # def construct_FV_edge_weights(xi, m, iL, iR, max_deriv=None, dtype='f8'): # '''Solves for the finite-volume interpolation weights. # # This code follows the methods outlined in Mignone (2014, JCoPh 270 784) to # compute the weights needed to reconstruct a function and its derivatives # to edges of computational cells. The polynomial is reconstructed to # reproduce the averages of the cell and its neighbours. # # Note that the polynomial computed near the domain edges will be lower # order, which also reduces the number of derivatives available # # args: # xi : locations of cell edges # m : Index of radial scaling giving volume, V = x^{m+1} / m+1. # iL : Number of cells to the left of the target cell to use in the # interpolation. # iR : Number of cells to the right of the target cell to use in the # interpolation. # # max_deriv : maximum derivative level to calculate. If not specified, # return all meaningful derivatives. # # dtype : data type used for calculation, default = 'f8' # # returns: # wp, wm : The weights used for reconstructing the function and its 1st # iL+iR derivatives to the left and right of the cell edges. # The shape is [len(xi)-1,max_deriv+1, 1+iL+iR] # ''' # # Order of the polynomial # order = 1 + iL + iR # # if max_deriv is None: # max_deriv = order - 1 # elif max_deriv > order - 1: # raise ValueError("Maximum derivative must be less than the order of the" # " polynomial fitted") # # # Setup the beta matrix of Mignone: # beta = _construct_volume_factors(xi, m, order, dtype) # # # The matrix of extrapolations to the RHS of cell # wp = _solve_FV_matrix_weights(xi[1:], iL, iR, beta, max_deriv, dtype) # # # The matrix of extrapolations to the LHS of cell # wm = _solve_FV_matrix_weights(xi[:-1], iR, iL, beta, max_deriv, dtype) # # return wp, wm , which may contain function names, class names, or code. Output only the next line.
self._xc = xc = compute_centroids(xe, m)
Predict the next line for this snippet: <|code_start|> # Reconstruct the face states Qp = Q[...,1:-1] + dQ_lim * (self._dxp[1:-1] - v_edge[1: ]*dt/2.) Qm = Q[...,1:-1] + dQ_lim * (self._dxm[1:-1] - v_edge[ :-1]*dt/2.) return np.where(v_edge[1:-1] > 0, Qp[...,:-1], Qm[...,1:]) class Weno3(object): '''Third-order upwind WENO reconstruction. Uses the geometrically consistent formulation of Mignone (2014). args: xe : Cell edge locations m : Index of radial scaling giving volume, V = x^{m+1} / m+1. ''' STENCIL = 2 def __init__(self, xe, m, coeff=1.0): self._xe = xe self._xc = xc = compute_centroids(xe, m) dx = np.diff(xe) self._dxp = (xe[1:] - xc) / dx self._dxm = (xe[:-1] - xc) / dx self._cdx2 = (coeff * (xe[1:] - xe[:-1]))[1:-1]**2 # Compute the linear WENO weights <|code_end|> with the help of current file imports: import numpy as np import matplotlib.pyplot as plt from scipy.special import erf from .FV_interpolation import compute_centroids, construct_FV_edge_weights and context from other files: # Path: DiscEvolution/FV_interpolation.py # def compute_centroids(xe, m): # '''First order upwind reconstruction # # args: # xe : Cell edge locations # m : Index of radial scaling giving volume, V = x^{m+1} / m+1. # ''' # return ((m + 1) * np.diff(xe**(m+2))) / ((m + 2) * np.diff(xe**(m+1))) # # def construct_FV_edge_weights(xi, m, iL, iR, max_deriv=None, dtype='f8'): # '''Solves for the finite-volume interpolation weights. # # This code follows the methods outlined in Mignone (2014, JCoPh 270 784) to # compute the weights needed to reconstruct a function and its derivatives # to edges of computational cells. The polynomial is reconstructed to # reproduce the averages of the cell and its neighbours. # # Note that the polynomial computed near the domain edges will be lower # order, which also reduces the number of derivatives available # # args: # xi : locations of cell edges # m : Index of radial scaling giving volume, V = x^{m+1} / m+1. # iL : Number of cells to the left of the target cell to use in the # interpolation. # iR : Number of cells to the right of the target cell to use in the # interpolation. # # max_deriv : maximum derivative level to calculate. If not specified, # return all meaningful derivatives. # # dtype : data type used for calculation, default = 'f8' # # returns: # wp, wm : The weights used for reconstructing the function and its 1st # iL+iR derivatives to the left and right of the cell edges. # The shape is [len(xi)-1,max_deriv+1, 1+iL+iR] # ''' # # Order of the polynomial # order = 1 + iL + iR # # if max_deriv is None: # max_deriv = order - 1 # elif max_deriv > order - 1: # raise ValueError("Maximum derivative must be less than the order of the" # " polynomial fitted") # # # Setup the beta matrix of Mignone: # beta = _construct_volume_factors(xi, m, order, dtype) # # # The matrix of extrapolations to the RHS of cell # wp = _solve_FV_matrix_weights(xi[1:], iL, iR, beta, max_deriv, dtype) # # # The matrix of extrapolations to the LHS of cell # wm = _solve_FV_matrix_weights(xi[:-1], iR, iL, beta, max_deriv, dtype) # # return wp, wm , which may contain function names, class names, or code. Output only the next line.
wp, wm = construct_FV_edge_weights(xe, m, 1, 1)
Given the code snippet: <|code_start|> # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=390000, prev_hash=binascii.unhexlify('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'), prev_index=0, ) out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', amount=390000 - 10000 - 10000, script_type=proto_types.PAYTOADDRESS, ) out1 = proto_types.TxOutputType(op_return_data=b'test of the op_return data', amount=10000, script_type=proto_types.PAYTOOPRETURN, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=binascii.unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.Failure() ]) <|code_end|> , generate the next line using the imports in this file: import unittest import common import binascii import itertools import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib import tx_api and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
self.assertRaises(CallException, self.client.sign_tx, 'Bitcoin', [inp1, ], [out1, ])
Predict the next line for this snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgGetaddressSegwitNative(common.KeepKeyTest): def test_show_segwit(self): self.setup_mnemonic_allallall() self.client.clear_session() <|code_end|> with the help of current file imports: import common import unittest import keepkeylib.ckd_public as bip32 from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto from keepkeylib.tools import parse_path and context from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(self.client.get_address("Testnet", parse_path("49'/1'/0'/0/0"), True, None, script_type=proto.SPENDWITNESS), 'tb1qqzv60m9ajw8drqulta4ld4gfx0rdh82un5s65s')
Using the snippet: <|code_start|> # to automatically pass unit tests. # # This mixing should be used only for purposes # of unit testing, because it will fail to work # without special DebugLink interface provided # by the device. def __init__(self, *args, **kwargs): super(DebugLinkMixin, self).__init__(*args, **kwargs) self.debug = None self.in_with_statement = 0 self.button_wait = 0 self.screenshot_id = 0 # Always press Yes and provide correct pin self.setup_debuglink(True, True) self.auto_button = True # Do not expect any specific response from device self.expected_responses = None # Use blank passphrase self.set_passphrase('') def close(self): super(DebugLinkMixin, self).close() if self.debug: self.debug.close() def set_debuglink(self, debug_transport): <|code_end|> , determine the next line of code. You have imports: import os import sys import time import binascii import hashlib import unicodedata import json import getpass import copy import termios import msvcrt import sys, tty from mnemonic import Mnemonic from . import tools from . import mapping from . import messages_pb2 as proto from . import messages_eos_pb2 as eos_proto from . import messages_nano_pb2 as nano_proto from . import messages_cosmos_pb2 as cosmos_proto from . import messages_ripple_pb2 as ripple_proto from . import messages_tendermint_pb2 as tendermint_proto from . import messages_thorchain_pb2 as thorchain_proto from . import types_pb2 as types from . import eos from . import nano from .debuglink import DebugLink from keepkeylib.tools import int_to_big_endian from copy import deepcopy from copy import deepcopy and context (class names, function names, or code) available: # Path: keepkeylib/debuglink.py # class DebugLink(object): # def __init__(self, transport, pin_func=pin_info, button_func=button_press): # self.transport = transport # self.verbose = False # # self.pin_func = pin_func # self.button_func = button_func # # def log(self, what, why): # if self.verbose: # self.log(what, why) # # def close(self): # self.transport.close() # # def _call(self, msg, nowait=False): # self.log("DEBUGLINK SEND", pprint(msg)) # self.transport.write(msg) # if nowait: # return # ret = self.transport.read_blocking() # self.log("DEBUGLINK RECV", pprint(ret)) # return ret # # def read_pin(self): # obj = self._call(proto.DebugLinkGetState()) # self.log("Read PIN:", obj.pin) # self.log("Read matrix:", obj.matrix) # # return (obj.pin, obj.matrix) # # def read_pin_encoded(self): # pin, _ = self.read_pin() # pin_encoded = self.encode_pin(pin) # self.pin_func(pin_encoded, self.verbose) # return pin_encoded # # def encode_pin(self, pin): # _, matrix = self.read_pin() # # # Now we have real PIN and PIN matrix. # # We have to encode that into encoded pin, # # because application must send back positions # # on keypad, not a real PIN. # pin_encoded = ''.join([str(matrix.index(p) + 1) for p in pin]) # # self.log("Encoded PIN:", pin_encoded) # return pin_encoded # # def read_layout(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.layout # # def read_mnemonic(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.mnemonic # # def read_node(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.node # # def read_recovery_word(self): # obj = self._call(proto.DebugLinkGetState()) # return (obj.recovery_fake_word, obj.recovery_word_pos) # # def read_reset_word(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_word # # def read_reset_entropy(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.reset_entropy # # def read_passphrase_protection(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.passphrase_protection # # def read_recovery_cipher(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.recovery_cipher # # def read_recovery_auto_completed_word(self): # obj = self._call(proto.DebugLinkGetState()) # return obj.recovery_auto_completed_word # # def read_memory_hashes(self): # obj = self._call(proto.DebugLinkGetState()) # return (obj.firmware_hash, obj.storage_hash) # # def fill_config(self): # self._call(proto.DebugLinkFillConfig(), nowait=True) # # def press_button(self, yes_no): # self.log("Pressing", yes_no) # self.button_func(yes_no, self.verbose) # self._call(proto.DebugLinkDecision(yes_no=yes_no), nowait=True) # # def press_yes(self): # self.press_button(True) # # def press_no(self): # self.press_button(False) # # def stop(self): # self._call(proto.DebugLinkStop(), nowait=True) . Output only the next line.
self.debug = DebugLink(debug_transport)
Using the snippet: <|code_start|># This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. _libusb_version = usb1.getVersion() _libusb_version = (_libusb_version.major, _libusb_version.minor, _libusb_version.micro) class FakeRead(object): # Let's pretend we have a file-like interface def __init__(self, func): self.func = func def read(self, size): return self.func(size) DEVICE_IDS = [ (0x2B24, 0x0002), # KeepKey ] <|code_end|> , determine the next line of code. You have imports: import importlib import logging import sys import time import atexit import usb1 from .transport import Transport, ConnectionError and context (class names, function names, or code) available: # Path: keepkeylib/transport.py # class Transport(object): # def __init__(self, device, *args, **kwargs): # self.device = device # self.session_depth = 0 # self._open() # # def _open(self): # raise NotImplementedException("Not implemented") # # def _close(self): # raise NotImplementedException("Not implemented") # # def _write(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _bridgeWrite(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _read(self): # raise NotImplementedException("Not implemented") # # def _bridgeRead(self): # raise NotImplementedException("Not implemented") # # def _session_begin(self): # pass # # def _session_end(self): # pass # # def ready_to_read(self): # """ # Returns True if there is data to be read from the transport. Otherwise, False. # """ # raise NotImplementedException("Not implemented") # # def session_begin(self): # """ # Apply a lock to the device in order to preform synchronous multistep "conversations" with the device. For example, before entering the transaction signing workflow, one begins a session. After the transaction is complete, the session may be ended. # """ # if self.session_depth == 0: # self._session_begin() # self.session_depth += 1 # # def session_end(self): # """ # End a session. Se session_begin for an in depth description of TREZOR sessions. # """ # self.session_depth -= 1 # self.session_depth = max(0, self.session_depth) # if self.session_depth == 0: # self._session_end() # # def close(self): # """ # Close the connection to the physical device or file descriptor represented by the Transport. # """ # self._close() # # def write(self, msg): # """ # Write mesage to tansport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # ser = msg.SerializeToString() # header = struct.pack(">HL", mapping.get_type(msg), len(ser)) # self._write(b"##" + header + ser, msg) # # def bridgeWrite(self, msg): # """ # Write message to transport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # self._bridgeWrite(msg) # # def read(self): # """ # If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. # Otherwise, returns None. # """ # if not self.ready_to_read(): # return None # # data = self._read() # if data is None: # return None # # return self._parse_message(data) # # def read_blocking(self): # """ # Same as read, except blocks untill data is available to be read. # """ # while True: # data = self._read() # if data != None: # break # # return self._parse_message(data) # # def bridge_read_blocking(self): # """ # blocks until data is available to be read. # """ # while True: # data = self._bridgeRead() # if data != None: # break # # return data # # # def _parse_message(self, data): # (msg_type, data) = data # if msg_type == 'protobuf': # return data # else: # inst = mapping.get_class(msg_type)() # inst.ParseFromString(data) # return inst # # def _read_headers(self, read_f): # # Try to read headers until some sane value are detected # is_ok = False # while not is_ok: # # # Align cursor to the beginning of the header ("##") # c = read_f.read(1) # i = 0 # while c != b"#": # i += 1 # if i >= 64: # # timeout # raise Exception("Timed out while waiting for the magic character") # c = read_f.read(1) # # if read_f.read(1) != b"#": # # Second character must be # to be valid header # raise Exception("Second magic character is broken") # # # Now we're most likely on the beginning of the header # try: # headerlen = struct.calcsize(">HL") # (msg_type, datalen) = struct.unpack(">HL", read_f.read(headerlen)) # break # except: # raise Exception("Cannot parse header length") # # return (msg_type, datalen) # # class ConnectionError(Exception): # pass . Output only the next line.
class WebUsbTransport(Transport):
Using the snippet: <|code_start|> DEFAULT_BIP32_PATH = "m/44h/931h/0h/0/0" def make_send(from_address, to_address, amount): return { 'type': 'thorchain/MsgSend', 'value': { 'amount': [{ 'denom': 'rune', 'amount': str(amount), }], 'from_address': from_address, 'to_address': to_address, } } class TestMsgThorChainSignTx(common.KeepKeyTest): def test_thorchain_sign_tx(self): self.requires_firmware("7.0.2") self.setup_mnemonic_nopin_nopassphrase() signature = self.client.thorchain_sign_tx( <|code_end|> , determine the next line of code. You have imports: import unittest import common import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types import keepkeylib.exchange_pb2 as proto_exchange from base64 import b64encode from binascii import hexlify, unhexlify from keepkeylib.tools import parse_path and context (class names, function names, or code) available: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) . Output only the next line.
address_n=parse_path(DEFAULT_BIP32_PATH),
Given the following code snippet before the placeholder: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgRippleGetAddress(KeepKeyTest): def test_ripple_get_address(self): self.requires_firmware("6.4.0") # data from https://iancoleman.io/bip39/#english self.setup_mnemonic_allallall() <|code_end|> , predict the next line using imports from the current file: import unittest from keepkeylib.tools import parse_path from common import KeepKeyTest and context including class names, function names, and sometimes code from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) . Output only the next line.
address = self.client.ripple_get_address(parse_path("m/44'/144'/0'/0/0"))
Given the code snippet: <|code_start|> DEFAULT_BIP32_PATH = "m/44h/118h/0h/0/0" class TestMsgCosmosGetAddress(common.KeepKeyTest): def test_standard(self): self.requires_firmware("6.3.0") self.setup_mnemonic_nopin_nopassphrase() vec = [ <|code_end|> , generate the next line using the imports in this file: import unittest import common import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types import keepkeylib.messages_cosmos_pb2 as cosmos_proto from keepkeylib.client import CallException from keepkeylib.tools import parse_path and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) . Output only the next line.
("cosmos15cenya0tr7nm3tz2wn3h3zwkht2rxrq7q7h3dj", parse_path(DEFAULT_BIP32_PATH)),
Predict the next line after this snippet: <|code_start|> self.client.set_expected_responses([proto.ButtonRequest(), proto.Success(message='wrong data')]) self._some_protected_call(True, True, True) self.assertRaises(CallException, scenario5) """ def test_no_protection(self): self.setup_mnemonic_nopin_nopassphrase() with self.client: self.assertEqual(self.client.debug.read_pin()[0], '') self.client.set_expected_responses([proto.Success()]) self._some_protected_call(False, True, True) def test_pin(self): self.setup_mnemonic_pin_passphrase() self.client.clear_session() with self.client: self.assertEqual(self.client.debug.read_pin()[0], self.pin4) self.client.setup_debuglink(button=True, pin_correct=True) self.client.set_expected_responses([proto.ButtonRequest(), proto.PinMatrixRequest(), proto.Success()]) self._some_protected_call(True, True, False) def test_incorrect_pin(self): self.setup_mnemonic_pin_passphrase() self.client.clear_session() self.client.setup_debuglink(button=True, pin_correct=False) <|code_end|> using the current file's imports: import time import unittest import common from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as types from keepkeylib.client import PinException, CallException and any relevant context from other files: # Path: keepkeylib/client.py # class PinException(CallException): # pass # # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] . Output only the next line.
self.assertRaises(PinException, self._some_protected_call, False, True, False)
Here is a snippet: <|code_start|># # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgSignmessageSegwitNative(KeepKeyTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Bitcoin', [0], "This is an example of a signed message.", script_type=proto_types.SPENDWITNESS) self.assertEqual(sig.address, 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j') self.assertEqual(hexlify(sig.signature), b'289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80') def test_sign_testnet(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Testnet', [0], "This is an example of a signed message.", script_type=proto_types.SPENDWITNESS) self.assertEqual(sig.address, 'tb1qyjjkmdpu7metqt5r36jf872a34syws336p3n3p') self.assertEqual(hexlify(sig.signature), b'289e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80') def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Bitcoin', [0], "VeryLongMessage!" * 64, script_type=proto_types.SPENDWITNESS) self.assertEqual(sig.address, 'bc1qyjjkmdpu7metqt5r36jf872a34syws33s82q2j') self.assertEqual(hexlify(sig.signature), b'285ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed') def test_sign_grs(self): self.setup_mnemonic_allallall() <|code_end|> . Write the next line using the current file imports: import unittest import base64 from binascii import hexlify from common import KeepKeyTest from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.tools import parse_path and context from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) , which may include functions, classes, or code. Output only the next line.
sig = self.client.sign_message('Groestlcoin', parse_path("84'/17'/0'/0/0"), "test", script_type=proto_types.SPENDWITNESS)
Given the following code snippet before the placeholder: <|code_start|>'''FakeTransport implements dummy interface for Transport.''' # Local serial port loopback: socat PTY,link=COM8 PTY,link=COM9 class FakeTransport(Transport): def __init__(self, device, *args, **kwargs): super(FakeTransport, self).__init__(device, *args, **kwargs) def _open(self): pass def _close(self): pass def ready_to_read(self): return False def _write(self, msg, protobuf_msg): pass def _read(self): <|code_end|> , predict the next line using imports from the current file: from .transport import Transport, NotImplementedException and context including class names, function names, and sometimes code from other files: # Path: keepkeylib/transport.py # class Transport(object): # def __init__(self, device, *args, **kwargs): # self.device = device # self.session_depth = 0 # self._open() # # def _open(self): # raise NotImplementedException("Not implemented") # # def _close(self): # raise NotImplementedException("Not implemented") # # def _write(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _bridgeWrite(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _read(self): # raise NotImplementedException("Not implemented") # # def _bridgeRead(self): # raise NotImplementedException("Not implemented") # # def _session_begin(self): # pass # # def _session_end(self): # pass # # def ready_to_read(self): # """ # Returns True if there is data to be read from the transport. Otherwise, False. # """ # raise NotImplementedException("Not implemented") # # def session_begin(self): # """ # Apply a lock to the device in order to preform synchronous multistep "conversations" with the device. For example, before entering the transaction signing workflow, one begins a session. After the transaction is complete, the session may be ended. # """ # if self.session_depth == 0: # self._session_begin() # self.session_depth += 1 # # def session_end(self): # """ # End a session. Se session_begin for an in depth description of TREZOR sessions. # """ # self.session_depth -= 1 # self.session_depth = max(0, self.session_depth) # if self.session_depth == 0: # self._session_end() # # def close(self): # """ # Close the connection to the physical device or file descriptor represented by the Transport. # """ # self._close() # # def write(self, msg): # """ # Write mesage to tansport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # ser = msg.SerializeToString() # header = struct.pack(">HL", mapping.get_type(msg), len(ser)) # self._write(b"##" + header + ser, msg) # # def bridgeWrite(self, msg): # """ # Write message to transport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # self._bridgeWrite(msg) # # def read(self): # """ # If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. # Otherwise, returns None. # """ # if not self.ready_to_read(): # return None # # data = self._read() # if data is None: # return None # # return self._parse_message(data) # # def read_blocking(self): # """ # Same as read, except blocks untill data is available to be read. # """ # while True: # data = self._read() # if data != None: # break # # return self._parse_message(data) # # def bridge_read_blocking(self): # """ # blocks until data is available to be read. # """ # while True: # data = self._bridgeRead() # if data != None: # break # # return data # # # def _parse_message(self, data): # (msg_type, data) = data # if msg_type == 'protobuf': # return data # else: # inst = mapping.get_class(msg_type)() # inst.ParseFromString(data) # return inst # # def _read_headers(self, read_f): # # Try to read headers until some sane value are detected # is_ok = False # while not is_ok: # # # Align cursor to the beginning of the header ("##") # c = read_f.read(1) # i = 0 # while c != b"#": # i += 1 # if i >= 64: # # timeout # raise Exception("Timed out while waiting for the magic character") # c = read_f.read(1) # # if read_f.read(1) != b"#": # # Second character must be # to be valid header # raise Exception("Second magic character is broken") # # # Now we're most likely on the beginning of the header # try: # headerlen = struct.calcsize(">HL") # (msg_type, datalen) = struct.unpack(">HL", read_f.read(headerlen)) # break # except: # raise Exception("Cannot parse header length") # # return (msg_type, datalen) # # class NotImplementedException(Exception): # pass . Output only the next line.
raise NotImplementedException("Not implemented")
Here is a snippet: <|code_start|>from __future__ import print_function '''SocketTransport implements TCP socket interface for Transport.''' class FakeRead(object): # Let's pretend we have a file-like interface def __init__(self, func): self.func = func def read(self, size): return self.func(size) <|code_end|> . Write the next line using the current file imports: import socket from select import select from .transport import Transport and context from other files: # Path: keepkeylib/transport.py # class Transport(object): # def __init__(self, device, *args, **kwargs): # self.device = device # self.session_depth = 0 # self._open() # # def _open(self): # raise NotImplementedException("Not implemented") # # def _close(self): # raise NotImplementedException("Not implemented") # # def _write(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _bridgeWrite(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _read(self): # raise NotImplementedException("Not implemented") # # def _bridgeRead(self): # raise NotImplementedException("Not implemented") # # def _session_begin(self): # pass # # def _session_end(self): # pass # # def ready_to_read(self): # """ # Returns True if there is data to be read from the transport. Otherwise, False. # """ # raise NotImplementedException("Not implemented") # # def session_begin(self): # """ # Apply a lock to the device in order to preform synchronous multistep "conversations" with the device. For example, before entering the transaction signing workflow, one begins a session. After the transaction is complete, the session may be ended. # """ # if self.session_depth == 0: # self._session_begin() # self.session_depth += 1 # # def session_end(self): # """ # End a session. Se session_begin for an in depth description of TREZOR sessions. # """ # self.session_depth -= 1 # self.session_depth = max(0, self.session_depth) # if self.session_depth == 0: # self._session_end() # # def close(self): # """ # Close the connection to the physical device or file descriptor represented by the Transport. # """ # self._close() # # def write(self, msg): # """ # Write mesage to tansport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # ser = msg.SerializeToString() # header = struct.pack(">HL", mapping.get_type(msg), len(ser)) # self._write(b"##" + header + ser, msg) # # def bridgeWrite(self, msg): # """ # Write message to transport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # self._bridgeWrite(msg) # # def read(self): # """ # If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. # Otherwise, returns None. # """ # if not self.ready_to_read(): # return None # # data = self._read() # if data is None: # return None # # return self._parse_message(data) # # def read_blocking(self): # """ # Same as read, except blocks untill data is available to be read. # """ # while True: # data = self._read() # if data != None: # break # # return self._parse_message(data) # # def bridge_read_blocking(self): # """ # blocks until data is available to be read. # """ # while True: # data = self._bridgeRead() # if data != None: # break # # return data # # # def _parse_message(self, data): # (msg_type, data) = data # if msg_type == 'protobuf': # return data # else: # inst = mapping.get_class(msg_type)() # inst.ParseFromString(data) # return inst # # def _read_headers(self, read_f): # # Try to read headers until some sane value are detected # is_ok = False # while not is_ok: # # # Align cursor to the beginning of the header ("##") # c = read_f.read(1) # i = 0 # while c != b"#": # i += 1 # if i >= 64: # # timeout # raise Exception("Timed out while waiting for the magic character") # c = read_f.read(1) # # if read_f.read(1) != b"#": # # Second character must be # to be valid header # raise Exception("Second magic character is broken") # # # Now we're most likely on the beginning of the header # try: # headerlen = struct.calcsize(">HL") # (msg_type, datalen) = struct.unpack(">HL", read_f.read(headerlen)) # break # except: # raise Exception("Cannot parse header length") # # return (msg_type, datalen) , which may include functions, classes, or code. Output only the next line.
class UDPTransport(Transport):
Predict the next line for this snippet: <|code_start|># You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. # # The script has been modified for KeepKey Device. class TestMsgSignmessage(common.KeepKeyTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Bitcoin', [0], "This is an example of a signed message.") self.assertEqual(sig.address, '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e') self.assertEqual(binascii.hexlify(sig.signature), '209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80') def test_sign_testnet(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Testnet', [0], "This is an example of a signed message.") self.assertEqual(sig.address, 'mirio8q3gtv7fhdnmb3TpZ4EuafdzSs7zL') self.assertEqual(binascii.hexlify(sig.signature), '209e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80') def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Bitcoin', [0], "VeryLongMessage!" * 64) self.assertEqual(sig.address, '14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e') self.assertEqual(binascii.hexlify(sig.signature), '205ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed') def test_sign_grs(self): self.setup_mnemonic_allallall() <|code_end|> with the help of current file imports: import unittest import common import binascii import base64 from keepkeylib.client import CallException from keepkeylib.tools import parse_path and context from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) , which may contain function names, class names, or code. Output only the next line.
sig = self.client.sign_message('Groestlcoin', parse_path("44'/17'/0'/0/0"), "test")
Continue the code snippet: <|code_start|> #reset policy ("ShapeShift") self.client.apply_policy('ShapeShift', 0) def test_ethereum_xfer_account_path_error_0(self): self.setup_mnemonic_nopin_nopassphrase() self.client.apply_policy('ShapeShift', 1) sig_v, sig_r, sig_s, hash, signature_der = self.client.ethereum_sign_tx( n=[0, 0], nonce=0, gas_price=20, gas_limit=20, value=1234567890, to_n=[0x8000002c, 0x8000003c, 0x80000002, 0, 0], address_type=proto_types.TRANSFER, chain_id=1, ) try: signature_der = self.client.ethereum_sign_tx( n=[0, 0], nonce=0, gas_price=20, gas_limit=20, to_n=[0x8000002c, 0x8000003c, 2, 0, 0], #error here -^- value=1234567890, address_type=proto_types.TRANSFER, chain_id=1, ) <|code_end|> . Use current file imports: import unittest import common import binascii import struct import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types import keepkeylib.exchange_pb2 as proto_exchange from keepkeylib.client import CallException from keepkeylib.tools import int_to_big_endian and context (classes, functions, or code) from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def int_to_big_endian(value): # import struct # # res = b'' # while 0 < value: # res = struct.pack("B", value & 0xff) + res # value = value >> 8 # # return res . Output only the next line.
except CallException as e:
Continue the code snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgSigntxDash(common.KeepKeyTest): def test_send_dash(self): self.setup_mnemonic_allallall() self.client.set_tx_api(tx_api.TxApiDash) inp1 = proto_types.TxInputType( <|code_end|> . Use current file imports: import unittest import common import binascii from keepkeylib.tools import parse_path from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib import tx_api and context (classes, functions, or code) from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
address_n=parse_path("44'/5'/0'/0/0"),
Based on the snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgSigntxDash(common.KeepKeyTest): def test_send_dash(self): self.setup_mnemonic_allallall() <|code_end|> , predict the immediate next line with the help of imports: import unittest import common import binascii from keepkeylib.tools import parse_path from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib import tx_api and context (classes, functions, sometimes code) from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
self.client.set_tx_api(tx_api.TxApiDash)
Continue the code snippet: <|code_start|> # balance=86242336390000000000000000000, # ) # self.assertIsInstance(res, proto_nano.NanoSignedTx) # self.assertEqual(hexlify(res.block_hash), '5d732d843c22f806011127655790484dbabd38dda20b24900c053c3dfc12523f') # self.assertEqual(hexlify(res.signature), '3fb596c34db1241201983cbf613fe9b68a6eae2420c7f294c7e883574fda10d5cc19c9e516b57ed0cbc5e7d3438f70f2ddd7a45bf3e693ff800b97e187de5701') # def test_block_6(self): # # https://www.nanode.co/block/a7e59d38b001d9348dbe16fa866d0b435259d381af1db019f3ff83fd7590e226 # self.setup_mnemonic_nopin_nopassphrase() # with self.client: # self.client.set_expected_responses([ # proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), # proto_nano.NanoSignedTx(), # ]) # res = self.client.nano_sign_tx( # 'Nano', NANO_ACCOUNT_0_PATH, # grandparent_hash=unhexlify('32ac7d8f5a16a498abf203b8dfee623c9e111ff25e7339f8cd69ec7492b23edd'), # parent_link=unhexlify(NANO_ACCOUNT_1_PUBLICKEY), # parent_representative=REP_NANODE, # parent_balance=86242336390000000000000000000, # link_recipient_n=OTHER_ACCOUNT_3_PATH, # representative=REP_NANODE, # balance=40000760000000000000000000000, # ) # self.assertIsInstance(res, proto_nano.NanoSignedTx) # self.assertEqual(hexlify(res.block_hash), 'a7e59d38b001d9348dbe16fa866d0b435259d381af1db019f3ff83fd7590e226') # self.assertEqual(hexlify(res.signature), '1dcd8a27aeac1cab9a2054d5cc6df1b80be46290596dcf6d195c2c286b1615d4139276f9be9c6f202ee1ee8a5569b4a4fc838b1d7306aa71c8e431a6b8075707') def test_invalid_block_1(self): self.setup_mnemonic_nopin_nopassphrase() <|code_end|> . Use current file imports: import unittest import common from binascii import hexlify, unhexlify from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib import messages_pb2 as proto from keepkeylib import messages_nano_pb2 as proto_nano from keepkeylib import types_pb2 as proto_types from keepkeylib import nano and context (classes, functions, or code) from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/nano.py # def encode_balance(balance): . Output only the next line.
with self.assertRaises(CallException):
Given snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. # # The script has been modified for KeepKey Device. NANO_ACCOUNT_0_PATH = parse_path("m/44'/165'/0'") NANO_ACCOUNT_0_ADDRESS = 'xrb_1bhbsc9yuh15anq3owu1izw1nk7bhhqefrkhfo954fyt8dk1q911buk1kk4c' NANO_ACCOUNT_1_PATH = parse_path("m/44'/165'/1'") NANO_ACCOUNT_1_ADDRESS = 'xrb_3p9ws1t6nx7r5xunf7khtbzqwa9ncjte9fmiy59eiyjkkfds6z5zgpom1cxs' NANO_ACCOUNT_1_PUBLICKEY = 'd8fcc8344a74b81f7746964fd27f7e20f45474c3b670f0cec87a329357927c7f' OTHER_ACCOUNT_3_PATH = parse_path("m/44'/100'/3'") OTHER_ACCOUNT_3_ADDRESS = 'xrb_1x9k73o5icut7pr8khu9xcgtbaau6z6fh5fxxb5m9s3fpzuoe6aio9xjz4et' OTHER_ACCOUNT_3_PUBLICKEY = '74f2286a382b7a2db0693f67ea9da4a11b27c8d78dbdea4733e42db7f7561110' REP_OFFICIAL_1 = 'xrb_3arg3asgtigae3xckabaaewkx3bzsh7nwz7jkmjos79ihyaxwphhm6qgjps4' REP_NANODE = 'xrb_1nanode8ngaakzbck8smq6ru9bethqwyehomf79sae1k7xd47dkidjqzffeg' RECIPIENT_DONATIONS = 'xrb_3wm37qz19zhei7nzscjcopbrbnnachs4p1gnwo5oroi3qonw6inwgoeuufdp' RECIPIENT_DONATIONS_PUBLICKEY = 'f2612dfe03fdec8169fcaa2aad9384d28853f22b01d4e5475c5601bd69c2429c' class TestMsgNanoSignTx(common.KeepKeyTest): def test_encode_balance(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import common from binascii import hexlify, unhexlify from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib import messages_pb2 as proto from keepkeylib import messages_nano_pb2 as proto_nano from keepkeylib import types_pb2 as proto_types from keepkeylib import nano and context: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/nano.py # def encode_balance(balance): which might include code, classes, or functions. Output only the next line.
self.assertEqual(hexlify(nano.encode_balance(0)), '00000000000000000000000000000000')
Next line prediction: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. # # The script has been modified for KeepKey Device. class TestMsgSigntxGRS(common.KeepKeyTest): def test_one_one_fee(self): # http://blockbook.groestlcoin.org/tx/f56521b17b828897f72b30dd21b0192fd942342e89acbb06abf1d446282c30f5 # ptx1: http://blockbook.groestlcoin.org/tx/cb74c8478c5814742c87cffdb4a21231869888f8042fb07a90e015a9db1f9d4a self.setup_mnemonic_allallall() ptx1hash='cb74c8478c5814742c87cffdb4a21231869888f8042fb07a90e015a9db1f9d4a' inp1 = proto_types.TxInputType(address_n=[44 | 0x80000000, 17 | 0x80000000, 0 | 0x80000000, 0, 2], # FXHDsC5ZqWQHkDmShzgRVZ1MatpWhwxTAA prev_hash=binascii.unhexlify(ptx1hash), prev_index=0, ) out1 = proto_types.TxOutputType(address='FtM4zAn9aVYgHgxmamWBgWPyZsb6RhvkA9', amount=210016 - 192, script_type=proto_types.PAYTOADDRESS, ) with self.client: <|code_end|> . Use current file imports: (import unittest import common import binascii import itertools import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib import tx_api) and context including class names, function names, or small code snippets from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
self.client.set_tx_api(tx_api.TxApiGroestlcoin)
Given the code snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. # https://blockbook-test.groestlcoin.org/tx/4ce0220004bdfe14e3dd49fd8636bcb770a400c0c9e9bff670b6a13bb8f15c72 class TestMsgSigntxSegwitGRS(KeepKeyTest): def test_send_p2sh(self): self.setup_mnemonic_allallall() self.client.set_tx_api(TxApiGroestlcoinTestnet) inp1 = proto_types.TxInputType( <|code_end|> , generate the next line using the imports in this file: import common import unittest from binascii import hexlify, unhexlify from keepkeylib import ckd_public as bip32 from common import KeepKeyTest from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib.tx_api import TxApiGroestlcoinTestnet and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/ckd_public.py # PRIME_DERIVATION_FLAG = 0x80000000 # I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest() # def point_to_pubkey(point): # def sec_to_public_pair(pubkey): # def public_pair_for_x(generator, x, is_even): # def is_prime(n): # def fingerprint(pubkey): # def get_address(public_node, address_type): # def public_ckd(public_node, n): # def get_subnode(node, i): # def serialize(node, version=0x0488B21E): # def deserialize(xpub): # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
address_n=parse_path("49'/1'/0'/1/0"), # 2N1LGaGg836mqSQqiuUBLfcyGBhyZYBtBZ7
Predict the next line after this snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. # https://blockbook-test.groestlcoin.org/tx/4ce0220004bdfe14e3dd49fd8636bcb770a400c0c9e9bff670b6a13bb8f15c72 class TestMsgSigntxSegwitGRS(KeepKeyTest): def test_send_p2sh(self): self.setup_mnemonic_allallall() <|code_end|> using the current file's imports: import common import unittest from binascii import hexlify, unhexlify from keepkeylib import ckd_public as bip32 from common import KeepKeyTest from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib.tx_api import TxApiGroestlcoinTestnet and any relevant context from other files: # Path: keepkeylib/ckd_public.py # PRIME_DERIVATION_FLAG = 0x80000000 # I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest() # def point_to_pubkey(point): # def sec_to_public_pair(pubkey): # def public_pair_for_x(generator, x, is_even): # def is_prime(n): # def fingerprint(pubkey): # def get_address(public_node, address_type): # def public_ckd(public_node, n): # def get_subnode(node, i): # def serialize(node, version=0x0488B21E): # def deserialize(xpub): # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
self.client.set_tx_api(TxApiGroestlcoinTestnet)
Given the code snippet: <|code_start|># # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. class TestMsgSigntx(common.KeepKeyTest): def test_transparent_one_one(self): self.setup_mnemonic_allallall() # tx: 08a18fc5a768f8b08c4f5b53a502e2b182107b90b5b4e5f23294074670e57357 # input 0: 9.99884999 TAZ inp1 = proto_types.TxInputType(address_n=[2147483692, 2147483649, 2147483648, 0, 0], # t1YxYiYy8Hjq5HBN7sioDtTs98SX2SzW5q8 #amount=999884999, prev_hash=binascii.unhexlify(b'08a18fc5a768f8b08c4f5b53a502e2b182107b90b5b4e5f23294074670e57357'), prev_index=0, ) out1 = proto_types.TxOutputType(address='tmJ1xYxP8XNTtCoDgvdmQPSrxh5qZJgy65Z', amount=999884999 - 1940, script_type=proto_types.PAYTOADDRESS, ) with self.client: <|code_end|> , generate the next line using the imports in this file: import unittest import common import binascii import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib.tx_api import TxApiZcashTestnet and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
self.client.set_tx_api(TxApiZcashTestnet)
Continue the code snippet: <|code_start|> DEFAULT_BIP32_PATH = "m/44h/118h/0h/0/0" def make_send(from_address, to_address, amount): return { 'type': 'cosmos-sdk/MsgSend', 'value': { 'from_address': from_address, 'to_address': to_address, 'amount': [{ 'denom': 'uatom', 'amount': str(amount) }] } } class TestMsgCosmosSignTx(common.KeepKeyTest): def test_cosmos_sign_tx(self): self.requires_firmware("6.3.0") self.setup_mnemonic_nopin_nopassphrase() signature = self.client.cosmos_sign_tx( <|code_end|> . Use current file imports: import unittest import common import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types import keepkeylib.exchange_pb2 as proto_exchange from base64 import b64encode from binascii import hexlify, unhexlify from keepkeylib.tools import parse_path and context (classes, functions, or code) from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) . Output only the next line.
address_n=parse_path(DEFAULT_BIP32_PATH),
Given the code snippet: <|code_start|> DEFAULT_BIP32_PATH = "m/44h/931h/0h/0/0" def make_deposit(asset, amount, memo, signer): return { 'type': 'thorchain/MsgDeposit', 'value': { 'coins': [{ 'asset': str(asset), 'amount': str(amount), }], 'memo': memo, 'signer': signer, } } class TestMsg2ThorChainSignTx(common.KeepKeyTest): def test_thorchain_sign_tx_deposit(self): self.requires_firmware("7.1.3") self.setup_mnemonic_nopin_nopassphrase() signature = self.client.thorchain_sign_tx( <|code_end|> , generate the next line using the imports in this file: import unittest import common import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types import keepkeylib.exchange_pb2 as proto_exchange from base64 import b64encode from binascii import hexlify, unhexlify from keepkeylib.tools import parse_path and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) . Output only the next line.
address_n=parse_path(DEFAULT_BIP32_PATH),
Based on the snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgSigntxBitcoinGold(common.KeepKeyTest): def test_send_bitcoin_gold_nochange(self): self.setup_mnemonic_allallall() self.client.set_tx_api(tx_api.TxApiBitcoinGold) inp1 = proto_types.TxInputType( <|code_end|> , predict the immediate next line with the help of imports: import unittest import common from binascii import hexlify, unhexlify from keepkeylib.ckd_public import deserialize from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib import tx_api and context (classes, functions, sometimes code) from other files: # Path: keepkeylib/ckd_public.py # def deserialize(xpub): # data = tools.b58decode(xpub, None) # # if tools.Hash(data[:-4])[:4] != data[-4:]: # raise Exception("Checksum failed") # # node = proto_types.HDNodeType() # node.depth = struct.unpack('>B', data[4:5])[0] # node.fingerprint = struct.unpack('>I', data[5:9])[0] # node.child_num = struct.unpack('>I', data[9:13])[0] # node.chain_code = data[13:45] # # key = data[45:-4] # if key[0] == '\x00': # node.private_key = key[1:] # else: # node.public_key = key # # return node # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
address_n=parse_path("44'/156'/0'/1/0"),
Predict the next line for this snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgSigntxBitcoinGold(common.KeepKeyTest): def test_send_bitcoin_gold_nochange(self): self.setup_mnemonic_allallall() <|code_end|> with the help of current file imports: import unittest import common from binascii import hexlify, unhexlify from keepkeylib.ckd_public import deserialize from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib import tx_api and context from other files: # Path: keepkeylib/ckd_public.py # def deserialize(xpub): # data = tools.b58decode(xpub, None) # # if tools.Hash(data[:-4])[:4] != data[-4:]: # raise Exception("Checksum failed") # # node = proto_types.HDNodeType() # node.depth = struct.unpack('>B', data[4:5])[0] # node.fingerprint = struct.unpack('>I', data[5:9])[0] # node.child_num = struct.unpack('>I', data[9:13])[0] # node.chain_code = data[13:45] # # key = data[45:-4] # if key[0] == '\x00': # node.private_key = key[1:] # else: # node.public_key = key # # return node # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): , which may contain function names, class names, or code. Output only the next line.
self.client.set_tx_api(tx_api.TxApiBitcoinGold)
Given the code snippet: <|code_start|># # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgSignmessageSegwit(KeepKeyTest): def test_sign(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Bitcoin', [0], "This is an example of a signed message.", script_type=proto_types.SPENDP2SHWITNESS) self.assertEqual(sig.address, '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1') self.assertEqual(hexlify(sig.signature), b'249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80') def test_sign_testnet(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Testnet', [0], "This is an example of a signed message.", script_type=proto_types.SPENDP2SHWITNESS) self.assertEqual(sig.address, '2N4VkePSzKH2sv5YBikLHGvzUYvfPxV6zS9') self.assertEqual(hexlify(sig.signature), b'249e23edf0e4e47ff1dec27f32cd78c50e74ef018ee8a6adf35ae17c7a9b0dd96f48b493fd7dbab03efb6f439c6383c9523b3bbc5f1a7d158a6af90ab154e9be80') def test_sign_long(self): self.setup_mnemonic_nopin_nopassphrase() sig = self.client.sign_message('Bitcoin', [0], "VeryLongMessage!" * 64, script_type=proto_types.SPENDP2SHWITNESS) self.assertEqual(sig.address, '3CwYaeWxhpXXiHue3ciQez1DLaTEAXcKa1') self.assertEqual(hexlify(sig.signature), b'245ff795c29aef7538f8b3bdb2e8add0d0722ad630a140b6aefd504a5a895cbd867cbb00981afc50edd0398211e8d7c304bb8efa461181bc0afa67ea4a720a89ed') def test_sign_grs(self): self.setup_mnemonic_allallall() <|code_end|> , generate the next line using the imports in this file: import unittest import base64 from binascii import hexlify from common import KeepKeyTest from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.tools import parse_path and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) . Output only the next line.
sig = self.client.sign_message('Groestlcoin', parse_path("49'/17'/0'/0/0"), "test", script_type=proto_types.SPENDP2SHWITNESS)
Predict the next line for this snippet: <|code_start|> ) self.client.set_tx_api(tx_api.TxApiTestnet) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_FeeOverThreshold), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Testnet', [inp1, inp2], [out, ]) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_Other), proto.Failure(code=proto_types.Failure_ActionCancelled), ]) <|code_end|> with the help of current file imports: import common import unittest from binascii import hexlify, unhexlify from keepkeylib import ckd_public as bip32 from common import KeepKeyTest from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib import tx_api and context from other files: # Path: keepkeylib/ckd_public.py # PRIME_DERIVATION_FLAG = 0x80000000 # I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest() # def point_to_pubkey(point): # def sec_to_public_pair(pubkey): # def public_pair_for_x(generator, x, is_even): # def is_prime(n): # def fingerprint(pubkey): # def get_address(public_node, address_type): # def public_ckd(public_node, n): # def get_subnode(node, i): # def serialize(node, version=0x0488B21E): # def deserialize(xpub): # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): , which may contain function names, class names, or code. Output only the next line.
self.assertRaises(CallException, self.client.sign_tx, 'Testnet', [inp3, inp4], [out, ])
Here is a snippet: <|code_start|> proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=unhexlify("d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882"))), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) client.sign_tx('Bitcoin', [inp, ], [out, ]) client.set_tx_api(TxApiSaved) class TestVuln20007(KeepKeyTest): def test_vuln(self): self.requires_firmware("6.4.1") PREVHASH_1 = unhexlify("b6973acd5876ba8b050ae2d4c7d8b5c710ee4879af938be3c2c61a262f1730e0") PREVHASH_2 = unhexlify("3a3322e60f2f4c55394fe05dddacafd6e55ff6d40859fd98d64adefc8c169ac8") PREVHASH_3 = unhexlify("d58af7adaf3f04a0d5d30c145e8cfb48e863f49c8de594a8927c19c460fee9a3") PREVHASH_4 = unhexlify("3b586fcc54424f1df5669828f9d828e888298669a50a5983fd0d71e7f4d38110") self.setup_mnemonic_vuln20007() inp1 = proto_types.TxInputType( # amount=150.0 <|code_end|> . Write the next line using the current file imports: import common import unittest from binascii import hexlify, unhexlify from keepkeylib import ckd_public as bip32 from common import KeepKeyTest from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.client import CallException from keepkeylib.tools import parse_path from keepkeylib import tx_api and context from other files: # Path: keepkeylib/ckd_public.py # PRIME_DERIVATION_FLAG = 0x80000000 # I64 = hmac.HMAC(key=node.chain_code, msg=data, digestmod=hashlib.sha512).digest() # def point_to_pubkey(point): # def sec_to_public_pair(pubkey): # def public_pair_for_x(generator, x, is_even): # def is_prime(n): # def fingerprint(pubkey): # def get_address(public_node, address_type): # def public_ckd(public_node, n): # def get_subnode(node, i): # def serialize(node, version=0x0488B21E): # def deserialize(xpub): # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): , which may include functions, classes, or code. Output only the next line.
address_n=parse_path("m/49'/1'/0'/0/0"),
Predict the next line for this snippet: <|code_start|># This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. class TestMsgGetaddressSegwit(common.KeepKeyTest): def test_show_segwit(self): self.setup_mnemonic_allallall() self.client.clear_session() <|code_end|> with the help of current file imports: import common import unittest import keepkeylib.ckd_public as bip32 from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto from keepkeylib.tools import parse_path and context from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(self.client.get_address("Testnet", parse_path("49'/1'/0'/1/0"), True, None, script_type=proto.SPENDP2SHWITNESS), '2N1LGaGg836mqSQqiuUBLfcyGBhyZbremDX')
Here is a snippet: <|code_start|> language='english') def test_transfer(self): self.setup_binance() message = { "account_number": "34", "chain_id": "Binance-Chain-Nile", "data": "null", "memo": "test", "msgs": [ { "inputs": [ { "address": "tbnb1hgm0p7khfk85zpz5v0j8wnej3a90w709zzlffd", "coins": [{"amount": 1000000000, "denom": "BNB"}], } ], "outputs": [ { "address": "tbnb1ss57e8sa7xnwq030k2ctr775uac9gjzglqhvpy", "coins": [{"amount": 1000000000, "denom": "BNB"}], } ], } ], "sequence": "31", "source": "1", } <|code_end|> . Write the next line using the current file imports: import unittest import common import binascii import keepkeylib.binance as binance from base64 import b64encode from keepkeylib.tools import parse_path and context from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) , which may include functions, classes, or code. Output only the next line.
response = binance.sign_tx(self.client, parse_path("m/44'/714'/0'/0/0"), message)
Continue the code snippet: <|code_start|> def test_message_testnet(self): self.setup_mnemonic_nopin_nopassphrase() sig = base64.b64decode('IFP/nvQalDo9lWCI7kScOzRkz/fiiScdkw7tFAKPoGbl6S8AY3wEws43s2gR57AfwZP8/8y7+F+wvGK9phQghN4=') ret = self.client.verify_message( 'Testnet', 'moRDikgmxcpouFtqnKnVVzLYgkDD2gQ3sk', sig, 'Ahoj') self.assertTrue(ret) def test_message_grs(self): self.setup_mnemonic_allallall() sig = base64.b64decode('INOYaa/jj8Yxz3mD5k+bZfUmjkjB9VzoV4dNG7+RsBUyK30xL7I9yMgWWVvsL46C5yQtxtZY0cRRk7q9N6b+YTM=') ret = self.client.verify_message( 'Groestlcoin', 'Fj62rBJi8LvbmWu2jzkaUX1NFXLEqDLoZM', sig, 'test') self.assertTrue(ret) def test_vuln1972(self): self.setup_mnemonic_allallall() signature = base64.b64decode('IFP/nvQalDo9lWCI7kScOzRkz/fiiScdkw7tFAKPoGbl6S8AY3wEws43s2gR57AfwZP8/8y7+F+wvGK9phQghN4=') address = 'moRDikgmxcpouFtqnKnVVzLYgkDD2gQ3sk' message = b'Ahoj' # Null pointer dereference caused the emulator to crash at this point. # After the fix, this shoud raise a CallException to signify that the # sig isn't valid for this coin's signing curve. <|code_end|> . Use current file imports: import unittest import common import binascii import base64 from keepkeylib.client import CallException from keepkeylib import messages_pb2 as proto and context (classes, functions, or code) from other files: # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] . Output only the next line.
self.assertRaises(CallException, self.client.call, proto.VerifyMessage(address=address, signature=signature, message=message, coin_name="Nano"))
Next line prediction: <|code_start|> cipher = self.client.debug.read_recovery_cipher() encoded_character = cipher[ord(character) - 97] ret = self.client.call_raw(proto.CharacterAck(character=encoded_character)) auto_completed = self.client.debug.read_recovery_auto_completed_word() if word == auto_completed: if len(mnemonic_words) != index + 1: ret = self.client.call_raw(proto.CharacterAck(character=' ')) break # Send final ack self.assertIsInstance(ret, proto.CharacterRequest) ret = self.client.call_raw(proto.CharacterAck(done=True)) # Workflow succesfully ended self.assertIsInstance(ret, proto.Success) self.client.init_device() self.assertEqual(self.client.debug.read_mnemonic(), mnemonic) # wipe device ret = self.client.call_raw(proto.WipeDevice()) self.client.debug.press_yes() ret = self.client.call_raw(proto.ButtonAck()) def test_vuln1971(self): self.setup_mnemonic_allallall() <|code_end|> . Use current file imports: (import unittest import common from keepkeylib import messages_pb2 as proto from keepkeylib import types_pb2 as proto_types from keepkeylib.tools import parse_path) and context including class names, function names, or small code snippets from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) . Output only the next line.
self.assertEqual(self.client.get_address("Testnet", parse_path("49'/1'/0'/1/0"), True, None, script_type=proto_types.SPENDP2SHWITNESS), '2N1LGaGg836mqSQqiuUBLfcyGBhyZbremDX')
Given snippet: <|code_start|># # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. @expect(messages.BinanceAddress) @field("address") def get_address(client, address_n, show_display=False): return client.call( messages.BinanceGetAddress(address_n=address_n, show_display=show_display) ) @expect(messages.BinancePublicKey) @field("public_key") def get_public_key(client, address_n, show_display=False): return client.call( messages.BinanceGetPublicKey(address_n=address_n, show_display=show_display) ) <|code_end|> , continue by predicting the next line. Consider current file imports: from . import messages_binance_pb2 as messages from .client import expect, session, field and context: # Path: keepkeylib/client.py # class expect(object): # # Decorator checks if the method # # returned one of expected protobuf messages # # or raises an exception # def __init__(self, *expected): # self.expected = expected # # def __call__(self, f): # def wrapped_f(*args, **kwargs): # ret = f(*args, **kwargs) # if not isinstance(ret, self.expected): # raise Exception("Got %s, expected %s" % (ret.__class__, self.expected)) # return ret # return wrapped_f # # def session(f): # # Decorator wraps a BaseClient method # # with session activation / deactivation # def wrapped_f(*args, **kwargs): # client = args[0] # try: # client.transport.session_begin() # return f(*args, **kwargs) # finally: # client.transport.session_end() # return wrapped_f # # class field(object): # # Decorator extracts single value from # # protobuf object. If the field is not # # present, raises an exception. # def __init__(self, field): # self.field = field # # def __call__(self, f): # def wrapped_f(*args, **kwargs): # ret = f(*args, **kwargs) # ret.HasField(self.field) # return getattr(ret, self.field) # return wrapped_f which might include code, classes, or functions. Output only the next line.
@session
Given the code snippet: <|code_start|> return True if device["interface_number"] == 0: return True # MacOS reports -1 as the interface_number for everything, # inspect based on the path instead. if platform.system() == "Darwin": if device["interface_number"] == -1: return device["path"].endswith(b"0") return False def is_debug_link(device): if device["usage_page"] == 0xFF01: return True if device["interface_number"] == 1: return True # MacOS reports -1 as the interface_number for everything, # inspect based on the path instead. if platform.system() == "Darwin": if device["interface_number"] == -1: return device["path"].endswith(b"1") return False <|code_end|> , generate the next line using the imports in this file: import math import time, json, base64, struct import binascii import platform import hid from hashlib import sha256 from .transport import Transport, ConnectionError and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/transport.py # class Transport(object): # def __init__(self, device, *args, **kwargs): # self.device = device # self.session_depth = 0 # self._open() # # def _open(self): # raise NotImplementedException("Not implemented") # # def _close(self): # raise NotImplementedException("Not implemented") # # def _write(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _bridgeWrite(self, msg, protobuf_msg): # raise NotImplementedException("Not implemented") # # def _read(self): # raise NotImplementedException("Not implemented") # # def _bridgeRead(self): # raise NotImplementedException("Not implemented") # # def _session_begin(self): # pass # # def _session_end(self): # pass # # def ready_to_read(self): # """ # Returns True if there is data to be read from the transport. Otherwise, False. # """ # raise NotImplementedException("Not implemented") # # def session_begin(self): # """ # Apply a lock to the device in order to preform synchronous multistep "conversations" with the device. For example, before entering the transaction signing workflow, one begins a session. After the transaction is complete, the session may be ended. # """ # if self.session_depth == 0: # self._session_begin() # self.session_depth += 1 # # def session_end(self): # """ # End a session. Se session_begin for an in depth description of TREZOR sessions. # """ # self.session_depth -= 1 # self.session_depth = max(0, self.session_depth) # if self.session_depth == 0: # self._session_end() # # def close(self): # """ # Close the connection to the physical device or file descriptor represented by the Transport. # """ # self._close() # # def write(self, msg): # """ # Write mesage to tansport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # ser = msg.SerializeToString() # header = struct.pack(">HL", mapping.get_type(msg), len(ser)) # self._write(b"##" + header + ser, msg) # # def bridgeWrite(self, msg): # """ # Write message to transport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method. # """ # self._bridgeWrite(msg) # # def read(self): # """ # If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. # Otherwise, returns None. # """ # if not self.ready_to_read(): # return None # # data = self._read() # if data is None: # return None # # return self._parse_message(data) # # def read_blocking(self): # """ # Same as read, except blocks untill data is available to be read. # """ # while True: # data = self._read() # if data != None: # break # # return self._parse_message(data) # # def bridge_read_blocking(self): # """ # blocks until data is available to be read. # """ # while True: # data = self._bridgeRead() # if data != None: # break # # return data # # # def _parse_message(self, data): # (msg_type, data) = data # if msg_type == 'protobuf': # return data # else: # inst = mapping.get_class(msg_type)() # inst.ParseFromString(data) # return inst # # def _read_headers(self, read_f): # # Try to read headers until some sane value are detected # is_ok = False # while not is_ok: # # # Align cursor to the beginning of the header ("##") # c = read_f.read(1) # i = 0 # while c != b"#": # i += 1 # if i >= 64: # # timeout # raise Exception("Timed out while waiting for the magic character") # c = read_f.read(1) # # if read_f.read(1) != b"#": # # Second character must be # to be valid header # raise Exception("Second magic character is broken") # # # Now we're most likely on the beginning of the header # try: # headerlen = struct.calcsize(">HL") # (msg_type, datalen) = struct.unpack(">HL", read_f.read(headerlen)) # break # except: # raise Exception("Cannot parse header length") # # return (msg_type, datalen) # # class ConnectionError(Exception): # pass . Output only the next line.
class HidTransport(Transport):
Given snippet: <|code_start|># (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. # # The script has been modified for KeepKey Device. from __future__ import print_function tx_api.cache_dir = 'txcache' VERBOSE = False class KeepKeyTest(unittest.TestCase): def setUp(self): transport = config.TRANSPORT(*config.TRANSPORT_ARGS, **config.TRANSPORT_KWARGS) if hasattr(config, 'DEBUG_TRANSPORT'): debug_transport = config.DEBUG_TRANSPORT(*config.DEBUG_TRANSPORT_ARGS, **config.DEBUG_TRANSPORT_KWARGS) if VERBOSE: self.client = KeepKeyDebuglinkClientVerbose(transport) else: self.client = KeepKeyDebuglinkClient(transport) self.client.set_debuglink(debug_transport) else: <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import config import time import semver from keepkeylib.client import KeepKeyClient, KeepKeyDebuglinkClient, KeepKeyDebuglinkClientVerbose from keepkeylib import tx_api and context: # Path: keepkeylib/client.py # class KeepKeyClient(ProtocolMixin, TextUIMixin, BaseClient): # pass # # class KeepKeyDebuglinkClient(ProtocolMixin, DebugLinkMixin, BaseClient): # pass # # class KeepKeyDebuglinkClientVerbose(ProtocolMixin, DebugLinkMixin, DebugWireMixin, BaseClient): # pass # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): which might include code, classes, or functions. Output only the next line.
self.client = KeepKeyClient(transport)
Given snippet: <|code_start|># This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. # # The script has been modified for KeepKey Device. from __future__ import print_function tx_api.cache_dir = 'txcache' VERBOSE = False class KeepKeyTest(unittest.TestCase): def setUp(self): transport = config.TRANSPORT(*config.TRANSPORT_ARGS, **config.TRANSPORT_KWARGS) if hasattr(config, 'DEBUG_TRANSPORT'): debug_transport = config.DEBUG_TRANSPORT(*config.DEBUG_TRANSPORT_ARGS, **config.DEBUG_TRANSPORT_KWARGS) if VERBOSE: self.client = KeepKeyDebuglinkClientVerbose(transport) else: <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import config import time import semver from keepkeylib.client import KeepKeyClient, KeepKeyDebuglinkClient, KeepKeyDebuglinkClientVerbose from keepkeylib import tx_api and context: # Path: keepkeylib/client.py # class KeepKeyClient(ProtocolMixin, TextUIMixin, BaseClient): # pass # # class KeepKeyDebuglinkClient(ProtocolMixin, DebugLinkMixin, BaseClient): # pass # # class KeepKeyDebuglinkClientVerbose(ProtocolMixin, DebugLinkMixin, DebugWireMixin, BaseClient): # pass # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): which might include code, classes, or functions. Output only the next line.
self.client = KeepKeyDebuglinkClient(transport)
Given the code snippet: <|code_start|># Copyright (C) 2012-2016 Pavol Rusnak <stick@satoshilabs.com> # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library. If not, see <http://www.gnu.org/licenses/>. # # The script has been modified for KeepKey Device. from __future__ import print_function tx_api.cache_dir = 'txcache' VERBOSE = False class KeepKeyTest(unittest.TestCase): def setUp(self): transport = config.TRANSPORT(*config.TRANSPORT_ARGS, **config.TRANSPORT_KWARGS) if hasattr(config, 'DEBUG_TRANSPORT'): debug_transport = config.DEBUG_TRANSPORT(*config.DEBUG_TRANSPORT_ARGS, **config.DEBUG_TRANSPORT_KWARGS) if VERBOSE: <|code_end|> , generate the next line using the imports in this file: import unittest import config import time import semver from keepkeylib.client import KeepKeyClient, KeepKeyDebuglinkClient, KeepKeyDebuglinkClientVerbose from keepkeylib import tx_api and context (functions, classes, or occasionally code) from other files: # Path: keepkeylib/client.py # class KeepKeyClient(ProtocolMixin, TextUIMixin, BaseClient): # pass # # class KeepKeyDebuglinkClient(ProtocolMixin, DebugLinkMixin, BaseClient): # pass # # class KeepKeyDebuglinkClientVerbose(ProtocolMixin, DebugLinkMixin, DebugWireMixin, BaseClient): # pass # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
self.client = KeepKeyDebuglinkClientVerbose(transport)
Here is a snippet: <|code_start|> ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.ButtonRequest(code=proto_types.ButtonRequest_SignTx), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXFINISHED), ]) (signatures, serialized_tx) = self.client.sign_tx('Bitcoin', [inp1, ], [out1, ]) # Accepted by network: tx fd79435246dee76b2f159d2db08032d666c95adc544de64c8c49f474df4a7fee self.assertEqual(binascii.hexlify(serialized_tx), b'010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b4830450221009a0b7be0d4ed3146ee262b42202841834698bb3ee39c24e7437df208b8b7077102202b79ab1e7736219387dffe8d615bbdba87e11477104b867ef47afed1a5ede7810121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0160cc0500000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000') def test_testnet_one_two_fee(self): self.setup_mnemonic_allallall() # see 87be0736f202f7c2bff0781b42bad3e0cdcb54761939da69ea793a3735552c56 # tx: e5040e1bc1ae7667ffb9e5248e90b2fb93cd9150234151ce90e14ab2f5933bcd # input 0: 0.31 BTC inp1 = proto_types.TxInputType( <|code_end|> . Write the next line using the current file imports: import unittest import common import binascii import itertools import pytest import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types from binascii import unhexlify from keepkeylib.tools import parse_path from keepkeylib.client import CallException from keepkeylib import tx_api and context from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): , which may include functions, classes, or code. Output only the next line.
address_n=parse_path("44'/1'/0'/0/0"),
Predict the next line for this snippet: <|code_start|> self.setup_mnemonic_nopin_nopassphrase() # tx: d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882 # input 0: 0.0039 BTC inp1 = proto_types.TxInputType(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e # amount=390000, prev_hash=TXHASH_d5f65e, prev_index=0, ) out1 = proto_types.TxOutputType(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1', amount=400000, script_type=proto_types.PAYTOADDRESS, ) with self.client: self.client.set_expected_responses([ proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.TxRequest(request_type=proto_types.TXMETA, details=proto_types.TxRequestDetailsType(tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXINPUT, details=proto_types.TxRequestDetailsType(request_index=1, tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0, tx_hash=TXHASH_d5f65e)), proto.TxRequest(request_type=proto_types.TXOUTPUT, details=proto_types.TxRequestDetailsType(request_index=0)), proto.ButtonRequest(code=proto_types.ButtonRequest_ConfirmOutput), proto.Failure(code=proto_types.Failure_NotEnoughFunds) ]) try: self.client.sign_tx('Bitcoin', [inp1, ], [out1, ], None, True) <|code_end|> with the help of current file imports: import unittest import common import binascii import itertools import pytest import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types from binascii import unhexlify from keepkeylib.tools import parse_path from keepkeylib.client import CallException from keepkeylib import tx_api and context from other files: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): , which may contain function names, class names, or code. Output only the next line.
except CallException as e:
Using the snippet: <|code_start|> # Accepted by network: tx fd79435246dee76b2f159d2db08032d666c95adc544de64c8c49f474df4a7fee self.assertEqual(binascii.hexlify(serialized_tx), b'010000000182488650ef25a58fef6788bd71b8212038d7f2bbe4750bc7bcb44701e85ef6d5000000006b4830450221009a0b7be0d4ed3146ee262b42202841834698bb3ee39c24e7437df208b8b7077102202b79ab1e7736219387dffe8d615bbdba87e11477104b867ef47afed1a5ede7810121023230848585885f63803a0a8aecdd6538792d5c539215c91698e315bf0253b43dffffffff0160cc0500000000001976a914de9b2a8da088824e8fe51debea566617d851537888ac00000000') def test_testnet_one_two_fee(self): self.setup_mnemonic_allallall() # see 87be0736f202f7c2bff0781b42bad3e0cdcb54761939da69ea793a3735552c56 # tx: e5040e1bc1ae7667ffb9e5248e90b2fb93cd9150234151ce90e14ab2f5933bcd # input 0: 0.31 BTC inp1 = proto_types.TxInputType( address_n=parse_path("44'/1'/0'/0/0"), # amount=31000000, prev_hash=TXHASH_e5040e, prev_index=0, ) out1 = proto_types.TxOutputType( address='msj42CCGruhRsFrGATiUuh25dtxYtnpbTx', amount=30090000, script_type=proto_types.PAYTOADDRESS, ) out2 = proto_types.TxOutputType( address_n=parse_path("44'/1'/0'/1/0"), amount=900000, script_type=proto_types.PAYTOADDRESS, ) with self.client: <|code_end|> , determine the next line of code. You have imports: import unittest import common import binascii import itertools import pytest import keepkeylib.messages_pb2 as proto import keepkeylib.types_pb2 as proto_types from binascii import unhexlify from keepkeylib.tools import parse_path from keepkeylib.client import CallException from keepkeylib import tx_api and context (class names, function names, or code) available: # Path: keepkeylib/tools.py # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # Path: keepkeylib/client.py # class CallException(Exception): # def __init__(self, code, message): # super(CallException, self).__init__() # self.args = [code, message] # # Path: keepkeylib/tx_api.py # def pack_varint(n): # def __init__(self, network, url): # def fetch_json(self, url, resource, resourceid): # def get_tx(self, txhash): # def __init__(self, network, url, zcash=None): # def get_tx(self, txhash): # def get_raw_tx(self, txhash): # class TxApi(object): # class TxApiInsight(TxApi): . Output only the next line.
self.client.set_tx_api(tx_api.TxApiTestnet)
Predict the next line for this snippet: <|code_start|> if ord(c) >= ord('a') and ord(c) <= ord('z'): return (ord(c) - ord('a')) + 6 if ord(c) >= ord('1') and ord(c) <= ord('5'): return (ord(c) - ord('1')) + 1 return 0 def symbol_from_string(p, name): length = len(name) result = 0 for i in range(0, length): result |= ord(name[i]) << (8 *(i+1)) result |= p return result def symbol_precision(sym): return pow(10, (sym & 0xff)) def public_key_to_buffer(pub_key): _t = 0 if pub_key[:3] == 'EOS': pub_key = pub_key[3:] _t = 0 elif pub_key[:7] == 'PUB_K1_': pub_key = pub_key[7:] _t = 0 elif pub_key[:7] == 'PUB_R1_': pub_key = pub_key[7:] _t = 1 <|code_end|> with the help of current file imports: import hashlib import binascii import struct from datetime import datetime from .tools import b58decode, b58encode, parse_path, int_to_big_endian from . import messages_eos_pb2 as proto and context from other files: # Path: keepkeylib/tools.py # def b58decode(v, length): # """ decode v into a string of len bytes.""" # long_value = 0 # for (i, c) in enumerate(v[::-1]): # long_value += __b58chars.find(c) * (__b58base ** i) # # result = b'' # while long_value >= 256: # div, mod = divmod(long_value, 256) # result = struct.pack('B', mod) + result # long_value = div # result = struct.pack('B', long_value) + result # # nPad = 0 # for c in v: # if c == __b58chars[0]: # nPad += 1 # else: # break # # result = b'\x00' * nPad + result # if length is not None and len(result) != length: # return None # # return result # # def b58encode(v): # """ encode v, which is a string of bytes, to base58.""" # # long_value = 0 # for c in iterbytes(v): # long_value = long_value * 256 + c # # result = '' # while long_value >= __b58base: # div, mod = divmod(long_value, __b58base) # result = __b58chars[mod] + result # long_value = div # result = __b58chars[long_value] + result # # # Bitcoin does a little leading-zero-compression: # # leading 0-bytes in the input become leading-1s # nPad = 0 # for c in iterbytes(v): # if c == 0: # nPad += 1 # else: # break # # return (__b58chars[0] * nPad) + result # # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # def int_to_big_endian(value): # import struct # # res = b'' # while 0 < value: # res = struct.pack("B", value & 0xff) + res # value = value >> 8 # # return res , which may contain function names, class names, or code. Output only the next line.
return _t, b58decode(pub_key, None)[:-4]
Predict the next line for this snippet: <|code_start|>def symbol_precision(sym): return pow(10, (sym & 0xff)) def public_key_to_buffer(pub_key): _t = 0 if pub_key[:3] == 'EOS': pub_key = pub_key[3:] _t = 0 elif pub_key[:7] == 'PUB_K1_': pub_key = pub_key[7:] _t = 0 elif pub_key[:7] == 'PUB_R1_': pub_key = pub_key[7:] _t = 1 return _t, b58decode(pub_key, None)[:-4] def h160(public_key): md = hashlib.new('ripemd160') md.update(public_key) return md.digest() def public_key_to_wif(pub_key, prefix): if len(pub_key) == 65: head = 0x03 if (pub_key[64] & 0x01) == 1 else 0x02 compressed_pub_key = bytes([head]) + pub_key[1:33] elif len(pub_key) == 33: compressed_pub_key = pub_key else: raise Exception("invalid public key length") <|code_end|> with the help of current file imports: import hashlib import binascii import struct from datetime import datetime from .tools import b58decode, b58encode, parse_path, int_to_big_endian from . import messages_eos_pb2 as proto and context from other files: # Path: keepkeylib/tools.py # def b58decode(v, length): # """ decode v into a string of len bytes.""" # long_value = 0 # for (i, c) in enumerate(v[::-1]): # long_value += __b58chars.find(c) * (__b58base ** i) # # result = b'' # while long_value >= 256: # div, mod = divmod(long_value, 256) # result = struct.pack('B', mod) + result # long_value = div # result = struct.pack('B', long_value) + result # # nPad = 0 # for c in v: # if c == __b58chars[0]: # nPad += 1 # else: # break # # result = b'\x00' * nPad + result # if length is not None and len(result) != length: # return None # # return result # # def b58encode(v): # """ encode v, which is a string of bytes, to base58.""" # # long_value = 0 # for c in iterbytes(v): # long_value = long_value * 256 + c # # result = '' # while long_value >= __b58base: # div, mod = divmod(long_value, __b58base) # result = __b58chars[mod] + result # long_value = div # result = __b58chars[long_value] + result # # # Bitcoin does a little leading-zero-compression: # # leading 0-bytes in the input become leading-1s # nPad = 0 # for c in iterbytes(v): # if c == 0: # nPad += 1 # else: # break # # return (__b58chars[0] * nPad) + result # # def parse_path(nstr): # """ # Convert BIP32 path string to list of uint32 integers with hardened flags. # Several conventions are supported to set the hardened flag: -1, 1', 1h # e.g.: "0/1h/1" -> [0, 0x80000001, 1] # :param nstr: path string # :return: list of integers # """ # if not nstr: # return [] # # n = nstr.split('/') # # # m/a/b/c => a/b/c # if n[0] == 'm': # n = n[1:] # # # coin_name/a/b/c => 44'/SLIP44_constant'/a/b/c # #if n[0] in slip44: # # coin_id = slip44[n[0]] # # n[0:1] = ['44h', '{}h'.format(coin_id)] # # def str_to_harden(x): # if x.startswith('-'): # return H_(abs(int(x))) # elif x.endswith(('h', "'")): # return H_(int(x[:-1])) # else: # return int(x) # # try: # return list(str_to_harden(x) for x in n) # except Exception: # raise ValueError('Invalid BIP32 path', nstr) # # def int_to_big_endian(value): # import struct # # res = b'' # while 0 < value: # res = struct.pack("B", value & 0xff) + res # value = value >> 8 # # return res , which may contain function names, class names, or code. Output only the next line.
return prefix + b58encode(compressed_pub_key + h160(compressed_pub_key)[:4])