Example #1
0
def drawTriangles(m,
                  image,
                  wireframe=False,
                  color=(255, 0, 0),
                  bordercol=(0, 0, 0),
                  hasBorder=True,
                  culling=True):
    triangles = []
    for i in range(0, len(m[0]) - 2, 3):
        triangles.append([
            m[0][i], m[1][i], m[0][i + 1], m[1][i + 1], m[0][i + 2],
            m[1][i + 2], m[2][i], m[2][i + 1], m[2][i + 2]
        ])
    ordTris = sorted(triangles, key=lambda l: l[6] + l[7] + l[8])
    for t in ordTris:
        if culling:
            x12 = t[0] - t[2]
            y12 = t[1] - t[3]
            x23 = t[0] - t[4]
            y23 = t[1] - t[5]
            if x12 * y23 - x23 * y12 <= 0:
                continue
        if not wireframe:
            tri = triangle.triangle(*t[:6])
            coloredtri = [xy + (color, ) for xy in tri]
        else:
            coloredtri = []
        if hasBorder:
            border = line(*t[:4])
            border.extend(line(*t[2:6]))
            border.extend(line(*t[:2] + t[4:6]))
            coloredtri += [xy + (bordercol, ) for xy in border]
            image.setPixels(coloredtri)
Example #2
0
def main():
    global linex, linex2
    linex2 = line.line()

    linex = line.line()
    app = QApplication(sys.argv)
    read = codegen1.reader('cif.txt')
    # linex.pp()

    read.file_in_list('cif.txt')

    ex = MainWindow()

    total_file_lines = read.calculate_lines('cif.txt')

    if total_file_lines > 80:
        print("OOPs! Mainframe can't handle more than 80 lines.")
    else:

        ggg = read.get_element_pos_length(10)

        ex.set_text(MF_LINE_COLUMN, 1, str(ggg[16]))

    print(ggg[16])

    ex.show()

    sys.exit(app.exec_())
Example #3
0
 def configure(self):
     self.backbone.move(100, 100)  # (50,50) is a given start position and will be changed later
     self.backbone.rotate(math.pi / 6)
     self.configuredSideChains = []
     numLocations = []
     for i in range(len(self.sideChains)):
         for j in range(len(self.sideChains[i][1])):
             numLocations.append(self.sideChains[i][1][j])
     scAngles = self.backbone.getAngles(numLocations)
     bondLength = 20  #####magic number###########
     locs = []
     for i in range(len(self.sideChains)):
         for j in range(len(self.sideChains[i][1])):
             locs.append(self.sideChains[i][1][j])
             pos = self.backbone.getPos(self.sideChains[i][1][j])
             angle = scAngles[self.sideChains[i][1][j] - 1].pop()
             self.l = line(pos, angle, 9)
             sChain = self.sideChains[i][0].copy()
             if isinstance(sChain, carbonBackbone):
                 sChain.numC += 1
             elif isinstance(sChain, sideChain) and isinstance(sChain.shape, carbonBackbone):
                 sChain.addCarbon()
             else:
                 self.configuredSideChains.append(line(pos, angle, bondLength))
                 pos = self.configuredSideChains[-1].endPos
             sChain.rotate(angle)
             sChain.move(pos[0], pos[1])
             self.configuredSideChains.append(sChain)
def main(imgs):

    #初始化
    #左轨道
    left_line = line.line()  #初始化的时候,line.detected=False
    #右轨道
    right_line = line.line()
    #透视变换与逆透视变换
    M, Minv = get_M_Minv()

    #处理图像
    for img in imgs:
        processing(img, M, Minv, left_line, right_line)
        return
Example #5
0
def windows():
    if not isdir(home + '\\.CGT'):
        if not isfile(home + '\\CITY'):
            city = open(home + '\\CITY', 'w')
            city.write(sub(r'.*/', '', str(get_localzone())).upper())
            city.close()
    if isdir(home + '\\.CGT'):
        if not isfile(home + '\\.CGT\\files\\CITY'):
            move(home + '\\CITY', home + '\\.CGT\\files\\CITY')
    try:
        _language = open(home + '\\CITY', 'r').read()
    except:
        _language = open(home + '\\.CGT\\files\\CITY', 'r').read()
    CGT_VERSION = '0.1.1'
    if isfile(home + '\\.CGT\\files\\VERSION'):
        language = open(home + '\\.CGT\\files\\LANGUAGE', 'r').read()
        if language == 'EN':
            try:
                curent_version = open(home + '\\.CGT\\files\\VERSION',
                                      'r').read()
                latest_version = get(
                    'https://raw.githubusercontent.com/sys113/CGT-dependencies/master/VERSION'
                ).text
                if latest_version > curent_version:
                    if latest_version > CGT_VERSION:
                        print(c.BLUE + 'version ' + c.RED + latest_version +
                              c.BLUE + ' released' + c.GREEN + ' : ' + c.RED +
                              'https://github.com/SYS113/CGT/releases')
                        print(line())
                else:
                    pass
            except:
                pass
        if language == 'FA':
            try:
                curent_version = open(home + '\\.CGT\\files\\VERSION',
                                      'r').read()
                latest_version = get(
                    'https://raw.githubusercontent.com/sys113/CGT-dependencies/master/VERSION'
                ).text
                if latest_version > curent_version:
                    if latest_version > CGT_VERSION:
                        print(c.BLUE + 'noskhe ' + c.RED + latest_version +
                              c.BLUE + ' montasher shod' + c.GREEN + ' : ' +
                              c.RED + 'https://github.com/SYS113/CGT/releases')
                        print(line())
                else:
                    pass
            except:
                pass
Example #6
0
 def act(choice):
     if choice == 1:
         act(2)
         act(3)
         act(4)
         act(5)
     elif choice == 2:
         print "x-intercept:"+line.x_inter
     elif choice == 3:
         print "y-intercept:"+line.y_inter
     elif choice == 4:
         print "equation:"+line.equation
     elif choice == 5:
         print "slope:"+line.slope
     elif choice == 6:
         points = raw_input("Enter two points as x1 y1 x2 y2:")
         points = intlist(points.split())
         lowx = min(points[0],points[2])
         highx = max(points[0],points[2])
         lowy = min(points[1],points[3])
         highy = max(points[1],points[3])
         grid = grid.grid([lowx,lowy,highx,highy])
         line = line.line(a,b,grid,"line")
         return grid,line
     elif choice == 7:
         return
     else:
         raise IndexError()
Example #7
0
	def __init__(self, dot1, dot2, dot3):
		self.dot1 = dot1
		self.dot2 = dot2
		self.dot3 = dot3
		self.line1 = line.line(dot1, dot2)
		self.line2 = line.line(dot1, dot3)
		self.line3 = line.line(dot2, dot3)
		self.lines = [self.line1, self.line2, self.line3]
		if self.line1.slope is not None:
			self.baseLine = self.line1
			self.tip = self.dot3
		else:
			self.baseLine = self.line2
			self.tip = self.dot2
		self.height = abs((self.baseLine.slope*self.tip.x - self.tip.y + self.baseLine.intercept)) / (self.baseLine.slope ** 2 + 1) ** 0.5
		self.area = self.height * self.baseLine.length * 0.5
Example #8
0
def main():
    while True:
        print(line())
        if os_release() == '7':
            pass
        else:
            check_new_ver()
        send = xinput(c.BLUE + ">" + c.GREEN + ">" + c.RED + "> " + c.CYAN)
        if send == 'c':
            if_c()
        elif send == 'e':
            if_e()
        elif send == 'z':
            if_z()
        elif send == '1':
            if_1()
        elif send == '2':
            if_2()
        elif send == '3':
            if_3()
        elif send == '4':
            if_4()
        elif send == '5':
            if_5()
        else:
            if_else()
Example #9
0
    def click_line(self):

        print('click line')
        self.do_line += 1
        if (self.do_line == 1):
            self.click_vec = []
        if (self.do_line == 2):

            line_id = self.graphic_id
            max_id = 0
            for i in self.graphics:
                max_id = max(max_id, i.graphic_id)
            self.graphic_id = max_id + 1
            algorithm = 'DDA'
            print(self.click_vec, self.R, self.G, self.B)
            new_line = line.line(self.canvas_image, line_id, self.canvas_width,
                                 self.canvas_height, self.R, self.G, self.B)
            new_line.draw_line(self.click_vec[0][0], self.click_vec[0][1],
                               self.click_vec[1][0], self.click_vec[1][1],
                               algorithm)
            self.do_line = 0
            self.graphics.append(new_line)
            self.refresh()
            self.click_vec = []
            return
            self.text2.setText('直线绘制完毕,点击的所有点为\n' + self.last_click_info)
        self.text2.setText('开始绘制直线')
Example #10
0
def solve(l, Xl, Yl, px, py):
    Z = np.zeros([l, l])
    #phase = np.zeros([l, l])
    ln = line()
    line_points = ln.points()

    XX = [line_points[i][0][0] for i in range(0, len(line_points))]
    YY = [line_points[i][0][1] for i in range(0, len(line_points))]
    LL = [line_points[i][1] for i in range(0, len(line_points))]

    # Plot dell'antenna
    plt.plot(YY, XX)

    intg = rk4(1 + 0 * 1j, line_points)
    for x in Xl:
        for y in Yl:

            intg.compute(x / 2, y / 2)

            Ax = intg.A_old[0]
            Ay = intg.A_old[1]  # NULLO

            Z[int(x + px)][int(y + py)] = abs(Ax)  #cm.phase(Ax))

    return Z
Example #11
0
    def __init__(self):
        loc = [0,0] #initial location for side chains
        bol = False #cycloBool
        self.suffixes = {'ol': text('OH', loc, 0), 'amine': text('NH2',loc, 0), 'ene': "double bond", 'en': "double bond", 'yne': "triple bond", 'yn': "triple bond", 'yl': "nothing - yl", 'ane': "alkane", 'an': "alkane" }
        self.numberPrefixes = {'di': 2, 'mono': 1, 'tri': 3,'quat': 4}
 #       self.numberPrefixes = {'di': 2, 'mono': 1, 'tri': 3,'quat': 4, 'penta': 5, 'hexa': 6, 'septa': 7, 'octa': 8, 'nona': 9, 'deca': 10, 'hendeca': 11, 'icosa': 20}
        self.alkaneRoots = {'meth': line(loc, 0, 0), 'eth': carbonBackbone( loc, 2, bol) , 'prop': carbonBackbone( loc, 3, bol) , 'but': carbonBackbone( loc, 4, bol) , 'pent': carbonBackbone( loc, 5, bol) , 'hex': carbonBackbone( loc, 6, bol) , 'hept': carbonBackbone( loc, 7, bol) , 'oct': carbonBackbone( loc, 8, bol) , 'non': carbonBackbone( loc, 9, bol) , 'dec': carbonBackbone( loc, 10, bol) , 'undec': carbonBackbone( loc, 11, bol) , 'dodec': carbonBackbone( loc, 12, bol) }
        self.sideChainRoots = {'iodo': text('I', loc, 0), 'chloro': text('Cl', loc, 0),'floro': text('F', loc, 0), 'bromo': text('Br', loc, 0), "hydroxy": text('OH',loc, 0)  } #sec-butyl, isoStuff, tertStuff 
        self.hyphenatedPrefixes = {'sec': "thing 1", 'tert': "thing 2"}
Example #12
0
 def draw_line(self,res_cmd):
     line_id=int(res_cmd[0])
     x1=int(res_cmd[1])
     y1=int(res_cmd[2])
     x2=int(res_cmd[3])
     y2=int(res_cmd[4])
     algorithm=res_cmd[5]
     new_line = line.line(self.canvas_image,line_id,self.canvas_width,self.canvas_height,self.R,self.G,self.B)
     new_line.draw_line(x1,y1,x2,y2,algorithm)
     self.graphics.append(new_line)
Example #13
0
def get_values_between_indices(a, p):
    l = line(*p)
    ret = []
    for i,j in l:
        try:
            value = a[j,i]
            ret.append(value)
        except IndexError:
            print 'Coord outside the range of the array'

    return np.array(ret)
Example #14
0
    def getLines(self):
        self.lines = []
        sx = self.startPos[0]
        sy = self.startPos[1]
 #       upAngle = 0 #this angle could be a bit bigger or smaller, but I think a 60 degree angle looks good
        downAngle = -math.pi/3
        if not self.cycloBool:
            for i in range(self.numC - 1): #a point is a carbon, so you have the number of carbons - 1 lines
                if i == 0:
                    self.lines.append( line([sx, sy], self.angle, self.bondLength))
                elif i%2 == 0:
                    self.lines.append( line(self.lines[i-1].endPos, self.angle, self.bondLength))
                else:
                    self.lines.append( line(self.lines[i-1].endPos, self.angle  + downAngle, self.bondLength))
            return self.lines
        angleDiff = 2*math.pi/self.numC #exterior angle math
        for i in range(self.numC):
            self.lines.append( line([sx, sy], math.pi/3 + self.angle - angleDiff*i, self.bondLength)) #math.pi/3 makes it start with a certain side
            sx = self.lines[i].endPos[0]
            sy = self.lines[i].endPos[1]
        return self.lines
Example #15
0
	def observe(self):
		#send getData signal to the arduino and get the data back
		#get data into self.Batch
		#Cartesian conversion from Polar coordinates.
		self.Batch = interact.observe()
                toCart.toCartesian(self.Batch)
                #print(self.Batch)
		self.transform()
                self.Batch = iqd.outlierRemoval(self.Batch,1)
                [a1 , b1] = line.line(self.Batch)
                self.m.append(a1)
                self.c.append(b1)
		return
Example #16
0
def drawColoredTriangles(ms, image, bordercol=(255, 255, 255)):
    mcols = edgemtx() + [[]]
    for m, col in ms:
        mcol = m + [[col] * len(m[0])]
        mcols = addEdgeMtxs(mcols, mcol)
    triangles = []
    for i in range(0, len(mcols[0]) - 2, 3):
        # print i, mcols[0][i], mcols[1][i], mcols[0][i + 1], mcols[1][i + 1], mcols[0][i + 2], mcols[1][i + 2], sum(mcols[2][i : i+3]), mcols[4][i]
        triangles.append([
            mcols[0][i], mcols[1][i], mcols[0][i + 1], mcols[1][i + 1],
            mcols[0][i + 2], mcols[1][i + 2],
            sum(mcols[2][i:i + 3]), mcols[4][i]
        ])
    ordTris = sorted(triangles, key=lambda l: l[6])
    for t in ordTris:
        tri = triangle.triangle(*t[:6])
        border = line(*t[:4])
        border.extend(line(*t[2:6]))
        border.extend(line(*t[:2] + t[4:6]))
        coloredtri = [xy + (t[7], )
                      for xy in tri] + [xy + (bordercol, ) for xy in border]
        image.setPixels(coloredtri)
Example #17
0
def drawTriangles(m,
                  image,
                  color=(255, 0, 0),
                  bordercol=(255, 255, 255),
                  hasBorder=True):
    triangles = []
    for i in range(0, len(m[0]) - 2, 3):
        triangles.append([
            m[0][i], m[1][i], m[0][i + 1], m[1][i + 1], m[0][i + 2],
            m[1][i + 2],
            sum(m[2][i:i + 3])
        ])
    ordTris = sorted(triangles, key=lambda l: l[6])
    for t in ordTris:
        tri = triangle.triangle(*t[:6])
        coloredtri = [xy + (color, ) for xy in tri]
        if hasBorder:
            border = line(*t[:4])
            border.extend(line(*t[2:6]))
            border.extend(line(*t[:2] + t[4:6]))
            coloredtri += [xy + (bordercol, ) for xy in border]
        image.setPixels(coloredtri)
 def __init__(self, xml_paragraph):
     (left, top, self._width, self._height) = xml_paragraph.get('bbox').split(',')
     self._width = int(float(self._width))
     self._height = int(float(self._height))
     self._x = int(float(left)) - self._width
     self._y = int(float(top)) - self._height
     #
     xml = xml_paragraph.find_all('textline')
     self._lines = []
     for l in xml:
         self._lines.append(line(l))
     #
     self._font = self._lines[0].font if len(self._lines) > 0 else None
     self._size = self._lines[0].size if len(self._lines) > 0 else None
Example #19
0
def main():
   global linex,linex2
   linex2 = line.line()

   linex = line.line()
   app = QApplication(sys.argv)
   read = codegen1.reader('cif.txt')
   # linex.pp()

   read.file_in_list('cif.txt')


   ex = MainWindow()


   total_file_lines = read.calculate_lines('cif.txt')

   if total_file_lines >80 :
      print("OOPs! Mainframe can't handle more than 80 lines.")
   else:


         ggg = read.get_element_pos_length(10)


         ex.set_text(MF_LINE_COLUMN,1,str(ggg[16]))



   print(ggg[16])



   ex.show()


   sys.exit(app.exec_())
Example #20
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setStyleSheet("""QToolTip {
                           background-color: yellow;
                           color: black;
                           opacity: 1;
                           border: black solid 1px;
                           }""")
        linex = line.line()

        self.mdi = QMdiArea()
        self.setCentralWidget(self.mdi)
        bar = self.menuBar()
        tb = self.addToolBar("Run")
        stg = self.addToolBar("Stage Code")

        file = bar.addMenu("File")
        view = bar.addMenu("Views")
        help = bar.addMenu("Help")

        file.addAction("New")
        file.addAction("Open File")
        file.addAction("Save")
        file.addAction("Save As..")
        file.addAction("cascade")
        file.addAction("Tiled")
        file.addAction("Quit")

        run = QAction(QIcon("D:\work\projects\conv-console\_run_icon"),
                      "Generate Code", self)

        stgg = QAction(QIcon("I:\jectPro\conv-console\stage.bmp"),
                       "Stage Code", self)
        stg.addAction(stgg)
        stg.actionTriggered[QAction].connect(self.stage_code)
        tb.addAction(run)
        tb.actionTriggered[QAction].connect(self.pressed_run)

        view.addAction("Property Window")

        file.triggered[QAction].connect(self.windowaction)
        file.triggered[QAction].connect(self.open_file)

        view.triggered[QAction].connect(self.show_propertyWindow)

        self.setWindowTitle("Convenience Console")

        self.show_propertyWindow()
Example #21
0
 def __init__(self, p1, p2, p3):
     self.a = point(p1)
     self.b = point(p2)
     self.c = point(p3)
     ab = line(self.a, self.b)
     bc = line(self.b, self.c)
     ca = line(self.c, self.a)
     s = (ab.length() + bc.length() + ca.length()) / 2
     self.area = math.sqrt(s * (s - ab.length()) * (s - bc.length()) *
                           (s - ca.length()))
     abc = line(self.a, self.b.midpoint(self.c))
     bac = line(self.b, self.a.midpoint(self.c))
     self.centroid = abc.intersection(bac)
     ax = self.a.dispX(self.centroid)
     ay = self.a.dispY(self.centroid)
     bx = self.b.dispX(self.centroid)
     by = self.b.dispY(self.centroid)
     cx = self.c.dispX(self.centroid)
     cy = self.c.dispY(self.centroid)
     self.Ix = (self.area / 12) * (math.pow(ay, 2) + math.pow(by, 2) +
                                   math.pow(cy, 2))
     self.Iy = (self.area / 12) * (math.pow(ax, 2) + math.pow(bx, 2) +
                                   math.pow(cx, 2))
     self.Ixy = (self.area / 12) * (ax * ay + bx * by + cx * cy)
Example #22
0
   def __init__(self, parent = None):
      super(MainWindow, self).__init__(parent)

      self.setStyleSheet("""QToolTip {
                           background-color: yellow;
                           color: black;
                           opacity: 1;
                           border: black solid 1px;
                           }""")
      linex = line.line()

      self.mdi = QMdiArea()
      self.setCentralWidget(self.mdi)
      bar = self.menuBar()
      tb = self.addToolBar("Run")
      stg = self.addToolBar("Stage Code")

      file = bar.addMenu("File")
      view = bar.addMenu("Views")
      help = bar.addMenu("Help")

      file.addAction("New")
      file.addAction("Open File")
      file.addAction("Save")
      file.addAction("Save As..")
      file.addAction("cascade")
      file.addAction("Tiled")
      file.addAction("Quit")


      run = QAction(QIcon("D:\work\projects\conv-console\_run_icon"),"Generate Code",self)

      stgg = QAction(QIcon("I:\jectPro\conv-console\stage.bmp"),"Stage Code",self)
      stg.addAction(stgg)
      stg.actionTriggered[QAction].connect(self.stage_code)
      tb.addAction(run)
      tb.actionTriggered[QAction].connect(self.pressed_run)

      view.addAction("Property Window")

      file.triggered[QAction].connect(self.windowaction)
      file.triggered[QAction].connect(self.open_file)

      view.triggered[QAction].connect(self.show_propertyWindow)

      self.setWindowTitle("Convenience Console")

      self.show_propertyWindow()
Example #23
0
 def __init__(self, dataStr):
     self.curves = []
     if not re.match(r"^[Mm]", dataStr):
         raise "no start point"
     _ds = re.sub(r"([Mm])", r"\1:", dataStr)
     _ds = re.sub(r"([LHVCSQTAZlhvcsqtaz])", r";\1:", _ds)
     _ds = re.sub(r"-", r",-", _ds)
     _ds = re.sub(r"([:,]),", r"\1", _ds)
     for c in _ds.split(";"):
         _dt = c.split(":")
         if len(_dt) < 2:
             break
         _command = re.sub(r"\s", "", _dt[0])
         _ss = re.sub("-", ",-", _dt[1])
         _ss = re.sub("\s", ",", _ss)
         _ss = re.sub(r"^[,]+", '', _ss)
         _ss = re.sub(r"[,]+", ',', _ss)
         _ps = _ss.split(",")
         
         if 'M' == _command or 'm' == _command:
             _obj = point(_ps[0], _ps[1])
         elif 'L' == _command:
             _obj = line(_obj.end, point(_ps[0], _ps[1]))
         elif 'l' == _command:
             _obj = line(_obj.end, _obj.end.move(_ps[0], _ps[1]))
         elif 'H' == _command:
             _obj = line(_obj.end, point(_ps[0], _obj.end.y))
         elif 'h' == _command:
             _obj = line(_obj.end, _obj.end.move(_ps[0], 0))
         elif 'V' == _command:
             _obj = line(_obj.end, point(_obj.end.x, _ps[1]))
         elif 'v' == _command:
             _obj = line(_obj.end, _obj.end.move(0, _ps[1]))
         elif 'C' == _command:
             _obj = curve(_obj.end, point(_ps[0], _ps[1]), point(_ps[2], _ps[3]), point(_ps[4], _ps[5]))
         elif 'c' == _command:
             _obj = curve(_obj.end, _obj.end.move(_ps[0], _ps[1]), _obj.end.move(_ps[2], _ps[3]), _obj.end.move(_ps[4], _ps[5]))
         elif 'S' == _command:
             _obj = curve(_obj.end, _obj.refCon(), point(_ps[0], _ps[1]), point(_ps[2], _ps[3]))
         elif 's' == _command:
             _obj = curve(_obj.end, _obj.refCon(), _obj.end.move(_ps[0], _ps[1]), _obj.end.move(_ps[2], _ps[3]))
         elif 'Q' == _command:
             _obj = qcurve(_obj.end, point(_ps[0], _ps[1]), point(_ps[2], _ps[3]))
         elif 'q' == _command:
             _obj = qcurve(_obj.end, _obj.end.move(_ps[0], _ps[1]), _obj.end.move(_ps[2], _ps[3]))
         elif 'T' == _command:
             _obj = qcurve(_obj.end, _obj.refCon(), point(_ps[0], _ps[1]))
         elif 't' == _command:
             _obj = qcurve(_obj.end, _obj.refCon(), _obj.end.move(_ps[0], _ps[1]))
         elif 'A' == _command:
             ''
         else: break
         
         
         self.curves.append(_obj)
Example #24
0
 def createMask(self,ps_,ind):
     self.ps=ps_;
     self.size=len(ps_);
     self.lines=[];        
     for i in range(0,self.size):
         self.lines.append(line(self.ps[i],self.ps[i-1]));
         
     for i in range(0,480):
         for j in range(0,640):
             p=point(j,i)
             h_=True;
             for ln in self.lines:
                 if(ln.check_outside(p,35)): 
                     self.mask[i][j]=1;
                     
                 if(ln.check_within_p1(p,35)):
                     self.mask[i][j]=1;
                     
                 if(not ln.check_within(p)):
                     h_=False;
             if(h_):
                 self.mask[i][j]=1;
Example #25
0
    def fill():
        toppoint = None
        botpoint = None
        if self.points[0].y <= self.points[1].y:
            if self.points[0].y <= self.points[2].y:
                botpoint = self.points[0]
            else:
                botpoint = self.points[2]
        elif self.points[1].y <= self.ponts[2].y:
            botpoint = self.points[1]
        else:
            botpoint = self.points[2]

        if self.points[0].y >= self.points[1].y:
            if self.points[0].y >= self.points[2].y:
                toppoint = self.points[0]
            else:
                toppoint = self.points[2]
        elif self.points[1].y >= self.ponts[2].y:
            toppoint = self.points[1]
        else:
            toppoint = self.points[2]

        side = line(self.points[0], self.points[1], 100)
Example #26
0
def features():
    city = open(home + '\\CITY', 'w')
    city.write(sub(r'.*/', '', str(get_localzone())).upper())
    city.close()
    if isdir(home + '\\.CGT'):
        if not isfile(home + '\\.CGT\\files\\CITY'):
            move(home + '\\CITY', home + '\\.CGT\\files\\CITY')
    try:
        _language = open(home + '\\CITY', 'r').read()
    except:
        _language = open(home + '\\.CGT\\files\\CITY', 'r').read()
    if isfile(Lang):
        if language == 'EN':
            clear()
            print(line())
            print('\t\t\t              ' + c.RED + ':' + c.GREEN + ':' +
                  c.BLUE + ': ' + c.RED + version + c.GREEN + ' - ' + c.BLUE +
                  'C' + c.GREEN + 'G' + c.RED + 'T' + c.GREEN + ' - ' + c.RED +
                  language + c.BLUE + ' :' + c.GREEN + ':' + c.RED + ':')
            print(line())
            print(c.END + c.RED + '           c' + c.BLUE + '.' + c.YELLOW +
                  'clear screen' + '          ' + c.RED + 'z' + c.BLUE + '.' +
                  c.YELLOW + 'change language to' + c.GREEN + ' : ' + c.RED +
                  'persian' + '            ' + c.RED + 'e' + c.BLUE + '.' +
                  c.YELLOW + 'exit from CGT')
            print(line())
            print(c.END + c.RED + ' 1' + c.BLUE + '.' + c.YELLOW + 'convert' +
                  c.GREEN + ' .img.lz4 ' + c.YELLOW + 'to' + c.GREEN + ' .img')
            print(c.END + c.RED + ' 2' + c.BLUE + '.' + c.YELLOW + 'unpack ' +
                  c.GREEN + 'boot' + c.RED + '/' + c.GREEN + 'recovery')
            print(c.END + c.RED + ' 3' + c.BLUE + '.' + c.YELLOW + 'repack ' +
                  c.GREEN + 'boot' + c.RED + '/' + c.GREEN + 'recovery')
            print(c.END + c.RED + ' 4' + c.BLUE + '.' + c.YELLOW +
                  'bypass screen lock' + c.RED + ' - ' + c.YELLOW + 'samsung' +
                  c.RED + ' - ' + c.YELLOW + 'method one ' + c.GREEN + '[' +
                  c.RED + 'need to boot' + c.GREEN + ']')
            print(c.END + c.RED + ' 5' + c.BLUE + '.' + c.YELLOW +
                  'generate imei')
        elif language == 'FA':
            clear()
            print(line())
            print('\t\t\t              ' + c.RED + ':' + c.GREEN + ':' +
                  c.BLUE + ': ' + c.RED + version + c.GREEN + ' - ' + c.BLUE +
                  'C' + c.GREEN + 'G' + c.RED + 'T' + c.GREEN + ' - ' + c.RED +
                  language + c.BLUE + ' :' + c.GREEN + ':' + c.RED + ':')
            print(line())
            print(c.END + c.RED + '           e' + c.BLUE + '.' + c.YELLOW +
                  'khoroj az CGT' + '          ' + c.RED + 'z' + c.BLUE + '.' +
                  c.YELLOW + 'taghir zaban be' + c.GREEN + ' : ' + c.RED +
                  'english' + '          ' + c.RED + 'c' + c.BLUE + '.' +
                  c.YELLOW + 'tamiz kardan safhe')
            print(line())
            print(c.END + c.RED + ' 1' + c.BLUE + '.' + c.YELLOW + 'tabdil' +
                  c.GREEN + ' .img.lz4 ' + c.YELLOW + 'be' + c.GREEN + ' .img')
            print(c.END + c.RED + ' 2' + c.BLUE + '.' + c.YELLOW +
                  'estekhraj ' + c.GREEN + 'boot' + c.RED + '/' + c.GREEN +
                  'recovery')
            print(c.END + c.RED + ' 3' + c.BLUE + '.' + c.YELLOW +
                  'feshorde kardan dobare ' + c.GREEN + 'boot' + c.RED + '/' +
                  c.GREEN + 'recovery')
            print(c.END + c.RED + ' 4' + c.BLUE + '.' + c.YELLOW +
                  'dor zadan ghofle safhe' + c.RED + ' - ' + c.YELLOW +
                  'samsung ' + c.RED + ' - ' + c.YELLOW + 'ravesh aval ' +
                  c.GREEN + '[' + c.RED + 'niaz be boot' + c.GREEN + ']')
            print(c.END + c.RED + ' 5' + c.BLUE + '.' + c.YELLOW +
                  'tolid imei')
    else:
        if _language == 'TEHRAN':
            clear()
            print(line())
            print('\t\t\t              ' + c.RED + ':' + c.GREEN + ':' +
                  c.BLUE + ': ' + c.RED + version + c.GREEN + ' - ' + c.BLUE +
                  'C' + c.GREEN + 'G' + c.RED + 'T' + c.GREEN + ' - ' + c.RED +
                  'FA' + c.BLUE + ' :' + c.GREEN + ':' + c.RED + ':')
            print(line())
            print(c.END + c.RED + '           e' + c.BLUE + '.' + c.YELLOW +
                  'khoroj az CGT' + '          ' + c.RED + 'z' + c.BLUE + '.' +
                  c.YELLOW + 'taghir zaban be' + c.GREEN + ' : ' + c.RED +
                  'english' + '          ' + c.RED + 'c' + c.BLUE + '.' +
                  c.YELLOW + 'tamiz kardan safhe')
            print(line())
            print(c.END + c.RED + ' 1' + c.BLUE + '.' + c.YELLOW + 'tabdil' +
                  c.GREEN + ' .img.lz4 ' + c.YELLOW + 'be' + c.GREEN + ' .img')
            print(c.END + c.RED + ' 2' + c.BLUE + '.' + c.YELLOW +
                  'estekhraj ' + c.GREEN + 'boot' + c.RED + '/' + c.GREEN +
                  'recovery')
            print(c.END + c.RED + ' 3' + c.BLUE + '.' + c.YELLOW +
                  'feshorde kardan dobare ' + c.GREEN + 'boot' + c.RED + '/' +
                  c.GREEN + 'recovery')
            print(c.END + c.RED + ' 4' + c.BLUE + '.' + c.YELLOW +
                  'dor zadan ghofle safhe' + c.RED + ' - ' + c.YELLOW +
                  'samsung ' + c.RED + ' - ' + c.YELLOW + 'ravesh aval ' +
                  c.GREEN + '[' + c.RED + 'niaz be boot' + c.GREEN + ']')
            print(c.END + c.RED + ' 5' + c.BLUE + '.' + c.YELLOW +
                  'tolid imei')
        elif _language != 'TEHRAN':
            clear()
            print(line())
            print('\t\t\t              ' + c.RED + ':' + c.GREEN + ':' +
                  c.BLUE + ': ' + c.RED + version + c.GREEN + ' - ' + c.BLUE +
                  'C' + c.GREEN + 'G' + c.RED + 'T' + c.GREEN + ' - ' + c.RED +
                  'EN' + c.BLUE + ' :' + c.GREEN + ':' + c.RED + ':')
            print(line())
            print(c.END + c.RED + '           c' + c.BLUE + '.' + c.YELLOW +
                  'clear screen' + '          ' + c.RED + 'z' + c.BLUE + '.' +
                  c.YELLOW + 'change language to' + c.GREEN + ' : ' + c.RED +
                  'persian' + '            ' + c.RED + 'e' + c.BLUE + '.' +
                  c.YELLOW + 'exit from CGT')
            print(line())
            print(c.END + c.RED + ' 1' + c.BLUE + '.' + c.YELLOW + 'convert' +
                  c.GREEN + ' .img.lz4 ' + c.YELLOW + 'to' + c.GREEN + ' .img')
            print(c.END + c.RED + ' 2' + c.BLUE + '.' + c.YELLOW + 'unpack ' +
                  c.GREEN + 'boot' + c.RED + '/' + c.GREEN + 'recovery')
            print(c.END + c.RED + ' 3' + c.BLUE + '.' + c.YELLOW + 'repack ' +
                  c.GREEN + 'boot' + c.RED + '/' + c.GREEN + 'recovery')
            print(c.END + c.RED + ' 4' + c.BLUE + '.' + c.YELLOW +
                  'bypass screen lock' + c.RED + ' - ' + c.YELLOW + 'samsung' +
                  c.RED + ' - ' + c.YELLOW + 'method one ' + c.GREEN + '[' +
                  c.RED + 'need to boot' + c.GREEN + ']')
            print(c.END + c.RED + ' 5' + c.BLUE + '.' + c.YELLOW +
                  'generate imei')
Example #27
0
    def getpoints(self):
        mtx = matrix()
        mtx.translate(self.loc)
        mtx.rotatex(self.angles.x)
        mtx.rotatey(self.angles.y)
        mtx.rotatez(self.angles.z)
        tatered = []
        for vertex in self.vertices:
            tatered.append(vertex.transform(mtx))

        for p, q in zip(
                line(tatered[0], tatered[1], 50).getpoints(),
                line(tatered[2], tatered[3], 50).getpoints()):
            for r in line(p, q, 50).getpoints():
                yield r
        for p, q in zip(
                line(tatered[4], tatered[5], 50).getpoints(),
                line(tatered[6], tatered[7], 50).getpoints()):
            for r in line(p, q, 50).getpoints():
                yield r

        for p, q in zip(
                line(tatered[0], tatered[1], 50).getpoints(),
                line(tatered[4], tatered[5], 50).getpoints()):
            for r in line(p, q, 50).getpoints():
                yield r
        for p, q in zip(
                line(tatered[2], tatered[3], 50).getpoints(),
                line(tatered[6], tatered[7], 50).getpoints()):
            for r in line(p, q, 50).getpoints():
                yield r

        for p, q in zip(
                line(tatered[0], tatered[2], 50).getpoints(),
                line(tatered[4], tatered[6], 50).getpoints()):
            for r in line(p, q, 50).getpoints():
                yield r
        for p, q in zip(
                line(tatered[1], tatered[3], 50).getpoints(),
                line(tatered[5], tatered[7], 50).getpoints()):
            for r in line(p, q, 50).getpoints():
                yield r

        for v in self.vertices:
            yield v.transform(mtx)
Example #28
0
pedistrain = cv2.Canny(pedistrain, 50, 200)

W, H = 64, 64
w, h = 240, 320
width = w - W + 1
height = h - H + 1

NoDr, Noth, Ped, maxZ = 0, 0, 0, "Nothing"

s = '111'

while True:
    ret, frame = cap.read()
    crop_frame = frame[:240, 320:]
    res = mt.signs(crop_frame, noDrive, pedistrain, W, H, w, h)
    lineRes = line.line(frame, ser)
    if res == 'NoDr':
        NoDr += 1
    elif res == 'Ped':
        Ped += 1
    else:
        Noth += 1

    if max(NoDr, Ped, Noth) >= 13:
        if max(NoDr, Ped, Noth) == NoDr:
            maxZ = "1"
        elif max(NoDr, Ped, Noth) == Ped:
            maxZ = "2"
        elif max(NoDr, Ped, Noth) == Noth:
            maxZ = "3"
Example #29
0
 def rect_border_line(start_x, start_y, end_x, end_y):
     # closure of canvas and border
     line(canvas, start_x, start_y, end_x, end_y, border)
Example #30
0
def line_message(message):
    line(message)
    return 'OK! message: ' + message
Example #31
0
    plt.figure()
    x, y, z = _test_profile()
    plt.contour(x, y, z)
    chord = [(0,1.0), (0.5, 0.5)]
    plt.plot(*chord)


if __name__ == '__main__':
    import doctest
    doctest.testmod()

    import matplotlib.pyplot as plt
    plt.figure(1); plt.clf()
    x, y, f = _test_profile()
    plt.contour(x, y, f)
    plt.colorbar()
    chord = [(0,0.6), (0.0, 0.6)]
    plt.plot(*chord)

    endpoints = chord_endpoints(chord, x, y)
    l = line(*endpoints)

    x_coords = get_values_between_indices(x, endpoints)
    y_coords = get_values_between_indices(y, endpoints)
    plt.plot(x_coords, y_coords, 'ko')

    d, p = profile_along_chord(chord, x, y, f)
    plt.draw()
    plt.show()

Example #32
0
def camtest():
    import shape
    fov = 100
    cam = Camera(0.5,0.5,0.8,0,0,0,0,0,1 / math.tan(fov / 2.))
    camargs = [100,100,-50,-300]
    camT = transform.C3(*camargs)*transform.T(-250, -250,-175)
    print camT
    ncamT = transform.C3invT(*camargs)
    print ncamT
    v = [250,250,1000]
    lights = [Light(500,0,500,(20,20,20),(200,200,200),(255,255,255)),
              Light(500,500,200,(20,20,20),(200,200,200),(255,255,255)),
              Light(0,250,500,(20,20,20),(200,200,200),(255,255,255))
    ]
    camlights = []
    for l in lights:
        x = dot4xyz(camT[0], l.x, l.y, l.z)
        y = dot4xyz(camT[1], l.x, l.y, l.z)
        z = dot4xyz(camT[2], l.x, l.y, l.z)
        w = dot4xyz(camT[3], l.x, l.y, l.z)*1.
        print x/w*250,y/w*250,z/w*250
        camlights.append(Light(x/w*250, y/w*250, z/w*250,l.Ia,l.Id,l.Is))
    tris, norms = shape.box(200,200,-100,100,100,200)
    print norms
    print ncamT * norms
    print list(triIter(tris))
    trot = transform.R('y',5)
    nrot = transform.TransMatrix()
    nrot.lst = matrix.transpose(transform.R('y',-5))
    tmat = transform.T(250,250,0)*trot*transform.T(-250,-250,0)
    tris = tmat*tmat*tmat*tris
    norms= trot*trot*trot*norms
    print norms
    print ncamT*norms
    amb = Texture(False, [255,0,0])
    diff = Texture(False, [255,0,0])
    spec = Texture(False, [255,150,150])
    mat = Material(amb, diff, spec, 10)
    for i in range(72):
        #print tris
        tricam = camT * tris
        #print tricam
        #tricam[3] = [1.] * len(tricam[3])
        #tricam = transform.T(*v) * tricam
        print 'trans done'
        a = time()
        zbuf = [[None]*500 for _ in range(500)]
        img = Image(500,500)
        trit = list(triIter(tricam))
        #print trit,tricam
        trit.sort(key=lambda tri: -tri[0][2] - tri[1][2] - tri[2][2])
        normcam = ncamT*norms
        normt = []
        for j in range(len(normcam[0])):
            sgn = (normcam[3][j] > 0) * 2 - 1
            normt.append(normalize(normcam[0][j]*sgn, normcam[1][j]*sgn, normcam[2][j]*sgn))
        print normt
        #print len(trit), len(normt)
        for j in range(len(trit)):
            # (p1, p2, p3, mat, vx, vy, vz, lights, texcache, zbuf):
            t = trit[j]
            ps = []
            for pt in t:
                pt[0]+=250
                pt[1]+=250
                pt[2]+=0
                print pt
                ps.append(Point(*pt + normt[j] + [0,0]))
            img.setPixels(renderTriangle(*ps + [mat] + v + [camlights, {}, zbuf]))
        for t in trit:
            l = line(*t[0][:2]+t[1][:2])
            l += line(*t[0][:2]+t[2][:2])
            l += line(*t[2][:2]+t[1][:2])
            img.setPixels([p + ((0,0,0),) for p in l])

        for j in range(len(trit)):
            t = trit[j]
            ps = []
            for pt in t:
                nls = line(pt[0] - 4, pt[1], pt[0] + 4, pt[1])
                nls += line(pt[0], pt[1] - 4, pt[0], pt[1] + 4)
                nls += line(pt[0] - 4, pt[1] - 4, pt[0] + 4, pt[1] + 4)
                nls += line(pt[0] - 4, pt[1] + 4, pt[0] + 4, pt[1] - 4)
                nls += line(pt[0], pt[1], pt[0] + normt[j][0]*20, pt[1] + normt[j][1]*20)
                print normt[j][0], normt[j][1]
                img.setPixels([p + ((0,255,0),) for p in nls])
        
        img.savePpm('cube/%d.ppm'%(i))
        tris = tmat * tris
        norms = nrot * norms
        print norms
        print i, (time() - a) * 1000, 'ms'
Example #33
0
    def paintEvent(self, event):
        painter = QPainter(self)
        colors = [Qt.red, Qt.blue, Qt.green, Qt.yellow, Qt.magenta, Qt.gray]
        painter.setPen(QPen(colors[1], 2))
        # print(self.lines)

        allLines = []
        allWalls = []

        for b in self.lines:
            walls = []
            for x in range(6):
                walls.append(wall(colors[x]))
            counter = 0
            for l in b:
                viewedLine = []
                for p in l:
                    # tutaj sa rzutowane punkty
                    x = (self.lens / p[1]) * p[0] + self.screen_size[0] / 2
                    y = self.screen_size[1] / 2 - (self.lens / p[1]) * p[2]
                    viewedPoint = (x, y)
                    # if(p[1] > self.lens): // to jest usuwanie krawedzie po za ekranem
                    viewedLine.append(viewedPoint)

                # if(len(viewedLine) > 1):  to jest usuwanie krawedzie po za ekranem
                objL = line(viewedLine, l)
                if counter in [0, 1, 2, 3]:
                    objL.attachWall(walls[0])
                    walls[0].attachLine(objL)
                if counter in [1, 4, 9, 6]:
                    objL.attachWall(walls[1])
                    walls[1].attachLine(objL)
                if counter in [9, 8, 11, 10]:
                    objL.attachWall(walls[2])
                    walls[2].attachLine(objL)
                if counter in [3, 7, 11, 5]:
                    objL.attachWall(walls[3])
                    walls[3].attachLine(objL)
                if counter in [6, 2, 10, 7]:
                    objL.attachWall(walls[4])
                    walls[4].attachLine(objL)
                if counter in [0, 4, 8, 5]:
                    objL.attachWall(walls[5])
                    walls[5].attachLine(objL)

                allLines.append(objL)

                # stare rysowanie
                painter.drawPolyline(
                    QPolygon([
                        QPoint(int(viewedLine[0][0]), int(viewedLine[0][1])),
                        QPoint(int(viewedLine[1][0]), int(viewedLine[1][1]))
                    ]))

                counter += 1

            for w in walls:
                w.createEquation()
                allWalls.append(w)

        print(allWalls)
        print(allLines)
Example #34
0
   def search(self, fmin=-1, fmax=-1, species=[], origin='All', dbsource='All', energy=-1, einstein=-1):
      """
      Search lines in the cache

      Arguments:
      fmin   -- the minimum frequency in MHz
      fmax   -- the maximum frequency in MHz
      species -- the species name (a string or list of strings). String 'All'
                 is an alias for no selection.
      origin -- (default All)
      energy -- maximum upper level energy expressed
              in Kelvins (default -1)
      einstein -- coefficient to match (default -1)

      """

      if (type(species) == str):
        if (species == 'All'):
          lspecies = []  # Empty list (no selection by species)
        else:
          lspecies = [species]  # Store single string to a list
      elif (type(species) == list):
        lspecies = species
      else:
        raise Exception, "Unexpected kind of argument: "+repr(species)

      db_connect = self.connect(new=False)
      db_connect.row_factory = sqlite3.Row
      db_cursor = db_connect.cursor()

      lines = []
      if fmin < 0:
         fmin = 0
      fmi = "%f" % fmin
      args = (fmi, )
      query = "select * from line where frequency >= ?"
      if fmax > 0:
         fma = "%f" % fmax
         query += " and frequency <= ?"
         args = args + (fma, )
      started = False
      for s in lspecies:
         # NB: AND logical operator has precedence over OR. Must use parenthesis e.g.
         # ... and ( species = AA or species like B* or species = CC )
         s = s.replace('*','%')
         query += (" and (" if not started else "or") + " species " + ('like' if ('%' in s) else '=') + " ? "
         args = args + (s, )
         started = True
      if started:
         query += ")"
      if origin != "All":
         query += " and origin = ?"
         args = args + (origin.lower(), )  # Case-insensitive search
      if dbsource != "All":
         query += " and dbsource = ?"
         args = args + (dbsource, )
      if energy > 0:
         uel = "%f" % energy
         query += " and upper_level_energy <= ?"
         args = args + (uel, )
      if einstein > 0:
         ein = "%f" % einstein
         query += " and einstein_coefficient >= ?"
         args = args + (ein, )

      db_cursor.execute(query, args)
      db_connect.commit()
      for row in db_cursor:
         l = line.line()
         l.species = row ['species']
         l.frequency = row ['frequency']
         l.err_frequency = row ['uncertainty']
         l.einstein_coefficient = row ['einstein_coefficient']
         l.upper_level.energy = row ['upper_level_energy']
         l.upper_level.statistical_weight = row ['upper_level_statistical_weight']
         l.upper_level.quantum_numbers = row ['upper_level_quantum_numbers']
         l.lower_level.energy = row ['lower_level_energy']
         l.lower_level.statistical_weight = row ['lower_level_statistical_weight']
         l.lower_level.quantum_numbers = row ['lower_level_quantum_numbers']
         l.origin = row ['origin']
         l.prev = row ['dbsource'] # we need to keep that info as well, for when calling part_func, while inserting lines.
         l.date = row ['date']
         lines.append(l)

      db_cursor.close()

      return lines
Example #35
0
center = [0.0, -len(img)/2.0]
PI = 3.1416
ds = 0.75
dt = 0.75
offspring = 2

# initial branch
b1 = Branch(0)
b1.angle = 90
b1.size = size
b1.thick = thick
b1.begin = [center[0] + 0.0, center[1] + 0.0]
b1.end = [center[0] + b1.size * math.cos((b1.angle) * PI / 180.0), center[1] + b1.size * math.sin((b1.angle) * PI / 180.0)]
branches = []
branches.append(b1)
ln.line(branches[0].begin, branches[0].end, thick, color, img)

i = 0
fr = 0
drawing = True

while(True):
    length = len(branches)
    for b in range(offspring):
        son = Branch(length - (i + 1))
        son.angle = branches[son.father].angle + (angle) * (-1)**(b)
        son.size = branches[son.father].size * ds
        son.thick = branches[son.father].thick * dt
        x = son.size * math.cos((son.angle) * PI / 180.0) + branches[son.father].end[0]
        y = son.size * math.sin((son.angle) * PI / 180.0) + branches[son.father].end[1]
        son.begin = branches[son.father].end
Example #36
0
import line

notify = line.line('token')

notify.send_message('hello world')
notify.send_photo(
    'https://p176.p0.n0.cdn.getcloudapp.com/items/2NuxGZrk/a.jpg')
notify.send_photo('a.png')
Example #37
0
from line import line
from base import Image

img = Image(500, 500)
y = lambda x: 500 * (x / 250. - 1)**2
dy = lambda x: 4 * (x / 250. - 1)
xs = range(0, 501, 4)
ys = [y(x) for x in xs]
xys = zip(xs, ys)
points = []
for x, y in xys:
    slope = dy(x)
    y0 = int(-slope * x + y)
    y500 = int(slope * (500 - x) + y)
    pts = line(0, y0, 500, y500)
    pts = filter(lambda tup: 500 > tup[0] >= 0 and 500 > tup[1] >= 0, pts)
    coloredpoints = [(px, py, (x / 2, y / 2, (x + y) / 4)) for px, py in pts]
    points.extend(coloredpoints)
img.setPixels(points)
img.saveAs('cool.png')
img.display()
Example #38
0
def drawEdges(m, image, color=(255, 0, 0)):  # draws the edges to an image
    for i in range(0, len(m[0]) - 1, 2):
        lin = line(m[0][i], m[1][i], m[0][i + 1], m[1][i + 1])
        coloredlin = [xy + (color, ) for xy in lin]
        image.setPixels(coloredlin)
Example #39
0
                    p = top_point[i - 2]
                koch_edges.append([p, top_point[i - 1]])
            koch_edges.append(
                [top_point[len(top_point) - 1], segs[len(segs) - 1]])
            koch_edges.append([segs[len(segs) - 1], pt2])
    else:
        return


# create the first polygon sides
for i in range(sides):
    angle = (i * step_angle) + (step_angle / 2.0) + 90.0
    x = radius * math.cos(angle * (3.1416 / 180.0))
    y = radius * math.sin(angle * (3.1416 / 180.0))
    fig_pts.append([int(x), int(y)])

# call function for each edge
for i in range(sides):
    curr_iter = 0
    koch_curve(fig_pts[i], fig_pts[(i + 1) % sides], curr_iter)

# draw the fractal
for i in range(len(koch_edges)):
    ln.line(koch_edges[i][0], koch_edges[i][1], thick, color, img)

# show image
plt.plot(), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('Iterations = {}, Thick = {}'.format(num_iter, thick)), plt.xticks(
    []), plt.yticks([])
plt.show()
Example #40
0
 def but_start(self):
     keyword = self.lineEdit_keyword.text()
     pagenum = self.lineEdit_page.text()
     if self.comboBox.currentText() == 'ALL':
         stormClimb(int(pagenum) + 1, keyword)
         EBCclimb(int(pagenum) + 1, keyword)
         ETtodayClimb(int(pagenum) + 1, keyword)
         udnClimb(int(pagenum) + 1, keyword)
         BBCclimb(int(pagenum), keyword)
         chinatimeClimb(int(pagenum) + 1, keyword)
         pttGossip(int(pagenum) + 1, keyword)
         pttMoney(int(pagenum) + 1, keyword)
         TVBSclimb(int(pagenum) + 1, keyword)
         todayClimb(int(pagenum) + 1, keyword)
         pchome(int(pagenum) + 1, keyword)
         crossing_news(int(pagenum) + 1, keyword)
         CW(int(pagenum) + 1, keyword)
         hket_news(int(pagenum) + 1, keyword)
         liberty_times(int(pagenum) + 1, keyword)
         line(int(pagenum) + 1, keyword)
         tech_news(int(pagenum) + 1, keyword)
         dcard(keyword)
         set_news(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'Storm(1頁16筆)':
         stormClimb(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'EBC(1頁30筆)':
         EBCclimb(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'ETtoday(1頁20筆)':
         ETtodayClimb(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'udn(1頁20筆)':
         udnClimb(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'BBC(1頁10筆)':
         BBCclimb(int(pagenum), keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == '中時(1頁20筆)':
         chinatimeClimb(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'ptt八卦版(1頁20筆)':
         pttGossip(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'ptt省錢版(1頁20筆)':
         pttMoney(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'TVBS(1頁25筆)':
         TVBSclimb(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == '今周刊(1頁10筆)':
         todayClimb(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'pchome':
         pchome(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == '天下雜誌':
         CW(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == '換日線':
         crossing_news(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'hket_news':
         hket_news(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == '自由時報(請輸入筆數)':
         liberty_times(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'line新聞':
         line(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'tech_news':
         tech_news(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == 'Dcard(僅輸入關鍵字)':
         dcard(keyword)
         self.label_news.setText('done!')
     if self.comboBox.currentText() == '三立新聞':
         set_news(int(pagenum) + 1, keyword)
         self.label_news.setText('done!')
Example #41
0
    def plotline(self,
                 line,
                 res=0,
                 scale=1,
                 transform=True,
                 interpolate=False,
                 save=False):
        """ FUNCTION plotline
        plots the field along the defined line

        INPUT:
        line:       line, the input line, defined along the cartesian basis
        integer:    res, the resolution (if 0 then assume gridsize)
        bool:       interpolate, a flag that determines whether trilinear interpolation should be used

        Shows a matplotlib output
        """
        if res == 0:
            res = self.f_size[np.argmax(line.dir)]
        # transform the position and direction to fit the grid, move position
        # to edge of grid
        if transform:
            tpos = self.trans_point_to_space(line.pos)
            tdir = self.trans_point_to_space(line.dir)
            tline = li.line(pos=tpos, dir=tdir)
        else:
            tline = line

        validCheck = self.has_line(tline)
        if not validCheck[0]:
            sys.exit("line choice invalid")
        start = validCheck[1][0]
        end = validCheck[1][1]
        # hacky way to avoid dups
        if np.array_equal(start, end):
            end = validCheck[1][2]

        if not tline.dir[0] == 0:
            if tline.dir[0] / (end[0] - start[0]) < 0:
                tstart = end
                tend = start
            else:
                tstart = start
                tend = end
        elif not tline.dir[1] == 0:
            if tline.dir[1] / (end[1] - start[1]) < 0:
                tstart = end
                tend = start
            else:
                tstart = start
                tend = end
        elif not tline.dir[2] == 0:
            if tline.dir[2] / (end[2] - start[2]) < 0:
                tstart = end
                tend = start
            else:
                tstart = start
                tend = end
        else:
            sys.exit("direction invalid")

        ndir = (tend - tstart) / res

        # pick integer values of position each time
        # ppos = parameterized position
        ppos = np.arange(res)
        data = np.zeros(res)
        for i in ppos:
            ipos = tstart + (ndir * i)
            if not interpolate:
                ipos = np.rint(ipos)
                try:
                    data[i] = self.f_field[int(ipos[0]),
                                           int(ipos[1]),
                                           int(ipos[2])]
                except IndexError:
                    # fix later
                    print("WARNING: plotpoint (%i, %i, %i) ignored" %
                          (ipos[0], ipos[1], ipos[2]))
                    continue
            else:
                data[i] = self.interpolate(ipos)

        data = scale * data

        if save:
            f = plt.figure(figsize=(12, 1), dpi=133)
        plt.plot(ppos, data)
        #plt.show()
        if save:
            f.savefig('temp.png', transparent=True)
        return data