Beispiel #1
0
        def __save(self):
                """Serializes the current history information and writes it to
                a file in self.path/{operation_start_time}-{sequence}.xml.
                """
                d = xmini.Document()
                d.appendChild(d.createElement("history"))
                self.__serialize_client_data(d)
                self.__serialize_operation_data(d)

                if not os.path.exists(self.path):
                        try:
                                # Only the right-most directory should be
                                # created.  Assume that if the parent structure
                                # does not exist, it shouldn't be created.
                                os.mkdir(self.path, misc.PKG_DIR_MODE)
                        except EnvironmentError as e:
                                if e.errno not in (errno.EROFS, errno.EACCES,
                                    errno.ENOENT):
                                        # Ignore read-only file system and
                                        # access errors as it isn't critical
                                        # to the image that this data is
                                        # written.
                                        raise apx.HistoryStoreException(e)
                                # Return, since without the directory, the rest
                                # of this will fail.
                                return
                        except KeyboardInterrupt:
                                raise
                        except Exception as e:
                                raise apx.HistoryStoreException(e)

                # Repeatedly attempt to write the history (only if it's because
                # the file already exists).  This is necessary due to multiple
                # operations possibly occuring within the same second (but not
                # microsecond).
                pathname = self.pathname
                for i in range(1, 100):
                        try:
                                f = os.fdopen(os.open(pathname,
                                    os.O_CREAT|os.O_EXCL|os.O_WRONLY,
                                    misc.PKG_FILE_MODE), "w")
                                d.writexml(f,
                                    encoding=sys.getdefaultencoding())
                                f.close()
                                return
                        except EnvironmentError as e:
                                if e.errno == errno.EEXIST:
                                        name, ext = os.path.splitext(
                                            os.path.basename(pathname))
                                        name = name.split("-", 1)[0]
                                        # Pick the next name in our sequence
                                        # and try again.
                                        pathname = os.path.join(self.path,
                                            "{0}-{1:>02d}{2}".format(name,
                                            i + 1, ext))
                                        continue
                                elif e.errno not in (errno.EROFS,
                                    errno.EACCES):
                                        # Ignore read-only file system and
                                        # access errors as it isn't critical
                                        # to the image that this data is
                                        # written.
                                        raise apx.HistoryStoreException(e)
                                # For all other failures, return, and avoid any
                                # further attempts.
                                return
                        except KeyboardInterrupt:
                                raise
                        except Exception as e:
                                raise apx.HistoryStoreException(e)
Beispiel #2
0
def add_sources(path):
    logger.info()
    from xml.dom import minidom

    SOURCES_PATH = xbmc.translatePath("special://userdata/sources.xml")

    if os.path.exists(SOURCES_PATH):
        xmldoc = minidom.parse(SOURCES_PATH)
    else:
        # Crear documento
        xmldoc = minidom.Document()
        nodo_sources = xmldoc.createElement("sources")

        for type in ['programs', 'video', 'music', 'picture', 'files']:
            nodo_type = xmldoc.createElement(type)
            element_default = xmldoc.createElement("default")
            element_default.setAttribute("pathversion", "1")
            nodo_type.appendChild(element_default)
            nodo_sources.appendChild(nodo_type)
        xmldoc.appendChild(nodo_sources)

    # Buscamos el nodo video
    nodo_video = xmldoc.childNodes[0].getElementsByTagName("video")[0]

    # Buscamos el path dentro de los nodos_path incluidos en el nodo_video
    nodos_paths = nodo_video.getElementsByTagName("path")
    list_path = [p.firstChild.data for p in nodos_paths]
    logger.debug(list_path)
    if path in list_path:
        logger.debug("La ruta %s ya esta en sources.xml" % path)
        return
    logger.debug("La ruta %s NO esta en sources.xml" % path)

    # Si llegamos aqui es por q el path no esta en sources.xml, asi q lo incluimos
    nodo_source = xmldoc.createElement("source")

    # Nodo <name>
    nodo_name = xmldoc.createElement("name")
    sep = os.sep
    if path.startswith("special://") or path.startswith("smb://"):
        sep = "/"
    name = path
    if path.endswith(sep):
        name = path[:-1]
    nodo_name.appendChild(xmldoc.createTextNode(name.rsplit(sep)[-1]))
    nodo_source.appendChild(nodo_name)

    # Nodo <path>
    nodo_path = xmldoc.createElement("path")
    nodo_path.setAttribute("pathversion", "1")
    nodo_path.appendChild(xmldoc.createTextNode(path))
    nodo_source.appendChild(nodo_path)

    # Nodo <allowsharing>
    nodo_allowsharing = xmldoc.createElement("allowsharing")
    nodo_allowsharing.appendChild(xmldoc.createTextNode('true'))
    nodo_source.appendChild(nodo_allowsharing)

    # Añadimos <source>  a <video>
    nodo_video.appendChild(nodo_source)

    # Guardamos los cambios
    filetools.write(SOURCES_PATH, '\n'.join([x for x in xmldoc.toprettyxml().encode("utf-8").splitlines() if x.strip()]))
Beispiel #3
0
    def CemuConfig(configFile, system):
        # Config file
        config = minidom.Document()
        if os.path.exists(configFile):
            try:
                config = minidom.parse(configFile)
            except:
                pass # reinit the file

        ## [ROOT]
        xml_root = CemuGenerator.getRoot(config, "content")

        # Default mlc path
        CemuGenerator.setSectionConfig(config, xml_root, "mlc_path", cemuMLC)

        # Remove auto updates
        CemuGenerator.setSectionConfig(config, xml_root, "check_update", "false")
        # Avoid the welcome window
        CemuGenerator.setSectionConfig(config, xml_root, "gp_download", "true")
        # Other options
        CemuGenerator.setSectionConfig(config, xml_root, "logflag", "0")
        CemuGenerator.setSectionConfig(config, xml_root, "advanced_ppc_logging", "false")
        CemuGenerator.setSectionConfig(config, xml_root, "use_discord_presence", "false")
        CemuGenerator.setSectionConfig(config, xml_root, "fullscreen_menubar", "false")
        CemuGenerator.setSectionConfig(config, xml_root, "cpu_mode", "1")
        CemuGenerator.setSectionConfig(config, xml_root, "vk_warning", "false")
        CemuGenerator.setSectionConfig(config, xml_root, "fullscreen", "true")

        # Language
        CemuGenerator.setSectionConfig(config, xml_root, "console_language", str(getCemuLangFromEnvironment()))

        ## [WINDOW POSITION]
        CemuGenerator.setSectionConfig(config, xml_root, "window_position", "")
        window_position = CemuGenerator.getRoot(config, "window_position")

        # Default window position
        CemuGenerator.setSectionConfig(config, window_position, "x", "-4")
        # Default games path
        CemuGenerator.setSectionConfig(config, window_position, "y", "-23")

        ## [WINDOW POSITION]
        CemuGenerator.setSectionConfig(config, xml_root, "window_size", "")
        window_size = CemuGenerator.getRoot(config, "window_size")

        # Default window size
        CemuGenerator.setSectionConfig(config, window_size, "x", "1")
        # Default games path
        CemuGenerator.setSectionConfig(config, window_size, "y", "1")

        ## [GAME PATH]
        CemuGenerator.setSectionConfig(config, xml_root, "GamePaths", "")
        game_root = CemuGenerator.getRoot(config, "GamePaths")

        # Default games path
        CemuGenerator.setSectionConfig(config, game_root, "Entry", cemuHomedir)

        ## [AUDIO]
        CemuGenerator.setSectionConfig(config, xml_root, "Audio", "")
        audio_root = CemuGenerator.getRoot(config, "Audio")

        # Turn audio ONLY on TV
        CemuGenerator.setSectionConfig(config, audio_root, "TVDevice", "default")
        CemuGenerator.setSectionConfig(config, audio_root, "TVVolume", "90")


        ## [GRAPHIC]
        CemuGenerator.setSectionConfig(config, xml_root, "Graphic", "")
        graphic_root = CemuGenerator.getRoot(config, "Graphic")

        # Graphical backend
        if system.isOptSet("gfxbackend"):
            if system.config["gfxbackend"] == "Vulkan":
                CemuGenerator.setSectionConfig(config, graphic_root, "api", "1") # Vulkan
            else:
                CemuGenerator.setSectionConfig(config, graphic_root, "api", "0") # OpenGL
        else:
            CemuGenerator.setSectionConfig(config, graphic_root, "api", "1")     # Vulkan

        # Async VULKAN Shader compilation
        if system.isOptSet("async") and system.config["async"] == "0":
            CemuGenerator.setSectionConfig(config, graphic_root, "AsyncCompile", "false")
        else:
            CemuGenerator.setSectionConfig(config, graphic_root, "AsyncCompile", "true")

        ## [GRAPHIC]
        CemuGenerator.setSectionConfig(config, graphic_root, "Overlay", "")
        overlay_root = CemuGenerator.getRoot(config, "Overlay")

        # Display FPS / CPU / GPU / RAM
        if system.isOptSet('showFPS') and system.getOptBoolean('showFPS') == True:
            CemuGenerator.setSectionConfig(config, overlay_root, "Position", "1")
            CemuGenerator.setSectionConfig(config, overlay_root, "FPS",       "true")
            CemuGenerator.setSectionConfig(config, overlay_root, "CPUUsage",  "true")
            CemuGenerator.setSectionConfig(config, overlay_root, "RAMUsage",  "true")
            CemuGenerator.setSectionConfig(config, overlay_root, "VRAMUsage", "true")
        else:
            CemuGenerator.setSectionConfig(config, overlay_root, "Position", "0")
            CemuGenerator.setSectionConfig(config, overlay_root, "FPS",       "false")
            CemuGenerator.setSectionConfig(config, overlay_root, "CPUUsage",  "false")
            CemuGenerator.setSectionConfig(config, overlay_root, "RAMUsage",  "false")
            CemuGenerator.setSectionConfig(config, overlay_root, "VRAMUsage", "false")

        # Save the config file
        xml = open(configFile, "w")

        # TODO: python 3 - workawround to encode files in utf-8
        xml = codecs.open(configFile, "w", "utf-8")
        dom_string = os.linesep.join([s for s in config.toprettyxml().splitlines() if s.strip()]) # remove ugly empty lines while minicom adds them...
        xml.write(dom_string)
Beispiel #4
0
 def __init__(self, context, request):
     super(AkomantosoXMLView, self).__init__(context, request)
     self.response = xmllib.Document()
Beispiel #5
0
def generate_xml(img_name, coords, img_size, out_root_path):
    '''
    输入:
        img_name:图片名称,如a.jpg
        coords:坐标list,格式为[[x_min, y_min, x_max, y_max, name]],name为概况的标注
        img_size:图像的大小,格式为[h,w,c]
        out_root_path: xml文件输出的根路径
    '''
    doc = DOC.Document()  # 创建DOM文档对象

    annotation = doc.createElement('annotation')
    doc.appendChild(annotation)

    title = doc.createElement('folder')
    title_text = doc.createTextNode('Tianchi')
    title.appendChild(title_text)
    annotation.appendChild(title)

    title = doc.createElement('filename')
    title_text = doc.createTextNode(img_name)
    title.appendChild(title_text)
    annotation.appendChild(title)

    source = doc.createElement('source')
    annotation.appendChild(source)

    title = doc.createElement('database')
    title_text = doc.createTextNode('The Tianchi Database')
    title.appendChild(title_text)
    source.appendChild(title)

    title = doc.createElement('annotation')
    title_text = doc.createTextNode('Tianchi')
    title.appendChild(title_text)
    source.appendChild(title)

    size = doc.createElement('size')
    annotation.appendChild(size)

    title = doc.createElement('width')
    title_text = doc.createTextNode(str(img_size[1]))
    title.appendChild(title_text)
    size.appendChild(title)

    title = doc.createElement('height')
    title_text = doc.createTextNode(str(img_size[0]))
    title.appendChild(title_text)
    size.appendChild(title)

    title = doc.createElement('depth')
    title_text = doc.createTextNode(str(img_size[2]))
    title.appendChild(title_text)
    size.appendChild(title)

    for coord in coords:

        object = doc.createElement('object')
        annotation.appendChild(object)

        title = doc.createElement('name')
        title_text = doc.createTextNode(coord[4])
        title.appendChild(title_text)
        object.appendChild(title)

        pose = doc.createElement('pose')
        pose.appendChild(doc.createTextNode('Unspecified'))
        object.appendChild(pose)
        truncated = doc.createElement('truncated')
        truncated.appendChild(doc.createTextNode('1'))
        object.appendChild(truncated)
        difficult = doc.createElement('difficult')
        difficult.appendChild(doc.createTextNode('0'))
        object.appendChild(difficult)

        bndbox = doc.createElement('bndbox')
        object.appendChild(bndbox)
        title = doc.createElement('xmin')
        title_text = doc.createTextNode(str(int(float(coord[0]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)
        title = doc.createElement('ymin')
        title_text = doc.createTextNode(str(int(float(coord[1]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)
        title = doc.createElement('xmax')
        title_text = doc.createTextNode(str(int(float(coord[2]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)
        title = doc.createElement('ymax')
        title_text = doc.createTextNode(str(int(float(coord[3]))))
        title.appendChild(title_text)
        bndbox.appendChild(title)

    # 将DOM对象doc写入文件
    f = open(os.path.join(out_root_path, img_name[:-4] + '.xml'), 'w')
    f.write(doc.toprettyxml(indent=''))
    f.close()
Beispiel #6
0
 def detail(self, servers_dict):
     xml_doc = minidom.Document()
     node = self._server_list_to_xml(xml_doc,
                                     servers_dict['servers'],
                                     detailed=True)
     return self.to_xml_string(node, True)
Beispiel #7
0
 def create(self, server_dict):
     xml_doc = minidom.Document()
     node = self._server_to_xml_detailed(xml_doc, server_dict['server'])
     node.setAttribute('adminPass', server_dict['server']['adminPass'])
     return self.to_xml_string(node, True)
def register_labelme_boxes(request, dataset_name):
    if not request.user.has_perm('datastore.annotation.add'):
        return render_to_response('registration/not_authorized.html')

    annotation_type = "labelme_boxes"
    ann_type = get_object_or_404(AnnotationType, name=annotation_type)

    if not Image:
        return HttpResponse(
            "Error. Server installation of python Image library is missing")

    dataset_path = os.path.join(settings.DATASETS_ROOT, dataset_name)
    annotation_path = os.path.join(settings.DATASETS_ROOT,
                                   dataset_name + "_annotations")
    dataset = get_object_or_404(Dataset, name=dataset_name)
    resp = HttpResponse()
    #for dt_item in dataset.dataitem_set.filter(id=29913): #url__contains="IMG_4093"):
    #totTODO=None
    totTODO = dataset.dataitem_set.all().count()
    for (iItem, dt_item) in enumerate(dataset.dataitem_set.all()):

        (str_img, str_img_path, str_img_file) = dt_item.get_name_parts()

        annotation_filename = os.path.join(annotation_path, str_img_path,
                                           str_img_file + ".xml")
        if not os.path.exists(annotation_filename):
            resp.write("Missing annotations file for %s<br/>\n" %
                       annotation_filename)
            continue

        x_out = minidom.Document()
        x_res = x_out.createElement("results")
        x_ann = x_out.createElement("annotation")

        xmldoc = minidom.parse(annotation_filename)
        object_tags = xget(xmldoc, "object")
        image_filename = os.path.join(dataset_path, str_img_path,
                                      str_img_file + ".jpg")
        print iItem, totTODO, image_filename

        im = Image.open(image_filename)
        (img_w, img_h) = im.size
        scale = min(500.0 / img_w, 500.0 / img_h)
        dX = (500 - img_w * scale) / 2
        dY = (500 - img_h * scale) / 2
        iSqn = 1

        x_sz = x_out.createElement("size")
        xadd(x_out, x_sz, "width", "%d" % img_w)
        xadd(x_out, x_sz, "height", "%d" % img_h)
        x_ann.appendChild(x_sz)

        for o in object_tags:
            object_name = xget_v(o, "name")
            if not object_name:
                continue
            object_name = object_name.strip()
            #print o.toxml();
            polygon = xget(o, "polygon")[0]
            points = xget(polygon, "pt")
            points_new = []
            for pt in points:
                x = float(xget_v(pt, "x"))
                y = float(xget_v(pt, "y"))
                points_new.append([x, y])
            (o_xmin, o_ymin) = reduce(
                lambda (x, y), (x2, y2): (min(x, x2), min(y, y2)), points_new)
            (o_xmax, o_ymax) = reduce(
                lambda (x, y), (x2, y2): (max(x, x2), max(y, y2)), points_new)
            #print object_name, o_xmin,o_ymin, o_xmax,o_ymax,type(object_name)

            xmin = float(o_xmin) * scale + dX
            xmax = float(o_xmax) * scale + dX
            ymin = float(o_ymin) * scale + dY
            ymax = float(o_ymax) * scale + dY
            w = xmax - xmin
            h = ymax - ymin
            iSqn += 1

            x_obj = x_out.createElement("bbox")
            x_obj.setAttribute(u"name", object_name)
            x_obj.setAttribute("left", "%d" % xmin)
            x_obj.setAttribute("top", "%d" % ymin)
            x_obj.setAttribute("width", "%d" % w)
            x_obj.setAttribute("height", "%d" % h)
            x_obj.setAttribute("sqn", "1")

            x_pt = x_out.createElement("pt")
            x_pt.setAttribute("x", "%d" % xmin)
            x_pt.setAttribute("y", "%d" % ymin)
            x_pt.setAttribute("ct", "0")
            x_obj.appendChild(pt)

            x_pt = x_out.createElement("pt")
            x_pt.setAttribute("x", "%d" % xmax)
            x_pt.setAttribute("y", "%d" % ymax)
            x_pt.setAttribute("ct", "0")
            x_obj.appendChild(pt)

            x_ann.appendChild(x_obj)

        x_res.appendChild(x_ann)
        x_out.appendChild(x_res)
        #print minidom.parseString(force_unicode(x_out.toxml("utf-8")))
        #print x_out.toxml("utf-8")
        #print minidom.parseString(x_out.toxml("utf-8"))
        #print "-----"
        annotation = Annotation(ref_data=dt_item,
                                annotation_type=ann_type,
                                author=request.user,
                                data=unicode(x_out.toxml("utf-8")))
        #print minidom.parseString(annotation.data);
        #print "====="

        annotation.save()
        #print minidom.parseString(annotation.data);
        a_id = annotation.id
        a_new = Annotation.objects.get(id=a_id)
        dt = a_new.data
        #print type(annotation.data)
        #print type(str(dt))
        #print str(dt)[1700:1800]
        #print annotation.data[1700:1800]
        #print minidom.parseString(str(dt)).toxml()

    resp.write("Done importing LabelMe annotations as boxes")
    return resp
Beispiel #9
0
def LogXML(logMsg, logType, nodes, fyTime=True, metric=True, names=True):
    xmlfilePath = nodes['xmlPath']
    inputFilename = nodes['filepath']
    plattype = nodes['platformtype']
    warnValue = float(nodes['warnvalue'])

    shortName = Plattypeprocess(plattype)
    if (len(shortName) == 8):
        checkVar = 'IQUAM'
    else:
        checkVar = "IQUAM-%s" % '-'.join(shortName)
    # 在内存中创建一个空的文档
    doc = minidom.Document()
    # 创建一个根节点Managers对象
    root = doc.createElement('XML')
    # 设置根节点的属性
    root.setAttribute('identify', 'QC')
    # 将根节点添加到文档对象中
    doc.appendChild(root)

    nodeOutputFiles = doc.createElement('OutputFiles')
    nodeOutputFile = doc.createElement('OutputFile')
    nodeOutputFiles.appendChild(nodeOutputFile)
    nodeInputFilename = doc.createElement('InputFilename')

    # 给叶子节点name设置一个文本节点,用于显示文本内容
    nodeInputFilename.appendChild(
        doc.createTextNode(str(os.path.basename(inputFilename))))

    if (names != True):
        nodeOutputFilename1 = doc.createElement("OutputFilename")
        nodeOutputFilename1.appendChild(
            doc.createTextNode(str(os.path.basename(names['iquamname']))))
        nodeOutputFile.appendChild(nodeOutputFilename1)

        nodeOutputFilename2 = doc.createElement("OutputFilename")
        nodeOutputFilename2.appendChild(
            doc.createTextNode(str(os.path.basename(names['scatname']))))
        nodeOutputFile.appendChild(nodeOutputFilename2)

        nodeOutputFilename3 = doc.createElement("OutputFilename")
        nodeOutputFilename3.appendChild(
            doc.createTextNode(str(os.path.basename(names['histname']))))
        nodeOutputFile.appendChild(nodeOutputFilename3)

        nodeOutputFilename4 = doc.createElement("OutputFilename")
        nodeOutputFilename4.appendChild(
            doc.createTextNode(str(os.path.basename(names['txtnamelabel']))))
        nodeOutputFile.appendChild(nodeOutputFilename4)

        nodeOutputFilename5 = doc.createElement("OutputFilename")
        nodeOutputFilename5.appendChild(
            doc.createTextNode(str(os.path.basename(names['txtname']))))
        nodeOutputFile.appendChild(nodeOutputFilename5)

        nodeDeviationstatic = doc.createElement('Deviationstatic')
        nodeDeviationstatic.setAttribute('bechekVariety', 'AHI8')
        nodeDeviationstatic.setAttribute('checkVariety', checkVar)
        nodeDeviationstatic.setAttribute('dataFormat', '15mm')
        nodeDeviationstatic.setAttribute('dataType', 'NOM')
        nodeDeviationstatic.setAttribute('productDate',
                                         fyTime.__format__('%Y%m%d%H%M%S'))
        nodeDeviationstatic.setAttribute('productVariety', 'AHI8#SST')
        metricStr = "{%s}" % re.sub(
            '[()\'\[\]]', '',
            str(metric).replace("',", ":").replace("OrderedDict", "")).replace(
                ' ', '')
        nodeDeviationstatic.setAttribute('values', metricStr)
        nodeOutputFile.appendChild(nodeDeviationstatic)

        if metric['QualID3_AE'] > warnValue:
            warntype = 1
            nodewarnType = doc.createElement("warningType")
            nodewarnType.appendChild(doc.createTextNode(str(warntype)))
            nodewarnMsg = doc.createElement("warningMsg")
            nodewarnMsg.appendChild(
                doc.createTextNode(
                    "info" if not warntype else "精度预警:AHI8 SST产品绝对偏差超过%s ℃" %
                    warnValue))

            nodewarning = doc.createElement("warning")
            nodewarning.appendChild(nodewarnType)
            nodewarning.appendChild(nodewarnMsg)
            root.appendChild(nodewarning)

    # 将各叶子节点添加到父节点OutputFilename中,
    # 最后将OutputFilename添加到根节点XML中
    nodeOutputFile.appendChild(nodeInputFilename)
    root.appendChild(nodeOutputFiles)

    nodeLog = doc.createElement('log')

    nodeLogtype = doc.createElement('logType')
    nodeLogtype.appendChild(doc.createTextNode(str(logType)))

    nodeLogmsg = doc.createElement('logMsg')
    nodeLogmsg.appendChild(doc.createTextNode(str(logMsg)))
    nodeLog.appendChild(nodeLogtype)
    nodeLog.appendChild(nodeLogmsg)
    root.appendChild(nodeLog)

    # 开始写xml文档
    fp = open(xmlfilePath, 'w')
    doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
    fp.close()
Beispiel #10
0
        def make_response(stuff):
            images, total = stuff

            # figure the total number of pages for the algebra noobs at Qoop. WTF?
            total_pages = int(floor(total / per_page))
            if (total % per_page): total_pages += 1

            doc = minidom.Document()
            answer = doc.createElement('answer')
            answer.setAttribute('status', 'ok')
            doc.appendChild(answer)
            photo_list = doc.createElement('photolist')
            photo_list.setAttribute('total_photos', "%s" % total)
            photo_list.setAttribute('page_number', str(page_number))
            photo_list.setAttribute('per_page', str(per_page))
            photo_list.setAttribute('total_pages', str(total_pages))
            photo_list.setAttribute('owner_id', browse)
            answer.appendChild(photo_list)

            for img in images:
                img_node = doc.createElement('photo')
                img_node.setAttribute('id', "%s" % img['image_id'])
                img_node.setAttribute('orig_format', 'jpg')
                if img['date']:
                    img_node.setAttribute('taken',
                                          img['date'].strftime("%Y-%m-%d"))
                if img['date_uploaded']:
                    img_node.setAttribute(
                        'upload', img['date_uploaded'].strftime("%Y-%m-%d"))

                title = doc.createElement('title')
                title.appendChild(doc.createTextNode(img['title']))
                desc = doc.createElement('description')
                desc.appendChild(doc.createTextNode(img['description']))
                orig_link = doc.createElement('original')
                if img.has_key('original_x'):
                    orig_link.setAttribute('x', str(img['original_x']))
                if img.has_key('original_y'):
                    orig_link.setAttribute('y', str(img['original_y']))
                orig_link.appendChild(
                    doc.createTextNode(self.image_url %
                                       (browse, "original", img['image_id'])))

                img_node.appendChild(title)
                img_node.appendChild(desc)
                img_node.appendChild(orig_link)

                if img.has_key('rendered_sizes'):
                    size_nodes = {}
                    for k, v in img['rendered_sizes'].items():
                        size_nodes[k] = doc.createElement(k)
                        size_nodes[k].setAttribute('x', str(v['x']))
                        size_nodes[k].setAttribute('y', str(v['y']))
                        size_nodes[k].appendChild(
                            doc.createTextNode(
                                self.image_url %
                                (browse, v['code'], img['image_id'])))
                        img_node.appendChild(size_nodes[k])

                photo_list.appendChild(img_node)

            xml = doc.toprettyxml()
            doc.unlink()
            return xml
Beispiel #11
0
import xml.etree.ElementTree as etree
import xml.dom.minidom as doc
import numpy as np
import string, re, os

if __name__ == '__main__':
    dataCollectionPoints = doc.Document()
    root = dataCollectionPoints.createElement('dataCollectionPoints')
    dataCollectionPoints.appendChild(root)

    dataCollectionMeasurements = doc.Document()
    rootMeasurement = dataCollectionMeasurements.createElement(
        'dataCollectionMeasurements')
    dataCollectionMeasurements.appendChild(rootMeasurement)

    inp = open(r"D:\Journal_paper\STPM\Caohejing_vissim\Caohejing_STPM.inp",
               'r')
    IsThisPoint = 0
    counter = 0
    for line in inp.readlines():
        if line.startswith('COLLECTION_POINT'):
            IsThisPoint = 1
            line0 = line.split()
            dataCollectionPoint = dataCollectionPoints.createElement(
                'dataCollectionPoint')
            dataCollectionPoint.setAttribute('name',
                                             line0[3][1:len(line0[3]) - 1])
            dataCollectionPoint.setAttribute('no', line0[1])

        if line.startswith('     POSITION LINK') and IsThisPoint == 1:
            line0 = line.split()
Beispiel #12
0
def make_xml(u_list,p_list,xml_f):
    doc = Dom.Document()  
    root_node = doc.createElement("Root")  
    for r_name in g_config.get_option("root"):
        r_value = g_config.get_str_para("root", r_name)
        root_node.setAttribute(r_name, r_value)
    
    
    doc.appendChild(root_node)  
    users_node = doc.createElement("users")  
    root_node.appendChild(users_node)
    
    for user_p in u_list:
        users_name_node = doc.createElement("user")  
        for s_name_ini in g_config.get_option("user"):
            s_value_ini = g_config.get_str_para("user", s_name_ini)
            users_name_node.setAttribute(s_name_ini, s_value_ini)

        user_para = user_p.get_user_attr()
        if user_para is not None:
            for u_key in user_para.keys():
                users_name_node.setAttribute(u_key, user_para[u_key])
    
        users_node.appendChild(users_name_node)
        
        scripts_node = doc.createElement("Scripts")  
        users_name_node.appendChild(scripts_node)
        
        scripts_name_node = doc.createElement("Script")  
        for s_name_ini in g_config.get_option("Script"):
            s_value_ini = g_config.get_str_para("Script", s_name_ini)
            scripts_name_node.setAttribute(s_name_ini, s_value_ini)

        script_para = user_p.get_script_attr()
        if script_para is not None:
            for u_key in script_para.keys():
                scripts_name_node.setAttribute(u_key, script_para[u_key])
        
        scripts_node.appendChild(scripts_name_node)
        
        
        codes_node = doc.createElement("codes")  
        scripts_name_node.appendChild(codes_node)
        
        codes_name_node = doc.createElement("code")  
        for s_name_ini in g_config.get_option("code"):
            s_value_ini = g_config.get_str_para("code", s_name_ini)
            codes_name_node.setAttribute(s_name_ini, s_value_ini)

        code_para = user_p.get_code_attr()
        if code_para is not None:
            for u_key in code_para.keys():
                codes_name_node.setAttribute(u_key, code_para[u_key])
        
        codes_node.appendChild(codes_name_node)
        
        scriptparams_node = doc.createElement("scriptparams")  
        scripts_name_node.appendChild(scriptparams_node)
        
        para_para = user_p.get_scriptparam_attr()
        #  待修改
        for p_key in para_para:
            scriptparams_name_node = doc.createElement("scriptparam")
            p_dict = para_para[p_key]
            if p_dict is not None:
                for u_key in p_dict.keys():
                    scriptparams_name_node.setAttribute(u_key, p_dict[u_key])
            scriptparams_node.appendChild(scriptparams_name_node)
        

    f = open(xml_f, "w")  
    f.write(doc.toprettyxml(indent = "\t", newl = "\n", encoding = "utf-8"))  
    f.close() 
    print "ok"   
    pass        
Beispiel #13
0
# NetRoot = doc4.getroot()
# doc5 = etree.parse('D:\\Journal_paper\\hierarchical control based on Markov decision process and path-based signal control\\simulation\\TLSconnections.xml')
# PhaseRoot = doc5.getroot()

doc1 = etree.parse('./TLSAction1.xml')
ActionRoot = doc1.getroot()
doc2 = etree.parse('./Chj_final.rou.xml')
RouteRoot = doc2.getroot()
doc3 = etree.parse('./loops_ctrl.xml')
LoopsRoot = doc3.getroot()
doc4 = etree.parse('./Chj_ctrl.net.xml')
NetRoot = doc4.getroot()
doc5 = etree.parse('./TLSconnections.xml')
PhaseRoot = doc5.getroot()

VehNum_files = doc.Document()
VehNum = VehNum_files.createElement('VehicleNumber')
VehNum_files.appendChild(VehNum)

#### parameters
Tsim = 3600
Tc = 60
Tu = 3  ## upper level control cycle
tc = 6  ## lower level control cycle
period = 10  ##seconds
Veh_L = 7

###### all the links in the network--------------- RegionID+EdgeID
AllEdgesList = []
for edge in NetRoot.findall('edge'):
    new_EdgeID = edge.get('Region') + edge.get('id')
Beispiel #14
0
def main():
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies
	useCookies = 1
	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			loginResult = cookies['loginAttempt'].value
		except KeyError:
			loginResult = 'success'
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
	else:
		currentUser = ''
		loginResult = 'success'
		sid = form.getfirst('gh_sid', '')

	# Get form info
	schematic = form.getfirst("schematic", "")
	recipeName = form.getfirst("recipeName", "")
	recipeID = form.getfirst("recipeID", "")
	ingredients = form.getfirst("ingredients", "")
	operation = form.getfirst("op", "")
	spawnID = form.getfirst("spawnID", "")
	galaxy = form.getfirst("galaxy", "")
	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)
	schematic = dbShared.dbInsertSafe(schematic)
	recipeName = dbShared.dbInsertSafe(recipeName)
	recipeID = dbShared.dbInsertSafe(recipeID)
	ingredients = dbShared.dbInsertSafe(ingredients)
	spawnID = dbShared.dbInsertSafe(spawnID)
	galaxy = dbShared.dbInsertSafe(galaxy)

	result = ""
	# Get a session
	logged_state = 0

	sess = dbSession.getSession(sid, 2592000)
	if (sess != ''):
		logged_state = 1
		currentUser = sess

	#  Check for errors
	errstr = ""
	if recipeName == "" and operation == "":
		errstr = "Error: You must provide a name for the recipe."
	if schematic == "" and recipeID == "":
		errstr = "Error: You must select a schematic to base the recipe on."
	if logged_state != 1:
		errstr = "Error: You must be logged in to do that."
	if galaxy == "" and schematic != "":
		errstr = "Error: You must select a galaxy before creating a recipe."

	# Only process if no errors
	if (errstr == ""):
		result = ""
		if (logged_state > 0):
			conn = dbShared.ghConn()
			if schematic == "":
				#  Make sure user owns recipe
				chkcursor = conn.cursor()
				tempSQL = "".join(("SELECT userID, schematicID FROM tRecipe WHERE recipeID=", recipeID, " AND userID='", currentUser, "';"))
				chkcursor.execute(tempSQL)
				row = chkcursor.fetchone()
				if row != None:
					if operation == "delete":
						result = deleteRecipe(conn, recipeID, currentUser)
					elif operation == "addspawn":
						result = addIngredient(conn, recipeID, spawnID, row[1], currentUser)
					else:
						result = updateRecipe(conn, recipeID, recipeName)
						if ingredients != "":
							result += updateIngredients(conn, recipeID, ingredients, row[1], currentUser)
				else:
					result = "Error: That recipe does not exist or is not yours."
				chkcursor.close()
			else:
				result = addRecipe(conn, schematic, recipeName, currentUser, galaxy)
				tmpPos = result.find("ID")
				# Save and strip ID on successful add
				if tmpPos > -1:
					recipeID = result[tmpPos+2:]
					result = result[:tmpPos]
				# Update ingredients if they were provided (saving suggestion)
				if ingredients != '':
					result += updateIngredients(conn, recipeID, ingredients, schematic, currentUser)
			conn.close()
		else:
			result = "Error: must be logged in to do that."
	else:
		result = errstr

	print 'Content-type: text/xml\n'
	doc = minidom.Document()
	eRoot = doc.createElement("result")
	doc.appendChild(eRoot)

	eName = doc.createElement("recipeID")
	tName = doc.createTextNode(str(recipeID))
	eName.appendChild(tName)
	eRoot.appendChild(eName)
	eText = doc.createElement("resultText")
	tText = doc.createTextNode(result)
	eText.appendChild(tText)
	eRoot.appendChild(eText)
	print doc.toxml()

	if (result.find("Error:") > -1):
		sys.exit(500)
	else:
		sys.exit(200)
Beispiel #15
0
    def XMLFileSave(self):
        global wireCount, componentCount

        allComponents = self.scene.items()
        totalComponents = wireCount + componentCount

        root = minidom.Document()
        xml = root.createElement('circuit')
        root.appendChild(xml)

        if componentCount != 0 and wireCount != 0:

            for QtGui.QGraphicsProxyWidget in allComponents[
                    wireCount:totalComponents]:
                ComponentWidget = QtGui.QGraphicsProxyWidget.widget()
                if ComponentWidget.componentType == "Ground":
                    node1 = ((QtGui.QGraphicsProxyWidget.pos().x() + 88),
                             (QtGui.QGraphicsProxyWidget.pos().y()))
                    node2 = ''

                elif ComponentWidget.rotated == True:
                    node1 = ((QtGui.QGraphicsProxyWidget.pos().x() - 49),
                             (QtGui.QGraphicsProxyWidget.pos().y()))
                    node2 = ((QtGui.QGraphicsProxyWidget.pos().x() - 49),
                             (QtGui.QGraphicsProxyWidget.pos().y() + 176))

                else:
                    node1 = (QtGui.QGraphicsProxyWidget.pos().x(),
                             (QtGui.QGraphicsProxyWidget.pos().y() + 49))
                    node2 = ((QtGui.QGraphicsProxyWidget.pos().x() + 176),
                             (QtGui.QGraphicsProxyWidget.pos().y() + 49))

                xmlcomponents = root.createElement('Component')
                xmlcomponents.setAttribute('type',
                                           ComponentWidget.componentType)
                xmlcomponents.setAttribute('value', str(ComponentWidget.value))
                xmlcomponents.setAttribute('metricPrefix',
                                           str(ComponentWidget.unit))
                xmlcomponents.setAttribute('name', str(ComponentWidget.name))
                xmlcomponents.setAttribute('rotated',
                                           str(ComponentWidget.rotated))
                xmlcomponents.setAttribute('DialogIndex',
                                           str(ComponentWidget.comboBoxIndex))
                xml.appendChild(xmlcomponents)

                componentNode1 = root.createElement("Node")
                componentNode1.appendChild(root.createTextNode(str(node1)))
                xmlcomponents.appendChild(componentNode1)

                componentNode2 = root.createElement("Node")
                componentNode2.appendChild(root.createTextNode(str(node2)))
                xmlcomponents.appendChild(componentNode2)

            for wires in allComponents[0:wireCount]:
                WirePos = wires.line()
                WirePos = str(WirePos)
                stringLength = len(WirePos) - 1
                wire = WirePos[20:stringLength]

                xmlwire = root.createElement('wire')
                xml.appendChild(xmlwire)

                wirePos = root.createElement('wirePos')
                wirePos.appendChild(root.createTextNode(wire))
                xmlwire.appendChild(wirePos)

            xmlStr = root.toprettyxml(indent='\t')

            try:
                if self.sender() == self.actionSaveAs:
                    self.savePathFile = self.fileName + ".xml"

                elif self.sender() == self.actionSave_2:
                    self.savePathFile = self.fileName

                with open(self.savePathFile, 'w') as f:
                    f.write(xmlStr)
                    self.statusbar.showMessage("Circuit Saved to XML File",
                                               msecs=3000)
                    fileSaved = True

            except Exception as err:
                self.statusbar.setStyleSheet(
                    "QStatusBar{padding-left:8px;background:rgba(255,0,0,255);color:black;font-weight:bold;}"
                )
                self.statusbar.showMessage(
                    "Error: XML File does not exist! : Use Save As",
                    msecs=4000)

        elif componentCount == 0:
            self.statusbar.setStyleSheet(
                "QStatusBar{padding-left:8px;background:rgba(255,0,0,255);color:black;font-weight:bold;}"
            )
            self.statusbar.showMessage("Error: No Components Added!",
                                       msecs=1600)

        elif wireCount == 0:
            self.statusbar.setStyleSheet(
                "QStatusBar{padding-left:8px;background:rgba(255,0,0,255);color:black;font-weight:bold;}"
            )
            self.statusbar.showMessage("Error: No Wires Added!", msecs=1600)
Beispiel #16
0
 def test_xml_element(self):
     doc = minidom.Document()
     connectivity_element = self.connectivity.xml_element(doc)
     self.assertEqual(connectivity_element.tagName, "connectivity")
     for attribute in ("cf_role", "start_index", "location_axis"):
         self.assertIn(attribute, connectivity_element.attributes)
Beispiel #17
0
def output():
    result = None

    check_tane = ""

    rootdir = application.config['upload_data']
    filelist = os.listdir(rootdir)
    num_ontologies = 0
    for f in filelist:
        filepath = os.path.join(rootdir, f)
        os.remove(filepath)

    if (request.method == 'POST'):

        doc = minidom.Document()
        doc.appendChild(doc.createComment("This is a simple xml."))
        config_list = doc.createElement("Config")
        doc.appendChild(config_list)
        data = doc.createElement("data")
        path = doc.createElement("path")
        numberofColumns = doc.createElement("numberOfColumns")
        dataset = request.form['dataset']
        session['example'] = dataset

        ontology_name_list = request.form['test'].split("*")

        del (ontology_name_list[len(ontology_name_list) - 1])

        if session['example'] == 'upload':

            ontology_file = request.files['upload_data']
            ontology_file.save(
                os.path.join(application.config['upload_data'], 'data.csv'))
            for ontology in ontology_name_list:
                ontology_file = request.files[ontology + '_upload_rdf']
                print(ontology_file)
                ontology_file.save(
                    os.path.join(application.config['upload_data'],
                                 ontology + '.rdf'))

        data_path = "experiment//" + session['example'] + "//data//data.csv"
        path.appendChild(doc.createTextNode(data_path))
        number_Columns = str(
            post_data_info(application, dataset, 'data.csv')[2] - 1)
        numberofColumns.appendChild(doc.createTextNode(number_Columns))
        data.appendChild(path)
        data.appendChild(numberofColumns)
        config_list.appendChild(data)
        algorithm = request.form['algorithm']
        # print(algorithm)
        threshold = 1 - int(request.form['slider_threshold']) / 100
        # print(threshold)

        checka = request.form['checka']
        # print(checka)

        fastofd = doc.createElement("FastOFD")
        synofd = doc.createElement("SynOFD")
        synaofd = doc.createElement("SynAOFD")
        isaofd = doc.createElement("IsaOFD")
        isaaofd = doc.createElement("IsaAOFD")
        isaaofd = doc.createElement("IsaAOFD")
        Tane = doc.createElement("Tane")

        if algorithm == "fastofd":
            fastofd.appendChild(doc.createTextNode("true"))
            synofd.appendChild(doc.createTextNode("true"))
            synaofd.appendChild(doc.createTextNode("true"))
            isaofd.appendChild(doc.createTextNode("true"))
            isaaofd.appendChild(doc.createTextNode("true"))
            Tane.appendChild(doc.createTextNode("false"))

        if algorithm == "tane":
            fastofd.appendChild(doc.createTextNode("false"))
            synofd.appendChild(doc.createTextNode("false"))
            synaofd.appendChild(doc.createTextNode("false"))
            isaofd.appendChild(doc.createTextNode("false"))
            isaaofd.appendChild(doc.createTextNode("false"))
            Tane.appendChild(doc.createTextNode("true"))
            check_tane = "is_tane"

        if algorithm == "synonymofd":

            fastofd.appendChild(doc.createTextNode("false"))
            synofd.appendChild(doc.createTextNode("true"))
            if checka == "1":
                synaofd.appendChild(doc.createTextNode("true"))
            if checka == "0":
                synaofd.appendChild(doc.createTextNode("false"))

            isaofd.appendChild(doc.createTextNode("false"))
            isaaofd.appendChild(doc.createTextNode("false"))
            Tane.appendChild(doc.createTextNode("false"))

        if algorithm == "inheritanceofd":

            fastofd.appendChild(doc.createTextNode("false"))
            synofd.appendChild(doc.createTextNode("false"))
            synaofd.appendChild(doc.createTextNode("false"))
            isaofd.appendChild(doc.createTextNode("true"))
            if checka == "1":
                isaaofd.appendChild(doc.createTextNode("true"))
            if checka == "0":
                isaaofd.appendChild(doc.createTextNode("false"))
            Tane.appendChild(doc.createTextNode("false"))

        data.appendChild(fastofd)
        data.appendChild(synofd)
        data.appendChild(synaofd)
        data.appendChild(isaofd)
        data.appendChild(isaaofd)
        data.appendChild(Tane)

        num_ontologies = len(ontology_name_list)

        for ontology in ontology_name_list:

            ontology_node = doc.createElement("ontology")
            name = doc.createElement("name")
            threshold_node = doc.createElement("threshold")
            path_node = doc.createElement("path")

            on_path = "experiment//" + session[
                'example'] + "//data//" + ontology + ".rdf"
            path_node.appendChild(doc.createTextNode(on_path))
            type_node = doc.createElement("type")
            sense_node = doc.createElement("sense")
            class_node = doc.createElement("class")

            ontology_sense = request.form[ontology + "_sense"]
            sense_node.appendChild(doc.createTextNode(ontology_sense))
            # print(ontology_sense)

            ontology_type = request.form[ontology + "_kind_type"]
            if ontology_type == "syn":
                class_node.appendChild(doc.createTextNode("syn"))
            if ontology_type == "inh":
                class_node.appendChild(doc.createTextNode("isa"))

                inh_threshold_node = doc.createElement("isathreshold")
                ontology_inh_threshold = request.form[ontology +
                                                      "_inh_threshold"]
                inh_threshold_node.appendChild(
                    doc.createTextNode(ontology_inh_threshold))
                # print(ontology_inh_threshold)
                ontology_node.appendChild(inh_threshold_node)

            # print(ontology_type)

            type_node.appendChild(doc.createTextNode("Minimum_Error"))

            threshold_node.appendChild(doc.createTextNode(str(threshold)))

            if (session['example'] == 'example_2'):
                name.appendChild(doc.createTextNode('native-country'))

            if (session['example'] == 'example_3'):
                name.appendChild(doc.createTextNode('Province'))

            if (session['example'] == 'example_1'):

                if (ontology == 'UN'):
                    name.appendChild(doc.createTextNode('countrycode'))
                if (ontology == 'ISO'):
                    name.appendChild(doc.createTextNode('countrycode'))
                if (ontology == 'disease'):
                    if (ontology_type == 'syn'):
                        name.appendChild(doc.createTextNode('disease'))
                    else:
                        name.appendChild(doc.createTextNode('disease'))
                if (ontology == 'medicine-EU'):
                    name.appendChild(doc.createTextNode('medicine'))
                if (ontology == 'medicine-US'):
                    name.appendChild(doc.createTextNode('medicin'))
            if (session['example'] == 'upload'):
                name.appendChild(
                    doc.createTextNode(request.form[ontology + "_attribute"]))

            ontology_node.appendChild(name)
            ontology_node.appendChild(threshold_node)
            ontology_node.appendChild(path_node)
            ontology_node.appendChild(type_node)
            ontology_node.appendChild(sense_node)
            ontology_node.appendChild(class_node)
            config_list.appendChild(ontology_node)

        f = open('conf.xml', 'w')
        doc.writexml(f, indent='\t', newl='\n', addindent='\t')
        f.close()

    file_object = open('running.bat', 'w')
    test = "java -version \n"
    # state = "java -jar OFD.jar \"conf.xml\" \"experiment/" + session['example'] + "/detail/\""
    state = "/usr/java/jdk1.8.0_151/bin/java -jar OFD.jar \"conf.xml\" \"experiment/" + session[
        'example'] + "/detail/\""
    file_object.write(test)
    file_object.write(state)
    file_object.close()

    # //////////////////////////////////////////////////////////////////////
    #  PROBLEMS WHEN RUNNING JAVA

    basedir = os.path.abspath(os.path.dirname(__file__))

    bat_path = os.path.join(basedir, 'running.bat')

    print(bat_path)

    if os.path.isfile(bat_path):
        os.system(bat_path)

    # //////////////////////////////////////////////////////////////////////////

    a = 0

    rootdir = application.config[session["example"]]
    data_dir = os.path.join(rootdir, 'detail')
    filelist = os.listdir(data_dir)
    for f in filelist:
        a = a + 1

    if (a == 0):
        example_data_info_1 = post_data_info(application, "example_1",
                                             "data.csv")
        example_data_info_2 = post_data_info(application, "example_2",
                                             "data.csv")
        example_data_info_3 = post_data_info(application, "example_3",
                                             "data.csv")
        result = {
            'example_1': {
                'ATTRIBUTES': example_data_info_1[3],
                'ONTOLOGY':
                ['UN', 'disease', 'medicine-US', 'medicine-EU', 'ISO']
            },
            'example_2': {
                'ATTRIBUTES': example_data_info_2[3],
                'ONTOLOGY': ['Abbreviation:native-country']
            },
            'example_3': {
                'ATTRIBUTES': example_data_info_3[3],
                'ONTOLOGY': ['Abbreviation:Province']
            },
            'error_report': {
                'TYPE':
                "1",
                'MESSAGE':
                " There are errors of setting ontology parameters, please set them again!"
            }
        }
        result = json.dumps(result)

        return render_template("input.html", result=result)

    experiment = session["example"]
    data_name = ""
    if experiment == "example_1":
        data_name = "Clinical"
    if experiment == "example_2":
        data_name = "Census"
    if experiment == "example_3":
        data_name = "Pollution"
    if experiment == "upload":
        data_name = "Uploaded Data"

    data_info = post_data_info(application, experiment, "data.csv")

    num_d = get_num_d(application, experiment)
    num_fd = num_d[0]
    num_syn_ofd = num_d[1]
    num_inh_ofd = num_d[2]

    running_time = num_d[3].split('(ms)')[0] + ' ms'
    ofds = get_ds(application, experiment)

    if check_tane == "is_tane":
        result = {
            'DATA_NAME': data_name,
            'RUNNING_TIME': running_time,
            'NUM_ROW': data_info[1] * 10,
            'NUM_COL': data_info[2],
            'NUM_FD': num_fd,
            'FD_LIST': ofds[0]
        }
        result = json.dumps(result)

        return render_template("tane_rsl.html", result=result)

    else:

        aofds_tmp = get_aofds(application, experiment)

        num_syn_aofd = len(aofds_tmp[1])
        num_inh_aofd = len(aofds_tmp[0])

        # # small -> big
        syn_aofd = aofds_tmp[1]
        # syn_aofd.sort(key=lambda x: x["ERROR_RATE"],reverse=True)
        inh_aofd = aofds_tmp[0]
        # inh_aofd.sort(key=lambda x: x["ERROR_RATE"],reverse=True)
        # aofds = []
        # aofds.append(syn_aofd)
        # aofds.append(inh_aofd)

        hierachy_isa = aofds_tmp[3]
        hierachy_syn = aofds_tmp[4]

        syn_aofd_dict = aofd_dict(syn_aofd)
        inh_aofd_dict = aofd_dict(inh_aofd)

        sort_hierachy(hierachy_syn, syn_aofd_dict)

        sort_hierachy(hierachy_isa, inh_aofd_dict)

        aofds_dict = [syn_aofd_dict, inh_aofd_dict]

        hierachy = [hierachy_syn, hierachy_isa]

        result = {
            'DATA_NAME': data_name,
            'RUNNING_TIME': running_time,
            'NUM_ROW': data_info[1] * 10,
            'NUM_COL': data_info[2],
            'ATTRIBUTES': data_info[3],
            'NUM_FD': num_fd,
            'NUM_SYN_OFD': num_syn_ofd,
            'NUM_INH_OFD': num_inh_ofd,
            'NUM_SYN_AOFD': num_syn_aofd,
            'NUM_INH_AOFD': num_inh_aofd,
            'NUM_ONTOLOGIES': num_ontologies,
            'OFD': ofds,
            # 'AOFD': aofds,
            'AOFDS_DICT': aofds_dict,
            'HIERACHY': hierachy
        }

        result = json.dumps(result)

        return render_template("output2.html", result=result)
def extractSolution(outpString):
    """
    This function extracts the solution of a free algebra Groebner basis
    computation performed in Singular, using the executable code that was
    generated by the template in the same folder on a certain
    instance.

    It returns a string representation of the solution in XML-format.
    The XML-string will be given as follows::

      <FA_Q_dp_SOL>
        <basis>
          <polynomial>
            generator_1
          </polynomial>
          <polynomial>
            generator_2
          </polynomial>
          ...
        </basis>
        <originalGenerators>
          <polynomial>
            generator_1
          </polynomial>
          <polynomial>
            generator_2
          </polynomial>
          ...
        </originalGenerators>
        <variables>
          <variable>
            variable_1
          </variable>
          <variable>
            variable_2
          </variable>
          ...
        </variables>
        <upToDeg>
          deg
        </upToDeg>
        
      </FA_Q_dp_SOL>

    Note that everything except from the basis-tag is optional,
    i.e. it is not necessarily appearing in the XML-file.

    If there is no solution given, or something is wrong with the given string,
    a ValueError is raised.

    :param outpString: The String that was returned by the Singular-execution
    :type  outpString: str
    :returns: XML-Representation of the solution.
    :rtype: str
    :raises: ValueError
    """
    if (type(outpString) != str):
        raise ValueError("Wrong Type of argument. String type expected.")
    solBeginStr = "=====Solution Begin====="
    solEndStr = "=====Solution End====="
    solBeginPos = outpString.index(solBeginStr) + len(solBeginStr)
    solEndStrPos = outpString.index(solEndStr)
    solStr = outpString[solBeginPos:solEndStrPos]
    if (solStr.strip() == ""):
        raise ValueError("There is no solution to be found in the output-file")
    faGBSol = solStr.split(',')
    faGBSol = map(lambda x: convertFromLetterplace(x.strip()), faGBSol)
    originalGenerators = []  #TODO placeholder
    variables = []  #TODO placeholder
    upToDeg = 0  #TODO placeholder
    #From here on, we can assume that we are dealing with a valid
    #string.
    #Construction of the XML-Document
    result = dom.Document()
    result.appendChild(result.createElement("FA_Q_dp_SOL"))
    tempNode = result.firstChild
    #Adding the basis
    tempNodeFABasis = tempNode.appendChild(result.createElement("basis"))
    for b in faGBSol:
        tempPolyNode =\
            tempNodeFABasis.appendChild(result.createElement("polynomial"))
        tempPolyNode.appendChild(result.createTextNode(b))
    #Adding the original generators list, if existent
    if (len(originalGenerators) > 0):
        tempNodeOrigGen = tempNode.appendChild(
            result.createElement("originalGenerators"))
        for b in originalGenerators:
            tempPolyNode =\
                tempNodeOrigGen.appendChild(result.createElement("polynomial"))
            tempPolyNode.appendChild(result.createTextNode(b))
    #Adding the variables, if existent
    if (len(variables) > 0):
        tempNodeVariables =\
    tempNode.appendChild(result.createElement("variables"))
        for b in variables:
            tempVarNode =\
                tempNodeVariables.appendChild(result.createElement("variable"))
            tempVarNode.appendChild(result.createTextNode(b))
    #Adding upToDeg, if positive
    if (upToDeg):
        tempNodeUpToDeg =\
            tempNode.appendChild(result.createElement("upToDeg"))
        tempNodeUpToDeg.appendChild(result.createTextNode(str(upToDeg)))
    return result.toprettyxml("  ")
Beispiel #19
0
 def show(self, server_dict):
     xml_doc = minidom.Document()
     node = self._server_to_xml_detailed(xml_doc, server_dict['server'])
     return self.to_xml_string(node, True)
Beispiel #20
0
def writeKodiConfigs(currentControllers):
    kodihatspositions    = {1: 'up', 2: 'right', 4: 'down', 8: 'left'}
    kodireversepositions = {'joystick1up': 'joystick1down', 'joystick1left': 'joystick1right', 'joystick2up': 'joystick2down', 'joystick2left': 'joystick2right' }
    kodiaxes             = { 'joystick1up': True, 'joystick1down': True, 'joystick1left': True, 'joystick1right': True,
                             'joystick2up': True, 'joystick2down': True, 'joystick2left': True, 'joystick2right': True }

    kodimapping = {
        # buttons
        "a": "b", "b": "a", "x": "y", "y": "x",
        "hotkey": "guide", "select": "back", "start": "start",
        "pageup": "leftbumper", "l2": "lefttrigger", "pagedown": "rightbumper", "r2": "righttrigger",

        # hats or axis
        "up": "up", "down": "down", "left": "left", "right": "right",

        # axes
        "joystick1up":    { "name": "leftstick",  "sens": "up"    },
        "joystick1down":  { "name": "leftstick",  "sens": "down"  },
        "joystick1left":  { "name": "leftstick",  "sens": "left"  },
        "joystick1right": { "name": "leftstick",  "sens": "right" },
        "joystick2up":    { "name": "rightstick", "sens": "up"    },
        "joystick2down":  { "name": "rightstick", "sens": "down"  },
        "joystick2left":  { "name": "rightstick", "sens": "left"  },
        "joystick2right": { "name": "rightstick", "sens": "right" }
    }

    controllersDone = {}

    for controller in currentControllers:
        cur = currentControllers[controller]

        # initialized the file
        kodiJoy = open(batoceraFiles.kodiJoystick.format(cur.guid), "w")
        # TODO: python 3 - workawround to encode files in utf-8
        kodiJoy = codecs.open(batoceraFiles.kodiJoystick.format(cur.guid), "w", "utf-8")
        config = minidom.Document()
        xmlbuttonmap = config.createElement('buttonmap')
        config.appendChild(xmlbuttonmap)

        # skip duplicates
        if cur.configName in controllersDone:
            break;
        else:
            controllersDone[cur.configName] = True

        xmldevice = config.createElement('device')
        xmldevice.attributes["name"] = cur.configName
        xmldevice.attributes["provider"] = "linux"
        xmldevice.attributes["buttoncount"] = cur.nbbuttons
        xmldevice.attributes["axiscount"] = str(2*int(cur.nbhats) + int(cur.nbaxes))
        xmlbuttonmap.appendChild(xmldevice)
        xmlcontroller = config.createElement('controller')
        xmlcontroller.attributes["id"] = "game.controller.default"

        sticksNode = {}

        for x in cur.inputs:
            input = cur.inputs[x]
            if input.name in kodimapping:
                    if input.type == 'button':
                        xmlbutton = config.createElement('feature')
                        xmlbutton.attributes["name"] = kodimapping[input.name]
                        xmlbutton.attributes["button"] = str(int(input.id))
                        xmlcontroller.appendChild(xmlbutton)

                    elif input.type == 'hat' and int(input.value) in kodihatspositions:
                        xmlhat = config.createElement('feature')
                        val = ""
                        if kodihatspositions[int(input.value)] == "left" or kodihatspositions[int(input.value)] == "right":
                            val = cur.nbaxes
                        else:
                            val = str(int(cur.nbaxes)+1)
                        if kodihatspositions[int(input.value)] == "down" or kodihatspositions[int(input.value)] == "right":
                            xmlhat.attributes["axis"] = "+" + val
                        else:
                            xmlhat.attributes["axis"] = "-" + val
                        xmlhat.attributes["name"] = kodihatspositions[int(input.value)]
                        xmlcontroller.appendChild(xmlhat)

                    elif input.type == 'axis' and input.name in kodiaxes:
                        if kodimapping[input.name]["name"] not in sticksNode:
                            sticksNode[kodimapping[input.name]["name"]] = config.createElement('feature')
                            sticksNode[kodimapping[input.name]["name"]].attributes["name"] = kodimapping[input.name]["name"]
                        for sens in [input.name, kodireversepositions[input.name]]:
                            xmlsens = config.createElement(kodimapping[sens]["sens"])
                            val = input.id
                            if (int(input.value) >= 0 and sens == input.name) or (int(input.value) < 0 and sens != input.name):
                                val =  "+" + val
                            else:
                                val =  "-" + val
                            xmlsens.attributes["axis"] = val
                            sticksNode[kodimapping[sens]["name"]].appendChild(xmlsens)
                    elif input.type == 'axis' and input.name not in kodiaxes:
                        xmlaxis = config.createElement('feature')
                        val = input.id
                        if int(input.value) >= 0:
                            val =  "+" + val
                        else:
                            val =  "-" + val
                        xmlaxis.attributes["axis"] = val
                        xmlaxis.attributes["name"] = kodimapping[input.name]
                        xmlcontroller.appendChild(xmlaxis)

        for node in sticksNode:
            xmlcontroller.appendChild(sticksNode[node])
        xmldevice.appendChild(xmlcontroller)
        kodiJoy.write(config.toprettyxml())
        kodiJoy.close()
# -*- coding: utf-8 -*-
"""

Created on Sat Jun 23 14:16:55 2018



@author: Balasubramaniam

"""

from xml.dom import minidom

#create DOM object

doc = minidom.Document()

#rootnode

rootElement = doc.createElement("Claims")
doc.appendChild(rootElement)

file = open("claimsdata.csv", "r")

for line in file:

    temp = line.split(",")

    if (temp[0] != "ClaimId"):

        #claim
    try:
        f=file(path, 'wb')
        writer = codecs.lookup(option['encoding'])[3](f)
        xmlDom.writexml(writer, encoding = option['encoding'], indent = option['indent'], \
        addindent = option['addindent'], newl = option['newl'])
        writer.close()
        return True
    except:
        print('Write xml file failed.... file:{0}'.format(path))
        return False



if __name__ == "__main__":
    # Create a xml dom
    xmlDom = minidom.Document()
    nonove = xmlDom.createElement('nonove')
    xmlDom.appendChild(nonove)

    # Generate a xml dom
    # Create child node, textnode, set attribute, appendChild
    for i in range(3):
        node = xmlDom.createElement('node')
        node.setAttribute('id', str(i))
        node.setAttribute('status', 'alive')
        textNode = xmlDom.createTextNode('node value ' + str(i))
        node.appendChild(textNode)
        nonove.appendChild(node)

    # Print xml dom
    # Print simple xml
Beispiel #23
0
def write_ofdmeta_xml(xml_path, DocID, title, Author, Subject, Abstract,
                      ModDate, DocUsage, Keywords, CustomDatas):
    impl = xml.dom.minidom.getDOMImplementation()
    doc = minidom.Document()
    dom = impl.createDocument(None, 'MetaRoot', None)
    root = dom.documentElement
    root.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema-instance")
    root.setAttribute("xs:SchemaLocation", "metadata.xsd")

    DocIDdom = dom.createElement('DocID')
    DocIDTEXT = doc.createTextNode(DocID)
    DocIDdom.appendChild(DocIDTEXT)
    root.appendChild(DocIDdom)

    titledom = dom.createElement('Title')
    TitleTEXT = doc.createTextNode(title)
    titledom.appendChild(TitleTEXT)
    root.appendChild(titledom)

    Authordom = dom.createElement('Author')
    AuthorTEXT = doc.createTextNode(Author)
    Authordom.appendChild(AuthorTEXT)
    root.appendChild(Authordom)

    Subjectdom = dom.createElement('Subject')
    SubjectTEXT = doc.createTextNode(Subject)
    Subjectdom.appendChild(SubjectTEXT)
    root.appendChild(Subjectdom)

    Abstractdom = dom.createElement('Abstract')
    AbstractTEXT = doc.createTextNode(Abstract)
    Abstractdom.appendChild(AbstractTEXT)
    root.appendChild(Abstractdom)

    ModDatedom = dom.createElement('ModDate')
    ModDateTEXT = doc.createTextNode(ModDate)
    ModDatedom.appendChild(ModDateTEXT)
    root.appendChild(ModDatedom)

    DocUsagedom = dom.createElement('DocUsage')
    DocUsageTEXT = doc.createTextNode(DocUsage)
    DocUsagedom.appendChild(DocUsageTEXT)
    root.appendChild(DocUsagedom)

    Keywordsdom = dom.createElement('Keywords')

    for Keyword in Keywords:
        Keyworddom = dom.createElement('Keyword')
        KeywordTEXT = doc.createTextNode(Keyword)
        Keyworddom.appendChild(KeywordTEXT)
        Keywordsdom.appendChild(Keyworddom)

    root.appendChild(Keywordsdom)

    CustomDatasdom = dom.createElement('CustomDatas')

    for (Customname, Customvalue) in CustomDatas.items():
        Customdom = dom.createElement('CustomData')
        CustomnameTEXT = doc.createTextNode(Customvalue)
        Customdom.appendChild(CustomnameTEXT)
        Customdom.setAttribute("Name", Customname)
        CustomDatasdom.appendChild(Customdom)

    root.appendChild(CustomDatasdom)

    f = open(xml_path, 'w')
    dom.writexml(f, addindent=' ', newl='\n', encoding='UTF-8')
    f.close()
Beispiel #24
0
import os,sys
import xml.etree.ElementTree as etree
import xml.dom.minidom as doc


Chj_net = etree.parse('D:\\Journal_paper\\hierarchical control based on Markov decision process and path-based signal control\\simulation\\Chj_ctrl.net.xml')
NetRoot = Chj_net.getroot()

loops_files = doc.Document()
addition = loops_files.createElement('additional')
loops_files.appendChild(addition)


for edge in NetRoot.findall('edge'):	
	region = edge.get('Region')
	edge_id = edge.get('id') 
	connection = edge.get('between')
	for lane in edge.findall('lane'):
		lane_id = lane.get('id')
		loop = loops_files.createElement('inductionLoop')
		loop.setAttribute('id',region+lane_id)
		if connection!=None:
			loop.setAttribute('position',connection)
		elif edge_id[0:7]=="Origion":
			loop.setAttribute('position','BoundaryIn')
		elif edge_id[0:11]=="Destination":
			loop.setAttribute('position','BoundaryOut')
		else:
			loop.setAttribute('position','Inside')
		loop.setAttribute('ForRoads',edge_id)
		loop.setAttribute('lane',lane_id)
Beispiel #25
0
 def _create_document(self):
     log.debug("Creating new updateinfo Document for %s" % self.tag)
     self.doc = minidom.Document()
     updates = self.doc.createElement('updates')
     self.doc.appendChild(updates)
Beispiel #26
0
def add_fusion_source():
    exist_source = False
    successful = False
    path_sources = xbmc.translatePath('special://userdata')
    path_sources = os.path.join(path_sources, 'sources.xml')

    #=========================================================================
    # try:
    #=========================================================================
    if os.path.exists(path_sources):
        xmldoc = minidom.parse(path_sources)
    else:
        xmldoc = minidom.Document()
        nodo_sources = xmldoc.createElement("sources")
        for type in ['programs', 'video', 'music', 'pictures', 'files', 'games']:
            nodo_type = xmldoc.createElement(type)
            element_default = xmldoc.createElement("default")
            element_default.setAttribute("pathversion", "1")
            nodo_type.appendChild(element_default)
            nodo_sources.appendChild(nodo_type)
            xmldoc.appendChild(nodo_sources)

    nodo_video = xmldoc.childNodes[0].getElementsByTagName("files")[0]
    nodos_paths = nodo_video.getElementsByTagName("path")
    list_path = []
    for path in nodos_paths:
        list_path += [path.firstChild.data]
    subfolder = 'https://repositorio.fusionorg.net/'
    if not subfolder in list_path:
        name = 'Repo FusionOrg'
        nodo_source = xmldoc.createElement("source")
        nodo_name = xmldoc.createElement("name")
        nodo_name.appendChild(xmldoc.createTextNode(name))
        nodo_source.appendChild(nodo_name)
        nodo_path = xmldoc.createElement("path")
        nodo_path.setAttribute("pathversion", "1")
        nodo_path.appendChild(xmldoc.createTextNode(subfolder))
        nodo_source.appendChild(nodo_path)
        nodo_allowsharing = xmldoc.createElement("allowsharing")
        nodo_allowsharing.appendChild(xmldoc.createTextNode('true'))
        nodo_source.appendChild(nodo_allowsharing)
        nodo_video.appendChild(nodo_source)
        successful = True
        exist_source = True
    else:
        exist_source = True

    content = '\n'.join(
        [x for x in xmldoc.toprettyxml().encode("utf-8").splitlines() if x.strip()])
    write_file(path_sources, content)

    #=========================================================================
    # except:
    #     pass
    #=========================================================================

    if successful:
        control.infoDialog(
            'Se Agrego correctamente El Repo de FusionOrg a Sources.xml')
    elif not successful and exist_source:
        control.infoDialog('El Repo de FusionOrg ya esta en las fuentes')
    elif not successful and not exist_source:
        control.infoDialog(
            'Fallo al agregar la fuente de FusionOrg a Sources.xml')
    def ToXml(self, Module):
        if self.Package:
            pass
        #
        # Create root node of module surface area
        #
        DomModule = minidom.Document().createElement('ModuleSurfaceArea')
        if Module.GetBinaryModule():
            DomModule.setAttribute('BinaryModule', 'true')

        #
        # Header
        #
        Tmp = HeaderXml()
        DomModule.appendChild(Tmp.ToXml(Module, 'Header'))
        #
        # ModuleProperties
        #
        Tmp = ModulePropertyXml()
        DomModule.appendChild(Tmp.ToXml(Module, Module.GetBootModeList(), Module.GetEventList(), Module.GetHobList(), \
                                        'ModuleProperties'))
        #
        # ClonedFrom
        #
        Tmp = ClonedFromXml()
        if Module.GetClonedFrom():
            DomModule.appendChild(
                Tmp.ToXml(Module.GetClonedFrom(), 'ClonedFrom'))
        #
        # LibraryClass
        #
        LibraryClassNode = CreateXmlElement('LibraryClassDefinitions', '', [],
                                            [])
        for LibraryClass in Module.GetLibraryClassList():
            Tmp = LibraryClassXml()
            LibraryClassNode.appendChild(
                Tmp.ToXml2(LibraryClass, 'LibraryClass'))
        DomModule.appendChild(LibraryClassNode)
        #
        # SourceFile
        #
        SourceFileNode = CreateXmlElement('SourceFiles', '', [], [])
        for SourceFile in Module.GetSourceFileList():
            Tmp = SourceFileXml()
            SourceFileNode.appendChild(Tmp.ToXml(SourceFile, 'Filename'))
        DomModule.appendChild(SourceFileNode)
        #
        # BinaryFile
        #
        BinaryFileNode = CreateXmlElement('BinaryFiles', '', [], [])
        for BinaryFile in Module.GetBinaryFileList():
            Tmp = BinaryFileXml()
            BinaryFileNode.appendChild(Tmp.ToXml(BinaryFile, 'BinaryFile'))
        DomModule.appendChild(BinaryFileNode)
        #
        # PackageDependencies
        #
        PackageDependencyNode = CreateXmlElement('PackageDependencies', '', [],
                                                 [])
        for PackageDependency in Module.GetPackageDependencyList():
            Tmp = PackageXml()
            PackageDependencyNode.appendChild(
                Tmp.ToXml(PackageDependency, 'Package'))
        DomModule.appendChild(PackageDependencyNode)

        #
        # Guid
        #
        GuidProtocolPpiNode = CreateXmlElement('Guids', '', [], [])
        for GuidProtocolPpi in Module.GetGuidList():
            Tmp = GuidXml('Module')
            GuidProtocolPpiNode.appendChild(
                Tmp.ToXml(GuidProtocolPpi, 'GuidCName'))
        DomModule.appendChild(GuidProtocolPpiNode)

        #
        # Protocol
        #
        GuidProtocolPpiNode = CreateXmlElement('Protocols', '', [], [])
        for GuidProtocolPpi in Module.GetProtocolList():
            Tmp = ProtocolXml('Module')
            GuidProtocolPpiNode.appendChild(
                Tmp.ToXml(GuidProtocolPpi, 'Protocol'))
        DomModule.appendChild(GuidProtocolPpiNode)

        #
        # Ppi
        #
        GuidProtocolPpiNode = CreateXmlElement('PPIs', '', [], [])
        for GuidProtocolPpi in Module.GetPpiList():
            Tmp = PpiXml('Module')
            GuidProtocolPpiNode.appendChild(Tmp.ToXml(GuidProtocolPpi, 'Ppi'))
        DomModule.appendChild(GuidProtocolPpiNode)
        #
        # Extern
        #
        ExternNode = CreateXmlElement('Externs', '', [], [])
        for Extern in Module.GetExternList():
            Tmp = ExternXml()
            ExternNode.appendChild(Tmp.ToXml(Extern, 'Extern'))
        DomModule.appendChild(ExternNode)
        #
        # PcdCoded
        #
        PcdEntryNode = CreateXmlElement('PcdCoded', '', [], [])
        for PcdEntry in Module.GetPcdList():
            Tmp = PcdEntryXml()
            PcdEntryNode.appendChild(Tmp.ToXml3(PcdEntry, 'PcdEntry'))
        DomModule.appendChild(PcdEntryNode)

        #
        # PeiDepex
        #
        if Module.GetPeiDepex():
            for Item in Module.GetPeiDepex():
                Tmp = DepexXml()
                DomModule.appendChild(Tmp.ToXml(Item, 'PeiDepex'))

        #
        # DxeDepex
        #
        if Module.GetDxeDepex():
            for Item in Module.GetDxeDepex():
                Tmp = DepexXml()
                DomModule.appendChild(Tmp.ToXml(Item, 'DxeDepex'))

        #
        # SmmDepex
        #
        if Module.GetSmmDepex():
            for Item in Module.GetSmmDepex():
                Tmp = DepexXml()
                DomModule.appendChild(Tmp.ToXml(Item, 'SmmDepex'))

        #
        # MiscellaneousFile
        #
        if Module.GetMiscFileList():
            Tmp = MiscellaneousFileXml()
            DomModule.appendChild(
                Tmp.ToXml(Module.GetMiscFileList()[0], 'MiscellaneousFiles'))
        #
        # UserExtensions
        #
        if Module.GetUserExtensionList():
            for UserExtension in Module.GetUserExtensionList():
                Tmp = UserExtensionsXml()
                DomModule.appendChild(
                    Tmp.ToXml(UserExtension, 'UserExtensions'))

        return DomModule
Beispiel #28
0
    def gen_xml(self, tile):
        """
        >>> from TileCache.Layer import Tile

        >>> l = ArcXML("foo", projection="fooproj")
        >>> xml = l.gen_xml(Tile(l, 0,0,0))
        >>> print xml.replace("\\n", "")
        <?xml version="1.0" encoding="UTF-8" ?><ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES><ENVELOPE minx="-180.0" miny="-90.0" maxx="0.0" maxy="90.0" /><FEATURECOORDSYS string="fooproj"/><FILTERCOORDSYS string="fooproj"/><IMAGESIZE height="256" width="256" /><LAYERLIST ><LAYERDEF id="foo" visible="true" /></LAYERLIST></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>
        >>> doc = m.parseString(xml)
        >>> feat_coord_sys = doc.getElementsByTagName("FEATURECOORDSYS")
        >>> len(feat_coord_sys)
        1
        >>> feat_coord_sys[0].getAttribute("string")
        u'fooproj'
        
        >>> l = ArcXML("foo")
        >>> xml = l.gen_xml(Tile(l, 0,0,0))
        >>> doc = m.parseString(xml)
        >>> feat_coord_sys = doc.getElementsByTagName("FEATURECOORDSYS")
        >>> len(feat_coord_sys)
        0

        >>> import os
        >>> f = open('tmp_tc_test_file', 'w')
        >>> f.write('foo<>"][')
        >>> f.close()
        >>> l = ArcXML("foo", projection="@tmp_tc_test_file")
        >>> xml = l.gen_xml(Tile(l, 0,0,0))
        >>> doc = m.parseString(xml)
        >>> feat_coord_sys = doc.getElementsByTagName("FEATURECOORDSYS")
        >>> feat_coord_sys[0].toxml()
        u'<FEATURECOORDSYS string="foo&lt;&gt;&quot;]["/>'
        >>> os.unlink("tmp_tc_test_file")

        """
        layers = []
        off_layers = []
        for layer_id in self.layers.split(","):
            if layer_id.strip():
                layers.append('<LAYERDEF id="%s" visible="true" />' % layer_id)
        for layer_id in self.off_layers.split(","):
            if layer_id.strip():
                off_layers.append(
                    '<LAYERDEF layer_id="%s" visible="false" />' % layer_id)
        bbox = tile.bounds()
        projection_text = ""
        if self.projection:
            doc = m.Document()
            feat = doc.createElement("FEATURECOORDSYS")
            feat.setAttribute("string", self.projection)
            projection_text = "%s\n%s" % (feat.toxml(), feat.toxml().replace(
                "FEATURE", "FILTER"))
        return """<?xml version="1.0" encoding="UTF-8" ?>
<ARCXML version="1.1">
<REQUEST>
<GET_IMAGE>
<PROPERTIES>
<ENVELOPE minx="%s" miny="%s" maxx="%s" maxy="%s" />
%s
<IMAGESIZE height="%s" width="%s" />
<LAYERLIST >
%s
%s
</LAYERLIST>
</PROPERTIES>
</GET_IMAGE>
</REQUEST>
</ARCXML>""" % (bbox[0],
                bbox[1], bbox[2], bbox[3], projection_text, tile.size()[0],
                tile.size()[1], "\n".join(layers), "\n".join(off_layers))
Beispiel #29
0
def save_xml(res_json,reserve_xmlpath):
    # xml_path = img_filename.replace(img_filename.split(".")[-1], "xml")

    # create a empty xml doc
    doc = XDM.Document()
    # create a root node
    root = doc.createElement("annotation")
    doc.appendChild(root)

    filenameNode = doc.createElement("filename")
    filenameNode.appendChild(doc.createTextNode(res_json["image_name"]))
    folderNode = doc.createElement("folder")
    root.appendChild(filenameNode)
    root.appendChild(folderNode)

    sourceNode = doc.createElement("source")
    sourceImageNode = doc.createElement("sourceImage")
    sourceAnnotationNode = doc.createElement("sourceAnnotation")
    sourceAnnotationNode.appendChild(doc.createTextNode("CVAT"))
    sourceNode.appendChild(sourceImageNode)
    sourceNode.appendChild(sourceAnnotationNode)
    root.appendChild(sourceNode)

    imagesizeNode = doc.createElement("imagesize")
    nrowNode = doc.createElement("nrows")
    nrowNode.appendChild(doc.createTextNode(res_json["imagesize"][0]))
    ncolsNode = doc.createElement("ncols")
    ncolsNode.appendChild(doc.createTextNode(res_json["imagesize"][1]))
    imagesizeNode.appendChild(nrowNode)
    imagesizeNode.appendChild(ncolsNode)
    root.appendChild(imagesizeNode)

    # create filename
    for i, text in enumerate(res_json["text"]):
        objectNode = doc.createElement("object")

        nameNode = doc.createElement("name")
        # nameNode.appendChild(doc.createTextNode("box"))
        nameNode.appendChild(doc.createTextNode(text['label']))

        deletedNode = doc.createElement("deleted")
        deletedNode.appendChild(doc.createTextNode("0"))

        verifiedNode = doc.createElement("verified")
        verifiedNode.appendChild(doc.createTextNode("0"))

        occludedNone = doc.createElement("occluded")
        occludedNone.appendChild(doc.createTextNode("no"))

        dateNode = doc.createElement("date")

        idNode = doc.createElement("id")
        idNode.appendChild(doc.createTextNode(str(i)))

        partsNode = doc.createElement("parts")
        haspartsNode = doc.createElement("hasparts")
        ispartof = doc.createElement("ispartof")
        partsNode.appendChild(haspartsNode)
        partsNode.appendChild(ispartof)

        typeNode = doc.createElement("type")
        typeNode.appendChild(doc.createTextNode("bounding_box"))

        polygonNode = doc.createElement("polygon")
        for j in text["pos"]:
            ptNode = doc.createElement("pt")
            xNode = doc.createElement("x")
            xNode.appendChild(doc.createTextNode(str(j[0])))
            yNode = doc.createElement("y")
            yNode.appendChild(doc.createTextNode(str(j[1])))
            ptNode.appendChild(xNode)
            ptNode.appendChild(yNode)
            polygonNode.appendChild(ptNode)


        usernameNode = doc.createElement("username")
        usernameNode.appendChild(doc.createTextNode("cvat"))
        polygonNode.appendChild(usernameNode)

        attributesNode = doc.createElement("attributes")
        attributesNode.appendChild(doc.createTextNode("text="+text["content"]+", "+"entity="+text["entity"]))

        objectNode.appendChild(nameNode)
        objectNode.appendChild(deletedNode)
        objectNode.appendChild(verifiedNode)
        objectNode.appendChild(occludedNone)
        objectNode.appendChild(dateNode)
        objectNode.appendChild(idNode)
        objectNode.appendChild(partsNode)
        objectNode.appendChild(typeNode)
        objectNode.appendChild(polygonNode)
        objectNode.appendChild(attributesNode)

        root.appendChild(objectNode)

    fp = open(os.path.join(reserve_xmlpath,res_json["image_name"][:-4]+".xml"), 'w', encoding='utf-8')
    doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
Beispiel #30
0
def outputFile(T0, tols, update):

    xml = minidom.Document()
    root = xml.createElement("ROOT")
    root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
    xml.appendChild(root)

    initUpdate = "Update"
    if (update == 0):
        initUpdate = "Init"

    root.appendChild(createXMLHeader(xml, options.run, initUpdate))

    dataSet = xml.createElement("DATA_SET")
    addDataSetFrontMatter(xml, dataSet, options.run, tols, update)

    root.appendChild(dataSet)

    currDPID = 0
    channelData = []

    for row in cursor.fetchall():
        if (update == 0):
            dataSet.appendChild(createDataNode(xml, row[1], row[2], T0,
                                               row[4]))
        else:
            if (currDPID > 0) and (currDPID != row[0]):
                writeUpdate(xml, dataSet, channelData, T0)
                currDPID = row[0]
                channelData = []
            channelData.append(row)

            ## dpchange = ToDatetime(row[3])
            ## diff = dpchange - T0
            ## lsnum = LSNum(diff,OneLS)
            ## if lsnum < 1:
            ##     lsnum = 1
            ## dataSet.appendChild(createDataNode(xml,row[1],row[2],row[3],lsnum))
    if (update != 0):
        writeUpdate(xml, dataSet, channelData, T0)

    root.appendChild(createElements(xml, options.run, options.dev))
    root.appendChild(createMaps(xml))
    outFilename = None
    print
    if (cursor.rowcount > 0):
        outFilename = options.outd + "/Hcal_DCS_Values_Run" + \
                      str(options.run) + "_" + initUpdate + ".xml"
        outf = open(outFilename, "w")
        outf.write(addStandalone(xml))
        outf.close()

        if not options.keep:
            if (os.system("zip -DjmT " + \
                          outFilename.replace(".xml", ".zip") + \
                          " " + outFilename + " >> " + logfilename + " 2>&1") == 0):
                outFilename = outFilename.replace(".xml", ".zip")
            else:
                raise "error zipping file"

    return outFilename