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


Python jsonpickle.encode方法代码示例

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


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

示例1: with_context

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def with_context(params, proc):
    ctx = create_context(params)

    if 'args' not in params:
        params['args'] = []

    if 'kwargs' not in params:
        params['kwargs'] = {}

    res = proc(ctx)

    if 'tmp_file_to_remove' in params:
        remove_tmp_file.delay(params['tmp_file_to_remove'])

    ctx.set_runs_on_server(False)
    ctx.config.set('use_server', True, config_name='config')
    return {'response': res, 'config': jsonpickle.encode(ctx.config)} 
开发者ID:augerai,项目名称:a2ml,代码行数:19,代码来源:tasks_api.py

示例2: create_report

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def create_report(self, runtime, span_records):
        report = ttypes.ReportRequest(runtime, span_records, None)
        for span in report.span_records:
            if not span.log_records:
                continue
            for log in span.log_records:
                index = span.log_records.index(log)
                if log.payload_json is not None:
                    try:
                        log.payload_json = \
                            jsonpickle.encode(log.payload_json,
                                              unpicklable=False,
                                              make_refs=False,
                                              max_depth=constants.JSON_MAX_DEPTH)
                    except:
                        log.payload_json = jsonpickle.encode(constants.JSON_FAIL)
                span.log_records[index] = log
        return report 
开发者ID:lightstep,项目名称:lightstep-tracer-python,代码行数:20,代码来源:thrift_converter.py

示例3: create_child_qtable

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def create_child_qtable(self, provider, option, transaction_hash, child_index):
        """
        Creates the QTable configuration for the child agent. This is done by copying the own QTable configuration and including the new host provider, the parent name and the transaction hash.
        :param provider: the name the child tree name.
        :param transaction_hash: the transaction hash the child is bought with.
        """

        next_state = VPSState(provider=provider, option=option)
        tree = self.tree + "." + str(child_index)
        dictionary = {
            "environment": self.environment,
            "qtable": self.qtable,
            "providers_offers": self.providers_offers,
            "self_state": next_state,
            "transaction_hash": transaction_hash,
            "tree": tree
        }

        filename = os.path.join(user_config_dir(), 'Child_QTable.json')
        with open(filename, 'w') as json_file:
            encoded_dictionary = jsonpickle.encode(dictionary)
            json.dump(encoded_dictionary, json_file) 
开发者ID:Tribler,项目名称:Dollynator,代码行数:24,代码来源:qtable.py

示例4: write_dictionary

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def write_dictionary(self):
        """
        Writes the QTABLE configuration to the QTable.json file.
        """
        config_dir = user_config_dir()
        filename = os.path.join(config_dir, 'QTable.json')
        to_save_var = {
            "environment": self.environment,
            "qtable": self.qtable,
            "providers_offers": self.providers_offers,
            "self_state": self.self_state,
            "tree": self.tree
        }
        with open(filename, 'w') as json_file:
            encoded_to_save_var = jsonpickle.encode(to_save_var)
            json.dump(encoded_to_save_var, json_file) 
开发者ID:Tribler,项目名称:Dollynator,代码行数:18,代码来源:qtable.py

示例5: predict

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def predict(imagepath, target_x, target_y, name, model):
    if imagepath.startswith('http://') or imagepath.startswith('https://') or imagepath.startswith('ftp://'):
        response = requests.get(imagepath)
        img = Image.open(BytesIO(response.content))
        img = img.resize((target_x, target_y))
    else:
        if not os.path.exists(imagepath):
            raise Exception('Input image file does not exist')
        img = image.load_img(imagepath, target_size=(target_x, target_y))

    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = processInputImage(name, x)
    preds = decodePrediction(name, model.predict(x))
    result = []
    for p in preds[0]:
        result.append({"synset": p[0], "text": p[1], "prediction": float("{0:.2f}".format((p[2] * 100)))})

    return json.loads(jsonpickle.encode(result, unpicklable=False)) 
开发者ID:tech-quantum,项目名称:sia-cog,代码行数:21,代码来源:objcls.py

示例6: tokenize

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def tokenize(data, language="english", filterStopWords = False, tagging = False):
    result = {}
    tags = []
    filterChars = [",", ".", "?", ";", ":", "'", "!", "@", "#", "$", "%", "&", "*", "(", ")", "+", "{", "}", "[", "]", "\\", "|"]
    sent_token = nltk.tokenize.sent_tokenize(data, language)
    word_token = nltk.tokenize.word_tokenize(data, language)
    word_token = [w for w in word_token if not w in filterChars]
    if filterStopWords is True:
        stop_words = set(stopwords.words(language))
        word_token = [w for w in word_token if not w in stop_words]

    if tagging is True:
        tags = nltk.pos_tag(word_token)

    result = {"sent_token": sent_token, "word_token": word_token, "pos_tag": tags}
    return json.loads(jsonpickle.encode(result, unpicklable=False)) 
开发者ID:tech-quantum,项目名称:sia-cog,代码行数:18,代码来源:nltkmgr.py

示例7: synset

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def synset(data):
    result = {}
    syns = wordnet.synsets(data)
    list = []
    for s in syns:
        r = {}
        r["name"] = s.name()
        r["lemma"] = s.lemmas()[0].name()
        r["definition"] = s.definition()
        r["examples"] = s.examples()
        list.append(r)

    result["list"] = list
    synonyms = []
    antonyms = []
    for syn in syns:
        for l in syn.lemmas():
            synonyms.append(l.name())
            if l.antonyms():
                antonyms.append(l.antonyms()[0].name())

    result["synonyms"] = synonyms
    result["antonyms"] = antonyms
    return json.loads(jsonpickle.encode(result, unpicklable=False)) 
开发者ID:tech-quantum,项目名称:sia-cog,代码行数:26,代码来源:nltkmgr.py

示例8: predictint

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def predictint():
    message = "Success"
    code = 200
    result = []
    try:
        start = datetime.utcnow()
        data = request.args.get('data')
        result = intentanalyzer.predict(data)
        result = json.loads(jsonpickle.encode(result, unpicklable=False))
        logmgr.LogPredSuccess("intent", constants.ServiceTypes.LangIntent, start)
    except Exception as e:
        code = 500
        message = str(e)
        logmgr.LogPredError("intent", constants.ServiceTypes.LangIntent, start, message)

    return jsonify({"statuscode": code, "message": message, "result": result}) 
开发者ID:tech-quantum,项目名称:sia-cog,代码行数:18,代码来源:intentapi.py

示例9: writeOutSubmissionsAsHtml

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def writeOutSubmissionsAsHtml(redditList, file):
    submissionsStr = ""
    for submission in redditList:
        submissionsStr += submission.getHtml() + u'\n'
        
    htmlStructure = u"""<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Reddit Saved Comments</title>
</head>

<body>
{0}
</body>
</html>
    """.format(submissionsStr)
        
    file.write(htmlStructure.encode('utf8')) 
开发者ID:makuto,项目名称:Liked-Saved-Image-Downloader,代码行数:23,代码来源:submission.py

示例10: test_load_by_isbn

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def test_load_by_isbn(self, mock_get):
        isbn_key = 'ISBN:0137903952'
        isbn_bibkeys = { isbn_key: { 'info_url': "https://openlibrary.org/books/%s/Artificial_intelligence" % self.target_olid } }
        mock_get.return_value.json.side_effect = [isbn_bibkeys, self.raw_edition.copy(), self.raw_author.copy()]

        actual = json.loads(jsonpickle.encode(self.ol.Edition.get(isbn=u'0137903952')))
        mock_get.assert_has_calls([
            call("%s/api/books.json?bibkeys=%s" % (self.ol.base_url, isbn_key)),
            call().raise_for_status(),
            call().json(),
            call("%s/books/%s.json" % (self.ol.base_url, self.target_olid)),
            call().raise_for_status(),
            call().json(),
            call("%s/authors/OL440500A.json" % self.ol.base_url),
            call().raise_for_status(),
            call().json()
        ])
        self.assertEqual(actual, self.expected,
                        "Data didn't match for ISBN lookup: \n%s\n\nversus:\n\n %s" % (actual, self.expected)) 
开发者ID:internetarchive,项目名称:openlibrary-client,代码行数:21,代码来源:test_openlibrary.py

示例11: _store_item_to_str

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def _store_item_to_str(self, item: object) -> str:
        return encode(item) 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:4,代码来源:blob_storage.py

示例12: run

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def run(self, params={}):
        client_id = params.get("client_id")
        urls = params.get("urls")

        # Create individual payload arrays for use in whole payload
        threat_types = self.get_threat_types(params)
        platform_types = self.get_platforms(params)
        threat_entries = self.make_threat_entries(urls=urls)
        threat_entry_types = self.get_threat_entry_types(params)

        # Create object hierarchy and payload to send to Google
        client = Client(client_id=client_id)
        threat_info = ThreatInfo(threatTypes=threat_types, platformTypes=platform_types,
                                 threatEntryTypes=threat_entry_types, threatEntries=threat_entries)
        request_payload = Request(client=client, threatInfo=threat_info)  # Create request payload

        # Marshall & serialize object hierarchy into JSON
        payload = jsonpickle.encode(request_payload, unpicklable=False)
        self.logger.info("Run: Created payload: {payload}".format(payload=payload))

        # Send request to Google
        response = requests.post(self.__URL,
                                 data=payload,
                                 params={"key": self.connection.API_KEY})

        # Check if status code is good. If not, raise an exception and halt.
        if not self.status_code_ok(status_code=response.status_code):
            raise Exception("Run: Non-200 status code received, halting. (Got {status_code})"
                            .format(status_code=response.status_code))

        # Get matches from the response. If they don't exist, then early call sys.exit.
        matches = response.json().get("matches")
        if not matches:
            self.logger.info("Run: No matches found!")
            matches = [{'threat':{'url':''}, 'threat_type':'','cache_duration':'','threat_entry_type':'','platform_type':''}]
            results = 0
        else:
            results = len(matches)
        return {"matches": matches, 'results': results} 
开发者ID:rapid7,项目名称:insightconnect-plugins,代码行数:41,代码来源:action.py

示例13: __eq__

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def __eq__(self, other):
        if isinstance(other, type(self)):
            other_encoded = jsonpickle.encode(other.as_dialogue())
            encoded = jsonpickle.encode(self.as_dialogue())
            return (other_encoded == encoded and
                    self.sender_id == other.sender_id)
        else:
            return False 
开发者ID:Rowl1ng,项目名称:rasa_wechat,代码行数:10,代码来源:trackers.py

示例14: encode

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def encode(self, active_features, input_feature_map):
        raise NotImplementedError("Featurizer must have the capacity to "
                                  "encode features to a vector") 
开发者ID:Rowl1ng,项目名称:rasa_wechat,代码行数:5,代码来源:featurizers.py

示例15: persist

# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import encode [as 别名]
def persist(self, path):
        featurizer_file = os.path.join(path, "featurizer.json")
        with io.open(featurizer_file, 'w') as f:
            f.write(str(jsonpickle.encode(self))) 
开发者ID:Rowl1ng,项目名称:rasa_wechat,代码行数:6,代码来源:featurizers.py


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