Example #1
0
    async def get_profile_image(self, ctx, *, msg):
        print("getting images")
        user_toon = msg.strip()
        if not ctx.message.mentions:
            if msg[0:3] == "<@!":
                user = msg[3:-1]
            else:
                result = User.toon_search(user_toon).first()
                user = result.discord_id
        else:
            user = str(ctx.message.mentions[0].id)

        if FileUtils.get_profile_image(user):
            limiter = 0
            for x in FileUtils.get_profile_image(user):
                if limiter < 3:
                    file = discord.File(FileUtils.path + "/" + user + "/" + x,
                                        filename=x)
                    await ctx.send(file=file, content="Uploaded: " + x[:-4])
                    limiter += 1
                else:
                    await ctx.message.channel.send(
                        "More than 3 images were found, limited to the first 3."
                    )
                    break
        else:
            if not ctx.message.mentions:
                await ctx.message.channel.send(
                    "Sorry, no profile images found associated with: " +
                    user_toon)
            else:
                await ctx.message.channel.send(
                    "No profile images found associated with: <@!" +
                    str(ctx.message.mentions[0].id) + ">")
Example #2
0
        def uninstall(self):
            try:
                MApplication.processEvents()
                self.UninstallationDirectory = str(self.leUninstallationDirectory.text())
                if len(self.UninstallationDirectory) > 0:
                    if self.UninstallationDirectory[-1] == fu.sep:
                        self.UninstallationDirectory = self.UninstallationDirectory[:-1]
                    if self.UninstallationDirectory == fu.HamsiManagerDirectory:
                        self.pageNo -= 1
                        Dialogs.showError(translate("Uninstall", "The path you selected is not valid."),
                                          translate("Uninstall",
                                                    "The selected path is Hamsi Manager source directory.<br>Please choose a valid uninstallation path."))
                    elif fu.isDir(self.UninstallationDirectory):
                        fu.removeFileOrDir(self.UninstallationDirectory)
                    else:
                        self.pageNo -= 1
                        Dialogs.showError(translate("Uninstall", "The path you selected is not valid."),
                                          translate("Uninstall",
                                                    "The selected path points to a file not a folder.<br>Please choose a valid Uninstallation path."))
                else:
                    self.pageNo -= 1
                    Dialogs.showError(translate("Uninstall", "The path you selected is not valid."),
                                      translate("Uninstall",
                                                "The selected path points to a file not a folder.<br>Please choose a valid Uninstallation path."))
                self.pageChanged(True)
            except:
                from Core import ReportBug

                ReportBug.ReportBug()
Example #3
0
def getPID():
    global isStarted
    if fu.isFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/mysqld.pid"):
        isStarted = True
        return fu.readFromFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/mysqld.pid").split("\n")[0]
    isStarted = False
    return None
Example #4
0
    def getFromAmarok(self):
        try:
            import Amarok

            Dialogs.showState(translate("CoverTable", "Checking For Amarok..."), 0, 1)
            if Amarok.checkAmarok():
                from Amarok import Operations

                directoriesAndValues = Operations.getDirectoriesAndValues()
                Dialogs.showState(translate("CoverTable", "Values Are Being Processed"), 1, 1)
                if directoriesAndValues is not None:
                    for rowNo in range(self.rowCount()):
                        if (getMainWindow().checkHiddenColumn("sourceCover") and
                                getMainWindow().checkHiddenColumn("destinationCover")):
                            if self.isChangeableItem(rowNo, "sourceCover"):
                                directoryPath = fu.joinPath(
                                    fu.getDirName(fu.getDirName(self.values[rowNo]["path"])),
                                    str(self.item(rowNo, 0).text()), str(self.item(rowNo, 1).text()))
                                if directoryPath in directoriesAndValues:
                                    directoryAndValues = directoriesAndValues[directoryPath]
                                    self.item(rowNo, 3).setText(
                                        directoryAndValues["coverPath"][0].replace(directoryPath, "."))
                                    self.item(rowNo, 4).setText("./" + Organizer.getIconName(
                                        directoryAndValues["artist"][0],
                                        directoryAndValues["album"][0],
                                        directoryAndValues["genre"][0],
                                        directoryAndValues["year"][0]))
        except:
            ReportBug.ReportBug()
Example #5
0
def SaveUserInfo(mobile, data):
    '''保存用户信息 /userinfo/mobile'''
    if not FileUtils.CheckFileExists(USERINFO_SAVE_DIR):
        FileUtils.CreateFileDir(USERINFO_SAVE_DIR)
    with open(USERINFO_SAVE_DIR + mobile + ".json", "w",
              encoding="utf-8") as f:
        json.dump(data, fp=f)
Example #6
0
def downloadFile(URL, path):
    result = False
    with open(path, "wb") as localFile:
        try:
            print "Downloading {0} to {1} ".format(URL, path)
            remoteFile = urllib2.urlopen(URL)
            fileSize = getFileSize(remoteFile)
            fileSizeValid = not (-1 == fileSize)
            CHUNK_SIZE = 1024
            if fileSizeValid:
                perctangeReported = 0
                downloadedSize = 0
                while True:
                    data = remoteFile.read(CHUNK_SIZE)
                    dataSize = len(data)
                    if dataSize > 0:
                        localFile.write(data)
                        downloadedSize = downloadedSize + dataSize
                    else:
                        break
                    downloadedPercentage = (100 * downloadedSize) / fileSize
                    if downloadedPercentage >= perctangeReported + 10:
                        perctangeReported = perctangeReported + 10
                        sys.stdout.write("=")
            else:
                localFile.write(remoteFile.read())
            result = True
            print " SUCCESS"
        except:
            result = False
            print " FAILED"
    if not result:
        fu.delete(path)
    return result
Example #7
0
def checkEmbeddedDB():
    global isAskEmbeddedDBConfiguration
    if uni.getBoolValue("isReadOnlyAmarokDB"):
        if (fu.isDir(fu.pathOfSettingsDirectory + "/Amarok/mysqle/amarok") and
                fu.isDir(fu.pathOfSettingsDirectory + "/Amarok/mysqle/mysql") and
                fu.isFile(fu.pathOfSettingsDirectory + "/Amarok/my.cnf")):
            return startReadOnlyEmbeddedDB()
        else:
            if isAskEmbeddedDBConfiguration:
                isAskEmbeddedDBConfiguration = False
                answer = Dialogs.ask(translate("Amarok", "Amarok Database Must Be Configure"),
                                     translate("Amarok",
                                               "Amarok database must be configure for Hamsi Manager. Are you want to configure Amarok database?"))
                if answer == Dialogs.Yes:
                    ReadOnlyEmbeddedDBConfigurator()
            else:
                return False
    else:
        if (fu.isFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/mysql/db.frm") and
                fu.isFile(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/my.cnf")):
            return startEmbeddedDB()
        else:
            if isAskEmbeddedDBConfiguration:
                isAskEmbeddedDBConfiguration = False
                answer = Dialogs.ask(translate("Amarok", "Amarok Database Must Be Configure"),
                                     translate("Amarok",
                                               "Amarok database must be configure for Hamsi Manager. Are you want to configure Amarok database?"))
                if answer == Dialogs.Yes:
                    EmbeddedDBConfigurator()
            else:
                return False
    return checkEmbeddedDB()
Example #8
0
 def changeCoverValues(self, _image=None, _valueType="file"):
     self.zoomValue = 1.0
     if _image is not None and _valueType == "file":
         _image = fu.checkSource(_image, "file", False)
         if _image is None:
             if self.isCorrectedWhenNotExist:
                 _image = fu.joinPath(fu.themePath, "Images", "ok.png")
             else:
                 _image = fu.joinPath(fu.themePath, "Images",
                                      "notExist.png")
     elif _valueType == "file":
         _image = fu.joinPath(fu.themePath, "Images", "notExist.png")
     self.pmapImage.detach()
     if _valueType == "data":
         self.pmapImage.loadFromData(_image)
     else:
         self.pmapImage.load(str(_image))
     self.lblImage.setPixmap(self.pmapImage)
     self.width = self.pmapImage.width()
     self.height = self.pmapImage.height()
     while 1 == 1:
         if self.width > self.defaultMaxSize[
                 0] or self.height > self.defaultMaxSize[1]:
             self.width *= 0.9
             self.height *= 0.9
         else:
             break
     self.lblImage.resize(int(self.width), int(self.height))
Example #9
0
def downloadFile(URL, path):
  result = False
  with open(path, 'wb') as localFile:
    try:
      print 'Downloading {0} to {1} '.format(URL, path)
      remoteFile = urllib2.urlopen(URL)
      fileSize = getFileSize(remoteFile)
      fileSizeValid = not (-1 == fileSize)
      CHUNK_SIZE = 1024      
      if fileSizeValid:
        perctangeReported = 0
        downloadedSize = 0
        while True:        
          data = remoteFile.read(CHUNK_SIZE)
          dataSize = len(data)
          if dataSize > 0:
            localFile.write(data)
            downloadedSize = downloadedSize + dataSize 
          else:
            break
          downloadedPercentage = ( 100 * downloadedSize) / fileSize
          if downloadedPercentage >= perctangeReported + 10:
            perctangeReported = perctangeReported + 10
            sys.stdout.write('=')            
      else:     
        localFile.write(remoteFile.read())
      result = True
      print ' SUCCESS'
    except:
      result = False
      print ' FAILED'
  if not result:
    fu.delete(path)
  return result
    
Example #10
0
def collect_content_from_url(a_arr_data):
    for page in a_arr_data:
        req = urllib2.Request(page.m_strURL)
        urlResponsContent = None
        try:
            urlResponsContent = urllib2.urlopen(req).read()
        except urllib2.HTTPError as e:
            print "Error Code: " + e.code + "\nMsg: " + ErrTransl.responses[
                e.code]
            print "Additional Info: " + e.read()
            continue
        except urllib2.URLError as e:
            print e.reason
            continue

        soup = BeautifulSoup(urlResponsContent, 'lxml')
        # strResponsContent = soup.findAll(text=True)

        strFilePath = ""
        if sys.platform.startswith('win'):
            strFilePath = "data\\"
        else:
            strFilePath = "./data/"
        strFilePath = strFilePath + str(page.m_nID) + ".json"
        dataPage = FileUtils.getDataFromFile(strFilePath)
        dataPage = YandexXML.WebPage().deserialize(dataPage)

        strTextContentOnly = getTextContent(dataPage.m_strURL, soup,
                                            config.c_arr_str_Reliable_URL)

        dataPage.m_strContent = strTextContentOnly
        FileUtils.setData2File(dataPage.serialize(), strFilePath)
Example #11
0
 def save(self):
     try:
         codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
         Scripts.saveScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName),
                            str(self.sciCommand.text()))
     except:
         ReportBug.ReportBug()
Example #12
0
def readMusicFile(_filePath, _isAlertWhenNotAvailable=True):
    _directoryPath = fu.getDirName(_filePath)
    isCanNoncompatible = False
    if fu.isReadableFileOrDir(_filePath):
        tagger = Taggers.getTagger()
        try:
            tagger.loadFile(_filePath)
        except:
            Dialogs.showError(translate("FileUtils/Musics", "Incorrect Tag"),
                              str(translate("FileUtils/Musics",
                                            "\"%s\" : this file has the incorrect tag so can't read tags.")
                              ) % Organizer.getLink(_filePath))
        if tagger.isAvailableFile() is False:
            isCanNoncompatible = True
        content = {}
        content["path"] = _filePath
        content["baseNameOfDirectory"] = fu.getBaseName(_directoryPath)
        content["baseName"] = fu.getBaseName(_filePath)
        content["artist"] = tagger.getArtist()
        content["title"] = tagger.getTitle()
        content["album"] = tagger.getAlbum()
        content["albumArtist"] = tagger.getAlbumArtist()
        content["trackNum"] = tagger.getTrackNum()
        content["year"] = tagger.getYear()
        content["genre"] = tagger.getGenre()
        content["firstComment"] = tagger.getFirstComment()
        content["firstLyrics"] = tagger.getFirstLyrics()
        content["images"] = tagger.getImages()
        if isCanNoncompatible and _isAlertWhenNotAvailable:
            Dialogs.show(translate("FileUtils/Musics", "Possible ID3 Mismatch"),
                         translate("FileUtils/Musics",
                                   "Some of the files presented in the table may not support ID3 technology.<br>Please check the files and make sure they support ID3 information before proceeding."))
        return content
Example #13
0
 def checkSource(self, _oldPath, _objectType="fileAndDirectory", _isCheckWritable=True):
     _path = fu.checkSource(_oldPath, _objectType, False)
     if _path is None:
         if _objectType == "file":
             answer = Dialogs.ask(translate("QuickMake", "Cannot Find File"),
                                  str(translate("FileUtils",
                                                "\"%s\" : cannot find a file with this name.<br>Are you want to organize parent directory with Hamsi Manager?")) % Organizer.getLink(
                                      _oldPath))
             if answer == Dialogs.Yes:
                 self.organizeWithHamsiManager(_oldPath)
             return None
         elif _objectType == "directory":
             answer = Dialogs.ask(translate("QuickMake", "Cannot Find Directory"),
                                  str(translate("FileUtils",
                                                "\"%s\" : cannot find a folder with this name.<br>Are you want to organize parent directory with Hamsi Manager?")) % Organizer.getLink(
                                      _oldPath))
             if answer == Dialogs.Yes:
                 self.organizeWithHamsiManager(_oldPath)
             return None
         else:
             answer = Dialogs.ask(translate("QuickMake", "Cannot Find File Or Directory"),
                                  str(translate("FileUtils",
                                                "\"%s\" : cannot find a file or directory with this name.<br>Are you want to organize parent directory with Hamsi Manager?")) % Organizer.getLink(
                                      _oldPath))
             if answer == Dialogs.Yes:
                 self.organizeWithHamsiManager(_oldPath)
             return None
     if _isCheckWritable:
         if fu.isWritableFileOrDir(_oldPath) is False:
             return None
     return _path
Example #14
0
def zip_build():
    latest_build_dir = env.get_env_variable( "Game", "latest_build_dir" )

    now = datetime.now()
    now_str = now.strftime( "%m_%d_%H_%M" )

    file_utils.zip_file_directory( latest_build_dir, builds_dir + game_name + "_" + now_str + ".zip" )
Example #15
0
    def generateBackgroundARFFFileForDataset(self, dataset:Dataset, backgroundFilePath: str, candidateAttrDirectories: list, includeValueBased: bool):
        addHeader = True
        for candidateAttrDirectory in candidateAttrDirectories:

            if (not candidateAttrDirectory.__contains__(dataset.name)) and FileUtils.listFilesInDir(candidateAttrDirectory)!=None: #none means dir exist

                merged = self.getMergedFile(candidateAttrDirectory,includeValueBased)
                if merged is not None:
                    MLAttributeManager.addArffFileContentToTargetFile(backgroundFilePath, merged[0].getAbsolutePath(),addHeader)
                    addHeader = False

                else:
                    instances = [] #List<Instances> instances = new ArrayList<>();
                    for file in listFilesInDir(candidateAttrDirectory):
                        if (file.contains('.arff') and not(not includeValueBased and file.contains(self.VALUES_BASED)) and not(file.contains('merged'))):
                            absFilePath = os.path.abspath(file)
                            instance = Loader().readArffAsDataframe(absFilePath)
                            instances.append(instance)

                        else:
                            Logger.Info(f'Skipping file: {file}')

                    mergedFile = self.mergeInstancesToFile(includeValueBased, candidateAttrDirectory, instances)
                    if mergedFile is None:
                        continue
                    self.addArffFileContentToTargetFile(backgroundFilePath, FileUtils.getAbsPath(mergedFile), addHeader)
                    addHeader = False
Example #16
0
 def changeFile(self, _filePath, _isNew=False):
     self.fileValues = fu.readTextFile(_filePath, uni.MySettings["fileSystemEncoding"])
     self.setWindowTitle(str(fu.getBaseName(self.fileValues["path"])))
     if self.pnlClearable is not None:
         clearAllChildren(self.pnlClearable, True)
     self.pnlClearable = MWidget()
     self.vblMain.insertWidget(0, self.pnlClearable, 20)
     vblClearable = MVBoxLayout(self.pnlClearable)
     self.infoLabels["path"] = MLabel(self.labels[0])
     self.infoLabels["content"] = MLabel(self.labels[1])
     dirPath = fu.getDirName(self.fileValues["path"])
     baseName = fu.getBaseName(self.fileValues["path"])
     self.infoValues["path"] = MLineEdit(str(fu.joinPath(dirPath, Organizer.emend(baseName, "file"))))
     self.infoValues["content"] = MPlainTextEdit(
         str(Organizer.emend(self.fileValues["content"], "text", False, True)))
     self.infoValues["content"].setLineWrapMode(MPlainTextEdit.NoWrap)
     self.sourceCharSet = MComboBox()
     self.sourceCharSet.addItems(uni.getCharSets())
     self.sourceCharSet.setCurrentIndex(self.sourceCharSet.findText(uni.MySettings["fileSystemEncoding"]))
     MObject.connect(self.sourceCharSet, SIGNAL("currentIndexChanged(int)"), self.sourceCharSetChanged)
     HBOXs = []
     HBOXs.append(MHBoxLayout())
     HBOXs[-1].addWidget(self.infoLabels["path"])
     HBOXs[-1].addWidget(self.infoValues["path"])
     HBOXs[-1].addWidget(self.sourceCharSet)
     for hbox in HBOXs:
         vblClearable.addLayout(hbox)
     vblClearable.addWidget(self.infoLabels["content"])
     vblClearable.addWidget(self.infoValues["content"])
Example #17
0
    def willDownload(self, _request):
        try:
            defaultFileName = str(MFileInfo(str(trStr(_request.url()))).fileName())
            fileDialogTitle = translate("UpdateControl", "You Can Click Cancel To Update Without Saving The Package.")
            if self.isNotInstall:
                fileDialogTitle = translate("UpdateControl", "Save New Version Of Hamsi Manager")
            fileName = Dialogs.getSaveFileName(fileDialogTitle,
                                               fu.joinPath(fu.getDirName(fu.HamsiManagerDirectory), defaultFileName))
            if self.isNotInstall is False or fileName is not None:
                if fileName is None:
                    import random

                    fileName = fu.joinPath(fu.getTempDir(), defaultFileName[:-7] + "-" + str(
                        random.randrange(0, 1000000)) + defaultFileName[-7:])
                self.pbtnDownloadAndInstall.setEnabled(False)
                newRequest = _request
                newRequest.setAttribute(MNetworkRequest.User, trQVariant(fileName))
                networkManager = self.wvWeb.page().networkAccessManager()
                reply = networkManager.get(newRequest)
                self.isFileExist = True
                self.connect(reply, SIGNAL("downloadProgress(qint64,qint64)"), self.downloading)
                self.connect(reply, SIGNAL("finished()"), self.downloaded)
                self.connect(reply, SIGNAL("error(QNetworkReply::NetworkError)"), self.errorOccurred)
        except:
            ReportBug.ReportBug()
Example #18
0
def antFileAction(path, key, action, value = "1"):
	antFile = path + s_antPath
	fp = open(antFile, "r")
	str = fp.read()
	fp.close()
	#查找的位置
	findKeyIndex = str.find(key)
	#没有找到,直接退出
	if findKeyIndex == -1:
		print antFile,"Not Found",key
		return
	index = len(key)
	#取到开始的字符
	lastText = str[0 : findKeyIndex + index]
	#取到之后的字符
	nextText = str[findKeyIndex + index: ]
	#查找下一个回车
	nexiIndex = nextText.find("\n")
	#分割下个字符串
	if -1 == nexiIndex:
		nexiIndex = len(nextText)
	#剩下的就是version
	findValue = nextText[0 : nexiIndex]
	if action == s_getAction:
		return findValue
	elif action == s_wirteAction:
		valueNextText = nextText[nexiIndex: ]
		text = lastText + "=" + value + valueNextText
        FileUtils.writeFile(antFile , text)
Example #19
0
    def add_debug_memory_info_in_code(self, path):
        self.path = path

        file_c_list = FileUtils.FileUtils.get_files_from_path(self.path)
        for file_c in file_c_list:
            if FileUtils.FileUtils.is_file_with_suffix(file_c[0], 'c') \
                    or FileUtils.FileUtils.is_file_with_suffix(file_c[0], 'h'):
                include_str = '#include \"'
                depth = file_c[1]
                for i in range(depth):
                    include_str += '../'
                include_str += 'python_record_memory.h'
                include_str += '\"\n'
                FileUtils.FileUtils.rename(file_c[0], file_c[0] + '_bk')
                file_handler = FileUtils.FileHandler(file_c[0])
                file_handler.append_plain(include_str)
                FileUtils.FileUtils.read_line_iterator(
                    file_c[0] + '_bk',
                    self._add_debug_memory_info_in_code,
                    args=file_handler)

        record_func_filename_h = FileUtils.FileUtils.path_join_filename(
            path, 'python_record_memory.h')
        record_func_filename_c = FileUtils.FileUtils.path_join_filename(
            path, 'python_record_memory.c')
        FileUtils.FileUtils.append_plain(record_func_filename_h,
                                         self.record_address_code_h)
        record_func_code_handler = FileUtils.FileHandler(
            record_func_filename_c)
        record_func_code_handler.append_plain(self.record_malloc_code_include)
        record_func_code_handler.append_plain(self.record_malloc_code_func)
        record_func_code_handler.append_plain(self.record_free_code_func)
 def showTableDetails(self, _fileNo, _infoNo):
     directoryPathOfCover = self.values[_fileNo]["path"]
     coverValues = [directoryPathOfCover,
                    fu.getRealPath(str(self.item(_fileNo, 2).text()), directoryPathOfCover),
                    fu.getRealPath(str(self.item(_fileNo, 3).text()), directoryPathOfCover),
                    fu.getRealPath(str(self.item(_fileNo, 4).text()), directoryPathOfCover)]
     CoverDetails.CoverDetails(coverValues, uni.getBoolValue("isOpenDetailsInNewWindow"), _infoNo)
Example #21
0
def extractAllFilesFromDirAndSubdirs(db, logger, extractDir, dirpathRoot):
    depotRoot1 = "I:\\objectstore1"
    depotRoot2 = "F:\\objectstore2"
    logger.log("extracting files from %s to %s" % (dirpathRoot, extractDir))
    dirfilelist = miscQueries.getAllPathsAndFilenamesFromDirAndSubdirs(
        db, dirpathRoot)
    logger.log("got %d dirs" % len(dirfilelist.keys()))

    for dirpath in dirfilelist:
        logger.log("directory %s" % dirpath)
        filelist = dirfilelist[dirpath]
        logger.log("%d files" % len(filelist))
        for filehash, filename in filelist:
            logger.log("filehash: %s, filename: %s" % (filehash, filename))
            fixedDirpath = dirpath.replace(":", "_")
            logger.log(fixedDirpath)
            destinationDir = os.path.join(extractDir, fixedDirpath)
            logger.log("destination: %s" % destinationDir)
            if not os.path.isdir(destinationDir):
                os.makedirs(destinationDir)

            if not FileUtils.CopyFileFromDepot(db, depotRoot1, destinationDir,
                                               filehash, filename):
                if not FileUtils.CopyFileFromDepot(
                        db, depotRoot2, destinationDir, filehash, filename):
                    logger.log(
                        "#############################file not found, setting status"
                    )
                    miscQueries.setFileStatus(db, filehash, "notFound")
Example #22
0
def getReadOnlyPID():
    global isReadOnlyStarted
    if fu.isFile(fu.pathOfSettingsDirectory + "/Amarok/mysqld.pid"):
        isReadOnlyStarted = True
        return fu.readFromFile(fu.pathOfSettingsDirectory + "/Amarok/mysqld.pid").split("\n")[0]
    isReadOnlyStarted = False
    return None
Example #23
0
def checkSize():
    setRecordType(1)
    if fu.isFile(fu.recordFilePath):
        if fu.getSize(fu.recordFilePath) > (int(uni.MySettings["maxRecordFileSize"]) * 1024):
            fu.moveFileOrDir(fu.recordFilePath,
                             fu.joinPath(fu.oldRecordsDirectoryPath, str(time.strftime("%Y%m%d_%H%M%S")) + ".txt"))
    restoreRecordType()
Example #24
0
    def _updateJobData(self, uiDict):
        paths = uiDict.get("paths", [])
        jobId = uiDict.get("jobId", None)
        
        path = pack("{}.tar".format(jobId), *paths)
        if path:                
            self.logger.debug("Sending File... {} ".format(path))
            returnValue = self.network.sendCommand("requestFileUpload", jobId=jobId)
            if not returnValue:
                return

            remotePath = returnValue.get("path", None)

            if remotePath:
                path = pack("{}.tar".format(jobId), *paths)
                self.logger.info("Sending Files... ")
                if path:                
                    self.network.sendFileSFTP(path, remotePath, callback=None)                    
                    FileUtils.deleteFile(path)
                    self.network.sendCommand("fileUploadCompleted", waitForResponse=True, path=remotePath, jobId=jobId)
                    return True
        else:
            return False

        return False
Example #25
0
def antFileAction(path, key, action, value="1"):
    antFile = path + s_antPath
    fp = open(antFile, "r")
    str = fp.read()
    fp.close()
    #查找的位置
    findKeyIndex = str.find(key)
    #没有找到,直接退出
    if findKeyIndex == -1:
        print antFile, "Not Found", key
        return
    index = len(key)
    #取到开始的字符
    lastText = str[0:findKeyIndex + index]
    #取到之后的字符
    nextText = str[findKeyIndex + index:]
    #查找下一个回车
    nexiIndex = nextText.find("\n")
    #分割下个字符串
    if -1 == nexiIndex:
        nexiIndex = len(nextText)
    #剩下的就是version
    findValue = nextText[0:nexiIndex]
    if action == s_getAction:
        return findValue
    elif action == s_wirteAction:
        valueNextText = nextText[nexiIndex:]
        text = lastText + "=" + value + valueNextText
    FileUtils.writeFile(antFile, text)
Example #26
0
def ListNotUtf8SourceFile(srcdir):
    paths = FileUtils.GetAllFiles(srcdir, ".h|.cpp")
    for path in paths:
        if not FileUtils.EnsureUtf8WithChinese(path):
            logging.warning(path)
        pass
    pass
Example #27
0
def changeFilePath(_oldPath, _newPath):
    _oldPath, _newPath = str(_oldPath), str(_newPath)
    withOutDevicePointValues, withOutDeviceValues = [], []
    for devicePoint in getDevices():
        if devicePoint[1] + "/" == _oldPath[:len(devicePoint[1]) + 1]:
            if devicePoint[1] + "/" == _newPath[:len(devicePoint[1]) + 1]:
                withOutDevicePointValues.append({"id": devicePoint[0],
                                                 "oldPath": Databases.correctForSql(_oldPath[len(devicePoint[1]):]),
                                                 "newPath": Databases.correctForSql(_newPath[len(devicePoint[1]):])
                })
            else:
                withOutDeviceValues.append({"id": devicePoint[0],
                                            "oldPath": Databases.correctForSql(_oldPath[len(devicePoint[1]):]),
                                            "newPath": Databases.correctForSql(_newPath)
                })
    _oldPath, _newPath = Databases.correctForSql(_oldPath), Databases.correctForSql(_newPath)
    _oldPathUrl, _newPathUrl = Databases.correctForSql(Organizer.quote(_oldPath)), Databases.correctForSql(Organizer.quote(_newPath))
    db = Amarok.checkAndGetDB()
    db.query("UPDATE urls SET rpath='.%s' WHERE rpath='.%s'" % (_newPath, _oldPath))
    for withOutDevice in withOutDeviceValues:
        directoryID = getOrInsertDirectory(fu.getDirName(withOutDevice["newPath"]), "-1")
        db.query("UPDATE urls SET rpath='.%s', directory=%s, deviceid = -1 WHERE deviceid = %s and rpath = '.%s' " % (
            withOutDevice["newPath"], directoryID, withOutDevice["id"], withOutDevice["oldPath"]))
    for withOutDevicePoint in withOutDevicePointValues:
        directoryID = getOrInsertDirectory(fu.getDirName(withOutDevicePoint["newPath"]), withOutDevicePoint["id"])
        db.query("UPDATE urls SET rpath='.%s', directory=%s WHERE deviceid = %s and rpath = '.%s'" % (
            withOutDevicePoint["newPath"], directoryID, withOutDevicePoint["id"], withOutDevicePoint["oldPath"]))
    db.query("UPDATE images SET path='%s' WHERE path='%s'" % (_newPath, _oldPath))
    db.query("UPDATE lyrics SET url='.%s' WHERE url='.%s'" % (_newPath, _oldPath))
    db.query("UPDATE statistics_permanent SET url='file://%s' WHERE url='file://%s'" % (_newPathUrl, _oldPathUrl))
    db.commit()
    return True
Example #28
0
    def handle(self):
        mod_MessageHandler.message('Got connection from', self.client_address)
        # Get message and client socket
        msg, sock = self.request
        mod_MessageHandler.message('Received ' + msg + ' from client.')
        # resp = time.ctime()
        # sock.sendto(resp.encode('ascii'), self.client_address)
        if msg == 'q':
            mod_MessageHandler.message(
                "Received shutdown signal from network.")
            # FileUtils.SetConfigValue("general", "ambientsound", "off")
            # # Wait until all ambient threads have exited
            # tts.SayThis('Waiting ' + str(maxThreadWaitTime + 2) + ' seconds for ambient sounds to drain.')
            # time.sleep(maxThreadWaitTime + 2)
            # tts.SayThis("Tah tah for now.")
            #
            # exit()

        elif msg == 'm':
            # Mute all sounds
            FileUtils.SetConfigValue("general", "switchsound", "off")
            FileUtils.SetConfigValue("general", "ambientsound", "off")
        elif msg == 'u':
            # Unmute all sounds
            FileUtils.SetConfigValue("general", "switchsound", "on")
            FileUtils.SetConfigValue("general", "ambientsound", "on")
            LoadAmbientSounds()
        else:
            try:
                ProcessSwitch(msg)
            except:
                mod_MessageHandler.error(
                    'Got invalid data from the switch processor.')
Example #29
0
 def hash(self):
     sourceFile = str(self.lePathOfPackage.text())
     sourceFile = fu.checkSource(sourceFile, "file")
     if sourceFile is not None:
         hashType = str(self.cbHash.currentText())
         if hashType is not None:
             hashDigestContent = fu.getHashDigest(sourceFile, hashType)
             if hashDigestContent is not False:
                 self.teHashDigest.setText(str(hashDigestContent))
                 if self.cbHashOutput.currentIndex() == 1:
                     if fu.createHashDigestFile(sourceFile, str(self.leHashDigestFile.text()), hashType, False,
                                                hashDigestContent):
                         Dialogs.show(translate("Hasher", "Hash Digest File Created"),
                                      str(translate("Hasher", "Hash digest writed into %s")) % str(
                                          self.leHashDigestFile.text()))
                     else:
                         Dialogs.showError(translate("Hasher", "Hash Digest File Is Not Created"),
                                           translate("Hasher", "Hash digest file not cteated."))
                 elif self.cbHashOutput.currentIndex() == 2:
                     MApplication.clipboard().setText(str(hashDigestContent))
                     Dialogs.show(translate("Hasher", "Hash Digest Copied To Clipboard"),
                                  str(translate("Hasher",
                                                "Hash digest copied to clipboard.Hash digest is : <br>%s")) % hashDigestContent)
             else:
                 Dialogs.showError(translate("Hasher", "Hash Digest Is Not Created"),
                                   translate("Hasher", "Hash digest not cteated."))
Example #30
0
 def uninstallPlugin(self, _pluginName, _isQuiet=False):
     isUninstalled = False
     pluginModule = __import__("MyPlugins." + _pluginName, globals(), locals(),
                               ["pluginName", "pluginFiles", "pluginDirectory", "uninstallThisPlugin",
                                "setupDirectory", "pluginVersion"], 0)
     if pluginModule.uninstallThisPlugin is None:
         if pluginModule.pluginDirectory == "":
             for pluginFile in pluginModule.pluginFiles:
                 if fu.isFile(fu.joinPath(pluginModule.setupDirectory, pluginFile)):
                     fu.removeFileOrDir(fu.joinPath(pluginModule.setupDirectory, pluginFile))
             isUninstalled = True
         else:
             if fu.isDir(fu.joinPath(pluginModule.setupDirectory, pluginModule.pluginDirectory)):
                 fu.removeFileOrDir(fu.joinPath(pluginModule.setupDirectory, pluginModule.pluginDirectory))
             isUninstalled = True
     else:
         isUninstalled = pluginModule.uninstallThisPlugin()
     if isUninstalled:
         Settings.setUniversalSetting(str(pluginModule.pluginName), str(""))
         if _isQuiet is False:
             Dialogs.show(translate("MyPlugins", "Plug-in Uninstallation Is Complete"),
                          str(translate("MyPlugins", "\"%s\" is uninstalled on your system.")) % (
                              pluginModule.pluginName))
     elif isUninstalled == "AlreadyUninstalled":
         if _isQuiet is False:
             Dialogs.show(translate("MyPlugins", "Plug-in Already Uninstalled"),
                          str(translate("MyPlugins", "\"%s\" already uninstalled on your system.")) % (
                              pluginModule.pluginName))
     else:
         if _isQuiet is False:
             Dialogs.showError(translate("MyPlugins", "Plug-in Uninstallation Failed"),
                               str(translate("MyPlugins", "\"%s\" failed to uninstall on your system.")) % (
                                   pluginModule.pluginName))
Example #31
0
    def downmultfile(self,
                     remoteHost,
                     remoteport,
                     loginname,
                     loginpassword,
                     remotePath,
                     localPath,
                     filename,
                     filesize,
                     block_size,
                     del_part_file_able,
                     mult_taskcount=None):
        # TODO 判断本地文件是否存在
        if FileUtils.CheckFileExists(localPath):
            lfilesize = FileUtils.GetFileSize(localPath)
            print(datetime.now(), filename, "本地文件size", filesize)
            if lfilesize == filesize:
                print(datetime.now(), filename, "本地文件已存在")
        else:
            mult_file_name = FileUtils.GetFileName(localPath)
            print(mult_file_name, )
            FileUtils.Mkdirs(mult_file_name + "/")

            part_file_count = math.ceil(float(filesize) / block_size)  # 分片文件数
            part_file_end = part_file_count - 1
            part_file_names = list()
            if mult_taskcount == None:
                mult_taskcount = part_file_count
            mult_threadPool = ThreadPoolExecutor(
                max_workers=mult_taskcount,
                thread_name_prefix="mult_ftp_down_task_")
            for i in range(part_file_count):
                part_file_name = mult_file_name + "/" + filename + "_part" + str(
                    i)
                part_file_names.append(part_file_name)
                part_file_start_size = i * block_size
                part_file_size = block_size

                if i == part_file_end:
                    part_filesize = filesize - part_file_start_size

                mult_threadPool.submit(MyFTP().downloadbymulti_thread,
                                       remoteHost, remoteport, loginname,
                                       loginpassword, remotePath,
                                       part_file_name, part_file_start_size,
                                       part_file_size)

            mult_threadPool.shutdown(wait=True)
            print(datetime.now(), filename, "part文件全部下载完毕")
            #
            print(datetime.now(), filename, "开始合并")

            FileUtils.MergFile(part_file_names, localPath, filesize,
                               block_size, part_file_count, part_file_end,
                               del_part_file_able, mult_file_name)  # del

        #开始上传文件
        print(datetime.now(), filename, "开始上传")
        UploadFile(filename, filesize, localPath, localPath)
Example #32
0
def getFilepathInDepot(filehash):
    depotRoot1 = "I:\\objectstore1"
    depotRoot2 = "F:\\objectstore2"

    filepath = FileUtils.getPathOfFileInDepot(depotRoot1, filehash)
    if not filepath:
        filepath = FileUtils.getPathOfFileInDepot(depotRoot2, filehash)
    return filepath
def test_writeToFile():
    desc = "Writing text in a file"
    expected = "Happy Holidays"
    script_folder = os.path.dirname(os.path.abspath(__file__))
    fileName = os.path.join(script_folder,"writeToFileTest.txt")
    FU.writeToFile(fileName, "Happy Holidays")
    actual = FU.getFileContent(fileName)
    print_test_results(FU.writeToFile, desc, expected, actual)
Example #34
0
def getReadOnlyPID():
    global isReadOnlyStarted
    if fu.isFile(fu.pathOfSettingsDirectory + "/Amarok/mysqld.pid"):
        isReadOnlyStarted = True
        return fu.readFromFile(fu.pathOfSettingsDirectory +
                               "/Amarok/mysqld.pid").split("\n")[0]
    isReadOnlyStarted = False
    return None
Example #35
0
def backupEmbeddedDB():
    if fu.isDir(uni.getKDE4HomePath() +
                "/share/apps/amarok/mysqle_backup_for_hamsi"):
        fu.removeFileOrDir(uni.getKDE4HomePath() +
                           "/share/apps/amarok/mysqle_backup_for_hamsi")
    fu.copyFileOrDir(
        uni.getKDE4HomePath() + "/share/apps/amarok/mysqle",
        uni.getKDE4HomePath() + "/share/apps/amarok/mysqle_backup_for_hamsi")
Example #36
0
 def add_oasis_to_custom_farm_list(self):
     time.sleep(0.7)
     oasis_tab = self.driver.window_handles[len(self.driver.window_handles)
                                            - 1]
     self.driver.switch_to.window(oasis_tab)
     oasis_url = self.driver.current_url
     self.driver.close()
     FileUtils.append_to_file(oasis_url)
Example #37
0
 def flush(self):
     FileUtils.makebackup(self.name)
     f = open(self.name, "w")
     sortkeys = self.dict.keys()
     sortkeys.sort()
     for k in sortkeys:
         f.write("%s=%s\n" % (k, str(self.dict[k])))
     f.close()
Example #38
0
def createDefaultScript(_filePath):
    defaultCodes = (
        "#!/usr/bin/env python\n" + "# -*- codding: utf-8 -*-\n" + "\n" +
        "#You can type and execute the commands you wish to run here.\n" +
        "#You can get detailed information from our official website.\n" +
        "from Core import Dialogs\nDialogs.show(\"This is an example\",\"You can develop the examples as you wish.\")"
        + "\n\n\n\n\n\n\n\n\n")
    fu.writeToFile(_filePath, defaultCodes)
def test_getFileContent():
    desc = ""
    expected = "Hello world!"
    script_folder = os.path.dirname(os.path.abspath(__file__))
    actual = FileUtils.getFileContent(os.path.join(script_folder,"demo.txt"))
    print_test_results(FileUtils.getFileContent, desc, expected, actual)
    actual = FileUtils.getFileContent(os.path.join(script_folder,"sample.txt"))
    print_test_results(FileUtils.getFileContent, desc, expected, actual)
Example #40
0
    def consume(self, message):

        if 'initials' in message and len(message['initials']) > 0:

            # creates the historic_data directory if it does not exist
            historic_data_dir = os.path.join(os.path.dirname(__file__),
                                             'historic_data')
            if not os.path.isdir(historic_data_dir):
                os.mkdir(historic_data_dir)

            # creates a id for the request and makes a folder inside of historic_data for it
            request_id = uuid.uuid4().__str__()
            download_dir = os.path.join(historic_data_dir, request_id)
            os.mkdir(download_dir)

            # initializes the chrome driver with the requires window size and position
            driver = webdriver.Chrome(executable_path='chromedriver.exe')
            driver.set_window_size(1080, 2500)
            driver.set_window_position(100, 0)

            # configures the download directory in which all files will be downloaded
            driver.command_executor._commands["send_command"] = (
                "POST", '/session/$sessionId/chromium/send_command')
            params = {
                'cmd': 'Page.setDownloadBehavior',
                'params': {
                    'behavior': 'allow',
                    'downloadPath': download_dir
                }
            }
            driver.execute("send_command", params)

            # iterates through all the collected companies retrieving it's historic data
            for initials in message['initials']:

                # tries up to 10 times to donwload csv
                self.download_historic_data(
                    driver,
                    f'https://finance.yahoo.com/quote/{initials}.SA/history?p={initials}.SA'
                )
                # waits 5 seconds for download to finish (we could use some kind callback for when the downloaded file appears)
                time.sleep(5)

                # if the download occours successfuly, we build a message with that file, send to the API and delete it
                if fu.directory_has_file(download_dir):

                    # builds a message to send to the API
                    message = self.build_api_message_from_file_and_initials(
                        fu.get_only_filename_in_directory(download_dir),
                        initials)
                    # actually send the message to the API
                    self.api_stub.yahoo_company_historic_data(message)
                    # deletes the downloaded file
                    os.remove(fu.get_only_filename_in_directory(download_dir))

            # closes the chrome driver and removes the directory created for this request
            driver.quit()
            os.rmdir(download_dir)
def test_writeToFile():
    desc = ""
    expected = "This is a a nice text."
    script_folder = os.path.dirname(os.path.abspath(__file__))
    fileName = os.path.join(script_folder,"writeToFileTest.txt")
    content = "This is a a nice text."
    FileUtils.writeToFile(fileName,content)
    actual = FileUtils.getFileContent(fileName)
    print_test_results(FileUtils.writeToFile, desc, expected, actual)
Example #42
0
def isRunableAsRoot():
    try:
        if fu.isFile(fu.joinPath(getLibraryDirectoryPath(), "kde4", "libexec", "kdesu")):
            if isRunningAsRoot():
                return False
            return True
        return False
    except:
        return False
Example #43
0
def getMyPluginsNames():
    plugins = []
    for name in fu.readDirectoryAll(fu.joinPath(fu.HamsiManagerDirectory, "MyPlugins")):
        try:
            if (name[:1] != "." and name[:2] != "__" and name[-2:] != "__" and
                    fu.isDir(fu.joinPath(fu.HamsiManagerDirectory, "MyPlugins", name))):
                plugins.append(name)
        except: pass
    return plugins
Example #44
0
def getInstalledThemes():
    themes = []
    for name in fu.readDirectoryAll(fu.joinPath(fu.HamsiManagerDirectory, "Themes")):
        try:
            if (name[:1] != "." and name[:2] != "__" and name[-2:] != "__" and
                    fu.isDir(fu.joinPath(fu.HamsiManagerDirectory, "Themes", name))):
                themes.append(name)
        except: pass
    return themes
Example #45
0
def extractFileOrSetDeleted(db, destinationDir, filehash, newFilename, logger):
    depotRoot1 = "I:\\objectstore1"
    depotRoot2 = "F:\\objectstore2"
    if not FileUtils.CopyFileFromDepot(db, depotRoot1, destinationDir,
                                       filehash, newFilename):
        if not FileUtils.CopyFileFromDepot(db, depotRoot2, destinationDir,
                                           filehash, newFilename):
            logger.log("file not found, setting status")
            miscQueries.setFileStatus(db, filehash, "deleted")
Example #46
0
    def doBeforeCloseProcesses(self):
        from Core import UpdateControl

        if uni.getBoolValue("isDontDeleteFileAndDirectory"):
            fu.checkSizeOfDeletedFiles()
        if UpdateControl.UpdateControl.isMakeUpdateControl():
            UpdateControl.UpdateControl(self, _isCloseParent=True)
            return False
        return True
Example #47
0
    def createWindow(self, _actionName, _makeThisAction, _isShowEmendWidgets):
        from Options import OptionsForm

        newOrChangedKeys = uni.newSettingsKeys + uni.changedDefaultValuesKeys
        wOptionsPanel = OptionsForm.OptionsForm(None, QuickMakeParameters[0], None, newOrChangedKeys)
        if MyDialogType == "MDialog":
            if isActivePyKDE4:
                self.setButtons(MyDialog.NoDefault)
        elif MyDialogType == "MMainWindow":
            self.setObjectName("Packager")
            setMainWindow(self)
        self.setWindowTitle(_actionName)
        pnlMain = MWidget(self)
        vblMain = MVBoxLayout(pnlMain)
        pnlInfo = MWidget()
        vblInfo = MVBoxLayout(pnlInfo)
        vblInfo.addStretch(3)
        if _isShowEmendWidgets:
            lblOldValue = MLabel(translate("QuickMake", "Old Value : "))
            lblNewValue = MLabel(translate("QuickMake", "New Value : "))
            leOldValue = MLineEdit(str(fu.getRealPath(QuickMakeParameters[1])))
            leOldValue.setEnabled(False)
            self.leNewValue = MLineEdit(str(Organizer.emend(fu.getRealPath(QuickMakeParameters[1]),
                                                            fu.getObjectType(fu.getRealPath(QuickMakeParameters[1])))))
            vblInfo.addWidget(lblOldValue)
            vblInfo.addWidget(leOldValue)
            vblInfo.addWidget(lblNewValue)
            vblInfo.addWidget(self.leNewValue)
        else:
            lblValue = MLabel(translate("QuickMake", "Value : "))
            leValue = MLineEdit(str(fu.getRealPath(QuickMakeParameters[1])))
            leValue.setEnabled(False)
            vblInfo.addWidget(lblValue)
            vblInfo.addWidget(leValue)
        vblInfo.addStretch(3)
        pbtnApply = MPushButton(_actionName)
        pbtnClose = MPushButton(translate("QuickMake", "Cancel"))
        MObject.connect(pbtnApply, SIGNAL("clicked()"), _makeThisAction)
        MObject.connect(pbtnClose, SIGNAL("clicked()"), self.close)
        tabwTabs = MTabWidget()
        tabwTabs.addTab(pnlInfo, translate("QuickMake", "Quick Make"))
        tabwTabs.addTab(wOptionsPanel, translate("QuickMake", "Quick Make Options"))
        vblMain.addWidget(tabwTabs)
        hblBox = MHBoxLayout()
        hblBox.addWidget(pbtnClose, 2)
        hblBox.addWidget(pbtnApply, 3)
        vblInfo.addLayout(hblBox)
        if MyDialogType == "MDialog":
            if isActivePyKDE4:
                self.setMainWidget(pnlMain)
            else:
                self.setLayout(vblMain)
        elif MyDialogType == "MMainWindow":
            self.setCentralWidget(pnlMain)
            moveToCenter(self)
        self.setMinimumSize(450, 350)
Example #48
0
 def delete(self):
     try:
         answer = Dialogs.ask(translate("ScriptManager", "Your Script Will Be Deleted!.."),
                              translate("ScriptManager",
                                        "Your script will be deleted. Are you sure you want to delete current script?"))
         if answer == Dialogs.Yes:
             fu.removeFile(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
             self.refreshScriptList()
     except:
         ReportBug.ReportBug()
Example #49
0
def saveAllRecords():
    global recordContents, isSetTitle
    if "isSaveActions" not in uni.MySettings.keys() or uni.getBoolValue("isSaveActions"):
        if fu.isFile(fu.recordFilePath) is False:
            create()
        setRecordType(1)
        fu.addToFile(fu.recordFilePath, recordContents)
        restoreRecordType()
    recordContents = ""
    isSetTitle = False
Example #50
0
def generateReadOnlyEmbeddedD(_isNoAlertIfSuccessfully=True):
    stopReadOnlyEmbeddedDB()
    if fu.isExist(fu.pathOfSettingsDirectory + "/Amarok/mysqle/amarok"):
        fu.removeFileOrDir(fu.pathOfSettingsDirectory + "/Amarok/mysqle/amarok")
    fu.copyFileOrDir(uni.getKDE4HomePath() + "/share/apps/amarok/mysqle/amarok",
                     fu.pathOfSettingsDirectory + "/Amarok/mysqle/amarok")
    if _isNoAlertIfSuccessfully is False:
        Dialogs.show(translate("EmbeddedDBCore", "Generated Embedded Server"),
                     translate("EmbeddedDBCore", "Embedded Amarok database server generated."))
    return True
Example #51
0
 def fillValues(self):
     filePath = str(self.leFilePath.text())
     if fu.isFile(filePath) and fu.isReadableFileOrDir(filePath):
         self.fileValues = fu.readTextFile(filePath, str(self.sourceCharSet.currentText()))
         self.pteFileContent.setPlainText(str(Organizer.emend(self.fileValues["content"], "text", False, True)))
         self.isChangeSourceCharSetChanged = True
         self.pbtnSave.setEnabled(True)
     else:
         self.isChangeSourceCharSetChanged = False
         self.pbtnSave.setEnabled(False)
Example #52
0
def replaceFileStrWithRegex(regex,nString,fileName):
    filePath = FUtil.findFileDirWithFileName(FUtil.getCurrentPath(),fileName);
    fileHandel = open(filePath,'r');
    fileHandel.seek(0);
    fileContent = fileHandel.read();
    content = re.sub(re.compile(regex), nString, fileContent);
    fileHandel.close();
    newfile = open(filePath,'w')
    newfile.write(content)
    newfile.close();
    replaceFileStrWithRegex('abcdefg','if ([[URL.scheme lowercaseString] isEqualToString:kCtripWirelessUrlSchemeString] || [[URL.scheme lowercaseString] isEqualToString:@"ctrip"])','CTURLDispatcher.m')
Example #53
0
def read(_recordFilePath=None):
    if _recordFilePath is None:
        _recordFilePath = fu.recordFilePath
    if fu.isFile(_recordFilePath):
        return fu.readFromFile(_recordFilePath, "utf-8")
    else:
        create()
        setRecordType(1)
        fu.addToFile(_recordFilePath, recordContents)
        restoreRecordType()
        return recordContents
Example #54
0
def checkForLicense(path, comment):
  with file(path, 'r') as original:
    data = original.read()
    if hasLicense(data):
      print path + " has a license"
      return    
    if addLicense(path):
      print "Adding license to: " + path
      backupPath = path + ".backup"
      fu.copy(path, backupPath) 
      prependLicense(path, comment, data)
      fu.delete(backupPath)