Exemplo n.º 1
0
 def OnExit(self, event):
     wx.MessageBox('Hello again')
Exemplo n.º 2
0
    def OnClickSearchScore(self, event):
        self.fanhao = self.txt_fanhao.GetValue()
        self.lblStates.SetLabel('正在查编辑得分:' + self.fanhao)
        headers = {
            'content-type':
            'application/json',
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
        }

        try:
            requ_other = requests.get(
                'http://www.ja14b.com/cn/vl_searchbyid.php?keyword=' +
                self.fanhao,
                headers=headers,
                timeout=2).content
        except:
            wx.MessageBox("获取网址超时", "Message", wx.OK | wx.ICON_INFORMATION)
            return
        self.lblStates.SetLabel('请求编辑得分成功,正在获取内容')
        # 获取标签内容
        soup_other = BeautifulSoup(requ_other,
                                   'html.parser',
                                   from_encoding='utf-8')
        # 先判断是否能正常搜索到内容
        is404 = soup_other.find(
            'p', {'style': 'text-align: center; color: #C0C0C0;'})
        if is404 is not None:
            wx.MessageBox("该番号查不到", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        isNone = soup_other.find('div', id='badalert')
        if isNone is not None:
            wx.MessageBox("该番号查不到", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        isDouble = soup_other.find('div', class_=re.compile(r'videos'))
        if isDouble is not None:
            print(isDouble)
            url = isDouble.a.get('href')
            url = 'http://www.ja14b.com/cn' + url[1:]
            print(url)
            requ_double = requests.get(url, headers=headers, timeout=2).content
            soup_double = BeautifulSoup(requ_double,
                                        'html.parser',
                                        from_encoding='utf-8')
            other_score = soup_double.find('span', class_='score')
            self.other_score = other_score.string[1:-1]
            self.lblOtherscore.SetLabel('编辑得分:' + self.other_score)
            print(other_score)
            self.lblStates.SetLabel('已经获取编辑得分')
            #wx.MessageBox("已经获取编辑得分", "Message", wx.OK | wx.ICON_INFORMATION)
        else:
            other_score = soup_other.find('span', class_='score')
            if other_score is None:
                self.other_score = '0'
            else:
                self.other_score = other_score.string[1:-1]
            self.lblOtherscore.SetLabel('编辑得分:' + self.other_score)
            print(other_score)
            self.lblStates.SetLabel('已经获取编辑得分')
 def showsusscebox(self):
     wx.MessageBox('用例已导出!', 'Info', wx.OK | wx.ICON_INFORMATION)
Exemplo n.º 4
0
 def OnAbout(self, event):
     wx.MessageBox(message=about_me,
                   caption='关于' + app_name,
                   style=wx.OK | wx.ICON_INFORMATION)
Exemplo n.º 5
0
    def OnClickStore(self, event):

        if self.name == '':
            wx.MessageBox("请勿乱点", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        def mdb_conn(password=""):
            # 功能:创建数据库连接 :param db_name: 数据库名称 :param db_name: 数据库密码,默认为空 :return: 返回数据库连接

            str = 'driver={Microsoft Access Driver (*.mdb)};PWD' + password + ";DBQ=fun.mdb"
            conn = pypyodbc.win_connect_mdb(str)
            return conn

        conn = mdb_conn()
        cur = conn.cursor()

        # 把所有数据插入av_record表
        sql_sel = "SELECT COUNT(*) FROM west_record WHERE movie_name = '" + self.name + "'"
        cur.execute(sql_sel)
        num_fanhao = cur.fetchall()[0][0]
        if num_fanhao == 1:
            wx.MessageBox("该电影已存在", "Message", wx.OK | wx.ICON_INFORMATION)
            print('该电影已存在!!')
            return
        else:
            sql_insert = "INSERT INTO west_record (movie_name,director,studio,series,catagorys,stars,last,score) VALUES ('" + self.name + "','" + self.av_director + "','" + self.av_studio + "','" + self.av_series + "','" \
                         + self.new_av_genres + "','" + self.new_av_stars + "','0','1')"
            cur.execute(sql_insert)
            conn.commit()
            print('增加新番号成功!!')

        # 把所有数据插入av_director表
        if self.av_director is not None:
            sql_sel = "SELECT COUNT(director) FROM av_director WHERE director = '" + self.av_director + "'"
            cur.execute(sql_sel)
            num_director = cur.fetchall()[0][0]
            if num_director == 1:
                print('导演已存在!!')
            else:
                sql_insert = "INSERT INTO av_director(director,num,pid) VALUES ('" + self.av_director + "','1','" + self.pid_director + "')"
                print('新导演添加!!')
                cur.execute(sql_insert)
                conn.commit()

        # 把所有数据插入av_zhizuo表
        if self.av_studio is not None:
            sql_sel = "SELECT COUNT(zhizuo) FROM av_zhizuo WHERE zhizuo = '" + self.av_studio + "'"
            cur.execute(sql_sel)
            num_zhizuo = cur.fetchall()[0][0]
            if num_zhizuo == 1:
                print('制作商已存在!!!')
            else:
                sql_insert = "INSERT INTO av_zhizuo(zhizuo,num,pid) VALUES ('" + self.av_studio + "','1','" + self.pid_studio + "')"
                print('新制作商添加!!!')
                cur.execute(sql_insert)
                conn.commit()

        # 把所有数据插入av_xilie表
        if self.av_series is not None:
            sql_sel = "SELECT COUNT(xilie) FROM av_xilie WHERE xilie = '" + self.av_series + "'"
            cur.execute(sql_sel)
            num_zhizuo = cur.fetchall()[0][0]
            if num_zhizuo == 1:
                #sql_insert = "UPDATE av_xilie SET num = num+1 WHERE xilie ='" + self.av_xilie + "'"
                print('该系列已存在!!!')
            else:
                sql_insert = "INSERT INTO av_xilie(xilie,num,pid) VALUES ('" + self.av_series + "','1','" + self.pid_series + "')"
                print('新系列添加!!!')
                cur.execute(sql_insert)
                conn.commit()

        # 把所有数据插入av_genre表
        for i in range(len(self.av_genres)):
            sql_sel = "SELECT COUNT(genre) FROM av_genres WHERE genre = '" + self.av_genres[
                i] + "'"
            cur.execute(sql_sel)
            num_genre = cur.fetchall()[0][0]
            if num_genre == 1:
                #sql_insert = "UPDATE av_genres SET num = num+1 WHERE genre ='" + self.av_genres[i] + "'"
                print('该类别已存在')
            else:
                sql_insert = "INSERT INTO av_genres(genre,num,pid) VALUES ('" + self.av_genres[i] + "','1','" + \
                             self.pid_genres[i] + "')"
                print(sql_insert)
                cur.execute(sql_insert)
                conn.commit()

        # 把所有数据插入av_stars表
        for j in range(len(self.av_stars)):
            sql_sel = "SELECT COUNT(star) FROM av_stars WHERE star = '" + self.av_stars[
                j] + "'"
            cur.execute(sql_sel)
            num_star = cur.fetchall()[0][0]
            if num_star == 1:
                print('该演员已存在!!!')
            else:
                sql_insert = "INSERT INTO av_stars(star,num,pid) VALUES ('" + self.av_stars[
                    j] + "','1','" + self.pid_stars[j] + "')"

                print('新演员添加!!!')
                cur.execute(sql_insert)
                conn.commit()

        cur.close()
        conn.close()

        #转移文件
        self.fanhaoPlus = self.lblDrag.GetLabel()
        filename_old = os.path.basename(self.fanhaoPlus)
        filename_new = self.name + '.' + filename_old.split('.')[-1]
        try:
            print(self.fanhaoPlus)
            shutil.move(self.fanhaoPlus,
                        'G:/fun_finder/资源/' + self.name + '/' + filename_old)
            os.rename('G:/fun_finder/资源/' + self.name + '/' + filename_old,
                      'G:/fun_finder/资源/' + self.name + '/' + filename_new)
        except:
            print('文件不存在')
        wx.MessageBox("入库成功", "Message", wx.OK | wx.ICON_INFORMATION)
Exemplo n.º 6
0
    def OnContinue(self, event):
        step = self.html.GetActiveStep()
        if step == 2:
            if len(config.files) == 0:
                wx.MessageBox(
                    _("""You have to add some files for rendering"""),
                    _("No files specified"), wx.ICON_ERROR)
                return
            if config.files[0][1] == '' and config.profile != 'raster':
                wx.MessageBox(
                    _("""Sorry the file you have specified does not have georeference.\n\nClick on the 'Georeference' button and give a bounding box or \ncreate a world file (.wld) for the specified file."""
                      ), _("Missing georeference"), wx.ICON_ERROR)
                return
        if step == 3:
            self.html.SaveStep(3)
            #print config.srs
            if config.files[0][1] != '':
                print type(config.srs)
                print config.srs
                srs = gdalpreprocess.SRSInput(config.srs)
                print srs
                if not srs:
                    wx.MessageBox(
                        _("""You have to specify reference system of your coordinates.\n\nTIP: for latitude/longitude in WGS84 you should type 'EPSG:4326'"""
                          ), _("Not valid spatial reference system"),
                        wx.ICON_ERROR)
                    return
                else:
                    config.srs = srs
        if step == 5:
            self.html.SaveStep(5)

            # If the user selected the output directory himself.
            if os.path.exists(config.outputdir):
                if not os.access(config.outputdir, os.W_OK):
                    wx.MessageBox(
                        _("The selected output directory '%s' is not writeable."
                          ) % config.outputdir, _("Bad permissions"),
                        wx.ICON_ERROR)
                    return
            # Default output directory on Windows and Mac.
            else:
                dirname = os.path.split(config.outputdir)[0]
                if not os.access(dirname, os.W_OK):
                    wx.MessageBox(
                        _("""The selected output directory '%s' can't be created, \
because its superdirectory '%s' is not writeable.""") %
                        (config.outputdir, dirname), _("Bad permissions"),
                        wx.ICON_ERROR)
                    return

        if step == 5 and config.profile == 'gearth':
            self.html.SaveStep(5)
            if config.format.startswith('garmin'):
                step = 6  # Skip settings of the viewers

        if step == 8:
            self._renderstart()
            self.SetStep(8)
        if step < 8:  # maximum is 7
            self.SetStep(step + 1)
        if step > 8:
            self.Destroy()
Exemplo n.º 7
0
 def _show_modification_prevented_error(self, message):
     wx.MessageBox('"%s" is read only' %
                   message.controller.datafile_controller.filename,
                   'Modification prevented',
                   style=wx.ICON_ERROR)
Exemplo n.º 8
0
def ValideDate(texte, date_min="01/01/1900", date_max="01/01/2999", avecMessages=True, mask=""):
    """ Verificateur de validite de date """
    if texte == "  /  /    " or texte == "" :
        return True

    listeErreurs = []

    # Recherche depuis l'expression régulière
    date = datePattern.match(texte)
    if date:
        # On vérifie que les chiffres existent
        jour = int(date.group("jour"))
        if jour == 0 or jour > 31:
            listeErreurs.append(_(u"le jour"))
        mois = int(date.group("mois"))
        if mois == 0 or mois > 12:
            listeErreurs.append(_(u"le mois"))
        annee = int(date.group("annee"))
        if annee < 1900 or annee > 2999:
            listeErreurs.append(_(u"l'année"))

        # Affichage du message d'erreur
        if listeErreurs:
            # Message en cas de date incomplète
            if avecMessages == True :
                nbErreurs = len(listeErreurs)
                if nbErreurs == 1:
                    message = _(u"Une incohérence a été détectée dans ") + listeErreurs[0]
                else:
                    message = _(u"Des incohérences ont été détectées dans ") + listeErreurs[0]
                    if nbErreurs == 2:
                        message += " et " + listeErreurs[1]
                    elif nbErreurs == 3:
                        message += ", " + listeErreurs[1]  + " et " + listeErreurs[2]
                message += _(u" de la date que vous venez de saisir. Veuillez la vérifier.")
                wx.MessageBox(message, "Erreur de date")
            return False
        else:
            # On vérifie que les dates sont comprises dans l'intervalle donné en paramètre
            date_min = int(str(date_min[6:10]) + str(date_min[3:5]) + str(date_min[:2]))
            date_max = int(str(date_max[6:10]) + str(date_max[3:5]) + str(date_max[:2]))
            date_sel = int(str(annee) + ('0' if mois < 10 else '') + str(mois) +
                                        ('0' if jour < 10 else '') + str(jour))

            if date_sel < date_min:
                if avecMessages == True :
                    message = _(u"La date que vous venez de saisir semble trop ancienne. Veuillez la vérifier.")
                    wx.MessageBox(message, "Erreur de date")
                return False
            if date_sel > date_max:
                if avecMessages == True :
                    message = _(u"La date que vous venez de saisir semble trop élevée. Veuillez la vérifier.")
                    wx.MessageBox(message, "Erreur de date")
                return False

            # On vérifie que la date peut être transformée en Datetime
            try:
                datetime.date(year=annee, month=mois, day=jour)
            except :
                pass
            else:
                return True

    if avecMessages == True :
        message = _(u"La date que vous venez de saisir ne semble pas valide !")
        wx.MessageBox(message, "Erreur de date")
    return False
Exemplo n.º 9
0
 def onhello(self, event):
     wx.MessageBox('芳芳,我爱你!(づ ̄3 ̄)づ╭❤~', '❤')
Exemplo n.º 10
0
 def eliminar_juego(self, evt):
     if self.game_controller.delete_game(self.id_juego):
         wx.MessageBox('El Video Juego se elimino exitosamente', 'Information', wx.OK | wx.ICON_INFORMATION)
         self.frame_father.load_data_listctrl_juego()
         self.frame.Close()
Exemplo n.º 11
0
 def OnURL(self, evt):
     wx.MessageBox(evt.GetString(), "URL Clicked")
Exemplo n.º 12
0
    def ConnectCore(self):
        flag_sock=0
        flag_sockFile=0

        while(1):
            if(staticVar.sock==0 and flag_sock==0):
                try:
                    self.serverCom.ConnectToServer(9000)
                    staticVar.sock=self.serverCom.sock
                    flag_sock=1
                except Exception:
                    (ErrorType, ErrorValue, ErrorTB) = sys.exc_info()
                    wx.MessageBox('Connect To Monitor Server Failure!\n'+
                                   str(ErrorValue[0])+' '+str(ErrorValue[1]), 
                               'Alert', wx.ICON_EXCLAMATION | wx.STAY_ON_TOP)
                    
                    
             
    
                    
            if(staticVar.sockFile==0 and flag_sockFile==0):
                try:
                    self.serverCom.ConnectToServer(9988)
                    staticVar.sockFile=self.serverCom.sockFile
                    flag_sockFile=1
                except Exception:
                    (ErrorType, ErrorValue, ErrorTB) = sys.exc_info()
                    wx.MessageBox('Connect To File Server Failure!\n'+
                                  str(ErrorValue[0])+' '+str(ErrorValue[1]),  
                               'Alert', wx.ICON_INFORMATION | wx.STAY_ON_TOP)

            if(flag_sock and flag_sockFile):
                break
            time.sleep(5)
             
        
        
        
        connect=ConnectServer()
        
        connect.CommonHeader=FrameHeader(0x55,0xA1,staticVar.getid()&0x00FF,staticVar.getid()>>8)
        connect.CommonTail=self.tail
        
        if(self.GPS_list==[]):
            #临时加的测试 
            self.GPS_list=[0]*9
            #############################
            
            Lon=114.4202
            Lat=30.5100
            Alti=35
            Lon_fen=0.4202*60
            Lat_fen=0.51*60
            Lon_fen_I=int(Lon_fen)
            Lon_fen_f=int((Lon_fen-int(Lon_fen))*1000)
            Lat_fen_I=int(Lat_fen)
            Lat_fen_f=int((Lat_fen-int(Lat_fen))*1000)
            
        
            self.GPS_list[1]=114
            self.GPS_list[2]=(Lon_fen_I<<2)+(Lon_fen_f>>8)
            self.GPS_list[3]=Lon_fen_f&0x00FF
            self.GPS_list[4]=30
            self.GPS_list[5]=(Lat_fen_I<<2)+(Lat_fen_f>>8)
            self.GPS_list[6]=Lat_fen_f&0x00FF
            self.GPS_list[8]=35
            
        list =self.GPS_list
        
        connect.LonLatAlti=LonLatAltitude(list[0],list[1],list[2],list[3],list[4]>>7,list[4]&0x7F,
                                          list[5],list[6],list[7]>>7,list[7]&0x7F,list[8])
        self.serverCom.SendQueryData(connect)
        
      
        self.thread_station=ReceiveServerData(self)
        self.thread_station.setDaemon(True)
        self.thread_station.start()
        

        self.thread_upload = SendFileThread(self.SpecFrame, self.queueFFTUpload,
                              self.queueAbUpload)
        self.thread_upload.setDaemon(True)
        self.thread_upload.start()

        self.timer = threading.Timer(15, self.hello, [])
        self.timer.start()
       
        '''
        thread_timer=Timer(self.thread_upload,self.thread_station)
        thread_timer.setDaemon(True)
        thread_timer.start()   
        '''

        self.m_connect.Enable(False)
import wx

import startup_vizop, vizop_misc, info

if __name__ == '__main__':

    #check existence and readability of runtime directories.
    sys_runtime_dirs = [
        os.path.join(vizop_misc.get_sys_runtime_files_dir(),
                     info.IconFolderTail),
        os.path.join(vizop_misc.get_sys_runtime_files_dir(), 'locale')
    ]

    if not os.path.isdir(vizop.get_usr_runtime_files_dir()):
        os.makedirs(vizop.get_usr_runtime_files_dir())

    for d in sys_runtime_dirs:
        if not os.path.isdir(d) and os.access(d, os.R_OK):
            #this is likely a fatal error - there is something wrong with
            #the installation
            wx.MessageBox("%s is missing or unreadable." % d, info.PROG_NAME,
                          wx.ICON_ERROR)

            #can't translate this message - might be missing our language files
            raise RuntimeError("%s is missing or unreadable." % d)

    print("Installed gettext handler at localedir: ",
          os.path.join(vizop_misc.get_sys_runtime_files_dir(), 'locale'))

    startup_vizop.launch_gui(app)
Exemplo n.º 14
0
 def OnAbout(self, event):
     wx.MessageBox('This is wxPython', 'About hello 2', wx.OK|wx.ICON_INFORMATION)
Exemplo n.º 15
0
    def __init__(self, dates, lives, devices):

        self._GraphActivates = True
        self._LiveData = []

        db = TempQuerySQL_2()

        datas = db.GetDataSample(devicename=devices, recorddate=dates)
        if len(datas) == 0:
            wx.MessageBox('Data Grafik pada tanggal tersebut kosong',
                          'Warning', wx.OK | wx.ICON_WARNING)

        # try:
        #Live Update
        self._LiveUpdate = lives

        #New Var
        self.GR_UsedSensor = devices
        self.GR_Data_Before = datas
        self.GR_Data_Before_key = list(datas.keys())
        self.GR_Data_Before_key.sort()

        self.xdata, self.ydata = [], []

        # {
        #     datetime.datetime string:
        #     [datetime.datetime obj, value]
        # }

        #APLLY DATA EXIST
        for key in self.GR_Data_Before_key:
            items = self.GR_Data_Before[key]
            x = items[0]
            y = items[1]
            self.xdata.append(x)
            self.ydata.append(y)

        starts = self.GR_Data_Before[self.GR_Data_Before_key[0]][0]
        ends = self.GR_Data_Before[self.GR_Data_Before_key[-1]][0]

        valmin = self.GR_Data_Before[self.GR_Data_Before_key[0]][1]
        valmax = self.GR_Data_Before[self.GR_Data_Before_key[-1]][1]

        #FIGURE
        self.fig, self.ax = plt.subplots()
        self.date = dates
        self.x_axis_start = starts
        self.x_axis_end = ends
        self.y_axis_max = float(valmax) + (float(valmax) * (10 / 100))
        self.y_axis_min = float(valmin) - (float(valmax) * (10 / 100))

        #SERIES
        self.line, = self.ax.plot_date([], [], '-', lw=3, color='blue')
        self.ax.set_ylim(self.y_axis_min, self.y_axis_max)
        self.ax.set_xlim(self.x_axis_start, self.x_axis_end)
        self.ax.set_xlabel('Time Record')
        self.ax.set_ylabel('Value ' + str(self.GR_UsedSensor))
        self.ax.xaxis.set_major_formatter(ds.DateFormatter('%H:%M:%S'))
        self.fig.suptitle(str('Data ' + str(self.GR_UsedSensor) + ' On : ') +
                          str(self.date),
                          fontsize=14,
                          fontweight='bold')
        self.fig.autofmt_xdate()
        self.ax.grid()

        figure = plt.gcf()  # Get current figure
        toolbar = figure.canvas.toolbar  # Get the toolbar handler
        toolbar.update()
        self.line.set_data(self.xdata, self.ydata)
        self.ax.grid()
        plt.rcParams['axes.facecolor'] = 'white'
        plt.rcParams['axes.edgecolor'] = 'white'
        plt.rcParams['axes.grid'] = True
        plt.rcParams['grid.alpha'] = 1
        plt.rcParams['grid.color'] = "#cccccc"
        plt.grid(True)
        plt.show()

        plt.clf()
        if self._LiveUpdate == True:
            self._LiveUpdate = False
        plt.close()
        time.sleep(1)
        self._GraphActivates = False
        return
Exemplo n.º 16
0
 def onabout(self, event):
     wx.MessageBox('爱你的车车', '关于')
Exemplo n.º 17
0
    def OnInfo(self, event):
        """
		"""
        wx.MessageBox(
            _('Libraries Import Manager.\nYou can import, refresh or upgrade librairies by using right options.\nDefault libraries directory is %s.'
              ) % (DOMAIN_PATH))
Exemplo n.º 18
0
    def Export(self, evt):
        """
        Handler for the "Export" button.
        Get the network on canvas and change it to an SBML string.
        """

        isReversible = True
        netIn = 0
        numNodes = api.node_count(netIn)
        numReactions = api.reaction_count(netIn)

        if numNodes == 0:  #or numReactions == 0 :
            wx.MessageBox("Please import a network on canvas", "Message",
                          wx.OK | wx.ICON_INFORMATION)
        else:
            allNodes = api.get_nodes(netIn)
            allReactions = api.get_reactions(netIn)
            allcompartments = api.get_compartments(netIn)
            numCompartments = len(allcompartments)
            #######################################

            # Creates an SBMLNamespaces object with the given SBML level, version
            # package name, package version.
            #
            # (NOTE) By default, the name of package (i.e. "layout") will be used
            # if the argument for the prefix is missing or empty. Thus the argument
            # for the prefix can be added as follows:
            #
            #    SBMLNamespaces sbmlns(3,1,"layout",1,"LAYOUT")
            #
            sbmlns = SBMLNamespaces(3, 1, "layout", 1)
            # create the document
            document = SBMLDocument(sbmlns)
            # set the "required" attribute of layout package  to "true"
            document.setPkgRequired("layout", False)

            # create the Model

            model = document.createModel()
            model.setId("Model_layout")
            document.setModel(model)

            # create the Compartment and species
            if numCompartments != 0:
                for i in range(numCompartments):
                    compartment = model.createCompartment()
                    comp_id = allcompartments[i].id
                    compartment.setId(comp_id)
                    compartment.setConstant(True)
                    for j in range(len(allcompartments[i].nodes)):
                        spec_id = allNodes[allcompartments[i].nodes[j]].id
                        species = model.createSpecies()
                        species.setId(spec_id)
                        species.setCompartment(comp_id)
                        species.setInitialConcentration(1.0)
                        species.setHasOnlySubstanceUnits(False)
                        species.setBoundaryCondition(False)
                        species.setConstant(False)
                        if allNodes[allcompartments[i].
                                    nodes[j]].floatingNode == False:
                            species.setBoundaryCondition(True)
            else:  #set default compartment
                compartment = model.createCompartment()
                comp_id = "c_0"
                compartment.setId(comp_id)
                compartment.setConstant(True)
                for i in range(numNodes):
                    spec_id = allNodes[i].id
                    species = model.createSpecies()
                    species.setId(spec_id)
                    species.setCompartment(comp_id)
                    species.setInitialConcentration(1.0)
                    species.setHasOnlySubstanceUnits(False)
                    species.setBoundaryCondition(False)
                    species.setConstant(False)
                    if allNodes[i].floatingNode == False:
                        species.setBoundaryCondition(True)
                        species.setConstant(True)

            # create reactions:
            for i in range(numReactions):
                reaction_id = allReactions[i].id
                rct = []  # id list of the rcts
                prd = []
                rct_num = len(allReactions[i].sources)
                prd_num = len(allReactions[i].targets)
                for j in range(rct_num):
                    rct.append(allNodes[allReactions[i].sources[j]].id)
                for j in range(prd_num):
                    prd.append(allNodes[allReactions[i].targets[j]].id)

                kinetic_law = ''
                parameter_list = []
                kinetic_law = kinetic_law + 'E' + str(i) + '*(k' + str(i)
                parameter_list.append('E' + str(i))
                parameter_list.append('k' + str(i))
                for j in range(rct_num):
                    kinetic_law = kinetic_law + '*' + rct[j]

                reaction = model.createReaction()
                reaction.setId(allReactions[i].id)
                reaction.setReversible(False)
                reaction.setFast(False)
                if isReversible:
                    reaction.setReversible(True)
                    kinetic_law = kinetic_law + ' - k' + str(i) + 'r'
                    parameter_list.append('k' + str(i) + 'r')
                    for j in range(prd_num):
                        kinetic_law = kinetic_law + '*' + prd[j]
                kinetic_law = kinetic_law + ')'
                for j in range(len(parameter_list)):
                    parameters = model.createParameter()
                    parameters.setId(parameter_list[j])
                    parameters.setValue(0.1)
                    parameters.setConstant(True)
                kinetics = reaction.createKineticLaw()
                kinetics.setFormula(kinetic_law)

                for j in range(rct_num):
                    reference = reaction.createReactant()
                    reference.setSpecies(rct[j])
                    ref_id = "SpecRef_" + reaction_id + "_rct" + str(j)
                    reference.setId(ref_id)
                    reference.setStoichiometry(1.)
                    reference.setConstant(False)

                for j in range(prd_num):
                    reference = reaction.createProduct()
                    reference.setSpecies(prd[j])
                    ref_id = "SpecRef_" + reaction_id + "_prd" + str(j)
                    reference.setId(ref_id)
                    reference.setStoichiometry(1.)
                    reference.setConstant(False)

            # create the Layout

            #
            # set the LayoutPkgNamespaces for Level 3 Version1 Layout Version 1
            #
            layoutns = LayoutPkgNamespaces(3, 1, 1)

            renderns = RenderPkgNamespaces(3, 1, 1)

            #
            # Get a LayoutModelPlugin object plugged in the model object.
            #
            # The type of the returned value of SBase::getPlugin() function is SBasePlugin, and
            # thus the value needs to be casted for the corresponding derived class.
            #

            mplugin = model.getPlugin("layout")

            # rPlugin = model.getPlugin("render")
            # if rPlugin is None:
            #   print("there is no render outside layout.")

            # lolPlugin = mplugin.getListOfLayouts().getPlugin("render")
            # if lolPlugin is None:
            #   print("there is no render info inside layout.")

            if mplugin is None:
                # print(
                #     "[Fatal Error] Layout Extension Level " + layoutns.getLevel() + " Version " + layoutns.getVersion() + " package version " + layoutns.getPackageVersion() + " is not registered.")
                # sys.exit(1)
                wx.MessageBox("There is no layout information.", "Message",
                              wx.OK | wx.ICON_INFORMATION)

            #
            # Creates a Layout object via LayoutModelPlugin object.
            #
            layout = mplugin.createLayout()
            layout.setId("Layout_1")
            layout.setDimensions(Dimensions(layoutns, 800.0, 800.0))
            # random network (40+800x, 40+800y)

            #create the CompartmentGlyph and SpeciesGlyphs

            if numCompartments != 0:
                for i in range(numCompartments):
                    comp_id = allcompartments[i].id

                    compartmentGlyph = layout.createCompartmentGlyph()
                    compG_id = "CompG_" + comp_id
                    compartmentGlyph.setId(compG_id)
                    compartmentGlyph.setCompartmentId(comp_id)
                    bb_id = "bb_" + comp_id
                    pos_x = allcompartments[i].position.x
                    pos_y = allcompartments[i].position.y
                    width = allcompartments[i].size.x
                    height = allcompartments[i].size.y
                    compartmentGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                    height))
                    for j in range(len(allcompartments[i].nodes)):
                        spec_id = allNodes[allcompartments[i].nodes[j]].id
                        speciesGlyph = layout.createSpeciesGlyph()
                        specG_id = "SpecG_" + spec_id
                        speciesGlyph.setId(specG_id)
                        speciesGlyph.setSpeciesId(spec_id)
                        bb_id = "bb_" + spec_id
                        pos_x = allNodes[
                            allcompartments[i].nodes[j]].position.x
                        pos_y = allNodes[
                            allcompartments[i].nodes[j]].position.y
                        width = allNodes[allcompartments[i].nodes[j]].size.x
                        height = allNodes[allcompartments[i].nodes[j]].size.y
                        speciesGlyph.setBoundingBox(
                            BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                        height))

                        textGlyph = layout.createTextGlyph()
                        textG_id = "TextG_" + spec_id
                        textGlyph.setId(textG_id)
                        bb_id = "bb_spec_text_" + spec_id
                        textGlyph.setBoundingBox(
                            BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                        height))
                        textGlyph.setOriginOfTextId(specG_id)
                        textGlyph.setGraphicalObjectId(specG_id)
            else:  #there is no compartment
                for i in range(numNodes):
                    spec_id = allNodes[i].id
                    speciesGlyph = layout.createSpeciesGlyph()
                    specG_id = "SpecG_" + spec_id
                    speciesGlyph.setId(specG_id)
                    speciesGlyph.setSpeciesId(spec_id)
                    bb_id = "bb_" + spec_id
                    pos_x = allNodes[i].position.x
                    pos_y = allNodes[i].position.y
                    width = allNodes[i].size.x
                    height = allNodes[i].size.y
                    speciesGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                    height))

                    textGlyph = layout.createTextGlyph()
                    textG_id = "TextG_" + spec_id
                    textGlyph.setId(textG_id)
                    bb_id = "bb_spec_text_" + spec_id
                    textGlyph.setBoundingBox(
                        BoundingBox(layoutns, bb_id, pos_x, pos_y, width,
                                    height))
                    textGlyph.setOriginOfTextId(specG_id)
                    textGlyph.setGraphicalObjectId(specG_id)

            # create the ReactionGlyphs and SpeciesReferenceGlyphs
            for i in range(numReactions):
                reaction_id = allReactions[i].id
                reactionGlyph = layout.createReactionGlyph()
                reactionG_id = "RectionG_" + reaction_id
                reactionGlyph.setId(reactionG_id)
                reactionGlyph.setReactionId(reaction_id)

                reactionCurve = reactionGlyph.getCurve()
                ls = reactionCurve.createLineSegment()
                centroid = api.compute_centroid(0, allReactions[i].sources,
                                                allReactions[i].targets)
                ls.setStart(Point(layoutns, centroid.x, centroid.y))
                ls.setEnd(Point(layoutns, centroid.x, centroid.y))

                rct = []  # id list of the rcts
                prd = []
                rct_num = len(allReactions[i].sources)
                prd_num = len(allReactions[i].targets)
                for j in range(rct_num):
                    rct.append(allNodes[allReactions[i].sources[j]].id)
                for j in range(prd_num):
                    prd.append(allNodes[allReactions[i].targets[j]].id)

                for j in range(rct_num):
                    ref_id = "SpecRef_" + reaction_id + "_rct" + str(j)

                    speciesReferenceGlyph = reactionGlyph.createSpeciesReferenceGlyph(
                    )
                    specsRefG_id = "SpecRefG_" + reaction_id + "_rct" + str(j)
                    specG_id = "SpecG_" + rct[j]
                    speciesReferenceGlyph.setId(specsRefG_id)
                    speciesReferenceGlyph.setSpeciesGlyphId(specG_id)
                    speciesReferenceGlyph.setSpeciesReferenceId(ref_id)
                    speciesReferenceGlyph.setRole(SPECIES_ROLE_UNDEFINED)

                    speciesReferenceCurve = speciesReferenceGlyph.getCurve()
                    cb = speciesReferenceCurve.createCubicBezier()
                    #cb = speciesReferenceCurve.createLineSegment()

                    cb.setStart(Point(layoutns, centroid.x, centroid.y))

                    handles = api.default_handle_positions(
                        netIn, allReactions[i].index)
                    pos_x = handles[1 + j].x
                    pos_y = handles[1 + j].y
                    cb.setBasePoint1(Point(layoutns, pos_x, pos_y))
                    cb.setBasePoint2(Point(layoutns, pos_x, pos_y))

                    pos_x = allNodes[allReactions[i].sources[j]].position.x
                    pos_y = allNodes[allReactions[i].sources[j]].position.y
                    width = allNodes[allReactions[i].sources[j]].size.x
                    height = allNodes[allReactions[i].sources[j]].size.y
                    cb.setEnd(
                        Point(layoutns, pos_x + 0.5 * width,
                              pos_y - 0.5 * height))

                for j in range(prd_num):
                    ref_id = "SpecRef_" + reaction_id + "_prd" + str(j)
                    speciesReferenceGlyph = reactionGlyph.createSpeciesReferenceGlyph(
                    )
                    specsRefG_id = "SpecRefG_" + reaction_id + "_prd" + str(j)
                    specG_id = "SpecG_" + prd[j]
                    speciesReferenceGlyph.setId(specsRefG_id)
                    speciesReferenceGlyph.setSpeciesGlyphId(specG_id)
                    speciesReferenceGlyph.setSpeciesReferenceId(ref_id)
                    speciesReferenceGlyph.setRole(SPECIES_ROLE_UNDEFINED)

                    speciesReferenceCurve = speciesReferenceGlyph.getCurve()
                    cb = speciesReferenceCurve.createCubicBezier()
                    #cb = speciesReferenceCurve.createLineSegment()
                    cb.setStart(Point(layoutns, centroid.x, centroid.y))

                    handles = api.default_handle_positions(
                        netIn, allReactions[i].index)
                    pos_x = handles[1 + j].x
                    pos_y = handles[1 + j].y
                    cb.setBasePoint1(Point(layoutns, pos_x, pos_y))
                    cb.setBasePoint2(Point(layoutns, pos_x, pos_y))

                    pos_x = allNodes[allReactions[i].targets[j]].position.x
                    pos_y = allNodes[allReactions[i].targets[j]].position.y
                    width = allNodes[allReactions[i].targets[j]].size.x
                    height = allNodes[allReactions[i].targets[j]].size.y
                    cb.setEnd(
                        Point(layoutns, pos_x + 0.5 * width,
                              pos_y - 0.5 * height))

            sbmlStr_layout = writeSBMLToString(
                document)  #sbmlStr is w/o layout info
            #self.SBMLText.SetValue(sbmlStr_layout)

            doc = readSBMLFromString(sbmlStr_layout)
            model_layout = doc.getModel()
            mplugin = model_layout.getPlugin("layout")

            # add render information to the first layout
            layout = mplugin.getLayout(0)

            rPlugin = layout.getPlugin("render")

            uri = RenderExtension.getXmlnsL2() if doc.getLevel(
            ) == 2 else RenderExtension.getXmlnsL3V1V1()

            # enable render package
            doc.enablePackage(uri, "render", True)
            doc.setPackageRequired("render", False)

            rPlugin = layout.getPlugin("render")

            rInfo = rPlugin.createLocalRenderInformation()
            rInfo.setId("info")
            rInfo.setName("Render Information")
            rInfo.setProgramName("RenderInformation")
            rInfo.setProgramVersion("1.0")

            # add some colors
            if numCompartments != 0:
                fill_color = allcompartments[0].fill_color
                border_color = allcompartments[0].border_color
                comp_border_width = allcompartments[0].border_width
                fill_color_str = '#%02x%02x%02x' % (fill_color.r, fill_color.g,
                                                    fill_color.b)
                border_color_str = '#%02x%02x%02x' % (
                    border_color.r, border_color.g, border_color.b)

            else:
                comp_border_width = 2.
                fill_color_str = '#9ea9ff'
                border_color_str = '#001dff'

            #nodeData does not have fill_color,border_color,border_width
            node = allNodes[0]
            # spec_fill_color   = node.fill_color
            # spec_border_color = node.border_color
            # spec_border_width = node.border_width
            # spec_fill_color_str   = '#%02x%02x%02x' % (spec_fill_color.r,spec_fill_color.g,spec_fill_color.b)
            # spec_border_color_str = '#%02x%02x%02x' % (spec_border_color.r,spec_border_color.g,spec_border_color.b)

            spec_fill_color_str = '#ffcc99'
            spec_border_color_str = '#ff6c09'
            spec_border_width = 2.

            if numReactions != 0:
                reaction_fill_color = allReactions[0].fill_color
                reaction_fill_color_str = '#%02x%02x%02x' % (
                    reaction_fill_color.r, reaction_fill_color.g,
                    reaction_fill_color.b)
                reaction_line_thickness = allReactions[i].line_thickness

            #add some colors
            color = rInfo.createColorDefinition()
            color.setId("black")
            color.setColorValue("#000000")

            color = rInfo.createColorDefinition()
            color.setId("comp_fill_color")
            color.setColorValue(fill_color_str)

            color = rInfo.createColorDefinition()
            color.setId("comp_border_color")
            color.setColorValue(border_color_str)

            color = rInfo.createColorDefinition()
            color.setId("spec_fill_color")
            color.setColorValue(spec_fill_color_str)

            color = rInfo.createColorDefinition()
            color.setId("spec_border_color")
            color.setColorValue(spec_border_color_str)

            if numReactions != 0:
                color = rInfo.createColorDefinition()
                color.setId("reaction_fill_color")
                color.setColorValue(reaction_fill_color_str)

            # add a list of styles
            style = rInfo.createStyle("compStyle")
            style.getGroup().setFillColor("comp_fill_color")
            style.getGroup().setStroke("comp_border_color")
            style.getGroup().setStrokeWidth(comp_border_width)
            style.addType("COMPARTMENTGLYPH")
            rectangle = style.getGroup().createRectangle()
            rectangle.setCoordinatesAndSize(RelAbsVector(0, 0),
                                            RelAbsVector(0, 0),
                                            RelAbsVector(0, 0),
                                            RelAbsVector(0, 100),
                                            RelAbsVector(0, 100))

            style = rInfo.createStyle("specStyle")
            style.getGroup().setFillColor("spec_fill_color")
            style.getGroup().setStroke("spec_border_color")
            style.getGroup().setStrokeWidth(spec_border_width)
            style.addType("SPECIESGLYPH")
            rectangle = style.getGroup().createRectangle()
            rectangle.setCoordinatesAndSize(RelAbsVector(0, 0),
                                            RelAbsVector(0, 0),
                                            RelAbsVector(0, 0),
                                            RelAbsVector(0, 100),
                                            RelAbsVector(0, 100))

            style = rInfo.createStyle("textStyle")
            style.getGroup().setStroke("black")
            style.getGroup().setStrokeWidth(1.)
            style.addType("TEXTGLYPH")

            if numReactions != 0:
                style = rInfo.createStyle("reactionStyle")
                style.getGroup().setStroke("reaction_fill_color")
                style.getGroup().setStrokeWidth(reaction_line_thickness)
                style.addType("REACTIONGLYPH SPECIESREFERENCEGLYPH")

            sbmlStr_layout_render = writeSBMLToString(doc)
            self.SBMLText.SetValue(sbmlStr_layout_render)
Exemplo n.º 19
0
 def _show_validation_error(self, message):
     wx.MessageBox(message.message, 'Validation Error', style=wx.ICON_ERROR)
Exemplo n.º 20
0
    def _set_properties(self, version, revision):
        """Set frame properties

        :param version: Version in the form of X.Y.Z
        :param revision: Version control revision with leading space

        *revision* should be an empty string in case of release and
        otherwise it needs a leading space to be separated from the rest
        of the title.
        """
        self.SetTitle(_("GRASS GIS %s Startup%s") % (version, revision))
        self.SetIcon(
            wx.Icon(os.path.join(globalvar.ICONDIR, "grass.ico"),
                    wx.BITMAP_TYPE_ICO))

        self.bstart.SetToolTip(_("Enter GRASS session"))
        self.bstart.Enable(False)
        self.bmapset.Enable(False)
        # this all was originally a choice, perhaps just mapset needed
        self.rename_location_button.Enable(False)
        self.delete_location_button.Enable(False)
        self.rename_mapset_button.Enable(False)
        self.delete_mapset_button.Enable(False)

        # set database
        if not self.gisdbase:
            # sets an initial path for gisdbase if nothing in GISRC
            if os.path.isdir(os.getenv("HOME")):
                self.gisdbase = os.getenv("HOME")
            else:
                self.gisdbase = os.getcwd()
        try:
            self.tgisdbase.SetValue(self.gisdbase)
        except UnicodeDecodeError:
            wx.MessageBox(parent=self,
                          caption=_("Error"),
                          message=_("Unable to set GRASS database. "
                                    "Check your locale settings."),
                          style=wx.OK | wx.ICON_ERROR | wx.CENTRE)

        self.OnSetDatabase(None)
        location = self.GetRCValue("LOCATION_NAME")
        if location == "<UNKNOWN>" or location is None:
            return
        if not os.path.isdir(os.path.join(self.gisdbase, location)):
            location = None

        # list of locations
        self.UpdateLocations(self.gisdbase)
        try:
            self.lblocations.SetSelection(self.listOfLocations.index(location),
                                          force=True)
            self.lblocations.EnsureVisible(
                self.listOfLocations.index(location))
        except ValueError:
            sys.stderr.write(
                _("ERROR: Location <%s> not found\n") %
                self.GetRCValue("LOCATION_NAME"))
            if len(self.listOfLocations) > 0:
                self.lblocations.SetSelection(0, force=True)
                self.lblocations.EnsureVisible(0)
                location = self.listOfLocations[0]
            else:
                return

        # list of mapsets
        self.UpdateMapsets(os.path.join(self.gisdbase, location))
        mapset = self.GetRCValue("MAPSET")
        if mapset:
            try:
                self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
                                            force=True)
                self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
            except ValueError:
                sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
                self.lbmapsets.SetSelection(0, force=True)
                self.lbmapsets.EnsureVisible(0)
Exemplo n.º 21
0
 def OnHello(self, event):
     wx.MessageBox('来自 wxPython', '你好')
Exemplo n.º 22
0
    def OnToggleButton3Togglebutton(self, event):
        if self.listBox1.GetCount() == 0:
            wx.MessageBox('Please Enter Values')

        else:
            try:
                j = 0
                k = 0
                flag = 0
                for j in range(0, self.listBox1.GetCount()):
                    for k in range(j + 1, self.listBox1.GetCount()):
                        if self.listBox1.GetString(
                                j) == self.listBox1.GetString(k):
                            wx.MessageBox(
                                'Same column names. Please enter again')
                            flag = 1

                for j in range(0, self.listBox1.GetCount()):
                    if self.listBox1.GetString(j).lower() == 'name':
                        wx.MessageBox(
                            'Do not enter name as an attribute(Column Name)')
                        flag = 1
                    if self.listBox1.GetString(j).lower() == 'latitude':
                        wx.MessageBox(
                            'Do not enter latitude as an attribute(Column Name)'
                        )
                        flag = 1

                    if self.listBox1.GetString(j).lower() == 'longitude':
                        wx.MessageBox(
                            'Do not enter longitude as an attribute(Column Name)'
                        )
                        flag = 1

                    if self.listBox1.GetString(j).lower() == 'altitude':
                        wx.MessageBox(
                            'Do not enter altitude as an attribute(Column Name)'
                        )
                        flag = 1

                if flag == 0:
                    for i in range(self.listBox1.GetCount()):
                        self.listBox1.GetString(i)
                        fw = open(r'C:\3d-Model\bin\curr_proj.txt', 'r')
                        pathDir = fw.readline()
                        print pathDir
                        fw.close()
                        os.chdir(pathDir)
                        paths = pathDir.split('\\')
                        index = len(paths) - 1
                        projName = 'column' + '.txt'
                        dataFile = 'dataType.txt'

                        fw = open(projName, 'a')
                        fw.writelines(self.listBox1.GetString(i) + "\n")
                        fw.close()

                        fd = open(dataFile, 'a')
                        fd.writelines(self.typeListBox.GetString(i) + "\n")
                        fd.close()

                        f = open(r'C:\3d-Model\bin\curr_proj.txt', 'r')
                        pathDir = f.readline()
                        f.close()

                        os.chdir(pathDir)
                        paths = pathDir.split('\\')
                        index = len(paths) - 1
                        projName = paths[index] + '.db'

                        conn = sqlite3.connect(projName)
                        cursor = conn.cursor()

                        cursor.execute(
                            '''ALTER TABLE information ADD COLUMN ''' +
                            self.listBox1.GetString(i) + ' ' +
                            self.typeListBox.GetString(i))

                    wx.MessageBox(
                        'Values Entered Successfully. Your Database has been created'
                    )
                    self.Destroy()
            except:
                wx.MessageBox(
                    'Same column names Or Connection to Database Server lost. Try again'
                )
Exemplo n.º 23
0
    def OnClickSearch(self, event):
        self.name = ''
        self.fanhaoPlus = ''
        self.av_director = ''
        self.pid_director = ''
        self.av_studio = ''
        self.pid_studio = ''
        self.av_series = ''
        self.pid_series = ''
        self.av_genres = []
        self.new_av_genres = ''
        self.pid_genres = []
        self.av_stars = []
        self.new_av_stars = ''
        self.pid_stars = []
        self.other_socre = ''
        self.comment = ''
        self.name = self.txt_fanhao.GetValue()
        self.lblStates.SetLabel('正在搜索:' + self.name)
        if self.name is None:
            return
        else:
            headers = {
                'content-type':
                'application/json',
                'User-Agent':
                'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
            }

            try:
                name_url = self.name.replace(' ', '+')
                print(name_url)
                requ = requests.get('http://www.data18.com/search/?k=' +
                                    name_url,
                                    timeout=2,
                                    headers=headers).content

            except:
                wx.MessageBox("获取网址超时", "Message", wx.OK | wx.ICON_INFORMATION)
                return

        self.lblStates.SetLabel('请求成功,正在处理内容。。。')
        # 获取标签内容
        soup = BeautifulSoup(requ, 'html.parser', from_encoding='utf-8')
        # 先判断是否能正常搜索到内容
        is404 = soup.find(text='0 Results')
        if is404 is not None:
            wx.MessageBox("该电影查不到", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        new_url_soup = soup.find(
            'a', href=re.compile('http://www.data18.com/movies/\d'))
        #通过movie标签查找
        if new_url_soup is not None:
            try:
                new_url = new_url_soup.get('href')
                requ_movie = requests.get(new_url, timeout=2,
                                          headers=headers).content
            except:
                wx.MessageBox("获取新网址超时", "Message",
                              wx.OK | wx.ICON_INFORMATION)
                return

            soup_movie = BeautifulSoup(requ_movie,
                                       'html.parser',
                                       from_encoding='utf-8')
            # 获取名字
            soup_name = soup_movie.find('h1')
            soup_name = soup_name.string
            self.lblName.SetLabel('名称:' + soup_name)
            self.name = soup_name

            # 创建文件夹
            if os.path.exists('资源/' + self.name):
                print('文件夹已经存在')
                self.lblStates.SetLabel('文件夹已经存在')
            else:
                os.makedirs('资源/' + self.name)
                print('创建文件夹成功')
                self.lblStates.SetLabel('创建文件夹成功')

            # 获取图片
            cover_url = soup_movie.find_all('a', class_='grouped_elements')
            cover_front_url = cover_url[0].get('href')
            cover_back_url = cover_url[1].get('href')
            print(cover_front_url, cover_back_url)
            try:
                self.lblStates.SetLabel('正在获取图片')
                pic_front = requests.get(cover_front_url, timeout=3)
                pic_back = requests.get(cover_back_url, timeout=3)
            except:
                print('【错误】当前图片无法下载')
                self.lblStates.SetLabel('请重试')
                wx.MessageBox("获取图片超时", "Message", wx.OK | wx.ICON_INFORMATION)
                return
            self.lblStates.SetLabel('获取信息成功')
            string_front = '资源/' + self.name + '/cover_front.jpg'
            fp = open(string_front, 'wb')
            # 创建文件
            fp.write(pic_front.content)
            fp.close()

            string_back = '资源/' + self.name + '/cover_back.jpg'
            fp = open(string_back, 'wb')
            # 创建文件
            fp.write(pic_back.content)
            fp.close()

            image_front = wx.Image(string_front, wx.BITMAP_TYPE_JPEG)
            self.bmp = wx.StaticBitmap(self,
                                       bitmap=image_front.ConvertToBitmap(),
                                       pos=(394, 88),
                                       size=(370, 523))
            image_back = wx.Image(string_back, wx.BITMAP_TYPE_JPEG)
            self.bmp = wx.StaticBitmap(self,
                                       bitmap=image_back.ConvertToBitmap(),
                                       pos=(24, 88),
                                       size=(370, 523))

            # 获取制作商
            soup_studio = soup_movie.find('u').string
            print(soup_studio)
            if soup_studio is None:
                self.av_studio = ''
                self.pid_studio = ''
            else:
                self.av_studio = soup_studio.string
                self.pid_studio = 'http://www.data18.com/sites/' + self.av_studio
            self.lblStudio.SetLabel('制作商: ' + self.av_studio)

            # 获取导演
            soup_director_raw = soup_movie.find('b', text='Director:')
            soup_director = soup_director_raw.find_next('a').string
            if soup_director is None:
                self.av_director = ''
                self.pid_director = ''
            else:
                self.av_director = soup_director.string
                self.pid_director = soup_director_raw.find_next('a').get(
                    'href')
            self.lblDirector.SetLabel('导演:' + self.av_director)

            # 获取系列
            soup_series_raw = soup_movie.find('b', text='Serie:')
            soup_series = soup_series_raw.find_next('a').string
            print(soup_series)
            if soup_series is None:
                self.av_series = ''
                self.pid_series = ''
            else:
                self.av_series = soup_series.string
                self.pid_series = soup_series_raw.find_next('a').get('href')
            self.lblSeries.SetLabel('系列:' + self.av_series)

            # 获取类别
            soup_genres = soup_movie.find(
                'b', text='Categories:').find_next_siblings('a')
            print(soup_genres)
            if soup_genres is None:
                self.av_genres = ['无类别']
                self.pid_genres = ['']
            else:
                for soup_genre in soup_genres:
                    self.av_genres.append(soup_genre.string)
                    pid_genre = soup_genre.get('href')
                    self.pid_genres.append(pid_genre)

            for av_genre in self.av_genres:
                av_genre = av_genre + ','
                self.new_av_genres = av_genre + self.new_av_genres
            print(self.new_av_genres)
            print(self.pid_genres)
            self.lblGenres.SetLabel('类别:' + self.new_av_genres)

            # 获取演员
            soup_stars = soup_movie.find_all('p',
                                             class_='line1',
                                             style='align: center;')
            print(soup_stars)
            for soup_star in soup_stars:
                soup_star_txt = soup_star.a.string
                pid_star = soup_star.a.get('href')
                self.av_stars.append(soup_star_txt)
                self.pid_stars.append(pid_star)

            print(self.av_stars)
            for av_star in self.av_stars:
                av_star = av_star + ','
                self.new_av_stars = av_star + self.new_av_stars
            self.lblStars.SetLabel('演员:' + self.new_av_stars)

        #通过content标签查找
        else:
            new_url = soup.find('p', class_='line1').a.get('href')
            try:
                requ_movie = requests.get(new_url, timeout=2,
                                          headers=headers).content
            except:
                wx.MessageBox("获取新网址超时", "Message",
                              wx.OK | wx.ICON_INFORMATION)
                return

            soup_movie = BeautifulSoup(requ_movie,
                                       'html.parser',
                                       from_encoding='utf-8')

            # 获取名字
            soup_name = soup_movie.find('h1')
            soup_name = soup_name.string
            self.lblName.SetLabel('名称:' + soup_name)
            self.name = soup_name

            cover_url = soup_movie.find('div', id='moviewrap').img.get('src')
            print(cover_url)

            # 创建文件夹
            if os.path.exists('资源/' + self.name):
                print('文件夹已经存在')
                self.lblStates.SetLabel('文件夹已经存在')
            else:
                os.makedirs('资源/' + self.name)
                print('创建文件夹成功')
                self.lblStates.SetLabel('创建文件夹成功')

            # 获取图片
            try:
                self.lblStates.SetLabel('正在获取图片')
                pic = requests.get(cover_url, timeout=3)
            except:
                print('【错误】当前图片无法下载')
                self.lblStates.SetLabel('请重试')
                wx.MessageBox("获取图片超时", "Message", wx.OK | wx.ICON_INFORMATION)
                return
            self.lblStates.SetLabel('获取信息成功')
            string = '资源/' + self.name + '/cover_front.jpg'
            fp = open(string, 'wb')
            # 创建文件
            fp.write(pic.content)
            fp.close()
            image = wx.Image(string, wx.BITMAP_TYPE_JPEG)
            self.bmp = wx.StaticBitmap(self,
                                       bitmap=image.ConvertToBitmap(),
                                       pos=(75, 170))

            # 获取制作商
            soup_studio = soup_movie.find('u').string
            print(soup_studio)
            if soup_studio is None:
                self.av_studio = ''
                self.pid_studio = ''
            else:
                self.av_studio = soup_studio.string
                self.pid_studio = 'http://www.data18.com/sites/' + self.av_studio
            self.lblStudio.SetLabel('制作商: ' + self.av_studio)

            # 获取系列
            soup_series_raw = soup_movie.find(text='Site:')
            soup_series = soup_series_raw.find_next('a').string
            print(soup_series)
            if soup_series is None:
                self.av_series = ''
                self.pid_series = ''
            else:
                self.av_series = soup_series.string
                self.pid_series = soup_series_raw.find_next('a').get('href')
            self.lblSeries.SetLabel('系列:' + self.av_series)

            # 获取导演
            soup_director = soup.find('a', href=re.compile(r'director'))
            if soup_director is None:
                self.av_director = ''
                self.pid_director = ''
            else:
                self.av_director = soup_director.string
                self.pid_director = soup_director.get('href').split('/')[-1]
            self.lblDirector.SetLabel('导演:' + self.av_director)

            # 获取类别
            soup_genres = soup_movie.find(
                'div', style='margin-top: 3px;').find_all('a')
            print(soup_genres)
            if soup_genres is None:
                self.av_genres = ['无类别']
                self.pid_genres = ['']
            else:
                for soup_genre in soup_genres:
                    self.av_genres.append(soup_genre.string)
                    pid_genre = soup_genre.get('href')
                    self.pid_genres.append(pid_genre)

            for av_genre in self.av_genres:
                av_genre = av_genre + ','
                self.new_av_genres = av_genre + self.new_av_genres
            print(self.new_av_genres)
            print(self.pid_genres)
            self.lblGenres.SetLabel('类别:' + self.new_av_genres)

            # 获取演员
            soup_stars = soup_movie.find(
                'b', text='Starring:').find_next_siblings('a')
            print(soup_stars)
            for soup_star in soup_stars:
                soup_star_txt = soup_star.get_text()
                pid_star = soup_star.get('href')
                self.av_stars.append(soup_star_txt)
                self.pid_stars.append(pid_star)

            for av_star in self.av_stars:
                av_star = av_star + ','
                self.new_av_stars = av_star + self.new_av_stars
            self.lblStars.SetLabel('演员:' + self.new_av_stars)
Exemplo n.º 24
0
class FileTransfer(Observable):
    DATA_POINTS = 500
    TIME_THRESHOLD = 30
    ATROPHY_TIME = 3

    states = FileTransferStates
    state = notifyprop('state')

    _xfer_display_strings = {
        # transfer state       # xfer, "direction" string
        states.TRANSFERRING:
        lambda x: _('{completed} of {size} ({speed}/sec) -- {time} remain').
        format(completed=util.nicebytecount(x.completed),
               size=util.nicebytecount(x.size),
               speed=util.nicebytecount(x.bytes_per_sec),
               time=util.nicetimecount(x.ETA)),
        states.FINISHED:
        lambda x: (_('Received from {name}') if x.direction == 'incoming' else
                   _('Sent to {name}')).format(name=x.buddy.name),
        states.CONNECTING:
        lambda x: _('Connecting to {name}...').format(name=x.buddy.name),
        states.WAITING_FOR_BUDDY:
        lambda x: _('Waiting for {name} to accept file').format(name=x.buddy.
                                                                name),
        states.WAITING_FOR_YOU:
        lambda _x: '',
        states.CANCELLED_BY_BUDDY:
        lambda x: _('Canceled by {name}').format(name=x.buddy.name),
        states.WAITING_FOR_BUDDY:
        lambda x: _('Waiting for {name} to accept file').format(name=x.buddy.
                                                                name),
        states.CONN_FAIL_XFER:
        lambda x:
        (_('Failed during transfer from {name}') if x.direction == 'incoming'
         else _('Failed during transfer to {name}')).format(name=x.buddy.name),
        states.CONN_FAIL:
        lambda x: _('Failed to connect to {name}').format(name=x.buddy.name),
        states.PROXY_XFER_FILESIZE_ERROR:
        lambda _x: _('File size too big for proxy transfer'),
    }

    def __init__(self):
        Observable.__init__(self)

        self.state = self.states.CONNECTING
        self.bytecounts = []
        self._bytes_per_sec = 0
        self.filepath = None
        self.completed = 0
        self._starttime = None
        self._done = False
        self.xfer_display_strings = self._xfer_display_strings.copy()

    def get_right_links(self):
        return [('open', _('Open'), lambda *a: None, self.allow_open),
                ('cancel', _('Cancel'), self.cancel, self.allow_cancel),
                ('remove', _('Remove'), lambda *a: None, self.allow_remove)]

    def get_bottom_links(self):
        return [('save', _('Save'), self.save, self.allow_save),
                ('saveas', _('Save as...'), self.saveas, self.allow_save_as),
                ('reject', _('Reject'), self.decline, self.allow_reject)]

    @property
    def should_show_buddy_name(self):
        return self.state in (self.states.TRANSFERRING,
                              self.states.WAITING_FOR_YOU)

    @property
    def details_string(self):
        return self.xfer_display_strings.get(self.state,
                                             lambda _x: self.state)(self)

    @property
    def elapsed(self):
        return default_timer() - self._starttime

    @property
    def average_speed(self):
        try:
            return self.completed / self.elapsed
        except ZeroDivisionError:
            return None

    @property
    def ETA(self):
        'The estimated number of seconds until the trasnfer is complete.'

        try:
            return (self.size - self.completed) / self.bytes_per_sec
        except ZeroDivisionError:
            return 0

    def _onrequest(self):
        # ask the user about the transfer
        self.protocol.hub.on_file_request(self.protocol, self)

    def _setcompleted(self, bytes):
        old = self.completed

        diff = bytes - old
        if diff <= 0:
            #log.debug('_setcompleted delta is <= 0 (%r - %r = %r)', bytes, old, diff)
            pass
        else:
            self._add_byte_data(default_timer(), bytes)

            self.setnotifyif('completed', bytes)

    @property
    def bytes_per_sec(self):
        now = default_timer()
        if self.state == self.states.TRANSFERRING:
            self._add_byte_data(now, self.completed)

        oldest = now
        newest = 0
        lowest = self.completed

        for t, b in self.bytecounts:
            if (self.completed - b):
                oldest = t if oldest > t else oldest
                newest = t if newest < t else newest
                lowest = b if lowest > b else lowest

        time_diff = now - oldest
        byte_diff = self.completed - lowest
        time_since_recv = now - newest

        if (time_since_recv) > self.ATROPHY_TIME:
            # been a long time since we got bytes
            self._bytes_per_sec = 0
        elif byte_diff and time_diff:
            self._bytes_per_sec = byte_diff / time_diff
        elif not byte_diff:
            self._bytes_per_sec = 0
        elif not time_diff:
            # uhh...infinite? wha?
            pass

        return self._bytes_per_sec

    def _add_byte_data(self, time, bytecount):
        time = int(time)
        bytecounts = self.bytecounts

        actual = filter(lambda x: x[1], bytecounts)

        if not actual and bytecount:
            self._starttime = default_timer()

        if not bytecounts:
            bytecounts.append((time, bytecount))

        oldtime = bytecounts[-1][0]
        if time > oldtime:
            bytecounts.append((time, bytecount))
        elif time == oldtime:
            bytecounts[-1] = (time, bytecount)

        self.bytecounts = bytecounts[-self.TIME_THRESHOLD:]

    def get_default_dir(self):
        if pref('filetransfer.create_subfolders', False):
            service = self.protocol.service
            bname = self.buddy.name
        else:
            service = bname = ''

        return path(profile.localprefs['save_to_dir']) / service / bname

    def save(self, filepath=None):
        if filepath is None:
            try:
                orig = filepath = self.get_default_dir() / self.name
            except Exception:
                print_exc()

                # There was an exception getting the default file transfer save-to location.
                # Open a dialog and let the user choose, and then save this location as a
                # new location to save in.
                try:
                    new_path = self.saveas(lookup_default=False)
                    profile.localprefs['save_to_dir'] = os.path.dirname(
                        new_path)
                except Exception:
                    print_exc()

                return

            orig, ext = os.path.splitext(orig)
            i = 0
            while os.path.exists(filepath):
                i += 1
                filepath = orig + (' (%d)' % i) + ext

        import wx
        parent = os.path.split(filepath)[0]
        if not os.path.exists(parent):
            try:
                os.makedirs(parent)
            except EnvironmentError, e:
                strerror = e.strerror or _('Directory does not exist')
                wx.MessageBox("Error saving file to %s.\n%s" %
                              (parent, strerror),
                              style=wx.ICON_ERROR | wx.OK)
                return self.saveas()

        try:

            if pref('filetransfer.preallocate', False) and getattr(
                    self, 'size', 0):
                self.allocate(filepath, self.size)

            f = open(filepath, 'wb')
        except EnvironmentError, e:
            wx.MessageBox("Error saving file to %s.\n%s" %
                          (parent, e.strerror),
                          style=wx.ICON_ERROR | wx.OK)
            return self.saveas()
Exemplo n.º 25
0
    def OnClickSearchStar(self, event):
        self.fanhao = self.txt_fanhao.GetValue()
        self.lblStates.SetLabel('正在搜索番号:' + self.fanhao)
        self.av_stars = []
        self.new_av_stars = ''
        self.pid_stars = []
        self.lblStars.SetLabel('演员:')
        if self.fanhao is None:
            return
        else:
            headers = {
                'content-type':
                'application/json',
                'User-Agent':
                'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
            }

            try:
                requ = requests.get(
                    'http://www.ja14b.com/cn/vl_searchbyid.php?list&keyword=' +
                    self.fanhao,
                    headers=headers,
                    timeout=2).content
            except:
                wx.MessageBox("获取网址超时", "Message", wx.OK | wx.ICON_INFORMATION)
                return

        self.lblStates.SetLabel('请求成功,正在处理内容。。。')
        # 获取标签内容
        soup = BeautifulSoup(requ, 'html.parser', from_encoding='utf-8')
        # 先判断是否能正常搜索到内容
        is404 = soup.find('em',
                          {'style': 'text-align: center; color: #C0C0C0;'})
        if is404 is not None:
            wx.MessageBox("该番号查不到", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        soup_stars = soup.find_all('span', class_='star')
        print(soup_stars)
        if soup_stars == []:
            wx.MessageBox("没有演员更新", "Message", wx.OK | wx.ICON_INFORMATION)
            return
        else:
            for soup_star in soup_stars:
                soup_star_txt = soup_star.get_text()
                print(soup_star_txt)
                self.av_stars.append(soup_star_txt)
                print(self.av_stars)

        for av_star in self.av_stars:
            av_star = av_star + ','
            self.new_av_stars = av_star + self.new_av_stars
        self.lblStars.SetLabel('演员:' + self.new_av_stars)

        for av_star in self.av_stars:
            requ = requests.get('https://www.javbus.com/searchstar/' + av_star,
                                headers=headers,
                                timeout=3).content
            soup = BeautifulSoup(requ, 'html.parser', from_encoding='utf-8')
            pid_star = soup.find('a', class_='avatar-box text-center')
            if pid_star is None:
                pid_star = ''
            else:
                pid_star = pid_star.get('href').split('/')[-1]
            self.pid_stars.append(pid_star)
            self.lblStates.SetLabel('更新演员pid:' + pid_star)
            print(self.pid_stars)

        wx.MessageBox("演员信息已更新", "Message", wx.OK | wx.ICON_INFORMATION)
Exemplo n.º 26
0
def ensureMinimal(minVersion, optionsRequired=False):
    """
    Checks to see if the default version of wxPython is greater-than
    or equal to `minVersion`.  If not then it will try to find an
    installed version that is >= minVersion.  If none are available
    then a message is displayed that will inform the user and will
    offer to open their web browser to the wxPython downloads page,
    and will then exit the application.
    """
    assert type(minVersion) == str

    # ensure that wxPython hasn't been imported yet.
    if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):
        raise AlreadyImportedError(
            "wxversion.ensureMinimal() must be called before wxPython is imported"
        )

    bestMatch = None
    minv = _wxPackageInfo(minVersion)

    # check the default version first
    defaultPath = _find_default()
    if defaultPath:
        defv = _wxPackageInfo(defaultPath, True)
        if defv >= minv and minv.CheckOptions(defv, optionsRequired):
            bestMatch = defv

    # if still no match then check look at all installed versions
    if bestMatch is None:
        installed = _find_installed()
        # The list is in reverse sorted order, so find the first
        # one that is big enough and optionally matches the
        # options
        for inst in installed:
            if inst >= minv and minv.CheckOptions(inst, optionsRequired):
                bestMatch = inst
                break

    # if still no match then prompt the user
    if bestMatch is None:
        if _EM_DEBUG:  # We'll do it this way just for the test code below
            raise VersionError("Requested version of wxPython not found")

        import wx, webbrowser
        versions = "\n".join(["      " + ver for ver in getInstalled()])
        app = wx.PySimpleApp()
        result = wx.MessageBox(
            "This application requires a version of wxPython "
            "greater than or equal to %s, but a matching version "
            "was not found.\n\n"
            "You currently have these version(s) installed:\n%s\n\n"
            "Would you like to download a new version of wxPython?\n" %
            (minVersion, versions),
            "wxPython Upgrade Needed",
            style=wx.YES_NO)
        if result == wx.YES:
            webbrowser.open(UPDATE_URL)
        app.MainLoop()
        sys.exit()

    sys.path.insert(0, bestMatch.pathname)
    # q.v. Bug #1409256
    path64 = re.sub('/lib/', '/lib64/', bestMatch.pathname)
    if os.path.isdir(path64):
        sys.path.insert(0, path64)
    global _selected
    _selected = bestMatch
Exemplo n.º 27
0
    def OnClickSearchComment(self, event):
        self.fanhao = self.txt_fanhao.GetValue()
        self.lblStates.SetLabel('正在查评论:' + self.fanhao)
        headers = {
            'content-type':
            'application/json',
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
        }

        try:
            requ_comment = requests.get(
                'http://www.ja14b.com/cn/vl_searchbyid.php?keyword=' +
                self.fanhao,
                headers=headers,
                timeout=2).content
        except:
            wx.MessageBox("获取网址超时", "Message", wx.OK | wx.ICON_INFORMATION)
            return
        self.lblStates.SetLabel('请求评论成功,正在获取内容')
        # 获取标签内容
        soup_comment = BeautifulSoup(requ_comment,
                                     'html.parser',
                                     from_encoding='utf-8')
        # 先判断是否能正常搜索到内容
        is404 = soup_comment.find(
            'p', {'style': 'text-align: center; color: #C0C0C0;'})
        if is404 is not None:
            wx.MessageBox("该番号查不到", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        isNone = soup_comment.find('div', id='badalert')
        if isNone is not None:
            wx.MessageBox("该番号查不到", "Message", wx.OK | wx.ICON_INFORMATION)
            return

        self.comment = ''
        isDouble = soup_comment.find('div', class_=re.compile(r'videos'))
        if isDouble is not None:
            print(isDouble)
            url = isDouble.a.get('href')
            url = 'http://www.ja14b.com/cn' + url[1:]
            print(url)
            requ_double = requests.get(url, headers=headers, timeout=2).content
            soup_double = BeautifulSoup(requ_double,
                                        'html.parser',
                                        from_encoding='utf-8')
            comments = soup_double.find_all('textarea', class_='hidden')
            for comment_new in comments:
                comment_new = comment_new.string
                if self.isComment(comment_new) == True:
                    print(comment_new)
                    self.comment = self.comment + comment_new + '\n'
            self.lblComment.SetLabel('评论:' + self.comment)
            print(self.lblComment)
            self.lblStates.SetLabel('已经获取评论')
            wx.MessageBox("获取评论成功", "Message", wx.OK | wx.ICON_INFORMATION)
        else:
            comments = soup_comment.find_all('textarea', class_='hidden')
            for comment_new in comments:
                comment_new = comment_new.string
                if self.isComment(comment_new) == True:
                    print(comment_new)
                    self.comment = self.comment + comment_new + '\n'
            self.lblComment.SetLabel('评论:' + self.comment)
            print(self.lblComment)
            self.lblStates.SetLabel('已经获取评论')
            wx.MessageBox("获取评论成功", "Message", wx.OK | wx.ICON_INFORMATION)
Exemplo n.º 28
0
 def notify(self):
     lastdb = self.conf['lastdb']
     if sys.platform.startswith('win32') and lastdb.startswith(os.environ['SystemDrive']) and self.conf.lastdb_is_default():
         wx.MessageBox(_('You db file is in default path, strongly advise save it to other path. Choose menu File->Change Account Path to change path.'), _('Note:'), wx.OK|wx.ICON_INFORMATION)
 def showfailbox(self):
     wx.MessageBox('用例导出失败!', 'Info', wx.OK | wx.ICON_INFORMATION)
Exemplo n.º 30
0
    def OnWizPageChanging(self, evt):
        """Event handler for the 'New Test Run' wizard"""
        error = False
        action = None
        forwarddir = evt.GetDirection()
        page = evt.GetPage()
        if page.__class__ == SelectProductDatabasePage:
            filename = page.GetValue()
            if len(filename) <= 0:
                error = True
                msg = 'Please enter database name!'
                page.SetFocus()
            else:

                class noTestSuites():
                    pass

                try:
                    model = afmodel.afModel(None)
                    model.requestOpenProduct(filename)
                    testsuites = model.getTestsuiteList()
                    if len(testsuites) == 0: raise noTestSuites()
                    comboboxitems = [(testsuite['ID'], testsuite['title'])
                                     for testsuite in testsuites]
                    page.GetNext().SetValue(comboboxitems)
                except noTestSuites:
                    error = True
                    msg = 'Database contains no test suites!'
                    page.SetFocus()
                except:
                    logging.error(sys.exc_info())
                    error = True
                    msg = 'Could not open database or invalid database format!'
                    page.SetFocus()

        elif page.__class__ == SelectOutputFilePage and forwarddir:
            filename = page.GetValue()
            if len(filename) <= 0:
                error = True
                msg = 'Please enter file name!'
                page.SetFocus()
            else:
                if os.path.exists(filename):
                    code = wx.MessageBox(
                        'File %s already exists.\nOkay to overwrite?' %
                        filename, "Save test run", wx.YES_NO | wx.ICON_WARNING)
                    if code != wx.YES:
                        evt.Veto()
                        page.SetFocus()
                        return
                try:
                    fp = open(filename, "w")
                    fp.close()
                except IOError:
                    error = True
                    msg = 'Could not open file for writing!'
                    page.SetFocus()

        elif page.__class__ == EnterTestrunInfo and forwarddir:
            values = page.GetValue()
            if len(values[0]) <= 0:
                error = True
                msg = 'Test run description required!'
                page.SetFocus(0)

            elif len(values[1]) <= 0:
                error = True
                msg = 'Tester name required!'
                page.SetFocus(1)

        if error:
            wx.MessageBox(msg, 'Warning', wx.OK | wx.ICON_WARNING)
            evt.Veto()