Exemplo n.º 1
0
    def _ep_data(self, ep_obj):
        """
        Creates an elementTree XML structure for a WDTV style episode.xml
        and returns the resulting data object.

        ep_obj: a TVShow instance to create the NFO for
        """

        eps_to_write = [ep_obj] + ep_obj.relatedEps

        indexer_lang = ep_obj.show.lang

        try:
            lINDEXER_API_PARMS = srIndexerApi(ep_obj.show.indexer).api_params.copy()

            lINDEXER_API_PARMS['actors'] = True

            if indexer_lang and not indexer_lang == sickrage.srCore.srConfig.INDEXER_DEFAULT_LANGUAGE:
                lINDEXER_API_PARMS['language'] = indexer_lang

            if ep_obj.show.dvdorder != 0:
                lINDEXER_API_PARMS['dvdorder'] = True

            t = srIndexerApi(ep_obj.show.indexer).indexer(**lINDEXER_API_PARMS)
            myShow = t[ep_obj.show.indexerid]
        except indexer_shownotfound as e:
            raise ShowNotFoundException(e.message)
        except indexer_error as e:
            sickrage.srCore.srLogger.error("Unable to connect to " + srIndexerApi(
                ep_obj.show.indexer).name + " while creating meta files - skipping - {}".format(e.message))
            return False

        rootNode = Element("details")

        # write an WDTV XML containing info for all matching episodes
        for curEpToWrite in eps_to_write:

            try:
                myEp = myShow[curEpToWrite.season][curEpToWrite.episode]
            except (indexer_episodenotfound, indexer_seasonnotfound):
                sickrage.srCore.srLogger.info(
                    "Unable to find episode %dx%d on %s... has it been removed? Should I delete from db?" %
                    (curEpToWrite.season, curEpToWrite.episode, srIndexerApi(ep_obj.show.indexer).name))
                return None

            if ep_obj.season == 0 and not getattr(myEp, 'firstaired', None):
                myEp["firstaired"] = str(datetime.date.fromordinal(1))

            if not (getattr(myEp, 'episodename', None) and getattr(myEp, 'firstaired', None)):
                return None

            if len(eps_to_write) > 1:
                episode = SubElement(rootNode, "details")
            else:
                episode = rootNode

            # TODO: get right EpisodeID
            episodeID = SubElement(episode, "id")
            episodeID.text = str(curEpToWrite.indexerid)

            title = SubElement(episode, "title")
            title.text = ep_obj.prettyName()

            if getattr(myShow, 'seriesname', None):
                seriesName = SubElement(episode, "series_name")
                seriesName.text = myShow["seriesname"]

            if curEpToWrite.name:
                episodeName = SubElement(episode, "episode_name")
                episodeName.text = curEpToWrite.name

            seasonNumber = SubElement(episode, "season_number")
            seasonNumber.text = str(curEpToWrite.season)

            episodeNum = SubElement(episode, "episode_number")
            episodeNum.text = str(curEpToWrite.episode)

            firstAired = SubElement(episode, "firstaired")

            if curEpToWrite.airdate != datetime.date.fromordinal(1):
                firstAired.text = str(curEpToWrite.airdate)

            if getattr(myShow, 'firstaired', None):
                try:
                    year_text = str(datetime.datetime.strptime(myShow["firstaired"], dateFormat).year)
                    if year_text:
                        year = SubElement(episode, "year")
                        year.text = year_text
                except Exception:
                    pass

            if curEpToWrite.season != 0 and getattr(myShow, 'runtime', None):
                runtime = SubElement(episode, "runtime")
                runtime.text = myShow["runtime"]

            if getattr(myShow, 'genre', None):
                genre = SubElement(episode, "genre")
                genre.text = " / ".join([x.strip() for x in myShow["genre"].split('|') if x.strip()])

            if getattr(myEp, 'director', None):
                director = SubElement(episode, "director")
                director.text = myEp['director']

            if getattr(myShow, '_actors', None):
                for actor in myShow['_actors']:
                    if not ('name' in actor and actor['name'].strip()):
                        continue

                    cur_actor = SubElement(episode, "actor")

                    cur_actor_name = SubElement(cur_actor, "name")
                    cur_actor_name.text = actor['name']

                    if 'role' in actor and actor['role'].strip():
                        cur_actor_role = SubElement(cur_actor, "role")
                        cur_actor_role.text = actor['role'].strip()

            if curEpToWrite.description:
                overview = SubElement(episode, "overview")
                overview.text = curEpToWrite.description

        # Make it purdy
        indentXML(rootNode)
        data = ElementTree(rootNode)
        return data
Exemplo n.º 2
0
            indent(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i


note = Element("note")
to = Element('to')  #자식 노드
to.text = "Tove"  #현재 엘리먼트(Tag)에 값 추가

note.append(to)  #부모 노드에 자식노드 추가

SubElement(note, "from").text = "jani"

dummy = Element("dummy")
note.insert(1, dummy)
note.remove(dummy)

note.attrib["date"] = "20120104"

SubElement(note, "heading").text = "Reminder"
SubElement(note, "body").text = "Don`t forget me this weekend!"

indent(note)

dump(note)

ElementTree(note).write("note.xml")
Exemplo n.º 3
0
def get_hiseq_container(run_dir):
    tree = ElementTree()
    tree.parse(os.path.join(run_dir, "RunInfo.xml"))  # HiSeq
    return tree.find("Run/Flowcell").text
Exemplo n.º 4
0
def parseXML(trackletFile):
    """ 
    Parses tracklet xml file and convert results to list of Tracklet objects

    :param trackletFile: name of a tracklet xml file
    :returns: list of Tracklet objects read from xml file
    """

    # convert tracklet XML data to a tree structure
    eTree = ElementTree()
    print('Parsing tracklet file', trackletFile)
    with open(trackletFile) as f:
        eTree.parse(f)

    # now convert output to list of Tracklet objects
    trackletsElem = eTree.find('tracklets')
    tracklets = []
    trackletIdx = 0
    nTracklets = None
    for trackletElem in trackletsElem:
        # print 'track:', trackletElem.tag
        if trackletElem.tag == 'count':
            nTracklets = int(trackletElem.text)
            print('File contains', nTracklets, 'tracklets')
        elif trackletElem.tag == 'item_version':
            pass
        elif trackletElem.tag == 'item':
            # print 'tracklet {0} of {1}'.format(trackletIdx, nTracklets)
            # a tracklet
            newTrack = Tracklet()
            isFinished = False
            hasAmt = False
            frameIdx = None
            for info in trackletElem:
                # print 'trackInfo:', info.tag
                if isFinished:
                    raise ValueError('more info on element after finished!')
                if info.tag == 'objectType':
                    newTrack.objectType = info.text
                elif info.tag == 'h':
                    newTrack.size[0] = float(info.text)
                elif info.tag == 'w':
                    newTrack.size[1] = float(info.text)
                elif info.tag == 'l':
                    newTrack.size[2] = float(info.text)
                elif info.tag == 'first_frame':
                    newTrack.firstFrame = int(info.text)
                elif info.tag == 'poses':
                    # this info is the possibly long list of poses
                    for pose in info:
                        # print 'trackInfoPose:', pose.tag
                        if pose.tag == 'count':  # this should come before the others
                            if newTrack.nFrames is not None:
                                raise ValueError('there are several pose lists for a single track!')
                            elif frameIdx is not None:
                                raise ValueError('?!')
                            newTrack.nFrames = int(pose.text)
                            newTrack.trans = np.nan * np.ones((newTrack.nFrames, 3), dtype=float)
                            newTrack.rots = np.nan * np.ones((newTrack.nFrames, 3), dtype=float)
                            newTrack.states = np.nan * np.ones(newTrack.nFrames, dtype='uint8')
                            newTrack.occs = np.nan * np.ones((newTrack.nFrames, 2), dtype='uint8')
                            newTrack.truncs = np.nan * np.ones(newTrack.nFrames, dtype='uint8')
                            newTrack.amtOccs = np.nan * np.ones((newTrack.nFrames, 2), dtype=float)
                            newTrack.amtBorders = np.nan * np.ones((newTrack.nFrames, 3), dtype=float)
                            frameIdx = 0
                        elif pose.tag == 'item_version':
                            pass
                        elif pose.tag == 'item':
                            # pose in one frame
                            if frameIdx is None:
                                raise ValueError('pose item came before number of poses!')
                            for poseInfo in pose:
                                # print 'trackInfoPoseInfo:', poseInfo.tag
                                if poseInfo.tag == 'tx':
                                    newTrack.trans[frameIdx, 0] = float(poseInfo.text)
                                elif poseInfo.tag == 'ty':
                                    newTrack.trans[frameIdx, 1] = float(poseInfo.text)
                                elif poseInfo.tag == 'tz':
                                    newTrack.trans[frameIdx, 2] = float(poseInfo.text)
                                elif poseInfo.tag == 'rx':
                                    newTrack.rots[frameIdx, 0] = float(poseInfo.text)
                                elif poseInfo.tag == 'ry':
                                    newTrack.rots[frameIdx, 1] = float(poseInfo.text)
                                elif poseInfo.tag == 'rz':
                                    newTrack.rots[frameIdx, 2] = float(poseInfo.text)
                                elif poseInfo.tag == 'state':
                                    newTrack.states[frameIdx] = stateFromText[poseInfo.text]
                                elif poseInfo.tag == 'occlusion':
                                    newTrack.occs[frameIdx, 0] = occFromText[poseInfo.text]
                                elif poseInfo.tag == 'occlusion_kf':
                                    newTrack.occs[frameIdx, 1] = occFromText[poseInfo.text]
                                elif poseInfo.tag == 'truncation':
                                    newTrack.truncs[frameIdx] = truncFromText[poseInfo.text]
                                elif poseInfo.tag == 'amt_occlusion':
                                    newTrack.amtOccs[frameIdx, 0] = float(poseInfo.text)
                                    hasAmt = True
                                elif poseInfo.tag == 'amt_occlusion_kf':
                                    newTrack.amtOccs[frameIdx, 1] = float(poseInfo.text)
                                    hasAmt = True
                                elif poseInfo.tag == 'amt_border_l':
                                    newTrack.amtBorders[frameIdx, 0] = float(poseInfo.text)
                                    hasAmt = True
                                elif poseInfo.tag == 'amt_border_r':
                                    newTrack.amtBorders[frameIdx, 1] = float(poseInfo.text)
                                    hasAmt = True
                                elif poseInfo.tag == 'amt_border_kf':
                                    newTrack.amtBorders[frameIdx, 2] = float(poseInfo.text)
                                    hasAmt = True
                                else:
                                    raise ValueError('unexpected tag in poses item: {0}!'.format(poseInfo.tag))
                            frameIdx += 1
                        else:
                            raise ValueError('unexpected pose info: {0}!'.format(pose.tag))
                elif info.tag == 'finished':
                    isFinished = True
                else:
                    raise ValueError('unexpected tag in tracklets: {0}!'.format(info.tag))
            # end: for all fields in current tracklet

            # some final consistency checks on new tracklet
            if not isFinished:
                warn('tracklet {0} was not finished!'.format(trackletIdx))
            if newTrack.nFrames is None:
                warn('tracklet {0} contains no information!'.format(trackletIdx))
            elif frameIdx != newTrack.nFrames:
                warn('tracklet {0} is supposed to have {1} frames, but perser found {1}!'.format(trackletIdx,
                                                                                                 newTrack.nFrames,
                                                                                                 frameIdx))
            if np.abs(newTrack.rots[:, :2]).sum() > 1e-16:
                warn('track contains rotation other than yaw!')

            # if amtOccs / amtBorders are not set, set them to None
            if not hasAmt:
                newTrack.amtOccs = None
                newTrack.amtBorders = None

            # add new tracklet to list
            tracklets.append(newTrack)
            trackletIdx += 1

        else:
            raise ValueError('unexpected tracklet info')
    # end: for tracklet list items

    print('Loaded', trackletIdx, 'tracklets.')

    # final consistency check
    if trackletIdx != nTracklets:
        warn('according to xml information the file has {0} tracklets, but parser found {1}!'.format(nTracklets,
                                                                                                     trackletIdx))

    return tracklets
Exemplo n.º 5
0
    def save(self):

        self.uichanges()

        self.saveFile = self.archive

        root = ET.Element('programElements')
        tree = ElementTree(root)

        for i in range(self.list.count()):
            self.liTxt = self.list.item(i).text()
            listitem = ET.SubElement(root, 'listitem')
            licon = self.list_icons_dict[self.liTxt]
            listitem.set('item_icon', licon)
            listitem.text = self.liTxt
        for g in range(self.stack.count()):
            self.stackTab = self.stack.widget(g)
            tabwidgetName = ET.SubElement(root, 'tabwid_name')
            tabwidgetName.text = self.stackTab.objectName()
            for p in range(self.stackTab.count()):
                self.tabtext = self.stackTab.tabText(p)
                self.ticon = self.tabwidget_icons_dict[
                    self.stackTab.objectName()][self.tabtext]
                self.tabcontents = self.tabtext

                if not os.path.exists(
                        os.path.splitext(self.saveFile)[0] +
                        '/{}'.format(tabwidgetName.text) +
                        '/{}/'.format(self.tabcontents)):
                    os.makedirs(
                        os.path.splitext(self.saveFile)[0] +
                        '/{}'.format(tabwidgetName.text) +
                        '/{}/'.format(self.tabcontents))

                with open(
                        r'{}'.format(os.path.splitext(self.saveFile)[0]) +
                        r'/{}'.format(tabwidgetName.text) +
                        r'/{}/{}.html'.format(self.tabcontents,
                                              self.tabcontents), 'w') as file:
                    file.write(self.stackTab.widget(p).toHtml())
                file.close()

                tabName = ET.SubElement(tabwidgetName, 'tabName')
                tabName.set('content', str(self.tabcontents))
                tabName.set('tabIcon', self.ticon)
                tabName.text = self.tabtext

        tree.write(open(self.saveFile + '/config.xml', 'wb'))

        if '_' in self.saveFile:

            # used to add all files in the working directory with the -o flag and when i deleted it, it worked the way it should.....idk
            subprocess.run([
                r'7z\7-Zip\7z.exe', 'a', '-p{}'.format(self.pw), '{}'.format(
                    self.saveFile), '{}'.format(self.saveFile)
            ],
                           shell=False)

        else:
            subprocess.run([
                r'7z\7-Zip\7z.exe', 'a', '{}'.format(self.saveFile),
                '{}'.format(self.saveFile)
            ],
                           shell=False)

        self.programconfig(self.saveFile)

        self.status = True
Exemplo n.º 6
0
 def load_fixtures(self):
     """ loading data """
     self.parse.return_value = ElementTree(
         fromstring(load_fixture(self.config_file)))
Exemplo n.º 7
0
import os
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as et

base_path = os.path.dirname(os.path.realpath(__file__))

xml_file = os.path.join(base_path, 'data/request.xml')

root = Element("requests")
tree = ElementTree(root)
toppfun = Element("toppfun")
enrichment = Element("enrichment-config")
trainingset = Element("trainingset")
gene = Element("gene")
features = Element("features")
feature = Element("feature")
Exemplo n.º 8
0
def createXML(sources, startFrame, endFrame, fps, timecode, audioRate,
              sampleFormat, ardourBasename, audiosFolder):
    '''Creates full Ardour XML to be written to a file'''
    global idCounter
    sources, repeated, tracks, idCounter = getAudioTimeline(audioRate, fps)
    tracks = sorted(set(tracks))[::-1]
    sampleFormat = checkSampleFormat(sampleFormat)
    ardourStart = toSamples((startFrame - 1), audioRate, fps)
    ardourEnd = toSamples((endFrame - 1), audioRate, fps)

    ######## ------------------------------------------------------------------
    ######## STATIC XML SECTIONS
    ######## ------------------------------------------------------------------

    Session = Element("Session")  # XML root = Session
    tree = ElementTree(Session)

    # Create Session Elements + Attributes
    xmlSections = [
        "Config", "Metadata", "Sources", "Regions", "Locations", "Bundles",
        "Routes", "Playlists", "UnusedPlaylists", "RouteGroups", "Click",
        "Speakers", "TempoMap", "ControlProtocols", "Extra"
    ]

    for section in xmlSections:
        Session.append(Element(section))

    # Create Option, IO, Tempo and Meter + Attributes
    for counter in range(
            valLength(atOption(audiosFolder, sampleFormat, timecode))):
        Option = SubElement(Session[0], "Option")  # Session > Config > Option
        createSubElementsMulti(Option,
                               atOption(audiosFolder, sampleFormat, timecode),
                               counter)

    Location = SubElement(Session[4],
                          "Location")  # Session > Locations > Location
    IO = SubElement(Session[10], "IO")  # Session > Click > IO
    Tempo = SubElement(Session[12], "Tempo")  # Session > TempoMap > Tempo
    Meter = SubElement(Session[12], "Meter")  # Session > TempoMap > Meter

    createSubElements(Session, atSession(audioRate, ardourBasename, idCounter))
    createSubElements(Location, atLocation(ardourStart, ardourEnd, idCounter))
    idCounter += 1
    createSubElements(IO, atIO(idCounter))
    idCounter += 1
    createSubElements(Tempo, atTempo())
    createSubElements(Meter, atMeter())

    Port = ""
    for counter in range(valLength(atPort())):
        Port = SubElement(IO, "Port")  # Session > Click > IO > Port
        createSubElementsMulti(Port, atPort(), counter)

    ######## ------------------------------------------------------------------
    ######## DYNAMIC XML SECTIONS
    ######## ------------------------------------------------------------------

    # create sources and sources' regions
    for source in sources:
        createAudioSources(Session, source)

    # create another sources' entry for stereo files
    stereoSources = []
    numAdded = 0
    for source in sources:
        if (source['channels']
                == 1) and not any(source['base_name'] == d['base_name']
                                  for d in stereoSources):
            newsrc = source.copy()
            newsrc['id'] = int(newsrc['id'] + idCounter)
            createAudioSources(Session, newsrc, 1)
            stereoSources.append(newsrc)
            numAdded += 1
    idCounter += numAdded

    # create playlists (tracks)
    for track in tracks:
        createPlaylists(Session, idCounter, track)

    # correct reference to master-source-0 and source-0 in repeated audios
    for rep in repeated:
        for sour in sources:
            if (rep['name'] == sour['name']):
                rep['sourceID'] = sour['id']

    # create playlists regions (timeline)
    for audio in (sources + repeated):
        track = tracks.index(audio['track'])
        if (audio['channels'] == 0):
            createPlaylistRegions(Session, idCounter, audio, track)
        else:
            for stereos in stereoSources:
                if (audio['name'] == stereos['name']):
                    audio['master-source-1'] = stereos['id']
                    audio['source-1'] = stereos['id']
                    createPlaylistRegions(Session, idCounter, audio, track)

    Session.set('id-counter', str(idCounter))

    return Session, sources
Exemplo n.º 9
0
                    if m.group(1) != "0":
                        failureElement = makeFailureElement(testOutput)
                        testCaseElement.append(failureElement)
                        incrNumAttr(testSuiteElement, "failures")
                    else:
                        systemOutElement = makeSystemOutElement(testOutput)
                        testCaseElement.append(systemOutElement)

                    testSuiteElement.append(testCaseElement)
                    parserState = parserStateEnum.newTest
                    testOutput = ""
                    incrNumAttr(testSuiteElement, "tests")
                    continue

                m = timePatt.match(line)
                if m:
                    setTimeAttr(attrDict, m.group(1))
                    continue

                continue


if __name__ == "__main__":
    import sys

    testSuitesElement = Element("testsuites")
    testSuiteElement = Element("testsuite", name="nbtest", hostname="")
    parseLog(sys.argv[1], testSuiteElement)
    testSuitesElement.append(testSuiteElement)
    ElementTree(testSuitesElement).write(sys.argv[1]+".xml", xml_declaration=True)
Exemplo n.º 10
0
#source_encoding = 'utf-8'

show_sphinx = False

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'minas_control'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
try:
    root = ElementTree(None, os.path.join('..', 'package.xml'))
    version = root.findtext('version')
    author_names = [a.text for a in root.findall('author')]
    copyright = u'2017-%s, %s' % (time.strftime('%Y'), ', '.join(author_names))
except Exception as e:
    raise RuntimeError('Could not extract version and authors from package.xml:\n%s' % e)

# The full version, including alpha/beta/rc tags.
release = version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
Exemplo n.º 11
0
def mainFunc(path_to_prediction_report):
    tree_all = Elem.parse(path_to_prediction_report)
    list_tree = tree_all.findall('report')
    root = Element('radiology_reports')
    for list_tree_elem in list_tree:
        root.append(list_tree_elem)
    print "No.of reports:", len(root)
    global tree
    tree = ElementTree(root)

    dicListPre = {}
    dicListTrue = {}
    global crfDic

    #load models
    models_path = "CRFmodelB_trainedmodel.pkl"
    models_file = open(models_path, 'rb')
    crfDic = pickle.load(models_file)

    train_test_onTrue("report")

    cascadedOnPre = []
    locLists = []
    for i in range(len(tokenListAll)):
        cascadedOnPre.append([])
        locLists.append([])
        for j in range(len(tokenListAll[i])):
            cascadedOnPre[i].append(['', ''])
            locLists[i].append('')

    for i in range(len(tokenListAll)):
        preLabels = list(cascadedOnPre[i])
        phrase1 = list(tokenListAll[i])
        locList = list(locLists[i])
        test_onPredicted(0, len(tokenListAll[i]), phrase1, preLabels, "report",
                         "report", locList)
        for j in range(len(cascadedOnPre[i])):
            cascadedOnPre[i][j] = preLabels[j]

    cascPreList = []
    cascPreList1 = []

    predictPredictList1 = []
    tokenFor2levelList1 = []

    predictpredictPredictList1 = []
    tokenFor3levelList1 = []

    count = 0
    for i in range(len(tokenListAll)):
        cascPreVal = []
        cascPreVal1 = []
        predictPredict1 = []
        tokenFor2level = []
        predictpredictPredict1 = []
        tokenFor3level = []
        for j in range(len(tokenListAll[i])):
            cascadedOnPre[i][j][0] = cascadedOnPre[i][j][0].strip('/')
            cascadedOnPre[i][j][1] = cascadedOnPre[i][j][1].strip('/')
            cascPre = cascadedOnPre[i][j][0].split('/')
            if len(cascPre) >= 2:
                predictPredict = "/".join(cascPre[:2])
                tokenFor2level.append(tokenListAll[i][j])
                predictPredict1.append(predictPredict)

            if len(cascPre) == 3:
                predictpredictPredict = "/".join(cascPre[0:3])
                tokenFor3level.append(tokenListAll[i][j])
                predictpredictPredict1.append(predictpredictPredict)

            cascPreVal.append(cascadedOnPre[i][j][0])
            cascPreVal1.append(cascadedOnPre[i][j][1])
        cascPreList.append(cascPreVal)
        cascPreList1.append(cascPreVal1)

        predictPredictList1.append(predictPredict1)
        tokenFor2levelList1.append(tokenFor2level)

        predictpredictPredictList1.append(predictpredictPredict1)
        tokenFor3levelList1.append(tokenFor3level)
    labeling_to_xml.mainFunc(docs_ori, cascPreList1)
Exemplo n.º 12
0
    def _ep_data(self, ep_obj):
        """
        Creates an elementTree XML structure for a MediaBrowser style episode.xml
        and returns the resulting data object.

        show_obj: a TVShow instance to create the NFO for
        """

        eps_to_write = [ep_obj] + ep_obj.relatedEps

        persons_dict = {'Director': [], 'GuestStar': [], 'Writer': []}

        indexer_lang = ep_obj.show.lang

        try:
            lINDEXER_API_PARMS = srIndexerApi(
                ep_obj.show.indexer).api_params.copy()

            if indexer_lang and not indexer_lang == sickrage.srCore.srConfig.INDEXER_DEFAULT_LANGUAGE:
                lINDEXER_API_PARMS['language'] = indexer_lang

            if ep_obj.show.dvdorder != 0:
                lINDEXER_API_PARMS['dvdorder'] = True

            t = srIndexerApi(ep_obj.show.indexer).indexer(**lINDEXER_API_PARMS)

            myShow = t[ep_obj.show.indexerid]
        except indexer_shownotfound as e:
            raise ShowNotFoundException(e.message)
        except indexer_error as e:
            sickrage.srCore.srLogger.error(
                "Unable to connect to " +
                srIndexerApi(ep_obj.show.indexer).name +
                " while creating meta files - skipping - {}".format(e.message))
            return False

        rootNode = Element("Item")

        # write an MediaBrowser XML containing info for all matching episodes
        for curEpToWrite in eps_to_write:

            try:
                myEp = myShow[curEpToWrite.season][curEpToWrite.episode]
            except (indexer_episodenotfound, indexer_seasonnotfound):
                sickrage.srCore.srLogger.info(
                    "Unable to find episode %dx%d on %s... has it been removed? Should I delete from db?"
                    % (curEpToWrite.season, curEpToWrite.episode,
                       srIndexerApi(ep_obj.show.indexer).name))
                return None

            if curEpToWrite == ep_obj:
                # root (or single) episode

                # default to today's date for specials if firstaired is not set
                if ep_obj.season == 0 and not getattr(myEp, 'firstaired',
                                                      None):
                    myEp['firstaired'] = str(datetime.date.fromordinal(1))

                if not (getattr(myEp, 'episodename', None)
                        and getattr(myEp, 'firstaired', None)):
                    return None

                episode = rootNode

                if curEpToWrite.name:
                    EpisodeName = SubElement(episode, "EpisodeName")
                    EpisodeName.text = curEpToWrite.name

                EpisodeNumber = SubElement(episode, "EpisodeNumber")
                EpisodeNumber.text = str(ep_obj.episode)

                if ep_obj.relatedEps:
                    EpisodeNumberEnd = SubElement(episode, "EpisodeNumberEnd")
                    EpisodeNumberEnd.text = str(curEpToWrite.episode)

                SeasonNumber = SubElement(episode, "SeasonNumber")
                SeasonNumber.text = str(curEpToWrite.season)

                if not ep_obj.relatedEps and getattr(myEp, 'absolute_number',
                                                     None):
                    absolute_number = SubElement(episode, "absolute_number")
                    absolute_number.text = str(myEp['absolute_number'])

                if curEpToWrite.airdate != datetime.date.fromordinal(1):
                    FirstAired = SubElement(episode, "FirstAired")
                    FirstAired.text = str(curEpToWrite.airdate)

                MetadataType = SubElement(episode, "Type")
                MetadataType.text = "Episode"

                if curEpToWrite.description:
                    Overview = SubElement(episode, "Overview")
                    Overview.text = curEpToWrite.description

                if not ep_obj.relatedEps:
                    if getattr(myEp, 'rating', None):
                        Rating = SubElement(episode, "Rating")
                        Rating.text = myEp['rating']

                    if getattr(myShow, 'imdb_id', None):
                        IMDB_ID = SubElement(episode, "IMDB_ID")
                        IMDB_ID.text = myShow['imdb_id']

                        IMDB = SubElement(episode, "IMDB")
                        IMDB.text = myShow['imdb_id']

                        IMDbId = SubElement(episode, "IMDbId")
                        IMDbId.text = myShow['imdb_id']

                indexerid = SubElement(episode, "id")
                indexerid.text = str(curEpToWrite.indexerid)

                # fill in Persons section with collected directors, guest starts and writers
                Persons = SubElement(episode, "Persons")
                for person_type, names in persons_dict.items():
                    # remove doubles
                    names = list(set(names))
                    for cur_name in names:
                        Person = SubElement(Persons, "Person")
                        cur_person_name = SubElement(Person, "Name")
                        cur_person_name.text = cur_name
                        cur_person_type = SubElement(Person, "Type")
                        cur_person_type.text = person_type

                if getattr(myShow, '_actors', None):
                    for actor in myShow['_actors']:
                        if not ('name' in actor and actor['name'].strip()):
                            continue

                        cur_actor = SubElement(Persons, "Person")

                        cur_actor_name = SubElement(cur_actor, "Name")
                        cur_actor_name.text = actor['name'].strip()

                        cur_actor_type = SubElement(cur_actor, "Type")
                        cur_actor_type.text = "Actor"

                        if 'role' in actor and actor['role'].strip():
                            cur_actor_role = SubElement(cur_actor, "Role")
                            cur_actor_role.text = actor['role'].strip()

                Language = SubElement(episode, "Language")
                try:
                    Language.text = myEp['language']
                except Exception:
                    Language.text = sickrage.srCore.srConfig.INDEXER_DEFAULT_LANGUAGE

                thumb = SubElement(episode, "filename")
                # TODO: See what this is needed for.. if its still needed
                # just write this to the NFO regardless of whether it actually exists or not
                # note: renaming files after nfo generation will break this, tough luck
                thumb_text = self.get_episode_thumb_path(ep_obj)
                if thumb_text:
                    thumb.text = thumb_text

            else:
                # append data from (if any) related episodes
                if curEpToWrite.episode:
                    if not EpisodeNumberEnd.text:
                        EpisodeNumberEnd.text = curEpToWrite.episode
                    else:
                        EpisodeNumberEnd.text = EpisodeNumberEnd.text + ", " + curEpToWrite.episode

                if curEpToWrite.name:
                    if not EpisodeName.text:
                        EpisodeName.text = curEpToWrite.name
                    else:
                        EpisodeName.text = EpisodeName.text + ", " + curEpToWrite.name

                if curEpToWrite.description:
                    if not Overview.text:
                        Overview.text = curEpToWrite.description
                    else:
                        Overview.text = Overview.text + "\r" + curEpToWrite.description

            # collect all directors, guest stars and writers
            if getattr(myEp, 'director', None):
                persons_dict['Director'] += [
                    x.strip() for x in myEp['director'].split('|')
                    if x.strip()
                ]
            if getattr(myEp, 'gueststars', None):
                persons_dict['GuestStar'] += [
                    x.strip() for x in myEp['gueststars'].split('|')
                    if x.strip()
                ]
            if getattr(myEp, 'writer', None):
                persons_dict['Writer'] += [
                    x.strip() for x in myEp['writer'].split('|') if x.strip()
                ]

        indentXML(rootNode)
        data = ElementTree(rootNode)

        return data
Exemplo n.º 13
0
    def _show_data(self, show_obj):
        """
        Creates an elementTree XML structure for a MediaBrowser-style series.xml
        returns the resulting data object.

        show_obj: a TVShow instance to create the NFO for
        """

        indexer_lang = show_obj.lang
        # There's gotta be a better way of doing this but we don't wanna
        # change the language value elsewhere
        lINDEXER_API_PARMS = srIndexerApi(show_obj.indexer).api_params.copy()

        if indexer_lang and not indexer_lang == sickrage.srCore.srConfig.INDEXER_DEFAULT_LANGUAGE:
            lINDEXER_API_PARMS['language'] = indexer_lang

        if show_obj.dvdorder != 0:
            lINDEXER_API_PARMS['dvdorder'] = True

        t = srIndexerApi(show_obj.indexer).indexer(**lINDEXER_API_PARMS)

        tv_node = Element("Series")

        try:
            myShow = t[int(show_obj.indexerid)]
        except indexer_shownotfound:
            sickrage.srCore.srLogger.error(
                "Unable to find show with id " + str(show_obj.indexerid) +
                " on " + srIndexerApi(show_obj.indexer).name + ", skipping it")
            raise

        except indexer_error:
            sickrage.srCore.srLogger.error(
                "" + srIndexerApi(show_obj.indexer).name +
                " is down, can't use its data to make the NFO")
            raise

        # check for title and id
        if not (getattr(myShow, 'seriesname', None)
                and getattr(myShow, 'id', None)):
            sickrage.srCore.srLogger.info("Incomplete info for show with id " +
                                          str(show_obj.indexerid) + " on " +
                                          srIndexerApi(show_obj.indexer).name +
                                          ", skipping it")
            return False

        if getattr(myShow, 'id', None):
            indexerid = SubElement(tv_node, "id")
            indexerid.text = str(myShow['id'])

        if getattr(myShow, 'seriesname', None):
            SeriesName = SubElement(tv_node, "SeriesName")
            SeriesName.text = myShow['seriesname']

        if getattr(myShow, 'status', None):
            Status = SubElement(tv_node, "Status")
            Status.text = myShow['status']

        if getattr(myShow, 'network', None):
            Network = SubElement(tv_node, "Network")
            Network.text = myShow['network']

        if getattr(myShow, 'airs_time', None):
            Airs_Time = SubElement(tv_node, "Airs_Time")
            Airs_Time.text = myShow['airs_time']

        if getattr(myShow, 'airs_dayofweek', None):
            Airs_DayOfWeek = SubElement(tv_node, "Airs_DayOfWeek")
            Airs_DayOfWeek.text = myShow['airs_dayofweek']

        FirstAired = SubElement(tv_node, "FirstAired")
        if getattr(myShow, 'firstaired', None):
            FirstAired.text = myShow['firstaired']

        if getattr(myShow, 'contentrating', None):
            ContentRating = SubElement(tv_node, "ContentRating")
            ContentRating.text = myShow['contentrating']

            MPAARating = SubElement(tv_node, "MPAARating")
            MPAARating.text = myShow['contentrating']

            certification = SubElement(tv_node, "certification")
            certification.text = myShow['contentrating']

        MetadataType = SubElement(tv_node, "Type")
        MetadataType.text = "Series"

        if getattr(myShow, 'overview', None):
            Overview = SubElement(tv_node, "Overview")
            Overview.text = myShow['overview']

        if getattr(myShow, 'firstaired', None):
            PremiereDate = SubElement(tv_node, "PremiereDate")
            PremiereDate.text = myShow['firstaired']

        if getattr(myShow, 'rating', None):
            Rating = SubElement(tv_node, "Rating")
            Rating.text = myShow['rating']

        if getattr(myShow, 'firstaired', None):
            try:
                year_text = str(
                    datetime.datetime.strptime(myShow['firstaired'],
                                               dateFormat).year)
                if year_text:
                    ProductionYear = SubElement(tv_node, "ProductionYear")
                    ProductionYear.text = year_text
            except Exception:
                pass

        if getattr(myShow, 'runtime', None):
            RunningTime = SubElement(tv_node, "RunningTime")
            RunningTime.text = myShow['runtime']

            Runtime = SubElement(tv_node, "Runtime")
            Runtime.text = myShow['runtime']

        if getattr(myShow, 'imdb_id', None):
            imdb_id = SubElement(tv_node, "IMDB_ID")
            imdb_id.text = myShow['imdb_id']

            imdb_id = SubElement(tv_node, "IMDB")
            imdb_id.text = myShow['imdb_id']

            imdb_id = SubElement(tv_node, "IMDbId")
            imdb_id.text = myShow['imdb_id']

        if getattr(myShow, 'zap2it_id', None):
            Zap2ItId = SubElement(tv_node, "Zap2ItId")
            Zap2ItId.text = myShow['zap2it_id']

        if getattr(myShow, 'genre', None) and isinstance(
                myShow["genre"], basestring):
            Genres = SubElement(tv_node, "Genres")
            for genre in myShow['genre'].split('|'):
                if genre.strip():
                    cur_genre = SubElement(Genres, "Genre")
                    cur_genre.text = genre.strip()

            Genre = SubElement(tv_node, "Genre")
            Genre.text = "|".join(
                [x.strip() for x in myShow["genre"].split('|') if x.strip()])

        if getattr(myShow, 'network', None):
            Studios = SubElement(tv_node, "Studios")
            Studio = SubElement(Studios, "Studio")
            Studio.text = myShow['network']

        if getattr(myShow, '_actors', None):
            Persons = SubElement(tv_node, "Persons")
            for actor in myShow['_actors']:
                if not ('name' in actor and actor['name'].strip()):
                    continue

                cur_actor = SubElement(Persons, "Person")

                cur_actor_name = SubElement(cur_actor, "Name")
                cur_actor_name.text = actor['name'].strip()

                cur_actor_type = SubElement(cur_actor, "Type")
                cur_actor_type.text = "Actor"

                if 'role' in actor and actor['role'].strip():
                    cur_actor_role = SubElement(cur_actor, "Role")
                    cur_actor_role.text = actor['role'].strip()

        indentXML(tv_node)

        data = ElementTree(tv_node)

        return data
# encoding = utf-8
Exemplo n.º 15
0
def get_acties(fnaam, select=None, arch="", user=None):
    """ lijst alle items van een bepaald soort

    fnaam is a pathlib.Path object

    zoeken mogelijk op id (groter dan / kleiner dan), soort, status, (deel van) titel
    een selecteer-key mag een van de volgejde waarden zijn:
    "idlt" - in dat geval moet de waarde een string zijn waarmee vergeleken wordt,
    "idgt" - in dat geval moet de waarde een string zijn waarmee vergeleken wordt,
    "soort" - in dat geval moet de waarde een list zijn van mogelijke soorten,
    "status" - in dat geval moet de waarde een list zijn van mogelijke statussen,
    "titel" - in dat geval moet de waarde een string zijn die in de titel moet voorkomen
    eventueel wildcards:
        als de string niet begint met een * dan moet de titel ermee beginnen
        als de string niet eindigt met een * dan moet de titel ermee eindigen
        als er een * in zit moet wat ervoor zit en erna komt in de titel zitten
    het laatste argument `user` wordt hier niet gebruikt maar is voor compatibiliteit
    met de django versie
    """
    if select is None:
        select = {}
        if not arch:
            return []
    lijst = []
    if select:
        keyfout = False
        for x in list(select.keys()):
            if x not in ("idlt", "id", "idgt", "soort", "status", "titel"):
                keyfout = True
                break
        if keyfout:
            raise DataError("Foutief selectie-argument opgegeven")
        if "id" in select:
            if "idlt" not in select and "idgt" not in select:
                raise DataError(
                    "Foutieve combinatie van selectie-argumenten opgegeven")
    if arch not in ("", "arch", "alles"):
        raise DataError("Foutieve waarde voor archief opgegeven "
                        "(moet niks, 'arch'  of 'alles' zijn)")
    sett = Settings(fnaam)
    if fnaam.exists():
        dnaam = str(fnaam)
    elif os.path.exists(os.path.join(datapad, fnaam)):
        dnaam = os.path.join(datapad, fnaam)
    else:
        raise DataError("datafile bestaat niet")
    tree = ElementTree(file=dnaam)
    rt = tree.getroot()
    for x in rt.findall("actie"):
        a = x.get("arch")
        if a is None:
            if arch == "arch":
                continue
        else:
            if (a == "arch" and arch == "") or (a != "arch"
                                                and arch == "arch"):
                continue
        nr = x.get("id")
        if "id" in select and select["id"] == "or":
            if nr <= select["idgt"] and nr >= select["idlt"]:
                continue
        else:
            if ("idgt" in select and nr <= select["idgt"]) \
                    or ("idlt" in select and nr >= select["idlt"]):
                continue
        ## alternatief en meer overeenkomend met de sql versie
        ## if 'id' in select:
        ## select_gt = select_lt = True
        ## if 'idgt' in select and nr <= select['idgt']:
        ## select_gt = False
        ## if 'idlt' in select and nr >= select['idlt']:
        ## select_lt = False
        ## if select['id'] == 'and' and (select_gt == False or select_lt == False):
        ## continue
        ## if select['id'] == 'or' and select_gt == False and select_lt == False:
        ## continue
        dd = x.get("datum")
        if dd is None:
            dd = ''
        lu = x.get("updated")
        if lu is None:
            lu = ""
        h = x.get("status")
        if "status" in select and h not in select["status"]:
            continue
        st = ''
        if h in list(sett.stat.keys()):
            st = sett.stat[h]
        h = x.get("soort")
        if h is None:
            h = ""
        if "soort" in select and h not in select["soort"]:
            continue
        ct = ''
        if h in list(sett.cat.keys()):
            ct = sett.cat[h]
        tl = x.find("titel").text
        if tl is None:
            tl = ""
        if "titel" in select and select["titel"].upper() not in tl.upper():
            continue
        lijst.append((nr, dd, st, ct, tl, lu, a))
    return lijst
Exemplo n.º 16
0
    def search(self, keyword, page=1, pagesize=50):
        if not keyword:
            return None

        from rooibos.federatedsearch.models import HitCount

        cached, created = HitCount.current_objects.get_or_create(
            source=self.get_source_id(),
            query='%s [%s:%s]' % (keyword, page, pagesize),
            defaults=dict(
                hits=0,
                valid_until=datetime.datetime.now() + datetime.timedelta(1)
            )
        )

        if not created and cached.results:
            return simplejson.loads(cached.results)

        opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),
            SmartRedirectHandler()
        )
        url = '%s?query="%s"&operation=searchRetrieve&version=1.1&' \
            'maximumRecords=%s&startRecord=%s' % (
                settings.ARTSTOR_GATEWAY,
                urllib.parse.quote(keyword),
                pagesize,
                (page - 1) * pagesize + 1,
            )
        socket.setdefaulttimeout(self.timeout)
        try:
            response = opener.open(urllib.request.Request(url))
        except urllib.error.URLError:
            return None

        try:
            results = ElementTree(file=response)
            total = results.findtext(
                '{http://www.loc.gov/zing/srw/}numberOfRecords') or 0
        except ExpatError:
            total = 0
        if not total:
            return None

        result = dict(records=[], hits=total)
        for image in results.findall('//{info:srw/schema/1/dc-v1.1}dc'):
            for ids in image.findall(
                    '{http://purl.org/dc/elements/1.1/}identifier'):
                if ids.text.startswith('URL'):
                    url = ids.text[len('URL:'):]
                elif ids.text.startswith('THUMBNAIL'):
                    tn = ids.text[len('THUMBNAIL:'):]
            title = image.findtext('{http://purl.org/dc/elements/1.1/}title')
            result['records'].append(dict(
                thumb_url=tn,
                title=title,
                record_url=url))

        cached.results = simplejson.dumps(result, separators=(',', ':'))
        cached.save()
        return result
Exemplo n.º 17
0
    def write(self):
        "actiegegevens terugschrijven"
        if self.file_exists:  # os.path.exists(self.fn):
            tree = ElementTree(file=str(self.fn))
            rt = tree.getroot()
            sett = rt.find('settings')
        else:
            rt = Element("acties")
            sett = SubElement(rt, 'settings')
        # terugschrijven imagecount
        sett.set('imagecount', str(
            self.imagecount))  # moet dit niet parent.parent.imagecount zijn?
        if self.startitem:
            sett.set('startitem', str(self.startitem))

        if not self.exists:
            x = SubElement(rt, "actie")
            x.set("id", self.id)
            x.set("datum", self.datum)
            found = True
        else:
            for x in rt.findall("actie"):
                if x.get("id") == self.id:
                    found = True
                    break
        if found:
            x.set("updated", dt.datetime.today().isoformat(' ')[:10])
            print(self.soort)
            h = self.soort
            if h is None or h == '':
                self.soort = " "
            x.set("soort", self.soort)
            x.set("status", self.status)
            if self.arch:
                x.set("arch", "arch")
            else:
                h = x.get("arch")
                if h is not None:
                    x.set("arch", "herl")
            h = x.find("titel")
            if h is None:
                h = SubElement(x, "titel")
            h.text = self.titel
            h = x.find("melding")
            if h is None:
                h = SubElement(x, "melding")
            h.text = self.melding
            h = x.find("oorzaak")
            if h is None:
                h = SubElement(x, "oorzaak")
            h.text = self.oorzaak
            h = x.find("oplossing")
            if h is None:
                h = SubElement(x, "oplossing")
            h.text = self.oplossing
            h = x.find("vervolg")
            if h is None:
                h = SubElement(x, "vervolg")
            h.text = self.vervolg
            h = x.find("stand")
            if h is None:
                h = SubElement(x, "stand")
            h.text = self.stand
            h = x.find("events")
            if h is not None:
                x.remove(h)
            h = SubElement(x, "events")
            for y, z in self.events:
                q = SubElement(h, "event", id=y)
                q.text = z
            h = x.find("images")
            if h is not None:
                x.remove(h)
            h = SubElement(x, "images")
            for fname in self.imagelist:
                q = SubElement(h, 'image', filename=fname)
                with open(fname, 'rb') as _in:
                    data = _in.read()
                log('length of data:', len(data))
                q.text = str(base64.b64encode(data))
                log('length of text:', len(q.text))
                ## q.text = str(base64.encodebytes(data))
                ## q.text = str(gzip.compress(data)) # let op: bdata, geen cdata !
            tree = ElementTree(rt)
            copyfile(str(self.fn), str(self.fn) + ".old")
            tree.write(str(self.fn), encoding='utf-8', xml_declaration=True)
            self.exists = True
        ## else:
        ## return False
        return found
Exemplo n.º 18
0
 def dump(self, stream):
     if self.prettyprint:
         self.indent(self.xml)
     document = ElementTree(self.xml)
     document.write(stream, encoding=self.encoding, xml_declaration=True)
Exemplo n.º 19
0
#TEMPI AZIONI - se si fanno modifiche cambiare anche altro script
tactionA = 60 * ktime  #[s]
tactionB = 40 * ktime  #[s]
tactionC = 30 * ktime  #[s]
tactionD = 40 * ktime  #[s]

nta = Element("nta")

#declaration of Uppaal variables
declaration = SubElement(
    nta, "declaration"
).text = "chan r,l,u,d,s; int tmove=%d; int tstay=%d; int tactionA=%d; int tactionB=%d; int tactionC=%d; int tactionD=%d; clock x; clock t; int flagactionA=0; int flagactionC=0; int flagactionB=0; int flagactionD=0; int task1completed=0; int task2completed=0; %s" % (
    tmove, tstay, tactionA, tactionB, tactionC, tactionD, dec)

createEnvironmentEncoding2(nta, initstate, pointarray, x_meter_side,
                           span_meter, diameter_footprint)
create_robot_4dof_tipoA(nta, tmove)  #if(tipoA)

#UPPAAL SYSTEM
system = SubElement(
    nta, "system").text = "Room1=Room(); Robot1=Robot(); system Robot1, Room1;"

tree = ElementTree(nta)
a = ET.tostring(nta)
b = minidom.parseString(ET.tostring(nta)).toprettyxml()

with open(sys.argv[2], "w") as f:
    f.write(b)

print("END process")
Exemplo n.º 20
0
  stdout, stderr = p.communicate()
  if not stderr: 
    for line in stdout.split("\n"):
      if "first job" in line:
        jobid = (line.split(":")[1]).strip(" ")
      if "job(s)" in line:
        nJobs = (line.split(" ")[0]).strip(" ")
    theSub = args.name 
    print theSub 
    print "Found jobid:", jobid
    print "nJobs: ", nJobs
    nomvar = "nom" if ("nom" in theSub) else "var"
    print nomvar
    jobid_pre = jobid.split("@")[0]
    print jobid.split("@")
    builder.start("Sub", {"Name":theSub, "Sample":sample, "Type":"nom"})
    for i in range(0,int(nJobs)):
      jobid_end_num = int(jobid_pre[-1]) + i 
      new_jobid = jobid_pre[0:-1] + str(jobid_end_num)
      builder.start("Job", {"ID": new_jobid , "N":str(i)})
      builder.end("Job")
    builder.end("Sub")
  else: print "Error\n", stderr            
builder.end("Jobs")

root = builder.close()
rough = tostring(root, 'utf-8')
reparsed = xdm.parseString(rough) 
tree = ElementTree(fromstring(reparsed.toprettyxml(indent=" ")))
tree.write(args.o)
Exemplo n.º 21
0
 def __init__(self, pod_root):
     """Create a Pod object using the ElementTree at the root"""
     self.root = pod_root
     self.xml_tree = ElementTree(pod_root)
Exemplo n.º 22
0
def boxm2CreateScene(scene_info,
                     boxm2_dir,
                     app1='boxm2_mog3_grey',
                     app2='boxm2_num_obs',
                     app3='boxm2_sum_log_msg_pos'):

    if not os.path.isdir(boxm2_dir + '/'):
        os.mkdir(boxm2_dir + '/')

    if not os.path.isdir(boxm2_dir + '/'):
        print "Invalid scene xml"
        sys.exit(-1)

    print 'Parsing: '
    print scene_info
    print boxm2_dir

    #parse xml file
    tree = ElementTree()
    tree.parse(scene_info)

    #find scene dimensions
    bbox_elm = tree.getroot().find('bbox')

    if bbox_elm is None:
        print "Invalid scene info file: No bbox"
        sys.exit(-1)

    minx = float(bbox_elm.get('minx'))
    miny = float(bbox_elm.get('miny'))
    minz = float(bbox_elm.get('minz'))
    maxx = float(bbox_elm.get('maxx'))
    maxy = float(bbox_elm.get('maxy'))
    maxz = float(bbox_elm.get('maxz'))

    #find scene resolution

    res_elm = tree.getroot().find('min_octree_cell_length')

    if res_elm is None:
        print "Invalid info file: No min_octree_cell_length"
        sys.exit(-1)

    resolution = float(res_elm.get('val'))

    print("Resolution: " + str(resolution))

    res_elm = tree.getroot().find('prior_probability')

    if res_elm is None:
        print "Invalid info file: No prior_probability"
        sys.exit(-1)

    prior_probability = float(res_elm.get('val'))

    #PARAMETERS
    ntrees_x = 32  #was 32
    ntrees_y = 32  #was 32
    ntrees_z = 32  #was 32
    max_num_lvls = 4
    min_pt = [minx, miny, minz]
    max_pt = [maxx, maxy, maxz]

    writeSceneFromBox(boxm2_dir, resolution, min_pt, max_pt, ntrees_x,
                      ntrees_y, ntrees_z, max_num_lvls, app1, app2, app3,
                      prior_probability)
Exemplo n.º 23
0
    def createok(self):

        self.saveFile = self.createle.text()
        self.pw = self.le_pass.text()

        global instance
        instance = self.saveFile

        if self.pw != "":

            if not os.path.exists(self.saveFile):

                self.savefile_fn = os.path.split(self.saveFile)
                self.savefile_fnh = self.savefile_fn[0]
                self.savefile_fnt = self.savefile_fn[1]

                os.makedirs(self.savefile_fnh +
                            '/_{}'.format(self.savefile_fnt))
                self.saveFile = self.savefile_fnh + '/_{}'.format(
                    self.savefile_fnt)

                instance = self.saveFile

                subprocess.run([
                    r'7z\7-Zip\7z.exe', 'a', '-p{}'.format(self.pw),
                    '{}'.format(self.saveFile), '{}'.format(self.saveFile)
                ],
                               shell=False)

                root = ET.Element('programElements')
                tree = ElementTree(root)

                tree.write(open(self.saveFile + '/config.xml', 'wb'))

                xml = ET.parse('settings/programSettings.xml')

                rfp = xml.find('recentfilepath')
                rfp.text = str(self.saveFile)

                xml.write(open('settings/programSettings.xml', 'wb'))
                # might have to make the self.notewin a different name than the one below
                self.notewin = NotesEditing()

                self.creatediaglog.close()

        else:

            if not os.path.exists(self.saveFile):
                os.makedirs(self.saveFile)

            root = ET.Element('programElements')
            tree = ElementTree(root)

            tree.write(open(self.saveFile + '/config.xml', 'wb'))

            xml = ET.parse('settings/programSettings.xml')

            rfp = xml.find('recentfilepath')
            rfp.text = str(self.saveFile)

            xml.write(open('settings/programSettings.xml', 'wb'))

            self.notewin = NotesEditing()

            self.creatediaglog.close()
Exemplo n.º 24
0
def getfavorites(addon_id = None, section = None,mode='section'):
    list1 = []
    debug = True
    print "addon_id,section",addon_id,section
    
    if debug:
        tree = ElementTree()
        tree.parse(xmlfile)
        root = tree.getroot()
        i = 0
        for addon in root.iter('addon'):
            try:
                id = str(addon.get('id'))
            except:
                id = None

            try:
                section_id = str(addon.get('section'))
            except:
                section_id = None

            
            section_id = section_id.replace('_playlist', '')
            print "addon_id,section,section_id",addon_id,section,section_id
            if mode == 'desktop':
                    try:id=id.replace(".","/")
                    except:continue
                    for media in addon.iter('media'):
                        title = str(media.attrib.get('title'))
                        url = str(media.text)
                        print '75id,section_id', id, section_id
                        list1.append((title,
                         url,
                         id,
                         section_id,
                         i))
                        i = i + 1

            elif mode=='addon':
                  if id == addon_id:
                    for media in addon.iter('media'):
                        title = str(media.attrib.get('title'))
                        url = str(media.text)
                        print '75id,section_id', id, section_id
                        list1.append((title,
                         url,
                         id,
                         section_id,
                         i))
                        i = i + 1

            elif mode=='section':
                
                for media in addon.iter('media'):
                    title = str(media.attrib.get('title'))
                    url = str(media.text)
                    print '94id,section_id', id, section_id
                    list1.append((title,
                     url,
                     id,
                     section_id,
                     i))
                    i = i + 1

        print 'list1', list1
        return list1
    else:
        list1.append(('Error reading favorites,repair favorites from Tools', '', '', '', 1))
        print 'error in reading favorite xml file'
        return list1

    return
Exemplo n.º 25
0
    def generate(self, basepath, opts):
        if (opts.includes):
            # Just print out includes and quit here - only used for dependency
            # queries.
            for i in self.includes:
                print i
            exit()

        verbose = opts.verbose
        # Analysis pass: Gather every behavior topics.
        behavior_topics = Set([])
        for b in self.behaviors.values():
            for o in b.output:
                behavior_topics.add((o, b.machine))
        if verbose:
            print "Behavior topics: " + str(behavior_topics)

        # Analysis pass: Register behavior priorities and strategies to the
        # exploitation matcher.
        # NOTE: Could be combined to the previous pass ?
        for s in self.strategies.values():
            u_class = s.utility_class
            for m in s.modules:
                module_name = m.module_name
                if module_name in self.behaviors:
                    bhvr = self.behaviors[module_name]
                    # Registration script is generated later:
                    self.registerExploitationMatch(bhvr, u_class)

        if verbose:
            print "Exploitation matches: " + str(self.exploitationMatches)
        
        # XML launch file, first pass
        # NOTE: Adding the elements also resolve dependencies such as filters
        # enumeration. This is not ideal, but necessary even if we don't use the
        # XML elements in model-only mode.
        launch_elem = Element("launch")

        # Always include included launch files first
        for rl in self.rootLaunch:
            launch_elem.extend(rl.generateXML(self))

        if (not opts.behavior_based):
            if (not opts.no_base_nodes):
                if verbose:
                    print "Adding base HBBA nodes"
                launch_elem.append(baseNodesXML(opts.new_rev, opts.debug))
            if (not opts.no_event_gen):
                if verbose:
                    print "Adding base event generators."
                launch_elem.append(eventNodesXML())

        main_elems = []
        for p in self.procmodules.values():
            main_elems.extend(p.generateXML(self, opts))
        for b in self.behaviors.values():
            main_elems.extend(b.generateXML(self, opts))
        if not opts.behavior_based:
            for m in self.motivations.values():
                main_elems.extend(m.generateXML(self))
        if not opts.disable_arbitration:
            for (t, m) in behavior_topics:
                if t not in self.integratedArbitration:
                    main_elems.extend(self.generateArbitrationXML(t, m, opts))

        if not opts.model_only:
            launch_elem.extend(main_elems)
        else:
            print "Generating output in model-only mode."

        # Python script and second XML generation pass
        if not opts.behavior_based:
            pyscript = ""
            if (self.customScript != ""):
                pyscript += "#Custom script:\n"
                pyscript += "eval_script(\"\"\" \n"
                pyscript += self.customScript
                pyscript += "\n\"\"\")\n\n"
            for e in self.emoIntensities.values():
                pyscript += e.generatePy()
            if not opts.new_rev:
                for s in self.strategies.values():
                    pyscript += s.generatePy()
                pyscript += "\n"
                for r in self.resources.values():
                    pyscript += r.generatePy()
                pyscript += "\n"
            for d in self.desires.values():
                pyscript += d.generatePy()
            pyscript += "\n"
            #if not opts.disable_arbitration:
            #    pyscript += "\n"
            #    pyscript += self.generateExploitationMatchesPy()

            pyscript += "\n\nprint \"Stop this script with Ctrl-C when ready.\"\n"
            pyscript += "rospy.spin()\n"

            if verbose:
                print "Generated Python script:\n"
                print pyscript
                print ""

            if not opts.model_only:
                pyfile_path = basepath + ".py"
                pyfile = file(pyfile_path, "w")
                pyfile.write(python_header_common.format(
                    os.path.join(os.getcwd(), basepath + ".launch"),
                    self.getRootTopicFullName("emo_intensity")))
                os.chmod(pyfile_path, os.stat(pyfile_path).st_mode | stat.S_IEXEC)
                if not opts.new_rev:
                    pyfile.write(python_header_model)

                pyfile.write(pyscript)
                pyfile.close()
                os.chmod(pyfile_path, 0777)

            # XML additions: 
            # The whole solver model as a rosparam:
            launch_elem.append(self.solverModelXML(opts))
            if not opts.model_only:
                # The static list of topic filters:
                launch_elem.append(self.topicFiltersXML(opts))
                # The static list of exploitation matches:
                launch_elem.append(self.generateExploitationMatchesXML(opts))
                # The static list of initial desires:
                launch_elem.extend(self.initialDesiresXML(opts))
            
            # The iw_observer ruleset as a rosparam:
            launch_elem.append(Element("param",
                name="/hbba/iw_observer/ruleset",
                value = self.iwoRuleset))

        elif verbose:
            print "Behavior-based mode - no Python script generated."

        # Final XML generation:
        launch_tree = ElementTree(launch_elem)
        xml_output = tostring(launch_elem)
        if opts.pretty:
            reparsed = minidom.parseString(xml_output)
            xml_output = reparsed.toprettyxml(indent="  ")

        if verbose:
            print "Generated XML:\n"
            print xml_output

        xmlfile = file(basepath + ".launch", "w")
        xmlfile.write(xml_output)
Exemplo n.º 26
0
                "CESM build type selected, but could not find Machines.")
        else:
            machines_dir = None

if machines_dir is None:
    compiler_xml = None
else:
    compiler_xml = os.path.join(machines_dir, "config_compilers.xml")
    assert file_exists(compiler_xml), "Machines directory should be "+ \
        machines_dir+" but no config_compilers.xml is there!"

# Get test specification directories from command line options.
suite_specs = []

if options.xml_test_list is not None:
    test_xml_tree = ElementTree()
    test_xml_tree.parse(options.xml_test_list)
    known_paths = {
        "here": os.path.abspath(os.path.dirname(options.xml_test_list)),
    }
    suite_specs.extend(suites_from_xml(test_xml_tree, known_paths))

if options.test_spec_dir is not None:
    suite_specs.append(
        TestSuiteSpec("__command_line_test__", ["__command_line_test__"],
                      [os.path.abspath(options.test_spec_dir)]))

# Create build directory if necessary.
build_dir = os.path.abspath(options.build_dir)

if not file_exists(build_dir):
Exemplo n.º 27
0
 def __init__(self, path, base_url):
     self.local_path = pathlib.Path(path)
     self.base_url = base_url
     self.files = []
     self.root_elem = Element('urlset', xmlns=SCHEMA)
     self.sitemap = ElementTree(self.root_elem)
Exemplo n.º 28
0
    def _load_jmdict(fname):
        with lzma.open(fname, 'rt', encoding='utf-8') as f:
            tree = ElementTree()
            tree.parse(f)

        data = set()

        def parse_entry(entry):
            kanji = [
                Variant(
                    ele.find('keb').text,
                    [EntryType(inf.text) for inf in ele.findall('ke_inf')],
                    [pri.text for pri in ele.findall('ke_pri')])
                for ele in entry.findall('k_ele')
            ]
            # FIXME ignoring re_restr for now
            readings = [
                Variant(
                    ele.find('reb').text,
                    [EntryType(inf.text) for inf in ele.findall('re_inf')] +
                    ([EntryType('nokanji')] if ele.find('re_nokanji') else []),
                    [pri.text for pri in ele.findall('re_pri')])
                for ele in entry.findall('r_ele')
            ]
            # NOTE: We are ignoring any <etym>, <bibl> or <audit> elements. The former two are not in use as of the time
            # this code is written (September 2014) and the latter one does not seem interesting at the moment. - jaseg
            links = [
                Link(
                    link.find('link_tag').text,
                    link.find('link_desc').text,
                    link.find('link_uri').text)
                for info in entry.findall('info')
                for link in info.findall('links')
            ]

            # NOTE: For now, we are ignoring the g_gend attribute as well as the <pri> and <example> elements since
            # these are not used at the time this code is written (September 2014). - jaseg
            # <!ELEMENT sense (s_inf*, lsource*, gloss*)>
            sense_elems = entry.findall('sense')
            translations = []
            for sense in sense_elems:
                stagk = [stagk.text for stagk in sense.findall('stagk')]
                stagr = [stagr.text for stagr in sense.findall('stagr')]
                pos = [EntryType(pos.text) for pos in sense.findall('pos')]
                xref = [xref.text for xref in sense.findall('xref')]
                ant = [ant.text for ant in sense.findall('ant')]
                field = [field.text for field in sense.findall('field')]
                misc = [EntryType(misc.text) for misc in sense.findall('misc')]
                dial = [EntryType(dial.text) for dial in sense.findall('dial')]
                sinf = [inf.text for inf in sense.findall('s_inf')]
                gloss_dict = groupdict(
                    (gloss.get(LANG_ATTR, 'eng'), gloss.text)
                    for gloss in sense.findall('gloss'))
                gloss = gloss_dict['eng']
                translations.append(
                    Translation(gloss, gloss_dict, stagk, stagr, pos, xref,
                                ant, field, misc, dial, sinf))

            return Entry(kanji, readings, translations, links)

        entries = [
            parse_entry(entry) for entry in tree.getroot().findall('entry')
        ]
        mapping = groupdict((key.moji, entry) for entry in entries
                            for key in entry.kanji + entry.readings)
        return entries, mapping
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
#parse the XML file - test.xml
root = tree.parse("test.xml")
#iterate over items to find specific product number - 12345678
for node in root.findall('./Items'):
    for type in list(node):
        if type.find('ProductNo').text == "12345678":
            print(type.find('MD5').text)
            print('found')
        else:
            print("not found")
Exemplo n.º 30
0
                add_lang_period = input("  > 학습 기간(년/개월 단위): ")
                add_lang_level = input("  > 수준(상,중,하): ")
                # 개발언어, 수준의 속성을 가지는 language Element 생성하고 값 삽입
                language = Element("language",
                                   name=add_lang_name,
                                   level=add_lang_level)
                # 개발기간의 속성을 가지는 period Element 생성하고 값 삽입
                period = Element("period", value=add_lang_period)
                language.append(
                    period)  # period Element를 language Element의 하위 element로 연결
                practicable.append(
                    language
                )  # language Element를 practicable_computer_lanuguages의 하위 element로 연결
            root.append(student)

            ElementTree(root).write("students_info.xml")

    elif menu_input == 3:  # 조회
        while True:
            read_menu_input = input(
                "<조회 서브 메뉴>\n1. 개별 학생 조회\n2. 전체 학생 조회\n3. 상위 메뉴\n4. 종료\n메뉴 입력 : "
            )
            if read_menu_input == '1':
                while True:
                    saved_number = []
                    search_con = input(
                        "<검색 조건>\n1. ID\n2. 이름\n3. 나이\n4. 전공\n5. 컴퓨터 언어 명\n6. 컴퓨터 언어 학습 기간"
                        "\n7. 컴퓨터 언어 레벨\n8. 상위메뉴\n메뉴 입력: ")
                    if search_con == '8':
                        break
                    else: