Exemplo n.º 1
0
    def test_etree(self):
        'Parker conversion from data to etree'
        eq = self.check_etree(xmljson.parker)

        # From https://developer.mozilla.org/en-US/docs/JXON#In_summary
        eq({'animal': {}}, '<animal/>')
        eq({'animal': 'Deka'}, '<animal>Deka</animal>')
        eq({'animal': 1}, '<animal>1</animal>')
        eq({'animal': Dict([('dog', 'Charlie'), ('cat', 'Deka')])},
           '<animal><dog>Charlie</dog><cat>Deka</cat></animal>')
        eq({'animal': {'dog': ['Charlie', 'Mad Max']}},
           '<animal><dog>Charlie</dog><dog>Mad Max</dog></animal>')

        # Test edge cases
        eq('x', '<x/>')             # Strings become elements
        eq({})                      # Empty objects become empty nodes
        eq(Dict([                   # Multiple keys become multiple nodes
            ('x', 'a'),
            ('y', 'b')
        ]), '<x>a</x>', '<y>b</y>')
        eq({'x': None}, '<x/>')     # None becomes an empty string
        with self.assertRaises(Exception):
            eq({'x': {'@x': 1}}, '<x x="1"/>')

        # Nested elements
        eq({'alice': Dict([
            ('bob', {'charlie': {}}),
            ('david', {'edgar': {}})])},
           '<alice><bob><charlie/></bob><david><edgar/></david></alice>')

        # Multiple elements at the same level become array elements.
        eq({'alice': {'bob': [{'charlie': {}}, {'david': {}}]}},
           '<alice><bob><charlie/></bob><bob><david/></bob></alice>')

        self.check_invalid_tags(xmljson.Parker)
Exemplo n.º 2
0
def to_frame(img_path, infer_result, conf_th = CONF_TH):
    
    # 2개 클래스 중 첫번째 클래스가 쓰러짐. 두번째 클래스는 쓰러지기 직전이라서 첫번째 값만 사용.
    bboxes = infer_result[0] 
    if len(bboxes) == 0:
        return Dict(file_name=Path(img_path).name, box=[])
    
    
    # 필터링 1, 2
    bboxes = bboxes[conf_th <= bboxes[:,4]]
    bboxes = bboxes[bboxes[:,4].argsort()][-TOP_N:,:]
    
    # 필터링 3
    bboxes_idx = []
    for i, box in enumerate(bboxes):
        x1, y1, x2, y2, c = box
        if MIN_SIZE <= (x2-x1) and MIN_SIZE <= (y2-y1):
            bboxes_idx.append(i)
    bboxes = bboxes[bboxes_idx]
       
    
    # 형식 변환하는 코드
    def to_box(bbox):
        box  = np.round(bbox[:4]).astype(np.uint).tolist()
        conf = bbox[4]
        return Dict(position=box, confidence_score=str(conf))
        
    boxes = [to_box(bbox) for bbox in bboxes[::-1]] # 혹시나 몰라서 conf가 높은 것을 앞에 적어 줌
    return Dict(file_name=Path(img_path).name, box=boxes)
def peers_main():
    if len(sys.argv) == 2 and sys.argv[1] == 'config':
        print("graph_title coiniclesnet peers")
        print("graph_vlabel peers")
        print("graph_category network")
        print(
            "graph_info This graph shows the number of node to node sessions of this coiniclesnet router"
        )
        print("_peers_outbound.info Number of outbound coiniclesnet peers")
        print("_peers_inbound.info Number of inbound coiniclesnet peers")
        print("_peers_outbound.label outbound peers")
        print("_peers_inbound.label inbound peers")
        print("_peers_clients.info Number of coiniclesnet client peers")
        print("_peers_clients.label coiniclesnet client peers")
    else:
        inbound = Dict(int)
        outbound = Dict(int)
        clients = Dict(int)
        try:
            j = jsonrpc("llarp.admin.link.neighboors")
            for peer in j['result']:
                if peer["svcnode"]:
                    if peer["outbound"]:
                        outbound[peer['ident']] += 1
                    else:
                        inbound[peer['ident']] += 1
                else:
                    clients[peer['ident']] += 1
        except RequestException:
            pass

        print("_peers_outbound.value {}".format(len(outbound)))
        print("_peers_inbound.value {}".format(len(inbound)))
        print("_peers_clients.value {}".format(len(clients)))
Exemplo n.º 4
0
def do_tortoisehg_report(repos, output):
    """generate a thg-reporegistry.xml file from a list of repos and print
    to output
    """
    import operator
    import xml.etree.ElementTree as ET

    root = ET.Element('reporegistry')
    item = ET.SubElement(root, 'treeitem')

    group = ET.SubElement(item, 'group', attrib=Dict(name='groupname'))

    def fullname_to_shortname(fullname):
        shortname = fullname.replace(os.environ['HOME'], '~')
        shortname = shortname.lstrip('./')
        return shortname

    for repo in sorted(repos, key=operator.attrgetter('fpath')):
        fullname = os.path.join(os.path.dirname(repo.fpath),
                                os.path.basename(repo.fpath))
        shortname = fullname_to_shortname(fullname)
        if repo.prefix != '.hg':
            shortname = "%s%s" % (shortname, repo.prefix)
        _ = ET.SubElement(group,
                          'repo',
                          attrib=Dict(root=repo.fpath,
                                      shortname=shortname,
                                      basenode='0' * 40))
        _
    print('<?xml version="1.0" encoding="UTF-8"?>', file=output)
    print("<!-- autogenerated: %s -->" % "TODO", file=output)
    print(ET.dump(root), file=output)
def con2dict(L_deff, W_deff, L_sig_max_f, L_sig_max_c, W_sig_max_f,
             W_sig_max_c, L_tau_max_f, L_tau_max_c, W_tau_max_f, W_tau_max_c,
             deff_max, lami_prop, core_prop):
    con = Dict()
    # Compare max deflection with the allow
    con["deff"] = L_deff / deff_max

    # Compare max stress with the allow
    con["stress"] = Dict()
    # Face
    con["stress"]["face"] = Dict()
    # Compressive
    con["stress"]["face"]["com"] = L_sig_max_f / lami_prop["sig1_max_com"]
    # Tensile
    con["stress"]["face"]["ten"] = L_sig_max_f / lami_prop["sig1_max_ten"]

    # Core
    con["stress"]["core"] = Dict()
    con["stress"]["core"]["com"] = L_sig_max_c / core_prop["sig1_max_com"]

    con["stress"]["core"]["ten"] = L_sig_max_c / core_prop["sig1_max_ten"]

    # Compare max shear stress with the allow
    con["shear"] = Dict()

    con["shear"]["face"] = L_tau_max_f / lami_prop["tau_max"]

    con["shear"]["core"] = L_tau_max_c / core_prop["tau_max"]
    return con
Exemplo n.º 6
0
def find_unique_repos(where):
    """
    Search for repositories and deduplicate based on ``repo.fpath``

    Args:
        where (str): path to search from

    Yields:
        Repository subclass
    """
    repos = Dict()
    path_uuids = Dict()
    log.debug("find_unique_repos(%r)" % where)
    for repo in find_find_repos(where):
        # log.debug(repo)
        repo2 = (hasattr(repo, 'search_upwards')
                 and repo.search_upwards(upwards=path_uuids))
        if repo2:
            if repo2 == repo:
                continue
            else:
                repo = repo2

        if (repo.fpath not in repos):
            log.debug("%s | %s | %s" %
                      (repo.prefix, repo.fpath, repo.unique_id))
            repos[repo.fpath] = repo
            yield repo
Exemplo n.º 7
0
    def event_parameters(self, **kwargs):
        """
        Create an EventParameters object
        
        Return dict of eventParameters element given arrays of high-level
        elements as keywords i.e. event=[ev1, ev2, ev3].

        Should be valid for BED or BED-RT
        """
        allowed = ('event', 'origin', 'magnitude', 'stationMagnitude',
                   'focalMechanism', 'reading', 'pick', 'amplitude',
                   'description', 'comment', 'creationInfo')

        dtnow = datetime.datetime.utcnow()
        ustamp = int(_ts(dtnow) * 10**6)
        catalogID_rid = "{0}/{1}".format('catalog', ustamp)

        eventParameters = Dict([
            ('@publicID', self._uri(catalogID_rid)),
            ('creationInfo',
             Dict([
                 ('creationTime', self._utc(_ts(dtnow))),
                 ('agencyID', self.agency),
                 ('version', str(ustamp)),
             ])),
        ])
        for k in kwargs:
            if k in allowed:
                eventParameters[k] = kwargs[k]
        return eventParameters
Exemplo n.º 8
0
    def test_etree(self, converter=None):
        'BadgerFish conversion from data to etree'
        eq = self.check_etree(converter or xmljson.badgerfish)

        # From https://developer.mozilla.org/en-US/docs/JXON#In_summary
        eq({'animal': {}}, '<animal/>')
        eq({'animal': 'Deka'}, '<animal>Deka</animal>')
        eq({'animal': 1}, '<animal>1</animal>')
        eq({'animal': {'@name': 1}}, '<animal name="1"/>')
        eq({'animal': {'@name': 'Deka', '$': 'is my cat'}},
           '<animal name="Deka">is my cat</animal>')
        eq({'animal': Dict([('dog', 'Charlie'), ('cat', 'Deka')])},
           '<animal><dog>Charlie</dog><cat>Deka</cat></animal>')
        eq({'animal': {'dog': ['Charlie', 'Mad Max']}},
           '<animal><dog>Charlie</dog><dog>Mad Max</dog></animal>')
        eq({'animal': {'$': ' in my house ', 'dog': 'Charlie'}},
           '<animal> in my house <dog>Charlie</dog></animal>')

        # TODO: handling split text
        # eq({'animal': {'$': ' in my house', 'dog': 'Charlie'}},
        #    '<animal> in my <dog>Charlie</dog> house</animal>')

        # Test edge cases
        eq('x', '<x/>')             # Strings become elements
        eq({})                      # Empty objects become empty nodes
        eq(Dict([                   # Multiple keys become multiple nodes
            ('x', {'@x': 1}),
            ('y', 'z')
        ]), '<x x="1"/>', '<y>z</y>')

        # Attributes
        eq({'p': {'@id': 1, '$': 'text'}}, '<p id="1">text</p>')
        eq({'div': {'@id': 2, '$': 'parent-text', 'p': {'$': 'text'}}},
            '<div id="2">parent-text<p>text</p></div>')

        # From http://www.sklar.com/badgerfish/
        # Text content of elements goes in the $ property of an object.
        eq({'alice': {'$': 'bob'}}, '<alice>bob</alice>')

        # Nested elements become nested properties
        eq({'alice': Dict([
            ('bob', {'$': 'charlie'}),
            ('david', {'$': 'edgar'})])},
           '<alice><bob>charlie</bob><david>edgar</david></alice>')

        # Multiple elements at the same level become array elements.
        eq({'alice': {'bob': [{'$': 'charlie'}]}},
           '<alice><bob>charlie</bob></alice>')
        eq({'alice': {'bob': [{'$': 'charlie'}, {'$': 'david'}]}},
           '<alice><bob>charlie</bob><bob>david</bob></alice>')

        # Attributes go in properties whose names begin with @.
        eq({'alice': {'$': 'bob', '@charlie': 'david'}},
            '<alice charlie="david">bob</alice>')

        self.check_invalid_tags(xmljson.BadgerFish)
Exemplo n.º 9
0
    def test_etree(self):
        'GData conversion from etree to data'
        eq = self.check_etree(xmljson.gdata)

        # From https://developer.mozilla.org/en-US/docs/JXON#In_summary
        eq({'animal': {}}, '<animal/>')
        eq({'animal': 'Deka'}, '<animal>Deka</animal>')
        eq({'animal': 1}, '<animal>1</animal>')
        eq({'animal': {'name': 1}}, '<animal name="1"/>')
        eq({'animal': {'$t': 'is my cat'}},
           '<animal>is my cat</animal>')
        eq({'animal': Dict([('dog', {'$t': 'Charlie'}), ('cat', {'$t': 'Deka'})])},
           '<animal><dog>Charlie</dog><cat>Deka</cat></animal>')
        eq({'animal': Dict([('dog', 'Charlie'), ('cat', 'Deka')])},
           '<animal dog="Charlie" cat="Deka"/>')
        eq({'animal': {'dog': ['Charlie', 'Mad Max']}},
           '<animal><dog>Charlie</dog><dog>Mad Max</dog></animal>')
        eq({'animal': {'$t': ' in my house ', 'dog': {'$t': 'Charlie'}}},
           '<animal> in my house <dog>Charlie</dog></animal>')
        eq({'animal': {'$t': ' in my house ', 'dog': 'Charlie'}},
           '<animal dog="Charlie"> in my house </animal>')

        # Test edge cases
        eq('x', '<x/>')             # Strings become elements
        eq({})                      # Empty objects become empty nodes
        eq(Dict([                   # Multiple keys become multiple nodes
            ('x', {}),
            ('y', 'z')
        ]), '<x/>', '<y>z</y>')

        # Attributes
        eq({'p': {'$t': 'text'}}, '<p>text</p>')
        eq({'div': {'$t': 'parent-text', 'p': {'$t': 'text'}}},
            '<div>parent-text<p>text</p></div>')

        # Text content of elements goes in the $ property of an object.
        eq({'alice': {'$t': 'bob'}}, '<alice>bob</alice>')

        # Nested elements become nested properties
        eq({'alice': Dict([
            ('bob', {'$t': 'charlie'}),
            ('david', {'$t': 'edgar'})])},
           '<alice><bob>charlie</bob><david>edgar</david></alice>')

        # Multiple elements at the same level become array elements.
        eq({'alice': {'bob': [{'$t': 'charlie'}]}},
           '<alice><bob>charlie</bob></alice>')
        eq({'alice': {'bob': [{'$t': 'charlie'}, {'$t': 'david'}]}},
           '<alice><bob>charlie</bob><bob>david</bob></alice>')

        # Attributes go in properties whose names begin with @.
        eq({'alice': {'$t': 'bob'}},
            '<alice>bob</alice>')

        self.check_invalid_tags(xmljson.GData)
Exemplo n.º 10
0
 def qml(self, event_parameters, default_namespace=BED_NAMESPACE):
     """
     Return dict of QuakeML root element given eventParameters dict
     """
     qml = Dict([
         ('@xmlns:q', Q_NAMESPACE),
         ('@xmlns', default_namespace),
         ('@xmlns:catalog', CATALOG_NAMESPACE),
         ('eventParameters', event_parameters),
     ])
     return Dict({'q:quakeml': qml})
Exemplo n.º 11
0
def build_value_refs(nodes):
    """
    build op reference of inputs and outputs
    """

    input_refs = Dict()
    output_refs = Dict()
    for idx, node in enumerate(nodes):
        for val_name in node.input:
            input_refs.setdefault(val_name, set()).add(idx)
        for val_name in node.output:
            output_refs.setdefault(val_name, set()).add(idx)
    return input_refs, output_refs
Exemplo n.º 12
0
def main():
    # 데이터 준비
    data_root = Path(sys.argv[1])
    
    stride = int(round(15/FPS))
    total_imgs = sorted(glob(f'{data_root}/*/*.jpg'))
    sample_imgs = total_imgs[::stride]
    print(f'len(total):{len(total_imgs)}')
    print(f'len(sample):{len(sample_imgs)}')
    print(f'top_{TOP_N}, {FPS}fps, min_size:{MIN_SIZE}')

    #추론할 파일 리스트를 json 포멧으로 변환
    anno, anno_path, img_base  = make_coco.to_json_format(data_root, sample_imgs)

    # launcher tool을 이용한 추론 실행
    out_pickle_path = '/aichallenge/temp_dir/launch_test.pickle'
    lt.run_test(config_file, checkpoint_file, 
                out_pickle_path)
    
    # 추론 결과 로드
    df = pd.read_pickle(out_pickle_path)
    pairs = list(zip(anno['images'], df))
    results_dict = {Path(img['file_name']).name: bboxes for img, bboxes in pairs}
    
    # 모든 파일에 대해 추론 결과 반영
    # 추론과정에서 skip 되었던 프레임은 이전 프레임 추론 결과를 그대로 적어 준다
    # 비디오 시작 프레임이 추론되지 않았으면 empty 박스를 적어 준다.
    videos = sorted(glob(f'{data_root}/*'))
    
    frame_results = []
    for video in videos:
        frames = sorted(glob(f'{video}/*.jpg'))
        prev_result = Dict(file_name='dummy', box=[])
        for f in frames:
            f = Path(f).name
            if f in results_dict:
                prev_result = to_frame(f, results_dict[f])
                frame_results.append(prev_result)
            else:
                t = Dict(file_name=f, box=prev_result['box'])
                frame_results.append(t)
                
    # 출력 포멧에 맞게 저장
    anno = Dict(annotations=frame_results)
    with open(SAVE_PATH, 'w') as f: 
        json.dump(anno, f)
    print(f'success  {SAVE_PATH}')
    print(f'fps({FPS})_topn({TOP_N})_th({CONF_TH:.2f})_minpx({MIN_SIZE})')
Exemplo n.º 13
0
def inferred_model_value_info(model):
    """
    collect value/type info for an ONNX model
    """

    model = infer_shapes(model)
    graph = model.graph
    value_info = Dict()
    for item in graph.value_info:
        value_info[item.name] = dict(
            dtype=tensor_dtype(item),
            shape=tensor_shape(item),
            external=False,
        )
    for item in graph.input:
        assert item.name not in value_info
        value_info[item.name] = dict(
            dtype=tensor_dtype(item),
            shape=tensor_shape(item),
            external=True,
        )
    for item in graph.output:
        #        assert item.name not in value_info, 'bypass-model not supported'
        value_info[item.name] = dict(
            dtype=tensor_dtype(item),
            shape=tensor_shape(item),
            external=True,
        )
    return value_info
Exemplo n.º 14
0
 def CreatTable_CGCS(self,tablepath,type=0):
     """修改参数界面的表格绘制函数"""
     self.tableinfor_2 = FiveFileParser.readTable(tablepath)
     self.UI.tableWidget.clear()
     if self.tableinfor_2  is not None:
         self.tableinfor_2=Dict(self.tableinfor_2[self.tableinfor_2.keys()[0]]['cellContent'])
         self.tableinfor_2Save = copy.deepcopy(self.tableinfor_2)#获取存储数据
         row,col=CalculateRowCol(self.tableinfor_2.keys())
         self.currentfilepath.setdefault('row',row)
         self.currentfilepath.setdefault('col',col)
         self.SetTableRowCol_CGCS(row,col)#更新表格的个数
         for i,data in enumerate(self.tableinfor_2.iteritems()):
             itemkey = QtWidgets.QTableWidgetItem()
             itemvalue=QtWidgets.QTableWidgetItem()
             if type==0:
                 itemkey.setBackground(QtGui.QBrush(QtGui.QColor(200, 184, 7)))
             else:
                 itemkey.setBackground(QtGui.QBrush(QtGui.QColor(188, 229, 255)))
             itemkey.setText(data[0])
             itemvalue.setText(data[1])
             itemkey.setFlags(QtCore.Qt.ItemIsEnabled)
             self.UI.tableWidget.setItem(i % self.currentfilepath['row'],
                             (i // self.currentfilepath['row']) * 2, itemkey)
             self.UI.tableWidget.setItem(i%self.currentfilepath['row'],(i // self.currentfilepath['row']) * 2+1,itemvalue)
     else:
         self.tableinfor_2=None
Exemplo n.º 15
0
    def test_html(self):
        'BadgerFish conversion from data to HTML'
        html_converter = xmljson.BadgerFish(element=lxml.html.Element)
        self.test_etree(html_converter)

        eq = self.check_etree(html_converter,
                              tostring=lxml.html.tostring,
                              fromstring=lxml.html.fromstring)
        eq(
            {
                'div':
                Dict([
                    ('p', {
                        '$': 'paragraph'
                    }),
                    ('hr', {}),
                    ('ul', {
                        'li': [{
                            '$': '1'
                        }, {
                            '$': '2'
                        }]
                    }),
                ])
            }, '<div><p>paragraph</p><hr><ul><li>1</li><li>2</li></ul></div>')
Exemplo n.º 16
0
def inferred_model_value_info(model):
    """
    collect value/type info for an ONNX model
    """

    assert isinstance(model,
                      onnx.ModelProto), 'model is not a ModelProto instance'

    model = infer_shapes(model)
    graph = model.graph
    value_info = Dict()
    for item in graph.value_info:
        value_info[item.name] = {
            'dtype': tensor_dtype(item),
            'shape': tensor_shape(item),
            'external': False,
        }
    for item in graph.input:
        assert item.name not in value_info
        value_info[item.name] = {
            'dtype': tensor_dtype(item),
            'shape': tensor_shape(item),
            'external': True,
        }
    for item in graph.output:
        #        assert item.name not in value_info, 'bypass-model not supported'
        value_info[item.name] = {
            'dtype': tensor_dtype(item),
            'shape': tensor_shape(item),
            'external': True,
        }
    return value_info
Exemplo n.º 17
0
def do_tortoisehg_report(repos, output):
    """
    Generate a thg-reporegistry.xml file from a list of repos and print
    to output

    Args:
        repos (iterable): iterable of Repository subclass instances
        output (writeable): output stream to which THG XML will be printed
    """
    import operator
    import xml.etree.ElementTree as ET

    root = ET.Element('reporegistry')
    item = ET.SubElement(root, 'treeitem')

    group = ET.SubElement(item, 'group', attrib=Dict(name='groupname'))

    def fullname_to_shortname(fullname):
        """
        Return a TortoiseHG-friendly path to a repository

        Args:
            fullname (str): path to repository

        Returns:
            str: path with $HOME replaced with ``~`` and leading ``./``
                stripped
        """
        shortname = fullname.replace(os.environ['HOME'], '~')
        shortname = shortname.lstrip('./')
        return shortname

    for repo in sorted(repos, key=operator.attrgetter('fpath')):
        fullname = os.path.join(os.path.dirname(repo.fpath),
                                os.path.basename(repo.fpath))
        shortname = fullname_to_shortname(fullname)
        if repo.prefix != '.hg':
            shortname = "%s%s" % (shortname, repo.prefix)
        _ = ET.SubElement(group,
                          'repo',
                          attrib=Dict(root=repo.fpath,
                                      shortname=shortname,
                                      basenode='0' * 40))
        _
    print('<?xml version="1.0" encoding="UTF-8"?>', file=output)
    print("<!-- autogenerated: %s -->" % "TODO", file=output)
    print(ET.dump(root), file=output)
Exemplo n.º 18
0
    def _put_words_into_rect(self, words, rects):
        # 将words按照坐标层级放入矩阵中
        groups = {'IN': Dict(list), 'OUT': Dict(list)}
        for name, r in rects.items():
            groups['IN'][name] = []
        for word in words:
            p = ((word['x0'] + word['x1']) // 2,
                 (word['y0'] + word['y1']) // 2)
            is_word_put_into_group = False
            for name, r in rects.items():
                if self._is_point_in_rect(p, r):
                    is_word_put_into_group = True
                    groups['IN'][name].append(word)
                    break

            if not is_word_put_into_group:
                groups['OUT'][word['x0']].append(word)
        return groups
Exemplo n.º 19
0
    def __init__(self, *args, **kwargs):
        super(Pharmacy, self).__init__(*args, **kwargs)
        self.__model_label__ = "Pharmacy"
        self._parent_model = 'parent_hospital'

        #self.drugs=Dict(lambda : Dict(int)) #self.drugs[drug_name][drug_type]=drug_number
        self.drugs = Dict()  # self.drugs[drug_code]=drug_num
        self.drug_object_list = list()
        self.user_type = 5
Exemplo n.º 20
0
 def _merge_words_by_line(words, delta=2):
     words_in_line = Dict(list)
     for word in words:
         row_num = round((word['y0'] + word['y1']) / 2)
         row_range = set([row_num - i for i in range(1, delta + 1)] +
                         [row_num + i for i in range(1, delta + 1)])
         if len(row_range & set(words_in_line.keys())) > 0:
             row_num = list(row_range & set(words_in_line.keys()))[0]
         words_in_line[row_num].append(word)
     return words_in_line
Exemplo n.º 21
0
def find_unique_repos(where):
    repos = Dict()
    path_uuids = Dict()
    log.debug("find_unique_repos(%r)" % where)
    for repo in find_find_repos(where):
        # log.debug(repo)
        repo2 = (hasattr(repo, 'search_upwards')
                 and repo.search_upwards(upwards=path_uuids))
        if repo2:
            if repo2 == repo:
                continue
            else:
                repo = repo2

        if (repo.fpath not in repos):
            log.debug("%s | %s | %s" %
                      (repo.prefix, repo.fpath, repo.unique_id))
            repos[repo.fpath] = repo
            yield repo
Exemplo n.º 22
0
def vimsottari_mahadasa(jdut1):
    """List all mahadashas and their start dates"""
    lord, start_date = dasha_start_date(jdut1)
    retval = Dict()
    for i in range(9):
        retval[lord] = start_date
        start_date += mahadasa[lord] * vimsottari_year
        lord = next_adhipati(lord)

    return retval
Exemplo n.º 23
0
def export_onnx_with_validation(model,
                                inputs,
                                export_basepath,
                                input_names=None,
                                output_names=None,
                                use_npz=True,
                                *args,
                                **kwargs):
    """
    export PyTorch model to ONNX model and export sample inputs and outputs in a Numpy file
    """

    is_list_or_tuple = lambda x: isinstance(x, (list, tuple))

    def _tensors_to_arrays(tensors):
        if torch.is_tensor(tensors):
            return tensors.data.cpu().numpy()
        arrays = []
        for tensor in tensors:
            arrays.append(_tensors_to_arrays(tensor))
        return arrays

    def _zip_dict(keys, values):
        ret = Dict()
        for idx, (key, value) in enumerate(zip(keys, values)):
            is_key_list = is_list_or_tuple(key)
            is_value_list = is_list_or_tuple(value)
            assert is_key_list == is_value_list, 'keys and values mismatch'
            if is_value_list:
                ret[str(idx)] = _zip_dict(key, value)
            else:
                ret[key] = value
        return ret

    torch_inputs = _ensure_tuple(inputs)  # WORKAROUND: for torch.onnx
    outputs = torch.onnx.export(model,
                                torch_inputs,
                                export_basepath + '.onnx',
                                input_names=_flatten_list(input_names),
                                output_names=_flatten_list(output_names),
                                *args,
                                **kwargs)
    if outputs is None:  # WORKAROUND: for torch.onnx
        outputs = model(*inputs)
    torch_outputs = _ensure_tuple(outputs)

    inputs = _zip_dict(input_names, _tensors_to_arrays(torch_inputs))
    outputs = _zip_dict(output_names, _tensors_to_arrays(torch_outputs))
    if use_npz:
        np.savez(export_basepath + '.npz', inputs=inputs, outputs=outputs)
    else:
        np.save(export_basepath + '.npy',
                np.array(Dict(inputs=inputs, outputs=outputs)))
    return torch_outputs
Exemplo n.º 24
0
 def _zip_dict(keys, values):
     ret = Dict()
     for idx, (key, value) in enumerate(zip(keys, values)):
         is_key_list = is_list_or_tuple(key)
         is_value_list = is_list_or_tuple(value)
         assert is_key_list == is_value_list, 'keys and values mismatch'
         if is_value_list:
             ret[str(idx)] = _zip_dict(key, value)
         else:
             ret[key] = value
     return ret
Exemplo n.º 25
0
 def CreateTable_TJCS(self,table):
     """创建参数表"""
     temp= FiveFileParser.readTable(table)
     self.UI.table_tianjiacanshu.clear()
     if temp  is not None:
         temp=Dict(temp[temp.keys()[0]]['cellContent'])
         self.tableinfor = Dict()
         row, col = CalculateRowCol(temp.keys())
         self.parefile['row'], self.parefile['col']=row,col
         self.SetTableRowCol_TJCS(row,col)
         self.tableinfor.setdefault('存储为','MUBAN')
         for data in temp.iteritems():
             self.tableinfor.setdefault(data[0],data[1])
         for i,data in enumerate(self.tableinfor.iteritems()):
             item = QtWidgets.QTableWidgetItem()
             item.setText(data[0])
             item.setFlags(QtCore.Qt.ItemIsEnabled)
             self.UI.table_tianjiacanshu.setItem(i % self.parefile['row'], (i // self.parefile['row']) * 2, item)
     else:
         self.tableinfor=Dict()
         self.tableinfor.setdefault('存储为', 'MUBAN')
Exemplo n.º 26
0
def load_files(directory):
    """load files"""
    if not os.path.isdir(directory):
        return []
    path_in_folder = Dict(list)
    for root, _, files in os.walk(directory):
        for file_ in files:
            path = os.path.join(root, file_)
            folder_name = re.split(r'/|\\', root)[-1]
            if os.path.isfile(path) and file_.endswith(('.pdf', '.PDF')):
                path_in_folder[folder_name].append(path)
    return path_in_folder
Exemplo n.º 27
0
def vimsottari_bhukti(maha_lord, start_date):
    """Compute all bhuktis of given nakshatra-lord of Mahadasa
    and its start date"""
    lord = maha_lord
    retval = Dict()
    for i in range(9):
        retval[lord] = start_date
        factor = mahadasa[lord] * mahadasa[maha_lord] / 120.
        start_date += factor * vimsottari_year
        lord = next_adhipati(lord)

    return retval
Exemplo n.º 28
0
def _select(sql, first, *args):
    """
    执行SQL,返回一个结果 或者多个结果组成的列表
    """
    global _db_ctx
    cursor = None
    sql = sql.replace('?', '%s')
    logging.info('SQL: %s, ARGS: %s' % (sql, args))
    try:
        cursor = _db_ctx.connection.cursor()
        cursor.execute(sql, args)
        if cursor.description:
            names = [x[0] for x in cursor.description]
        if first:
            values = cursor.fetchone()
            if not values:
                return None
            return Dict(names, values)
        return [Dict(names, x) for x in cursor.fetchall()]
    finally:
        if cursor:
            cursor.close()
Exemplo n.º 29
0
def vimsottari_antara(maha_lord, bhukti_lord, start_date):
    """Compute all antaradasas from given bhukit's start date.
    The bhukti's lord and its lord (mahadasa lord) must be given"""
    lord = bhukti_lord
    retval = Dict()
    for i in range(9):
        retval[lord] = start_date
        factor = mahadasa[lord] * (mahadasa[maha_lord] / 120.)
        factor *= (mahadasa[bhukti_lord] / 120.)
        start_date += factor * vimsottari_year
        lord = next_adhipati(lord)

    return retval
Exemplo n.º 30
0
    def __init__(self):
        """
        self.database 连接的数据库
        self.fields 查询返回的列名,默认为"*"
        self.datatable 查询的表名 比如 "ROSUNDB.dbo.zy", "ROSUNDB.dbo.dl",在数据库查看
        self.condition 查询需要的条件
        具体sql语法,语句查看[http://www.runoob.com/sql/sql-tutorial.html]
        """
        self.database = None
        self.fields = None
        self.datatable = None
        self.condition = None
        self.data = [[1,2],[3,4]]

        self.name = None
        self.year = None

        self.data_dict = Dict()
        self.data_dicto_compare = Dict()
        self.data_list = []
        self.date_list = []
        self.x_list = []
        self.y_list = []