def toXML(self): '''Generate the xml representation of the letter matrix''' # <control type="panel"> control = Element('control', type='panel', id=str(CONTROL_PANEL)) if True: SubElement(control, 'posx').text = str(self.posx) SubElement(control, 'posy').text = str(self.posy) SubElement(control, 'width').text = str(self.width) SubElement(control, 'height').text = str(self.height) SubElement(control, 'onleft').text = '-' SubElement(control, 'onright').text = '-' SubElement(control, 'onup').text = '-' SubElement(control, 'ondown').text = '-' SubElement(control, 'viewtype', label='').text = 'panel' SubElement(control, 'pagecontrol').text = '-' SubElement(control, 'scrolltime').text = '-' SubElement(control, 'hitrect', x=str(-10), y=str(-10), w=str(1), h=str(1)) # <itemlayout> itemlayout = SubElement(control, 'itemlayout', height=str(self.letterHeight), width=str(self.letterWidth)) if True: self.addItemLayout(itemlayout, self.theme.inactive, 1) self.addItemLayout(itemlayout, self.theme.active, 2) # </itemlayout> SubElement(control, 'focusedlayout', height=str(self.height), width=str(self.width)) # <content> content = SubElement(control, 'content') if True: # <item> for letter in self.letters: content.append(letter.toXML()) # </item> # </content> # </control> return control
def gencix(major, minor): # First generate first pass at the CILE over all of the lib tree cixfile = "activeperl-%d.%d.cix" % (major, minor) command = "python ../../../ci2.py scan -n -r -p -l Perl -T /tmp/ActivePerl-%d.%d/perl/lib -i \"*.pm\"> %s" % ( major, minor, cixfile) retval = os.system(command) if retval != 0: print "Error scanning ActivePerl library" sys.exit(retval) # # Grab the output of that scan root = parse(cixfile).getroot() newroot = Element("codeintel", version="2.0") cixfile = SubElement(newroot, "file", lang="Perl", mtime=str(int(time.time())), path=os.path.basename('perl.cix')) for file in root.getiterator('file'): print >> sys.stderr, "Processing", file.get('path') for blob in file: if blob.get("src"): # Don't want the src string. del blob.attrib["src"] cixfile.append(blob) cix = genPerlStdCIX( cixfile, "/tmp/ActivePerl-%d.%d/perl/lib/pod/perlfunc.pod" % (major, minor)) parent_map = dict((c, p) for p in cixfile.getiterator() for c in p) for variable in newroot.getiterator('variable'): attributes = variable.get('attributes') if attributes and '__local__' in variable.get('attributes'): parent_map[variable].remove(variable) # Generate the CIX. print >> sys.stderr, "Prettying" prettify(newroot) tree = ElementTree(newroot) #fname = '../../../lib/codeintel2/stdlibs/perl-%d.%d.cix' % (major, minor) fname = 'perl-%d.%d.cix' % (major, minor) #os.system('p4 edit %s' % fname) stream = open(fname, "w") print >> sys.stderr, "Writing" stream.write('<?xml version="1.0" encoding="UTF-8"?>\n') tree.write(stream) stream.close()
def gencix(major, minor): # First generate first pass at the CILE over all of the lib tree cixfile = "activeperl-%d.%d.cix" % (major, minor) command = "python ../../../ci2.py scan -n -r -p -l Perl -T /tmp/ActivePerl-%d.%d/perl/lib -i \"*.pm\"> %s" % (major, minor, cixfile) retval = os.system(command) if retval != 0: print "Error scanning ActivePerl library" sys.exit(retval) # # Grab the output of that scan root = parse(cixfile).getroot() newroot = Element("codeintel", version="2.0") cixfile = SubElement(newroot, "file", lang="Perl", mtime=str(int(time.time())), path=os.path.basename('perl.cix')) for file in root.getiterator('file'): print >> sys.stderr, "Processing", file.get('path') for blob in file: if blob.get("src"): # Don't want the src string. del blob.attrib["src"] cixfile.append(blob) cix = genPerlStdCIX(cixfile, "/tmp/ActivePerl-%d.%d/perl/lib/pod/perlfunc.pod" % (major, minor)) parent_map = dict((c, p) for p in cixfile.getiterator() for c in p) for variable in newroot.getiterator('variable'): attributes = variable.get('attributes') if attributes and '__local__' in variable.get('attributes'): parent_map[variable].remove(variable) # Generate the CIX. print >>sys.stderr, "Prettying" prettify(newroot) tree = ElementTree(newroot) #fname = '../../../lib/codeintel2/stdlibs/perl-%d.%d.cix' % (major, minor) fname = 'perl-%d.%d.cix' % (major, minor) #os.system('p4 edit %s' % fname) stream = open(fname, "w") print >>sys.stderr, "Writing" stream.write('<?xml version="1.0" encoding="UTF-8"?>\n') tree.write(stream) stream.close()
def toXML(self): # <window> window = Element('window', id=str(WINDOW_ID)) if True: # Fade in for 1.0 second (but not in screensaver mode) if not self.screensaverMode: SubElement(window, 'animation', effect='fade', time=str(1000)).text = 'WindowOpen' # <controls> controls = SubElement(window, 'controls') if True: # <control type="image"> color = Image(1280, 720, BACKGROUND_IMAGE, self.theme.background) controls.append(color.toXML()) # </control> # <control type="image"> if self.theme.image: image = Image(self.theme.imageWidth, self.theme.imageHeight, self.theme.image) else: # Placeholder for if we change the theme by pressing T image = Image(1280, 720, '-') controls.append(image.toXML()) # </control> #sprites = Sprites(self.layout, self.theme) #controls.append(sprites.toXML()) # <control type="panel"> matrix = Matrix(self.letters, self.layout, self.theme) controls.append(matrix.toXML()) # </control> # </controls> # </window> return window
def __init__(self, lstData, GeoType, strPath, strFilename, strLayername): dctWriteKML = {'Point': self.writePoint, 'Polyline': self.writeLine, 'Polygon': self.writePolygon} #Create new element tree with a root of KML... objRoot = Element("{http://earth.google.com/kml/2.1}kml") objTree = ElementTree(element=objRoot) elemDoc = SubElement(objRoot, 'Document') elemDocName = SubElement(elemDoc, 'name') #According the KML spec, default Polystyle stuff goes here... elemDocName.text = strLayername #Add a document name element here...populate from supplied parameters for objRow in lstData: elemPlace = SubElement(elemDoc, 'Placemark') elemName =SubElement(elemPlace,'name') elemName.text = objRow['Name'] #Add support for the description tag... elemDesc = SubElement(elemPlace, 'description') elemDesc.text = objRow['Description'] elemGeo = dctWriteKML.get(GeoType, self.errHandler)(objRow['Geometry'], elemPlace) elemPlace.append(elemGeo) self.Write(objTree, strPath, strFilename)
def add_task(self, taskid, tasktype, folder=None): """Add a task to the default xml task sheet Args: taskid: unique ID for new task for tracking individual tasks tasktype: Identifier to track purpose of task folder: Name of output folder if necessary Returns: None Raises: None """ if tasktype == "processSolr": if folder == None: folder = self.solrFolder root = self.tree.getroot() newTask = SubElement(root, "task") newNode = Element("status") newNode.text = "pending" newTask.append(newNode) newNode = Element("taskid") newNode.text = str(taskid) newTask.append(newNode) newNode = Element("directory") newNode.text = str(folder) newTask.append(newNode) self.tree.write("outfile.xml") elif tasktype == "processTopic": print "Processing topic modeling data" if folder == None: folder = self.topicFolder else: print "Unknown task" + tasktype
def main(): if len(sys.argv) != 2: print 'Usage: ' + sys.argv[0] + ' <CSV file>' sys.exit(1) pathToCSV = sys.argv[1] f = open(pathToCSV) dataDict = csv.DictReader(f) intensity = "Resting" triggerMethod = "Distance" tcxTrackpoints = {} earliestEpochMS = earliestTimeInDict(dataDict) earliestEpoch = math.floor(int(earliestEpochMS) / 1000) root = Element("TrainingCenterDatabase") root.set("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd") root.set("xmlns:ns2", "http://www.garmin.com/xmlschemas/UserProfile/v2") root.set("xmlns:ns3", "http://www.garmin.com/xmlschemas/ActivityExtension/v2") root.set("xmlns:ns4", "http://www.garmin.com/xmlschemas/ProfileExtension/v1") root.set("xmlns:ns5", "http://www.garmin.com/xmlschemas/ActivityGoals/v1") root.set("xmlns", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2") root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") actsElement = SubElement(root, "Activities") actElement = SubElement(actsElement, "Activity", Sport="Running") idElement = SubElement(actElement, "Id") idElement.text = stringGMTimeFromEpoch(earliestEpoch) lastTimeEpoch = 0 lapElement = SubElement(actElement, "Lap", StartTime=stringGMTimeFromEpoch(earliestEpoch)) totalDistanceMeters = 0 maxSpeed = 0 calories = 0.0 maxBPM = 0 numRows = 0 totalBPM = 0 trackpoints = list() for row in dataDict: trackpointElement = Element("Trackpoint") trackpoints.append(trackpointElement) # TIME epochMS = row['timestamp_epoch'] epoch = math.floor(int(epochMS) / 1000) timeElement = SubElement(trackpointElement, "Time") timeElement.text = stringGMTimeFromEpoch(epoch) # POSITION latValue = row['LATITUDE'] longValue = row['LONGITUDE'] if (abs(float(latValue)) <= 180 and abs(float(longValue)) <= 180 and abs(float(latValue)) > 0.1 and abs(float(longValue)) > 0.1): posElement = SubElement(trackpointElement, "Position") latElement = SubElement(posElement, "LatitudeDegrees") latElement.text = latValue longElement = SubElement(posElement, "LongitudeDegrees") longElement.text = longValue # Altitude alt = row['ELEVATION'] altElement = SubElement(trackpointElement, "AltitudeMeters") altElement.text = alt # DISTANCE distanceMeters = row['DISTANCE'] distElement = SubElement(trackpointElement, "DistanceMeters") distElement.text = distanceMeters # BPM heartRate = math.trunc(float(row['HEARTRATE'])) # if heartRate > 0: bpmElement = SubElement(trackpointElement, 'HeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\"') bpmValElement = SubElement(bpmElement, "Value") bpmValElement.text = str(heartRate) extElement = SubElement(trackpointElement, 'Extensions') # SPEED speed = float(row['SPEED']) speed *= MPS_TO_MPH ns3Element = SubElement(extElement, 'ns3:TPX') speedElement = SubElement(ns3Element, 'ns3:Speed') speedElement.text = str(speed) if lastTimeEpoch == 0 or epoch > lastTimeEpoch: lastTimeEpoch = epoch if totalDistanceMeters == 0 or float(distanceMeters) > float(totalDistanceMeters): totalDistanceMeters = distanceMeters rowCalories = row['CALORIEBURN'] calories = rowCalories if maxBPM == 0 or heartRate > maxBPM: maxBPM = heartRate numRows += 1 totalBPM += heartRate # TIME totalTimeSeconds = lastTimeEpoch - earliestEpoch avgBPM = totalBPM / numRows totalTimeElement = SubElement(lapElement, "TotalTimeSeconds") totalTimeElement.text = str(int(totalTimeSeconds)) # DISTANCE totalDistanceElement = SubElement(lapElement, "DistanceMeters") totalDistanceElement.text = totalDistanceMeters # CALORIES totalCalsElement = SubElement(lapElement, "Calories") totalCalsElement.text = str(int(float(calories))) # BPM # if avgBPM > 0: avgBPMElement = SubElement(lapElement, 'AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') avgBPMValElement = SubElement(avgBPMElement, "Value") avgBPMValElement.text = str(int(avgBPM)) # if maxBPM > 0: maxBPMElement = SubElement(lapElement, 'MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') maxBPMValElement = SubElement(maxBPMElement, "Value") maxBPMValElement.text = str(int(maxBPM)) # INTENSITY intensityElement = SubElement(lapElement, "Intensity") intensityElement.text = "Active" #TRIGGER triggerElement = SubElement(lapElement, "TriggerMethod") triggerElement.text = "Distance" # Append trackpoints trackElement = SubElement(lapElement, "Track") for trackpoint in trackpoints: trackElement.append(trackpoint) print XMLHeader() + tostring(root)
def main(argv): scale = 1.0 pathToCSV = "" forceHRM = False removePauses = False sport = "Running" lat = 0.0 longt = 0.0 ylat = 37.337766 ylong = -121.920347 try: opts, args = getopt.getopt(argv, "hbpYs:i:t:l:",["scale=", "ifile=", "sport=", "location="]) except getopt.GetoptError: usage() sys.exit(1) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ("-s", "--scale"): scale = float(arg) elif opt in ("-i", "--ifile"): pathToCSV = arg elif opt in ("-t", "--sport"): sport = arg elif opt in ("-l", "--location"): lat, longt = arg.split(",") lat = float(lat) longt = float(longt) elif opt == '-Y': lat = ylat longt = ylong elif opt == '-b': forceHRM = True elif opt == '-p': removePauses = True if pathToCSV == "": usage() sys.exit(1) f = open(pathToCSV) dataDict = csv.DictReader(f) intensity = "Resting" triggerMethod = "Distance" tcxTrackpoints = {} earliestEpochMS = earliestTimeInDict(dataDict) earliestEpoch = math.floor(int(earliestEpochMS) / 1000) root = Element("TrainingCenterDatabase") root.set("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd") root.set("xmlns:ns2", "http://www.garmin.com/xmlschemas/UserProfile/v2") root.set("xmlns:ns3", "http://www.garmin.com/xmlschemas/ActivityExtension/v2") root.set("xmlns:ns4", "http://www.garmin.com/xmlschemas/ProfileExtension/v1") root.set("xmlns:ns5", "http://www.garmin.com/xmlschemas/ActivityGoals/v1") root.set("xmlns", "http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2") root.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") actsElement = SubElement(root, "Activities") actElement = SubElement(actsElement, "Activity", Sport=sport) idElement = SubElement(actElement, "Id") idElement.text = stringGMTimeFromEpoch(earliestEpoch) lastTimeEpoch = 0 lapElement = SubElement(actElement, "Lap", StartTime=stringGMTimeFromEpoch(earliestEpoch)) totalDistanceMeters = 0 maxSpeed = 0 calories = 0.0 maxBPM = 0 maxSpeed = 0.0 numRows = 0 totalBPM = 0 epochStart = 0 diff = 0 trackpoints = list() for row in dataDict: speed = scale * float(row['SPEED']) stepRate = int(row['STEP_RATE']) mCadence = int(row['CADENCE']) if speed > maxSpeed: maxSpeed = speed if not removePauses or (speed > 0 and stepRate > 0): if epochStart != 0: diff += int(row['timestamp_epoch']) - epochStart epochStart = 0 trackpointElement = Element("Trackpoint") trackpoints.append(trackpointElement) # TIME epochMS = row['timestamp_epoch'] epoch = math.floor((int(epochMS) - diff) / 1000) timeElement = SubElement(trackpointElement, "Time") timeElement.text = stringGMTimeFromEpoch(epoch) # POSITION if (lat == 0.0 and longt == 0.0): latValue = row['LATITUDE'] longValue = row['LONGITUDE'] else: latValue = str(lat) longValue = str(longt) if (abs(float(latValue)) <= 180 and abs(float(longValue)) <= 180 and abs(float(latValue)) > 0.1 and abs(float(longValue)) > 0.1): posElement = SubElement(trackpointElement, "Position") latElement = SubElement(posElement, "LatitudeDegrees") latElement.text = latValue longElement = SubElement(posElement, "LongitudeDegrees") longElement.text = longValue # Altitude alt = row['ELEVATION'] altElement = SubElement(trackpointElement, "AltitudeMeters") altElement.text = alt # DISTANCE distanceMeters = str(scale * float(row['DISTANCE'])) distElement = SubElement(trackpointElement, "DistanceMeters") distElement.text = distanceMeters # BPM heartRate = math.trunc(float(row['HEARTRATE'])) if forceHRM or heartRate > 0: bpmElement = SubElement(trackpointElement, 'HeartRateBpm xsi:type=\"HeartRateInBeatsPerMinute_t\"') bpmValElement = SubElement(bpmElement, "Value") bpmValElement.text = str(heartRate) extElement = SubElement(trackpointElement, 'Extensions') # SPEED speed *= MPS_TO_MPH ns3Element = SubElement(extElement, 'ns3:TPX') speedElement = SubElement(ns3Element, 'ns3:Speed') speedElement.text = str(speed) if lastTimeEpoch == 0 or epoch > lastTimeEpoch: lastTimeEpoch = epoch if totalDistanceMeters == 0 or float(distanceMeters) > float(totalDistanceMeters): totalDistanceMeters = distanceMeters rowCalories = row['CALORIEBURN'] calories = rowCalories if maxBPM == 0 or heartRate > maxBPM: maxBPM = heartRate numRows += 1 totalBPM += heartRate # CADENCE cadenceElement = SubElement(trackpointElement, "Cadence") if mCadence == 0: cadenceElement.text = str(stepRate / 2) else: cadenceElement.text = str(mCadence) elif epochStart == 0: epochStart = int(row['timestamp_epoch']) # TIME totalTimeSeconds = lastTimeEpoch - earliestEpoch avgBPM = totalBPM / numRows totalTimeElement = SubElement(lapElement, "TotalTimeSeconds") totalTimeElement.text = str(int(totalTimeSeconds)) # DISTANCE totalDistanceElement = SubElement(lapElement, "DistanceMeters") totalDistanceElement.text = totalDistanceMeters # MAX SPEED if maxSpeed > 0.0: maxSpeedElement = SubElement(lapElement, "MaximumSpeed") maxSpeedElement.text = str(maxSpeed) # CALORIES totalCalsElement = SubElement(lapElement, "Calories") totalCalsElement.text = str(int(float(calories))) # BPM if forceHRM or avgBPM > 0: avgBPMElement = SubElement(lapElement, 'AverageHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') avgBPMValElement = SubElement(avgBPMElement, "Value") avgBPMValElement.text = str(int(avgBPM)) if forceHRM or maxBPM > 0: maxBPMElement = SubElement(lapElement, 'MaximumHeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t"') maxBPMValElement = SubElement(maxBPMElement, "Value") maxBPMValElement.text = str(int(maxBPM)) # INTENSITY intensityElement = SubElement(lapElement, "Intensity") intensityElement.text = "Active" #TRIGGER triggerElement = SubElement(lapElement, "TriggerMethod") triggerElement.text = "Distance" # Append trackpoints trackElement = SubElement(lapElement, "Track") for trackpoint in trackpoints: trackElement.append(trackpoint) print XMLHeader() + tostring(Comment("Scale: "+str(scale))) + tostring(root)