def decode_directory(frompath, topath, transl_dict = None):

    #Пробуем обрабатывать все файлы, у которых нет расширения
    for root, directories, files in os.walk(frompath):
        for file in files:
            fn, ext = splitext(file)
            if ext == "":
                new_path = root.replace(frompath, topath)
                decode_datafile(joinPath(root, file), joinPath(new_path, file) + ".txt", transl_dict)
예제 #2
0
 def writeToFile(self, dir):
     with open(joinPath(dir, "station"), "w") as ff:
         ff.write(self.station.name)
     with open(joinPath(dir, "pid"), "a") as ff:
         ff.write(self.pid+"\n")
     with open(joinPath(dir, "url"), "w") as ff:
         ff.write(self.station.url)
     with open(joinPath(dir, "number"), "w") as ff:
         ff.write(self.number)
def encode_directory(inputdir, outputdir):

    #Пробуем обрабатывать все файлы с расширением .txt
    for root, directories, files in os.walk(inputdir):
        for file in files:
            fn, ext = splitext(file) #Получаем имя файла без .txt
            if ext == ".txt":
                new_path = root.replace(inputdir, outputdir)
                encode_datafile(joinPath(root, file), joinPath(new_path, fn))
예제 #4
0
파일: mkfile.py 프로젝트: arruda/amao
def criar_texto_mkfile(questao):
    """
    Gera o conteudo do makefile para utilizar todos os .cpp necessarios
    """
    conteudo = "CC=g++\nCFLAGS=-c -Wall\nLDFLAGS=\nSOURCES="
    for fonte in questao.fontes.all():
        conteudo += joinPath(settings.MEDIA_ROOT, fonte.__str__()) + " "
    conteudo += "\nOBJECTS=$(SOURCES:.cpp=.o)\nEXECUTABLE="
    conteudo += joinPath(settings.MEDIA_ROOT,"execs",questao.avaliacao.aluno.slug,questao.avaliacao.slug,questao.slug,questao.questao.slug)
    conteudo += "\nall: $(SOURCES) $(EXECUTABLE)\n$(EXECUTABLE): $(OBJECTS)\n\t$(CC) $(LDFLAGS) $(OBJECTS) -o $@"
    conteudo += "\n.cpp.o:\n\t$(CC) $(CFLAGS) $< -o $@\nclean:\n\trm -rf "
    conteudo += joinPath(settings.MEDIA_ROOT,"fontes",str(questao.avaliacao.aluno.slug),str(questao.avaliacao.slug),str(questao.slug),"*.o") 
        
    return conteudo
예제 #5
0
def buildHtml(contentRoot = None, outputRoot = None, directory = "", allowAbort = True, templateManager = None, pageProcessors = None,
	umask = None, group = None):
	if not contentRoot:
		contentRoot = settings.SIMPLECONTENT_ROOT
	if not outputRoot:
		outputRoot = settings.SIMPLECONTENT_OUTPUT_ROOT
	if not directory and not contentRoot.endswith("/"):
		contentRoot += "/"
	if not templateManager:
		templateManager = getTemplateManager()
	if not pageProcessors:
		pageProcessors = getPageProcessors(includeStatic = True)
	if not umask:
		umask = getattr(settings, "SIMPLECONTENT_OUTPUT_UMASK", None)
	if not group:
		group = getattr(settings, "SIMPLECONTENT_OUTPUT_GROUP", None)
		group = group and grp.getgrnam(group).gr_gid

	try:
		os.makedirs(os.path.join(outputRoot, directory))
	except: pass

	for entry in os.listdir(joinPath(contentRoot, directory)):
		fileInfo = {
			'relPath': joinPath(directory, entry),
			'srcPath': joinPath(contentRoot, directory, entry),
			'outPath': joinPath(outputRoot, directory, entry),
			'outUmask': umask,
			'outGroup': group
		}
		if os.path.isdir(fileInfo["srcPath"]):
			buildHtml(contentRoot, outputRoot, fileInfo["relPath"], allowAbort, templateManager, pageProcessors)
			continue

		try:
			content = renderTemplate(fileInfo, templateManager, allowAbort = allowAbort, pageProcessors = pageProcessors)
		except Exception, e:
			print "Error rendering page '%s': %s" % (fileInfo["relPath"], e)
			continue

		if content:
			open(fileInfo["outPath"], 'w').write(content.encode('utf8'))
		if umask:
			os.chmod(fileInfo["outPath"], umask)
		if group:
			os.chown(fileInfo["outPath"], -1, group)
예제 #6
0
	def checkOldLogs(self, event):
		path = self.dp_LogPath.GetPath()
		if path:
			logFile = joinPath(path, "TheWatcher.log")
			if isfile(logFile):
				self.pg_LogDetails.SetPropertyValue("Name", "TheWatcher.log")
				# size = "%d %s" % (stat(logFile).st_size, "bytes")
				self.pg_LogDetails.SetPropertyValue("Size", getFileSize(logFile))
예제 #7
0
def getStatusFromFiles(dir):
    try:
        with open(joinPath(dir, "station"), "r") as ff:
            name = ff.readline()
        with open(joinPath(dir, "number"), "r") as ff:
            number = int(ff.readline())
        with open(joinPath(dir, "url"), "r") as ff:
            url = ff.readline()
        with open(joinPath(dir, "pid"), "r") as ff:
            pid = int(ff.readline())
        with open(joinPath(dir, "tag"), "r") as ff:
            tag = ff.readline()
    except IOError as e:
        print e
        return None

    station = Station(name, url, False)
    return Status(station, number, pid, tag)
예제 #8
0
파일: models.py 프로젝트: arruda/amao
 def gerar_makefile(self):
     """Gera um makefile para os fontes necessarios e retorna o path para o arquivo gerado.
     """
     filePath = joinPath(settings.MEDIA_ROOT,"fontes",str(self.user.username),"makefile")
     
     #abre o arquivo no caminho posto acima, escreve no arquivo e da close
     mkfile = open(filePath,'w')                   
     mkfile.write(criar_texto_mkfile(self))        
     mkfile.close()        
     
     return filePath
예제 #9
0
def __moveToDir(srcPath, destDirPath):
    """ Moves 1 item (recursively) """
    srcPath = absPath(srcPath)
    destDirPath = absPath(destDirPath)
    srcTail = fileBaseName(normpath(srcPath))
    destPath = joinPath(destDirPath, srcTail)
    if srcPath == destPath: return
    __removeFromDir(srcTail, destDirPath)
    if not isDir(destDirPath): makeDir(destDirPath)
    move(srcPath, destDirPath)
    print('Moved "%s" to "%s"' % (srcPath, destPath))
    return destPath
예제 #10
0
파일: util.py 프로젝트: abake48/distbuilder
def __copyToDir(srcPath, destDirPath):
    """ Copies 1 item (recursively) """
    srcPath = absPath(srcPath)
    destDirPath = absPath(destDirPath)
    srcTail = fileBaseName(normpath(srcPath))
    destPath = joinPath(destDirPath, srcTail)
    if srcPath == destPath: return
    __removeFromDir(srcTail, destDirPath)
    if isFile(srcPath): copyFile(srcPath, destPath)
    elif isDir(srcPath): copyDir(srcPath, destPath)
    print('Copied "%s" to "%s"' % (srcPath, destPath))
    return destPath
예제 #11
0
    def request_and_save(self, whatData:str, Economy:list, Product:list, Partner:list,
                        output_path:str, Period = None, display_progress_rate=True):
        '''
        @param whatData: What data do you want to get? We support "import",
                        "export" , and "both"
        @param Economy: What economy do you want to know?
        @param Product: What product do you want to know?
        @param Partner: What partner do you want to know?
        @param output_path: After crawling the ordered data, where should we store them
        @param display_progress_rate:
            If this parameter is set to True, then you can track the progress of
            the crawler when it start crawling.

        @param Period: not support yet.

        Note: when the number of Economy is more than 1, the crawler will store the
            data into saperate files. Their names whould become
            output_path_<Economy_name>.xlsx.  
        '''
        if(whatData not in SUPPORT_DATA):
            raise ValueError("[!] The data you request is not supported.  ")

        # This block may move to _save_one_ws to get more flexibility in the fulture, 
        # though put it here can increase some efficiency
        Economy = tuple([self.economyCode.search(i) for i in Economy])
        Product = tuple([self.productCode.search(i) for i in Product])
        Partner = tuple([self.partnerCode.search(i) for i in Partner])
        # ---
        
        category = CATEGORY[whatData.lower()]
        for economy in Economy:
            wb = Workbook()
            ws = wb.active
            for i, param in enumerate(category):
                if(i != 0):
                    ws = wb.create_sheet()
                self._save_one_sheet(ws, param, economy, Product, Partner, Period, 
                                     display_progress_rate=display_progress_rate)
            
            adjust_output_path = output_path
            folder, file = splitPath(output_path)

            if(not isdir(folder)):
                mkdir(folder)
            if(len(Economy) != 1):
                fileName, ext = file.split('.')
                adjust_fileName = "{}_{}".format(fileName, economy.name.strip().replace(' ', '_'))
                adjust_output_path = joinPath(folder, "{}.{}".format(adjust_fileName, ext))
            
            wb.save(adjust_output_path)
            if(display_progress_rate):
                print("Finish saving the data of economy:{}. ".format(economy.name.strip()))
예제 #12
0
파일: lockable.py 프로젝트: arruda/amao
 def get_lock_path(self):
     "retorna a path para o arquivo de lock dessa questao"
     if hasattr(self,'avaliacao'):
         dct = {'questao':self.questao,
                 'avaliacao':self.avaliacao,
                 'aluno':self.avaliacao.aluno,
                 }
     else:
         dct = {'questao':self}
     #obriga a criar o diretorio caso esse nao exista.
     dct['criar']=True
     dct['header']=settings.MEDIA_ROOT
         
     return joinPath(path_helper('fontes',**dct),".lock")
예제 #13
0
    def reprojectPolorisation(self, polarisation, sourceFile, state, manifest,
                              configuration, inputFileName, outputRoot):
        outputPath = joinPath(outputRoot, polarisation)

        if not os.path.exists(outputPath):
            os.makedirs(outputPath)

        outputFile = joinPath(
            outputPath,
            wc.getOutputFileName(inputFileName, polarisation, manifest,
                                 configuration["filenameDemData"],
                                 configuration["filenameSrs"]))

        if not self.testProcessing:
            try:
                env = {"GDAL_DATA": "/usr/share/gdal/2.2"}

                subprocess.run(
                    "gdalwarp -overwrite -s_srs {} -t_srs {} -r bilinear -dstnodata 0 -of GTiff -tr 10 10 --config CHECK_DISK_FREE_SPACE NO {} {}"
                    .format(configuration["sourceSrs"],
                            configuration["targetSrs"], sourceFile,
                            outputFile),
                    env=env,
                    check=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    shell=True).stdout

            except subprocess.CalledProcessError as e:
                errStr = "command '{}' return with error (code {}): {}".format(
                    e.cmd, e.returncode, e.output)
                log.error(errStr)
                raise RuntimeError(errStr)
        else:
            wc.createTestFile(outputFile)

        state["reprojectedFiles"][polarisation].append(outputFile)
예제 #14
0
 def setupFileLogging(self):
     self.fileLogger = logging.getLogger(__application__)
     self.fileLogger.setLevel(logging.DEBUG)
     if self.logData != None:
         log_format = self.logData["log_format"]
         logfilename = joinPath(self.logData["path"], "TheWatcher.log")
         if self.logData["timestamp"] == True:
             timestamp = self.logData["ts_format"]
         else:
             timestamp = "%d/%m/%Y %I:%M:%S %p"
     else:
         log_format = "%(asctime)-15s - %(levelname)s - %(message)s"
         logfilename = "TheWatcher.log"
         timestamp = "%d/%m/%Y %I:%M:%S %p"
     self.loggingFileHandler = logging.FileHandler(logfilename)
     fmt = logging.Formatter(log_format, datefmt=timestamp)
     self.loggingFileHandler.setFormatter(fmt)
     self.fileLogger.addHandler(self.loggingFileHandler)
    def __init__(self,
                 rel_path: str,
                 year: int = 0,
                 dt_corr: float = 0,
                 date_fmt: str = 'sex',
                 separator: str = ', ',
                 titles: list = None,
                 time_column_idx: int = 0):

        rootdir = os.path.abspath("./")
        self.txtPath = joinPath(rootdir, rel_path)
        self.year = year
        self.dt_corr = dt_corr
        self.date_fmt = date_fmt
        self.separator = separator
        self.titles = titles
        self.time_column_idx = time_column_idx
        self.time_key = None
예제 #16
0
 def setupFileLogging(self):
     self.fileLogger = logging.getLogger(__application__)
     self.fileLogger.setLevel(logging.DEBUG)
     if self.logData != None:
         log_format = self.logData["log_format"]
         logfilename = joinPath(self.logData["path"], "TheWatcher.log")
         if self.logData["timestamp"] == True:
             timestamp = self.logData["ts_format"]
         else:
             timestamp = "%d/%m/%Y %I:%M:%S %p"
     else:
         log_format = "%(asctime)-15s - %(levelname)s - %(message)s"
         logfilename = "TheWatcher.log"
         timestamp = "%d/%m/%Y %I:%M:%S %p"
     self.loggingFileHandler = logging.FileHandler(logfilename)
     fmt = logging.Formatter(log_format, datefmt=timestamp)
     self.loggingFileHandler.setFormatter(fmt)
     self.fileLogger.addHandler(self.loggingFileHandler)
예제 #17
0
파일: util.py 프로젝트: abake48/distbuilder
def download(url, saveToPath=None, preserveName=True):
    print("Downloading: %s..." % (url, ))
    download._priorPct = 0

    def __ondownLoadProgress(blockCount, blockSize, fileSize):
        if fileSize != -1:
            pct = int(100 * ((blockCount * blockSize) / fileSize))
            if pct - download._priorPct >= 10:
                download._priorPct = pct
                stdout.write("Done!\n" if pct ==
                             100 else "{0}%...".format(pct))
                stdout.flush()

    if saveToPath is None and preserveName:
        downloadDir = tempDirPath()
        downloadName = fileBaseName(urllib.parse.urlsplit(url)[2])
        removeFromDir(downloadName, downloadDir)
        saveToPath = joinPath(downloadDir, downloadName)
    localPath, _ = urllib.request.urlretrieve(url, saveToPath,
                                              __ondownLoadProgress)
    print("Saved to: %s" % (localPath, ))
    return localPath
예제 #18
0
def plot_jcamp_dir(base_path='jcamp'):
    def sizeInches(wPix, hPix, dpi=96):  # from pixels to inches in 96 dpi
        return (wPix / dpi, hPix / dpi)  # 96 dpi

    fig = plt.figure('jcamp-dx ' + base_path, sizeInches(1500, 800))
    fig.subplots_adjust(left=0.03,
                        bottom=.05,
                        wspace=0.12,
                        hspace=0.45,
                        right=0.97,
                        top=0.96)
    plt.rcParams.update({'font.size': 5})

    dct = []
    for nf, fnme in enumerate(idir(joinPath(base_path, '*dx'),
                                   recursive=True)):
        dct = jcamp.JCAMP_reader(fnme)
        if nf < 25:
            plt.title(dct['title'][:30])
            plt.subplot(5, 5, nf + 1)
            plt.plot(dct['x'], dct['y'])
    plt.show()
예제 #19
0
    def insertRow(self, layer):
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)

        column = 0  # Layer
        layerName = layer.name()
        nameIcon = 'check_green.svg' if layer.selectedFeatureCount(
        ) == 0 else 'check_yellow.svg'
        icon = QIcon(joinPath(dirname(__file__), nameIcon))
        btn = QPushButton(icon, layerName, self.tableWidget)
        btn.setObjectName(layer.id())
        btn.setToolTip(layerName)
        btn.clicked.connect(self._onRunCatalog)
        layer.selectionChanged.connect(self._onSelectionChanged)
        self.tableWidget.setCellWidget(row, column, btn)

        column = 1  # Total

        msgtrans = QCoreApplication.translate("CatalogOTF", "None")
        item = QTableWidgetItem(msgtrans)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.tableWidget.setItem(row, column, item)

        self.tableWidget.resizeColumnsToContents()
예제 #20
0
파일: util.py 프로젝트: abake48/distbuilder
 def moveItem(root, item, isSubDir=False):
     srcPath = joinPath(root, item)
     destDir = joinPath(destDirPath, relpath(root, srcDirPath))
     if isSubDir and isDir(destDir): return
     __moveToDir(srcPath, destDir)
예제 #21
0
파일: util.py 프로젝트: abake48/distbuilder
def _toSrcDestPair(pathPair, destDir=None, basePath=None):
    #print( "_toSrcDestPair: pathPair=%s, destDir=%s, basePath=%s" % (pathPair, destDir, basePath) )

    src = dest = None
    if isinstance(pathPair, string_types):
        # string pair representation
        if PATH_PAIR_DELIMITER in pathPair:
            pathPair = pathPair.split(PATH_PAIR_DELIMITER)
            try:
                src = pathPair[0].strip()
            except:
                pass
            try:
                dest = pathPair[1].strip()
            except:
                pass
        # shortcut syntax - only provide the source,
        # (the destination is relative)
        else:
            src = pathPair
    elif isinstance(pathPair, dict):
        # if a dictionary is provided, use the first k/v pair
        try:
            src, dest = iteritems(pathPair).next()
        except:
            pass
    else:
        # a two element tuple (or list) is the expected src/dest format
        try:
            src = pathPair[0]
        except:
            pass
        try:
            dest = pathPair[1]
        except:
            pass

    if src is None: return None
    src = normpath(src)
    if dest == True:  # True=="same"
        if not isabs(src): dest = src
        else:
            raise Exception("A resource destination cannot be the same "
                            "as an ABSOLUTE source path")
    elif dest is not None:
        dest = normpath(dest)

    relSrcDir = basePath if basePath else THIS_DIR
    srcHead, srcTail = splitPath(src)

    # NOTE: for a relative source path to have a **nested** destination
    # path, the destination MUST be explicitly provided
    if srcHead == "" or not isParentDir(relSrcDir, srcHead):
        srcHead = relSrcDir
        src = absPath(src, basePath)

    if destDir is None:  # (i.e. PyInstaller Argument)
        if dest is None: dest = relpath(srcHead, THIS_DIR)
    else:
        if dest is None: dest = srcTail
        if dest.startswith(PATH_DELIM):
            # must remove a leading slash from dest for joinPath to
            # make the dest a child of destDir
            try:
                dest = dest[1:]
            except:
                pass
        dest = absPath(joinPath(destDir, dest), relSrcDir)

    #print( "result: src=%s, dest=%s" % (src, dest) )
    return (src, dest)
예제 #22
0
파일: util.py 프로젝트: abake48/distbuilder
def _optLocalBinPath(relativePath):
    return normpath(joinPath(OPT_LOCAL_BIN_DIR, relativePath))
예제 #23
0
파일: util.py 프로젝트: abake48/distbuilder
def _usrBinPath(relativePath):
    return normpath(joinPath(USER_BIN_DIR, relativePath))
예제 #24
0
파일: util.py 프로젝트: abake48/distbuilder
def _pythonPath(relativePath):
    return normpath(joinPath(PY_DIR, relativePath))
예제 #25
0
파일: util.py 프로젝트: abake48/distbuilder
def sitePackagePath(packageName):
    packagePath = joinPath(SITE_PACKAGES_PATH, packageName)
    return packagePath if exists(packagePath) else None
예제 #26
0
                           default="")
    argParser.add_argument("-l",
                           dest="listStations",
                           action="store_true",
                           help="list available stations",
                           default=False)
    argParser.add_argument("num",
                           nargs="?",
                           help="station number",
                           default=None)
    args, unknown = argParser.parse_known_args(sys.argv[1:])
    currentPath = os.path.dirname(os.path.realpath(__file__))
    configPath = ""

    if not args.configFile:
        configFile = joinPath(currentPath, "config")
    else:
        configFile = args.configFile

    config = Config(configFile)

    if args.listStations:
        for i in xrange(1, len(config.stations)):
            print i, config.stations[i]
        exit(0)

    if not args.playerFile:
        playerFile = joinPath(currentPath, config.player)
    else:
        playerFile = args.playerFile
예제 #27
0
 def clearLogs(self, event):
     path = self.dp_LogPath.GetPath()
     if path:
         logFile = joinPath(path, "TheWatcher.log")
         if isfile(logFile):
             remove(logFile)
예제 #28
0
	def clearLogs(self, event):
		path = self.dp_LogPath.GetPath()
		if path:
			logFile = joinPath(path, "TheWatcher.log")
			if isfile(logFile):
				remove(logFile)
예제 #29
0
     break
 elif command == "status":
     status = streams.getStatusFromFiles(config.dirName)
     if not status:
         answer = "stopped\n"
     else:
         answer = str(status) + "\n"
 elif command == "help":
     answer = help_string()
 elif command == "play":
     if len(line) < 2:
         answer = "no station number given"
     else:
         try:
             num = int(line[1])
             pidFile = joinPath(config.dirName, "pid")
             if num > 0:
                 station = config.stations[num]
                 tagFile = joinPath(config.dirName, "tag")
                 popen = streams.startPlayer(config.player,
                                             station,
                                             tagFile,
                                             pidFile)
                 if popen:
                     status = streams.Status(station,
                                             num,
                                             popen.pid)
                     status.writeToFile(config.dirName)
             else:
                 streams.killOld(pidFile)
                 answer = "stopped\n"
예제 #30
0
class Downloader(object):
    # ------------- configurations --------------------

    _optionTagName = "option"

    _selectors = Selectors(links="table td a.iframe:not(.vidlink)",
                           video_button="a.closebox[title='Play Video']")
    _inputsIds = InputsIds(name="EmaiL",
                           password="******",
                           submit="idenT_conT")
    _injectorDetails = InjectorDetails(
        funcsFile=joinPath("js", "oldvideo_funcs.js"),
        mainFile=joinPath("js", "oldvideo_main.js"),
        fromElmId="_from_vid",
        toElmId="_to_vid",
        doneElmId="_done_button",
        doneLink="#done")

    timeout = 180

    # --------------------------------------------------

    def __init__(self):
        self._funcsScript = open(self._injectorDetails.funcsFile,
                                 encoding='utf-8').read()
        self._mainScript = open(self._injectorDetails.mainFile,
                                encoding='utf-8').read().format(
                                    self._injectorDetails.fromElmId,
                                    self._injectorDetails.toElmId,
                                    self._injectorDetails.doneLink,
                                    self._injectorDetails.doneElmId)

    def start(self):
        self.browser = webdriver.Chrome()
        return self

    def end(self):
        self.browser.close()

    def navigate(self, url):
        self.browser.get(url)
        return self

    def _find_id(self, id):
        return self.browser.find_element_by_id(id)

    def _get_input_fields(self):
        return self.browser.find_element_by_id(self._inputsIds.name), \
               self.browser.find_element_by_id(self._inputsIds.password)

    def _select_server(self):
        pass
        # self.browser \
        #     .find_element_by_id(self._inputsIds.server) \
        #     .find_elements_by_tag_name(self._optionTagName)[-1].click()

    def login(self, username='', password=''):
        self._select_server()

        usr_input, pass_input = self._get_input_fields()
        if username: usr_input.send_keys(username + "@campus.technion.ac.il")
        if password: pass_input.send_keys(password)
        if username and password:
            self._find_id(self._inputsIds.submit).click()

        self._wait_for_video_page()

        return self

    def _wait_for_video_page(self):
        Wait(self.browser, self.timeout).until(
            EC.presence_of_element_located((By.CLASS_NAME, "videolist")))
        return self

    def load_links(self):
        links = self.browser.find_elements_by_css_selector(
            self._selectors.links)
        self.links = list(map(lambda l: l.get_attribute("href"), links))
        return self

    def _prompt_download(self):
        start, end = 0, len(self.links)

        self.browser.execute_script('\n'.join(
            [self._funcsScript.format(start, end), self._mainScript]))

        Wait(self.browser, self.timeout).until(
            EC.url_contains(self._injectorDetails.doneLink))

        start = clamp_value(
            start, end,
            int(
                self._find_id(
                    self._injectorDetails.fromElmId).get_attribute("value")))
        end = clamp_value(
            start, end,
            int(
                self._find_id(
                    self._injectorDetails.toElmId).get_attribute("value")) + 1)
        return start, end

    def download(self):
        start, end = self._prompt_download()
        self.browser.set_window_size(0, 0)
        for link in self.links[start:end]:
            filename = link.split("/")[-1]
            self.navigate(link)
            rtsp_link = self.browser \
                .find_element_by_css_selector(self._selectors.video_button) \
                .get_attribute("href")
            self.browser.back()
            os.system("msdl -s2 {} -o {}".format(rtsp_link, filename))
예제 #31
0
 def _onRunCatalog(self):
     btn = self.sender()
     icon = QIcon(joinPath(dirname(__file__), 'cancel_red.svg'))
     btn.setIcon(icon)
     layerID = btn.objectName()
     self.runCatalog.emit(layerID)
예제 #32
0
     break
 elif command == "status":
     status = streams.getStatusFromFiles(config.dirName)
     if not status:
         answer = "stopped\n"
     else:
         answer = str(status) + "\n"
 elif command == "help":
     answer = help_string()
 elif command == "play":
     if len(line) < 2:
         answer = "no station number given"
     else:
         try:
             num = int(line[1])
             pidFile = joinPath(config.dirName, "pid")
             if num > 0:
                 station = config.stations[num]
                 tagFile = joinPath(config.dirName, "tag")
                 popen = streams.startPlayer(
                     config.player, station, tagFile, pidFile)
                 if popen:
                     status = streams.Status(
                         station, num, popen.pid)
                     status.writeToFile(config.dirName)
             else:
                 streams.killOld(pidFile)
                 answer = "stopped\n"
         except Exception as e:
             print e
             answer = "invalid station number\n"
예제 #33
0
파일: util.py 프로젝트: abake48/distbuilder
def _toLibResPath(relPath):
    path = joinPath(__THIS_LIB_DIR, relPath)
    return path if exists(path) else None
예제 #34
0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as clr
from matplotlib.backends.backend_pdf import PdfPages

# Directorio raíz del proyecto
ROOT_DIR = os.path.abspath("./")
# Se importa a sys.path
if ROOT_DIR not in sys.path:
    sys.path.append(ROOT_DIR)

# fullPath = "/Users/JAG/progs/python/tristan/joao/"
fullPath = ROOT_DIR
fullPath2 = ROOT_DIR
ratePath = joinPath(fullPath, 'Name,Time,Rates2.txt')
pressurePath = joinPath(fullPath, 'EnvSens/')  # Datos de Joao
# fullPath2 = "/Users/JAG/progs/python/tristan/data10m/"
pressurePathx = joinPath(fullPath2, 'd_sdg18_posmet_10m.txt')  # Datos de Hans
# save figures
'''
2018 Nov16: DOY = 320 
2018 Dic12: DOY = 346
'''

########################################
# Read And Customise Data Frame (Joao) #
########################################

# Passar os 754 valores de correctedRates para uma média horária; e assim obter apenas 672 valores (28dias x 24h)
예제 #35
0
파일: util.py 프로젝트: abake48/distbuilder
def absPath(relativePath, basePath=None):
    if relativePath is None: return None
    if isabs(relativePath): return relativePath
    if basePath is None: basePath = THIS_DIR
    return realpath(normpath(joinPath(basePath, relativePath)))
예제 #36
0
    import argparse
    argParser = argparse.ArgumentParser()
    argParser.add_argument("-c", dest="configFile", metavar="config",
                           help="config location", default="")
    argParser.add_argument("-p", dest="playerFile", metavar="player",
                           help="player location", default="")
    argParser.add_argument("-l", dest="listStations", action="store_true",
                           help="list available stations", default=False)
    argParser.add_argument("num", nargs="?",
                           help="station number", default=None)
    args, unknown = argParser.parse_known_args(sys.argv[1:])
    currentPath = os.path.dirname(os.path.realpath(__file__))
    configPath = ""

    if not args.configFile:
        configFile = joinPath(currentPath, "config")
    else:
        configFile = args.configFile

    config = Config(configFile)

    if args.listStations:
        for i in xrange(1, len(config.stations)):
            print i, config.stations[i]
        exit(0)

    if not args.playerFile:
        playerFile = joinPath(currentPath, config.player)
    else:
        playerFile = args.playerFile
예제 #37
0
파일: util.py 프로젝트: abake48/distbuilder
def _pythonScriptsPath(relativePath):
    return normpath(joinPath(PY_SCRIPTS_DIR, relativePath))
예제 #38
0
from os.path import splitext
from os.path import isdir
from os.path import isfile
from os.path import basename
from os.path import dirname

from .script import Script, namedVersions
    
def getExclusions():
    excluded = ["__init__.py", "script.py", "__pycache__"]
    if isfile("excluded_modules.conf"):
        with open("excluded_modules.conf", "r") as file:
            excluded += [line for line in file if len(line) > 0]
    return excluded
    
all_mod_list = [splitext(f)[0] for f in listdir(dirname(__file__)) if f not in getExclusions() and (splitext(f)[1] == ".py" or (isdir(f) and isfile(joinPath(f, "__init__.py"))))]
__all__ = []
for modName in all_mod_list:
    exec("from . import {0} as module_{0}".format(modName))
    module = eval("module_" + modName)
    
    try:    #Create Script
        exec("{0} = module.getScript(\"{0}\")".format(modName))
    except AttributeError:
        exec("{0} = Script(\"{0}\")".format(modName))
    __all__.append(modName)
    script = eval(modName)
    
    #Set script.getVersion if available, else default (platform.system())
    if callable(getattr(module, 'getCompatibleVersions', None)):
        script.setVersionFunc(module.getCompatibleVersions)
예제 #39
0
파일: util.py 프로젝트: abake48/distbuilder
def _usrLocalBinPath(relativePath):
    return normpath(joinPath(USER_LOCAL_BIN_DIR, relativePath))
예제 #40
0
파일: models.py 프로젝트: arruda/amao
def get_upload_path_fontes(instance, filename):
    return joinPath("fontes",str(instance.questao.user.username), filename)
예제 #41
0
파일: util.py 프로젝트: abake48/distbuilder
def _userHiddenLocalBinDirPath(relativePath):
    return normpath(
        joinPath("%s/.local/bin" % (_userHomeDirPath(), ), relativePath))
예제 #42
0
파일: util.py 프로젝트: abake48/distbuilder
PY_EXT = ".py"
PY_DIR = dirPath(PYTHON_PATH)
SITE_PACKAGES_PATH = get_python_lib()

# (client script's dir)
THIS_DIR = dirPath(realpath(argv[0]))

__THIS_LIB_DIR = dirPath(realpath(__file__))

PATH_PAIR_DELIMITER = ";"
SYS_CMD_DELIM = "&" if IS_WINDOWS else ";"
SYS_CMD_COND_DELIM = "&&"

# Windows
PY_SCRIPTS_DIR = joinPath(PY_DIR, "Scripts")

# *Nix
USER_BIN_DIR = "/usr/bin"
USER_LOCAL_BIN_DIR = "/usr/local/bin"
OPT_LOCAL_BIN_DIR = "/opt/local/bin"

# Shockingly platform independent
# (though can vary by os language and configuration...)
DESKTOP_DIR_NAME = "Desktop"

DEBUG_ENV_VAR_NAME = "DEBUG_MODE"
DEBUG_ENV_VAR_VALUE = "1"

# strictly Apple
_MACOS_APP_EXT = ".app"
예제 #43
0
파일: util.py 프로젝트: abake48/distbuilder
 def read(self, dirPath):
     self.script = None
     filePath = joinPath(dirPath, self.fileName())
     with open(filePath, 'r') as f:
         self.script = f.read()
예제 #44
0
		if content:
			open(fileInfo["outPath"], 'w').write(content.encode('utf8'))
		if umask:
			os.chmod(fileInfo["outPath"], umask)
		if group:
			os.chown(fileInfo["outPath"], -1, group)

	if not directory:
		dynamicPages = getDynamicPages()
		for path, view in dynamicPages.items():
			info = view(templateManager)
			fileInfo = {
				'srcPath': info['srcPath'],
				'relPath': path,
				'outPath': joinPath(outputRoot, path)
			}
			template = info['template']
			variables = info['variables']

			content = renderTemplate(fileInfo, templateManager, allowAbort = allowAbort, pageProcessors = pageProcessors,
				template = template, variables = variables)
			if content:
				open(fileInfo["outPath"], 'w').write(content.encode('utf8'))
			if umask:
				os.chmod(fileInfo["outPath"], umask)
			if group:
				os.chown(fileInfo["outPath"], -1, group)

		for pageProcessor in pageProcessors:
			pageProcessor.processEnd()