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


Python sublime.decode_value函数代码示例

本文整理汇总了Python中sublime.decode_value函数的典型用法代码示例。如果您正苦于以下问题:Python decode_value函数的具体用法?Python decode_value怎么用?Python decode_value使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: reload_settings

 def reload_settings(self):
     self.settings_default = sublime.decode_value(sublime.load_resource(from_package('Mediawiker.sublime-settings')))
     self.settings = sublime.load_settings('Mediawiker.sublime-settings')
     try:
         self.settings_user = sublime.decode_value(sublime.load_resource(from_package('Mediawiker.sublime-settings', name='User')))
     except IOError:
         self.settings_user = {}
开发者ID:tosher,项目名称:Mediawiker,代码行数:7,代码来源:mw_properties.py

示例2: __init__

    def __init__(self):
        self.client_key = "40af22476e380eadfef5"
        self.client_secret = "ec5cfba3fb9fb063d0d4"

        self.settings = tools.load_settings("LaTeXing",
                                            zotero_user_key="",
                                            zotero_user_id="",
                                            zotero_cite_key_pattern="{Author}{year}"
                                            )

        # Load map
        self.map = sublime.decode_value(sublime.load_resource("Packages/LaTeXing/latexing/api/zotero.map"))

        # bibtex: zotero type
        self.type_map = self.map["types"]

        # bibtex: zotero field
        self.field_map = self.map["fields"]

        # Check for user maps
        try:
            self.user_map = sublime.decode_value(sublime.load_resource("Packages/User/LaTeXing/zotero.map"))
            self.type_map.update(self.user_map["types"] if "types" in self.user_map else {})
            self.field_map.update(self.user_map["fields"] if "fields" in self.user_map else {})
        except:
            pass

        self.status = "Ok"
        self.items = []
        self.items_no_key = {}
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:30,代码来源:zotero.py

示例3: __init__

    def __init__(self, scheme_file, color_filter=None):
        """Initialize."""
        if color_filter is None:
            color_filter = self.filter
        self.legacy = not scheme_file.lower().endswith('.sublime-color-scheme')
        self.color_scheme = path.normpath(scheme_file)
        self.scheme_file = path.basename(self.color_scheme)
        if self.legacy:
            self.scheme_obj = color_filter(
                readPlistFromBytes(
                    re.sub(
                        br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'',
                        sublime.load_binary_resource(sublime_format_path(self.color_scheme))
                    )
                )
            )
        else:
            sublime.decode_value(
                sublime.load_resource(sublime_format_path(self.color_scheme)),
                preserve_lines=True
            )
        self.scheme_file = scheme_file
        self.matched = {}
        self.variables = {}

        self.parse_scheme()
开发者ID:arnedesmedt,项目名称:dotfiles,代码行数:26,代码来源:st_color_scheme_matcher.py

示例4: __init__

    def __init__(self):
        self.client_id = "141"
        self.client_secret = "4*ic:5WfF;LxE534"

        self.settings = tools.load_settings("LaTeXing", mendeley_oauth_token="", mendeley_internal_cite_key=False, mendeley_cite_key_pattern="{Author}{year}")

        # Load map
        self.map = sublime.decode_value(sublime.load_resource("Packages/LaTeXing/latexing/api/mendeley.map"))

        # bibtex: zotero type
        self.type_map = self.map["types"]

        # bibtex: zotero field
        self.field_map = self.map["fields"]

        # Check for user maps
        try:
            self.user_map = sublime.decode_value(sublime.load_resource("Packages/User/LaTeXing/mendeley.map"))
            self.type_map.update(self.user_map["types"] if "types" in self.user_map else {})
            self.field_map.update(self.user_map["fields"] if "fields" in self.user_map else {})
        except:
            pass

        self.status = "Ok"
        self.items = []
        self.items_no_key = {}
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:26,代码来源:mendeley.py

示例5: run

    def run(self, cmd, code):
        """
        Attempt to parse code as JSON.

        Returns '' if it succeeds, the error message if it fails.
        Use ST's loose parser for its setting files, or when specified.
        """
        is_sublime_file = os.path.splitext(self.filename)[1].startswith('.sublime-')

        if self.get_view_settings().get('strict') and not is_sublime_file:
            strict = True
        else:
            strict = False

        try:
            if strict:
                self.regex = self.strict_regex
                json.loads(code)
            else:
                self.regex = self.loose_regex
                sublime.decode_value(code)

            return ''
        except ValueError as err:
            return str(err)
开发者ID:SublimeLinter,项目名称:SublimeLinter-json,代码行数:25,代码来源:linter.py

示例6: decodeEntity

def decodeEntity(xml, category='iso'):
    global entities
    if not isinstance(xml, str):
        return xml
    if entities[category]:
        forward, reverse = entities[category]
    else:
        if category == 'iso':
            forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/IsoEntities.json'))
        elif category == 'html':
            forward = sublime.decode_value(sublime.load_resource('Packages/' + package_name + '/HtmlEntities.json'))
        reverse = dict((v, k) for k, v in forward.items())
        entities[category] = (forward, reverse)

    def parseEntity(match):
        entity = match.group(1)
        try:
            if entity.isdigit():
                return reverse[int(entity)]
            else:
                return chr(forward[entity])
        except:
            return match.group(0)
    xml = re.sub('&([a-zA-Z0-9]+);', parseEntity, xml)
    return xml
开发者ID:john1688,项目名称:docphp,代码行数:25,代码来源:docphp.py

示例7: run

    def run(self, cmd, code):
        """Attempt to parse code as JSON, return '' if it succeeds, the error message if it fails."""

        # Use ST's loose parser for its setting files.
        strict = os.path.splitext(self.filename)[1] not in self.extensions

        try:
            if strict:
                self.__class__.regex = self.strict_regex

                # establish basic JSON compliance with in built python JSON library
                template = json.loads(code)

                # now validate against the AWS api
                cfn = boto3.client('cloudformation')
                template = cfn.validate_template(TemplateBody=code)
                print(template)
            else:
                self.__class__.regex = self.loose_regex
                sublime.decode_value(code)

            return ''

        except ValueError as err:
            return str(err)
开发者ID:claytonbrown,项目名称:SublimeLinter-contrib-AWS-Cloudformation-JSON,代码行数:25,代码来源:linter.py

示例8: _parse_snippet_xml

  def _parse_snippet_xml(self, name, xml):
    snippet = {}

    for node in xml.childNodes:
      if node.nodeType == node.ELEMENT_NODE:
        value_node = node.firstChild
        if value_node == None:
          continue
        snippet[node.tagName] = value_node.data

    if len(snippet) == 0:
      return None

    if 'content' not in snippet:
      return None

    if 'context' in snippet:
      snippet['context'] = sublime.decode_value(snippet['context'])

    if 'commands' in snippet:
      snippet['commands'] = sublime.decode_value(snippet['commands'])

    if snippet['content'][0] == "\n":
      snippet['content'] = snippet['content'][1:]

    if snippet['content'][len(snippet['content']) - 1] == "\n":
      snippet['content'] = snippet['content'][:len(snippet['content']) - 1]

    if len(snippet['content']) == 0:
      return None

    if 'scope' in snippet:
      # load old snippets
      snippet['_scope'] = snippet['scope']

      is_old = (
        re.search(r'^\(?([\w\+]+\.[\w\+]+,?\s*)*$', snippet['scope']) != None or
        '++' in snippet['scope']
      )

      if is_old:
        snippet['scope'] = (
          '((?:\W|^)' + snippet['scope'].
            replace(', ', '(?:\W|$)|(?:\W|^)').
            replace('+', '\\+').replace('.', '\\.') + '(?:\W|$))'
        )

      snippet['scope'] = re.compile(snippet['scope'])

    snippet['name'], _ = os.path.splitext(os.path.basename(name))
    snippet['path'] = name

    if 'order' in snippet:
      snippet['order'] = int(snippet['order'])

    return snippet
开发者ID:dinfekted,项目名称:sublime-snippet-caller,代码行数:56,代码来源:snippet_caller.py

示例9: library

    def library(self):
        url = "/documents?limit=500&reverse=false&order=asc&view=all"
        json_documents = sublime.decode_value(self.client.get(url))

        documents = json_documents
        while len(json_documents) == 500:
            json_documents = sublime.decode_value(self.client.get(url + "&marker=" + json_documents[-1]['id']))
            documents += json_documents

        return documents
开发者ID:LaTeXing,项目名称:LaTeXing,代码行数:10,代码来源:mendeley.py

示例10: merge_overrides

    def merge_overrides(self):
        """Merge override schemes."""

        package_overrides = []
        user_overrides = []
        if self.scheme_file.endswith('.hidden-color-scheme'):
            pattern = '%s.hidden-color-scheme'
        else:
            pattern = '%s.sublime-color-scheme'
        for override in sublime.find_resources(pattern % path.splitext(self.scheme_file)[0]):
            if override.startswith('Packages/User/'):
                user_overrides.append(override)
            else:
                package_overrides.append(override)
        for override in (package_overrides + user_overrides):
            try:
                ojson = sublime.decode_value(sublime.load_resource(override))
            except IOError:
                # Fallback if file was created manually and not yet found in resources
                # Though it is unlikely this would ever get executed as `find_resources`
                # probably wouldn't have seen it either.
                with codecs.open(packages_path(override), 'r', encoding='utf-8') as f:
                    ojson = sublime.decode_value(sanitize_json(f.read()))

            for k, v in ojson.get('variables', {}).items():
                self.scheme_obj['variables'][k] = v

            for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
                self.scheme_obj[GLOBAL_OPTIONS][k] = v

            for item in ojson.get('rules', []):
                self.scheme_obj['rules'].append(item)

            self.overrides.append(override)

        # Rare case of being given a file but sublime hasn't indexed the files and can't find it
        if (
            not self.overrides and
            self.color_scheme.endswith(('.sublime-color-scheme', '.hidden-color-scheme')) and
            self.color_scheme.startswith('Packages/')
        ):
            with codecs.open(packages_path(self.color_scheme), 'r', encoding='utf-8') as f:
                ojson = sublime.decode_value(sanitize_json(f.read()))

                for k, v in ojson.get('variables', {}).items():
                    self.scheme_obj['variables'][k] = v

                for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
                    self.scheme_obj[GLOBAL_OPTIONS][k] = v

                for item in ojson.get('rules', []):
                    self.scheme_obj['rules'].append(item)

                self.overrides.append(self.color_scheme)
开发者ID:PwnArt1st,项目名称:dotfiles,代码行数:54,代码来源:color_scheme_matcher.py

示例11: decodeEntity

def decodeEntity(xml, category="iso"):
    global entities
    if not isinstance(xml, str):
        return xml
    if entities[category]:
        forward, reverse = entities[category]
    else:
        resourceMap = {"iso": "IsoEntities.json", "html": "HtmlEntities.json"}
        forward = sublime.decode_value(sublime.load_resource("Packages/" + package_name + "/" + resourceMap[category]))

        reverse = dict((v, k) for k, v in forward.items())
        entities[category] = (forward, reverse)

    def parseEntity(match):
        entity = match.group(1)
        try:
            if entity.isdigit():
                return reverse[int(entity)]
            else:
                return chr(forward[entity])
        except:
            return match.group(0)

    xml = re.sub("&([a-zA-Z0-9]+);", parseEntity, xml)
    return xml
开发者ID:garveen,项目名称:docphp,代码行数:25,代码来源:docphp.py

示例12: manage_package

    def manage_package(self, package):
        self.done = False
        file_list = list_package_files(package)
        platform_keymap = "default (%s).sublime-keymap" % (PLATFORM.lower())
        for filename in file_list:

            if filename.lower().endswith("default.sublime-keymap")or \
            filename.lower().endswith(platform_keymap):
                content = get_resource(package, filename)
                if content == None:
                    continue

                try:
                    if VERSION < 3013:
                        minified_content = json_minify(content)
                        minified_content = strip_dangling_commas(minified_content)
                        minified_content = minified_content.replace("\n", "\\\n")
                        if self.debug:
                            self.debug_minified[package] = minified_content
                        key_map = json.loads(minified_content)
                    else:
                        key_map = sublime.decode_value(content)
                except:
                    if not self.prev_error:
                        traceback.print_exc()
                        self.prev_error = True
                        sublime.error_message("Could not parse a keymap file. See console for details")
                    #error_path = os.path.join(os.path.basename(orig_path), filename)
                    logger.warning("FindKeyConflicts[Warning]: An error " + "occured while parsing '" + package + "'")
                    continue
                self.handle_key_map(package, key_map)
        self.done = True
开发者ID:Mondego,项目名称:pyreco,代码行数:32,代码来源:allPythonContent.py

示例13: run

	def run(self, edit, type="", text="", region=None, dest=None):
		if type == "insert":
			self.view.insert(edit, 0, text)
		elif type == "add":
			self.view.insert(edit, self.view.size(), text)
		elif type == "replace":
			self.view.insert(edit, region, text)
		elif type == "set_read_only":
			self.view.set_read_only(True)
		elif type == "test":
			if not isStable():
				self.view.show_popup_menu(["A", "B"], self.nothing)
		elif type == "remote_hash":
			if not isStable():
				sublime.active_window().show_input_panel("URL:", "", self.remote_hash, None, None)
		elif type == "hash":
			if not isStable():
				print(hashlib.sha256(self.view.substr(sublime.Region(0,self.view.size())).encode("utf-8")).hexdigest())
		elif type == "tojson":
			if not isStable():
				jsonObj = sublime.decode_value(self.view.substr(sublime.Region(0,self.view.size())))
				self.view.replace(edit, sublime.Region(0,self.view.size()), sublime.encode_value(jsonObj, True));
		elif type == "reload":
			if isDebug():
				getAction().addAction("javatar.command.utils.reload", "Reload Javatar")
				print("Reloading Javatar...")
				import sys
				from imp import reload
				for mod in sys.modules:
					if mod.lower().startswith("javatar") and not mod.lower().endswith("_utils") and sys.modules[mod] is not None:
						print("Reloading module " + mod + "...")
						reload(sys.modules[mod])
				from ..Javatar import plugin_loaded
				plugin_loaded()
开发者ID:xiamizy,项目名称:Javatar,代码行数:34,代码来源:javatar_utils.py

示例14: allFunctions

	def allFunctions(self):
		"""retorna todas las funciones"""
		modulos=sublime.decode_value(open(RutasPython.funciones()).read())
		lista=[]
		for modulo in modulos:
			lista+=[ (funcion+"\t•"+modulo, self.ponerCursor(modulo+"."+funcion)) for funcion in modulos[modulo]]
		return sorted(lista)
开发者ID:programadorsito,项目名称:Packages,代码行数:7,代码来源:completion.py

示例15: getBowerPackages

	def getBowerPackages(self):
		if (self._bowerComponents is not None):
			return
			
		cacheFile = self.getCachePath() + "\\bower-component-list.json"

		if not os.path.isfile(cacheFile):
			apiUrl = 'https://bower-component-list.herokuapp.com'

			## TODO: do it async
			urllib.request.urlretrieve(apiUrl, cacheFile)
		
		content = self.file_get_contents(cacheFile)

		self._bowerComponents = []

		for idx, val in enumerate(sublime.decode_value(content)):

			name = val.get('name')
			desc = val.get('description', "Description not provided")
			updated = val.get('updated', "Last updated not provided")
			stars = 0 if not val['stars'] else val['stars']

			if ((not name) or (not desc) or (not updated) or stars < 1):
				continue

			component = [name, desc, updated]

			self._bowerComponents.append(component)
开发者ID:hajnalben,项目名称:SublimeAngularTools,代码行数:29,代码来源:Bower.py


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