Example #1
0
    def smartPasteLeave(self, event):
        if setting_fftool.has_query:
            return

        ss = self.smartPaste.get(1.0, tk.END)
        arr = utils.split_str(ss, False)
        if len(arr) and arr[0] == self.smartNotice:
            # print("默认")
            return

        # 检查文件是否存在 /指定格式
        narr = []
        ft = (".mp4", ".mov", ".avi", ".mkv", ".mpg")
        for item in arr:
            typestr = utils.get_file_type(item).lower()
            if not ft.count(typestr) or not os.path.isfile(item):
                continue
            narr.append(item)

        if len(narr):
            narr = utils.pathlib_paths(narr)
            self.updateList(narr)
            self.start_btn.set_state(True)
            self.clearQuery()

        self.smartPaste.delete(1.0, tk.END)
        self.smartPaste.insert(tk.INSERT, self.smartNotice)
Example #2
0
def add_stat(statfile, version, time, date, lc, vh, test=False):
    """
    Agrega una entrada al archivo de estadísticas.

    :param test: Indica testeo
    :param statfile: Archivo de estadísticas
    :param version: Versión del template
    :param time: Tiempo de compilación
    :param date: Fecha de compilación
    :param lc: Total de líneas de código
    :param vh: Version hash
    :return:
    """

    # Se carga el archivo y se encuentra la última entrada
    dataarr = []
    try:
        data = open(statfile)
        for i in data:
            dataarr.append(i)
        lastentrypos = len(dataarr) - 1
    except:
        data = open(statfile, 'w')
        lastentrypos = -1
    if lastentrypos >= 0:
        lastentry = split_str(dataarr[lastentrypos].strip(), ' ')
        lastid = int(lastentry[0])
        lastver = lastentry[1].split('.')
        if len(lastver) == 4:
            lastverid = int(lastver[3])
            lastver = lastentry[1]
            lastver = lastver.replace('.' + str(lastverid), '')
        else:
            lastverid = 0
            lastver = lastentry[1]

        dataarr[lastentrypos] = '{0}\n'.format(dataarr[lastentrypos])
    else:
        lastid = 0
        lastver = ''
        dataarr.append(
            generate_statline('ID', 'VERSION', 'CTIME', 'FECHA', 'LINEAS',
                              'HASH\n'))
    data.close()

    # Se comprueba que la version sea distinta
    if version == lastver:
        version = '{0}.{1}'.format(version, lastverid + 1)

    # Se crea una nueva línea
    newentry = generate_statline(lastid + 1, version,
                                 str(time)[0:5], date, lc, vh)
    dataarr.append(newentry)

    # Se guarda el nuevo archivo
    if not test:
        data = open(statfile, 'w')
        for i in dataarr:
            data.write(i)
        data.close()
Example #3
0
def generate_planets(sun_pos_x, sun_size_r, options):

    height = options.height
    nb_planets = options.nb_planets
    min_size_planet = options.min_size_planet
    max_size_planet = options.max_size_planet
    distance_planet = options.distance_planet

    ring_proba = options.ring_proba
    moon_proba = options.moon_proba

    last_celestial = (sun_pos_x, sun_size_r)
    planets = []

    ls_seed = utils.split_str(options.id, nb_planets)

    for i in range(nb_planets):
        random.seed(ls_seed[i])
        random_size = random.randint(min_size_planet, max_size_planet)
        planet_x = utils.new_pos_x(last_celestial[0], last_celestial[1],
                                   random_size, distance_planet)
        planet_y = int(height / 2)

        # print(planet_x, planet_y)

        planet_group = etree.Element('g')
        etree.SubElement(planet_group, 'title').text = 'planet_{}'.format(i)
        planet = etree.SubElement(planet_group,
                                  'ellipse',
                                  id='planet_{}'.format(i))

        planet.set('cx', str(planet_x))
        planet.set('cy', str(planet_y))
        planet.set('rx', str(random_size))
        planet.set('ry', str(random_size))

        planet.set('fill', '#000000')
        planet.set('stroke', '#ffffff')
        planet.set('stroke-width', '2')

        if random.random() < ring_proba:
            for ring_svg in generate_rings(planet_x, planet_y, random_size,
                                           options):  # Adding rings to planets
                planet_group.append(ring_svg)

        if random.random() < moon_proba:
            for moon_svg in generate_moons(planet_x,
                                           options):  # Adding moons to planets
                planet_group.append(moon_svg)

        planet_group.append(generate_names(planet_x,
                                           options))  # Adding name to planets

        planets.append(planet_group)
        last_celestial = (planet_x, random_size)

    return planets
Example #4
0
def plot_stats(statfile):
    """
    Grafica las estadísticas.

    :param statfile: Archivo de estadísticas
    :return:
    """
    data = open(statfile)
    numcomp = []
    timecomp = []
    lcode = []
    k = 0
    for i in data:
        if k > 0:
            j = split_str(i.strip(), ' ')
            numcomp.append(int(j[0]))
            timecomp.append(float(j[2]))
            lcode.append(int(j[4]))
        k += 1
    nlen = len(numcomp)
    lastid = numcomp[nlen - 1]
    if nlen >= 3:
        # Tiempo de compilación
        tme = stats.tmean(timecomp)
        trc = stats.trim_mean(timecomp, 0.15)
        plt.figure(1)
        fig, ax = plt.subplots()
        ax.plot(numcomp, timecomp, 'c', label=u'Tiempo compilación (s)')
        ax.plot([numcomp[0], numcomp[nlen - 1]], [tme, tme],
                'r--',
                label=u'Tiempo medio ({0:.3g}s)'.format(tme))
        ax.plot([numcomp[0], numcomp[nlen - 1]], [tme, tme],
                'b--',
                label=u'Media acotada ({0:.3g}s)'.format(trc))
        ax.xaxis.set_major_locator(MaxNLocator(integer=True))
        ax.set_xlabel(u'Número de compilación')
        ax.set_ylabel(u'Tiempo de compilación [s]')
        ax.set_title(u'Estadísticas')
        plt.xlim(1, lastid)
        ax.legend()
        fig.savefig('stats/stats-ctime.png', dpi=600)

        # Líneas de código
        fig, ax = plt.subplots()
        ax.plot(numcomp, lcode)
        ax.set_xlabel(u'Número de compilación')
        ax.set_ylabel(u'Líneas de código')
        ax.set_title(u'Estadísticas')
        plt.ylim([min(lcode) * 0.97, max(lcode) * 1.03])
        ax.xaxis.set_major_locator(MaxNLocator(integer=True))
        plt.xlim(1, lastid)
        fig.savefig('stats/stats-lcode.png', dpi=600)

    data.close()
Example #5
0
    def leave_right(self, event):
        """移出右侧粘贴框
        """
        if self.hasQuery:
            return
        ss = self.paste_r.get(1.0, tk.END)
        arr = utils.split_str(ss, False)
        if len(arr) and arr[0] == self.msg_right:
            # print("默认")
            return

        # 如果是文件路径,则取出文件名和扩展名 / 文件夹名
        narr = []
        for i in range(len(arr)):
            arr[i] = utils.pathlib_path(arr[i])
            item = arr[i]
            item = item.strip("\t").strip(" ")
            item = item.strip("\t").strip(" ")
            item = item.strip('"').strip("'")
            p = Path(item)
            if p.name:
                narr.append(p.name)

        if not len(narr):
            self.paste_r.delete(1.0, tk.END)
            self.paste_r.insert(tk.INSERT, self.msg_right)
            return

        # self.varR.set(tuple(narr))
        # self.varC.set(tuple([]))
        self.svR.set(narr)
        self.svC.set([])
        self.sortRS['text'] = self.sortDesc[0]
        self.RightIsReverse = False

        # vlstr = self.varL.get()
        # vrstr = self.varR.get()
        # varIsN = util.stringVarisN
        # if varIsN(vlstr) or varIsN(vrstr):
        validL = self.svL.is_null()
        validR = self.svR.is_null()
        if not validL or not validR:
            utils.set_state(self.start_btn, True)

        self.paste_r.delete(1.0, tk.END)
        self.paste_r.insert(tk.INSERT, self.msg_right)
Example #6
0
    def paste_right_click(self, _):
        ss = utils.clipboard_get()
        arr = utils.split_str(ss, True)
        if len(arr) and arr[0] == self.smart_notice:
            # print("默认")
            return

        # 检查文件是否存在 /指定格式
        new_arr = []
        t = self.file_types_tup
        for item in arr:
            s = utils.get_file_type(item).lower()
            if not t.count(s) or not os.path.isfile(item):
                continue
            new_arr.append(item)

        if len(new_arr):
            new_arr = utils.pathlib_paths(new_arr, True)
            self.tree.set_list(new_arr)
Example #7
0
def get_last_ver(statfile):
    """
    Retorna la última versión compilada.

    :param statfile:
    :return:
    """
    data = open(statfile)
    datal = []
    for d in data:
        datal.append(d.strip())
    lastline = split_str(datal[len(datal) - 1], ' ')
    ver = lastline[1]
    vtime = lastline[3]
    if ver.count('.') == 3:
        ver = ver.split('.')
        ver = '{0}.{1}.{2}-{3}'.format(ver[0], ver[1], ver[2], ver[3])
    lastver = '{0} ({1})'.format(ver, vtime)
    data.close()

    return lastver
def read_thermo(filename, elems, specs):
    """Read and interpret thermodynamic database for species data.

    Reads the thermodynamic file and returns the species thermodynamic
    coefficients as well as the species-specific temperature range
    values (if given).

    Parameters
    ----------
    filename : str
        Name of thermo database file.
    elems : list of str
        List of element names in mechanism.
    specs : list of SpecInfo
        List of species in mechanism.

    Returns
    -------
    None

    """

    with open(filename, 'r') as file:

        # loop through intro lines
        while True:
            line = file.readline()

            # skip blank or commented lines
            if re.search('^\s*$', line) or re.search('^\s*!', line): continue

            # skip 'thermo' at beginning
            if 'thermo' in line.lower(): break

        # next line either has common temperature ranges or first species
        last_line = file.tell()
        line = file.readline()

        line_split = line.split()
        if line_split[0][0:1].isdigit():
            T_ranges = utils.read_str_num(line)
        else:
            # no common temperature info
            file.seek(last_line)
            # default

        # now start reading species thermo info
        while True:
            # first line of species info
            line = file.readline()

            # don't convert to lowercase, needs to match thermo for Chemkin

            # break if end of file
            if line is None or line[0:3].lower() == 'end': break

            # skip blank/commented line
            if re.search('^\s*$', line) or re.search('^\s*!', line): continue

            # species name, columns 0:18
            spec = line[0:18].strip()

            # Apparently, in some cases, notes are in the
            # columns of shorter species names, so make
            # sure no spaces.
            if spec.find(' ') > 0:
                spec = spec[0: spec.find(' ')]

            # now need to determine if this species is in mechanism
            if next((sp for sp in specs if sp.name == spec), None):
                sp_ind = next(i for i in range(len(specs))
                              if specs[i].name == spec
                              )
            else:
                # not in mechanism, read next three lines and continue
                line = file.readline()
                line = file.readline()
                line = file.readline()
                continue

            # set species to the one matched
            spec = specs[sp_ind]

            # ensure not reading the same species more than once...
            if spec.mw:
                # already done! skip next three lines
                line = file.readline()
                line = file.readline()
                line = file.readline()
                continue

            # now get element composition of species, columns 24:44
            # each piece of data is 5 characters long (2 for element, 3 for #)
            elem_str = utils.split_str(line[24:44], 5)

            for e_str in elem_str:
                e = e_str[0:2].strip()
                # skip if blank
                if e == '' or e == '0': continue
                # may need to convert to float first, in case of e.g. "1."
                e_num = float(e_str[2:].strip())
                e_num = int(e_num)

                spec.elem.append([e, e_num])

                # calculate molecular weight
                spec.mw += e_num * elem_wt[e.lower()]

            # temperatures for species
            T_spec = utils.read_str_num(line[45:73])
            T_low = T_spec[0]
            T_high = T_spec[1]
            if len(T_spec) == 3:
                T_com = T_spec[2]
            else:
                T_com = T_ranges[1]

            spec.Trange = [T_low, T_com, T_high]

            # second species line
            line = file.readline()
            coeffs = utils.split_str(line[0:75], 15)
            spec.hi[0] = float(coeffs[0])
            spec.hi[1] = float(coeffs[1])
            spec.hi[2] = float(coeffs[2])
            spec.hi[3] = float(coeffs[3])
            spec.hi[4] = float(coeffs[4])

            # third species line
            line = file.readline()
            coeffs = utils.split_str(line[0:75], 15)
            spec.hi[5] = float(coeffs[0])
            spec.hi[6] = float(coeffs[1])
            spec.lo[0] = float(coeffs[2])
            spec.lo[1] = float(coeffs[3])
            spec.lo[2] = float(coeffs[4])

            # fourth species line
            line = file.readline()
            coeffs = utils.split_str(line[0:75], 15)
            spec.lo[3] = float(coeffs[0])
            spec.lo[4] = float(coeffs[1])
            spec.lo[5] = float(coeffs[2])
            spec.lo[6] = float(coeffs[3])

            # stop reading if all species in mechanism accounted for
            if not next((sp for sp in specs if sp.mw == 0.0), None): break

    return None
Example #9
0
    def paste_leave_left(self, event):
        """移出左侧粘贴框
        """
        if self.hasQuery:
            return
        ss = self.paste_l.get(1.0, tk.END)
        arr = utils.split_str(ss, False)
        if len(arr) and arr[0] == self.msgLeft:
            # print("默认")
            return

        # 检查文件/文件夹是否存在
        narr = []
        no_exists_arr = []
        for i in range(len(arr)):
            arr[i] = utils.pathlib_path(arr[i])
            item = arr[i]
            if len(item) < 3:
                continue
            if os.path.exists(item):
                narr.append(item)
            else:
                no_exists_arr.append(item)

        if not len(narr):
            self.paste_l.delete(1.0, tk.END)
            self.paste_l.insert(tk.INSERT, self.msgLeft, "right")
            return

        # 去重
        tarr = []
        for item in narr:
            if not tarr.count(item):
                tarr.append(item)
        narr = tarr

        # self.varL.set(tuple(narr))
        # self.varC.set(tuple([]))
        self.svL.set(narr)
        self.svC.set([])
        self.sortLS['text'] = self.sortDesc[0]
        self.LeftIsReverse = False
        self.list_l.xview_moveto(1.0)

        # vlstr = self.varL.get()
        # vrstr = self.varR.get()
        # validL = False if util.stringVarisN(vlstr) else True
        # validR = False if util.stringVarisN(vrstr) else True
        validL = False if self.svL.is_null() else True
        validR = False if self.svR.is_null() else True
        if validL and validR:
            utils.set_state(self.start_btn, True)

        self.paste_l.delete(1.0, tk.END)
        self.paste_l.insert(tk.INSERT, self.msgLeft, "right")

        num1 = len(no_exists_arr)
        if num1:
            file_name_str = "\n".join(str(item) for item in no_exists_arr)
            utils.showinfo('{0}个文件不存在,将不参与重命名:{1}\n'.format(
                num1, file_name_str))