当前位置: 首页>>代码示例>>Python>>正文


Python StringUtils.toStr2方法代码示例

本文整理汇总了Python中pyaid.string.StringUtils.StringUtils.toStr2方法的典型用法代码示例。如果您正苦于以下问题:Python StringUtils.toStr2方法的具体用法?Python StringUtils.toStr2怎么用?Python StringUtils.toStr2使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyaid.string.StringUtils.StringUtils的用法示例。


在下文中一共展示了StringUtils.toStr2方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _toggleSideWidget

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def _toggleSideWidget(self, open =True):
        """_openWidget doc..."""

        if self._anim:
            self._anim.stop()
            self._anim.deleteLater()
            self._anim = None

        self.sideWidget.show()
        anim = QtCore.QPropertyAnimation(self.sideWidget, StringUtils.toStr2('pos'))
        anim.setDuration(250)

        if self.dockOnLeft:
            outValue = -self._getSideWidgetWidth()
            inValue  = 0
        else:
            w = self.size().width()
            outValue = w
            inValue  = w - self._getSideWidgetWidth()

        anim.setStartValue(QtCore.QPoint(outValue if open else inValue, 0))
        anim.setEndValue(QtCore.QPoint(inValue if open else outValue, 0))
        anim.finished.connect(self._handleAnimFinished)
        self._anim = anim
        anim.start()
开发者ID:sernst,项目名称:PyGlass,代码行数:27,代码来源:SideBarOverlay.py

示例2: _handleResponseReady

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def _handleResponseReady(self, request, response):
        """Event handler for the response object being ready for use."""

        if self._cacheControlPublic:
            response.cache_control = "public"

        # -------------------------------------------------------------------------------------------
        # Cache Expiration: Set the caching values according to the _expires property
        rep = self._explicitResponse
        if rep is None or (isinstance(rep, ViewResponse) and rep.allowCaching):
            response.cache_control.max_age = self.expires if not self.expires is None else 0
        else:
            response.cache_control.max_age = 0

        # -------------------------------------------------------------------------------------------
        # Cache Validators
        if self._etag is not None:
            response.etag = StringUtils.toUnicode(self._etag)

        if self._lastModified is not None:
            response.last_modified = self._lastModified

        # If required encode the response headers as strings to prevent unicode errors. This is
        # necessary for certain WSGI server applications, e.g. flup.
        if self.ziggurat.strEncodeEnviron:
            for n, v in DictUtils.iter(response.headers):
                if StringUtils.isStringType(v):
                    response.headers[n] = StringUtils.toStr2(v)

        # Clean up per-thread sessions.
        ConcreteModelsMeta.cleanupSessions()
开发者ID:sernst,项目名称:Ziggurat,代码行数:33,代码来源:ZigguratBaseView.py

示例3: _importCompiled

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def _importCompiled(cls, widgetPath):
        """_importCompiled doc..."""
        if imp:
            return imp.load_compiled('PySideUiFileSetup', StringUtils.toStr2(widgetPath))

        loader = importlib.machinery.SourcelessFileLoader('PySideUiFileSetup', widgetPath)
        return loader.load_module()
开发者ID:sernst,项目名称:PyGlass,代码行数:9,代码来源:UiFileLoader.py

示例4: loads

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def loads(self, srcString, srcType):
        if srcString is None:
            self._log.write('ERROR: Source string is empty or invalid.')
            return False

        srcString = StringUtils.toStr2(srcString)

        self._path = None
        self._src  = srcString
        self._type = srcType
        return True
开发者ID:sernst,项目名称:PyAid,代码行数:13,代码来源:DataFormatConverter.py

示例5: flush

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def flush(self, **kwargs):
        if not self._buffer:
            return

        items = []
        for logItem in self._buffer:
            item = self.logMessageToString(logMessage=logItem) + '\n'
            item = StringUtils.toStr2(item)
            items.append(item)

        for cb in self._writeCallbacks:
            try:
                cb(self, items)
            except Exception:
                pass

        if not self._logPath:
            self.clear()
            return

        elif self._logFile:
            try:
                out = StringUtils.toStr2('\n').join(items)
                exists = os.path.exists(self._logFile)
                with FileLock(self._logFile, 'a') as lock:
                    lock.file.write(out)
                    lock.release()

                try:
                    if not exists and not OsUtils.isWindows():
                        os.system('chmod 775 %s' % self._logFile)
                except Exception:
                    pass

            except Exception as err:
                print("LOGGER ERROR: Unable to write log file.")
                print(err)

        self.clear()
开发者ID:sernst,项目名称:PyAid,代码行数:41,代码来源:Logger.py

示例6: cleanDictKeys

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def cleanDictKeys(cls, source, force =False):
        """ Python 2.6 and below don't allow unicode argument keys, so these must be converted to
            byte strings explicitly to prevent exceptions.
        """

        vi = sys.version_info
        if not force and (vi[0] >= 3 or (vi[1] >= 7 and vi[2] >= 5)):
            return source

        out = dict()
        for n,v in cls.iter(source):
            out[StringUtils.toStr2(n, True)] = v
        return out
开发者ID:sernst,项目名称:PyAid,代码行数:15,代码来源:DictUtils.py

示例7: _postAnalyze

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def _postAnalyze(self):
        self.logger.write('%s gauge calculated tracks' % self._count)

        self._trackwayCsv.save()

        csv = CsvWriter(
            path=self.getPath('Simple-Gauge-Errors.csv', isFile=True),
            autoIndexFieldName='Index',
            fields=[
                ('uid', 'UID'),
                ('fingerprint', 'Fingerprint') ])
        for track in self._errorTracks:
            csv.createRow(uid=track.uid, fingerprint=track.fingerprint)
        csv.save()

        if self._errorTracks:
            self.logger.write('Failed to calculate gauge for %s tracks' % len(self._errorTracks))

        csv = CsvWriter(
            path=self.getPath('Simple-Gauge-Ignores.csv', isFile=True),
            autoIndexFieldName='Index',
            fields=[
                ('uid', 'UID'),
                ('fingerprint', 'Fingerprint') ])
        for track in self._ignoreTracks:
            csv.createRow(uid=track.uid, fingerprint=track.fingerprint)
        csv.save()

        if self._ignoreTracks:
            self.logger.write('%s tracks lacked suitability for gauge calculation' % len(
                self._ignoreTracks))

        plotData = [
            ('stride', 'red', 'AU', 'Stride-Normalized Weighted'),
            ('pace', 'green', 'AU', 'Pace-Normalized Weighted'),
            ('width', 'blue', 'AU', 'Width-Normalized Weighted'),
            ('abs', 'purple', 'm', 'Absolute Unweighted') ]

        for data in plotData:
            out = []
            source = ListUtils.sortListByIndex(
                source=getattr(self._trackwayGauges, StringUtils.toStr2(data[0])),
                index=0,
                inPlace=True)

            for item in source:
                out.append(PositionValue2D(x=len(out), y=item[1].value, yUnc=item[1].uncertainty))
            self._plotTrackwayGauges(out, *data[1:])

        self.mergePdfs(self._paths, 'Gauges.pdf')
开发者ID:sernst,项目名称:Cadence,代码行数:52,代码来源:SimpleGaugeStage.py

示例8: toFile

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
 def toFile(cls, path, value, pretty =False, gzipped =False, throwError =False):
     try:
         res = StringUtils.toStr2(cls.asString(value, pretty=pretty))
         if gzipped:
             f = gzip.open(path, 'wb')
             f.write(StringUtils.toBytes(res))
         else:
             f = open(path, 'w+')
             f.write(res)
         f.close()
         return True
     except Exception as err:
         if throwError:
             raise
         else:
             print(err)
         return False
开发者ID:sernst,项目名称:PyAid,代码行数:19,代码来源:JSON.py

示例9: createRevision

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def createRevision(
            cls, databaseUrl, message, resourcesPath =None, localResourcesPath =None, info =None
    ):
        config = cls.getConfig(
            databaseUrl=databaseUrl,
            resourcesPath=resourcesPath,
            localResourcesPath=localResourcesPath)

        previousRevisions = cls.getRevisionList(
            databaseUrl=databaseUrl,
            resourcesPath=resourcesPath,
            config=config)

        alembicCmd.revision(
            config=config,
            message=StringUtils.toUnicode(len(previousRevisions)) + ': ' + message)

        if not info:
            return True

        scriptInfo = alembicScript.ScriptDirectory.from_config(config)
        scriptPath = None
        for item in os.listdir(scriptInfo.versions):
            if item.startswith(scriptInfo.get_current_head()):
                scriptPath = os.path.join(scriptInfo.versions, item)
                break
        if not scriptPath:
            return True

        info = StringUtils.toUnicode(info)

        f = open(scriptPath, 'r+')
        script = StringUtils.toUnicode(f.read())
        f.close()

        index   = script.find('"""')
        index   = script.find('"""', index + 1)
        script  = script[:index] + info + '\n' + script[index:]
        f       = open(scriptPath, 'w+')
        f.write(StringUtils.toStr2(script))
        f.close()
        return True
开发者ID:sernst,项目名称:PyGlass,代码行数:44,代码来源:AlembicUtils.py

示例10: mergePdfs

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def mergePdfs(self, paths, fileName =None):
        """ Takes a list of paths to existing PDF files and merges them into a single pdf with
            the given file name.

            [fileName] :: String :: None
                The name of the file to be written. If not specified, a file name will be created
                using the name of this class. """

        merger = PdfFileMerger()
        for p in paths:
            with open(p, 'rb') as f:
                merger.append(PdfFileReader(f))

        if not fileName:
            fileName = '%s-Report.pdf' % self.__class__.__name__
        if not StringUtils.toStr2(fileName).endswith('.pdf'):
            fileName += '.pdf'

        with open(self.getPath(fileName, isFile=True), 'wb') as f:
            merger.write(f)
开发者ID:sernst,项目名称:Cadence,代码行数:22,代码来源:AnalysisStage.py

示例11: __str__

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def __str__(self):
        modelInfo = self._getPrintAttrs()
        if isinstance(modelInfo, dict):
            out = ""
            for n, v in DictUtils.iter(modelInfo):
                out += " " + StringUtils.toUnicode(n) + "[" + StringUtils.toUnicode(v) + "]"
            modelInfo = out
        elif modelInfo:
            modelInfo = " " + StringUtils.toUnicode(modelInfo)
        else:
            modelInfo = ""

        return StringUtils.toStr2(
            "<%s[%s] cts[%s] upts[%s]%s>"
            % (
                self.__class__.__name__,
                StringUtils.toUnicode(self.i),
                StringUtils.toUnicode(self.cts.strftime("%m-%d-%y %H:%M:%S") if self.cts else "None"),
                StringUtils.toUnicode(self.upts.strftime("%m-%d-%y %H:%M:%S") if self.upts else "None"),
                modelInfo,
            )
        )
开发者ID:sernst,项目名称:PyGlass,代码行数:24,代码来源:PyGlassModelsDefault.py

示例12: putContents

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def putContents(
            cls, content, path, append =False, raiseErrors =False,
            gzipped =False
    ):
        if not StringUtils.isStringType(content):
            content = ''
        content = StringUtils.toStr2(content)

        try:
            mode = 'a+' if append and os.path.exists(path) else 'w+'
            if gzipped:
                f = open(path, mode)
            else:
                f = open(path, mode)
            f.write(content)
            f.close()
        except Exception as err:
            if raiseErrors:
                raise
            print(err)
            return False

        return True
开发者ID:sernst,项目名称:PyAid,代码行数:25,代码来源:FileUtils.py

示例13: __new__

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def __new__(mcs, name, bases, attrs):
        name = StringUtils.toStr2(name)

        for n, v in list(attrs.items()):
            attrName = n[1:]
            if isinstance(v, Column) and n.startswith('_') and not attrName in attrs:
                v.key  = attrName
                v.name = attrName

                # Add dynamic property
                attrs[attrName] = hybrid_property(
                    ModelPropertyGetter(n),
                    ModelPropertySetter(n),
                    None,
                    ModelPropertyExpression(n))

                # Add external-key property
                info = getattr(v, 'info')
                if info and 'model' in info:
                    columnName = info['column'] if 'column' in info else 'i'
                    attrs[info['get']] = property(
                        ExternalKeyProperty(attrName, info['model'], columnName))

        return DeclarativeMeta.__new__(mcs, name, bases, attrs)
开发者ID:sernst,项目名称:PyGlass,代码行数:26,代码来源:AbstractPyGlassModelsMeta.py

示例14: modelsInit

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
    def modelsInit(cls, databaseUrl, initPath, initName):
        out = dict()
        zipIndex = initPath[0].find(cls._ZIP_FIND)
        if zipIndex == -1:
            moduleList = os.listdir(initPath[0])
        else:
            splitIndex = zipIndex + len(cls._ZIP_FIND)
            zipPath = initPath[0][: splitIndex - 1]
            modulePath = initPath[0][splitIndex:]
            z = zipfile.ZipFile(zipPath)
            moduleList = []
            for item in z.namelist():
                item = os.sep.join(item.split("/"))
                if item.startswith(modulePath):
                    moduleList.append(item.rsplit(os.sep, 1)[-1])

        # Warn if module initialization occurs before pyglass environment initialization and
        # then attempt to initialize the environment automatically to prevent errors
        if not PyGlassEnvironment.isInitialized:
            cls.logger.write(
                StringUtils.dedent(
                    """
                [WARNING]: Database initialization called before PyGlassEnvironment initialization.
                Attempting automatic initialization to prevent errors."""
                )
            )
            PyGlassEnvironment.initializeFromInternalPath(initPath[0])

        if not cls.upgradeDatabase(databaseUrl):
            cls.logger.write(
                StringUtils.dedent(
                    """
                [WARNING]: No alembic support detected. Migration support disabled."""
                )
            )

        items = []
        for module in moduleList:
            if module.startswith("__init__.py") or module.find("_") == -1:
                continue

            parts = module.rsplit(".", 1)
            parts[0] = parts[0].rsplit(os.sep, 1)[-1]
            if not parts[-1].startswith(StringUtils.toStr2("py")) or parts[0] in items:
                continue
            items.append(parts[0])

            m = None
            n = None
            r = None
            c = None
            try:
                n = module.rsplit(".", 1)[0]
                m = initName + "." + n
                r = __import__(m, locals(), globals(), [n])
                c = getattr(r, StringUtils.toText(n))
                out[n] = c
                if not c.__table__.exists(c.ENGINE):
                    c.__table__.create(c.ENGINE, True)
            except Exception as err:
                cls._logger.writeError(
                    [
                        "MODEL INITIALIZATION FAILURE:",
                        "INIT PATH: %s" % initPath,
                        "INIT NAME: %s" % initName,
                        "MODULE IMPORT: %s" % m,
                        "IMPORT CLASS: %s" % n,
                        "IMPORT RESULT: %s" % r,
                        "CLASS RESULT: %s" % c,
                    ],
                    err,
                )

        return out
开发者ID:sernst,项目名称:PyGlass,代码行数:76,代码来源:PyGlassModelUtils.py

示例15: __str__

# 需要导入模块: from pyaid.string.StringUtils import StringUtils [as 别名]
# 或者: from pyaid.string.StringUtils.StringUtils import toStr2 [as 别名]
 def __str__(self):
     return StringUtils.toStr2('<%s[%s] uid[%s] %s>' % (
         self.__class__.__name__,
         StringUtils.toUnicode(self.i),
         StringUtils.toUnicode(self.uid),
         StringUtils.toUnicode(self.fingerprint)))
开发者ID:sernst,项目名称:Cadence,代码行数:8,代码来源:TracksTrackDefault.py


注:本文中的pyaid.string.StringUtils.StringUtils.toStr2方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。