Multiply with XML in FLEX - apache-flex

I write a code which is return the following XML which contain in a string type variable.
<imageedit>
<matrix a="0.5213903738845257" b="0" c="0" d="0.5213903738845257" tx="559.6" ty="1.0784769629138395"/>
<cutout x="0" y="0" width="400" height="568"/>
</imageedit>
Now i want to multiply all the nodes with 3 and again store in that string type variable. how can i do this?

You can use E4X to access attributes like this:
var xml : XML = <imageedit>
<matrix a="0.5213903738845257" b="0" c="0" d="0.5213903738845257" tx="559.6" ty="1.0784769629138395"/>
<cutout x="0" y="0" width="400" height="568"/>
</imageedit>
xml.matrix.#a = Number(xml.matrix.#a)*3
and the same for other attributes. You can also iterate through them with 'for each'.

Related

Not able to format milliseconds with DateTimeFormatter

I am not able to get milliseconds with DateTimeFormatter. I lost a few hair to this already:
<fx:Declarations>
<s:DateTimeFormatter id="dtf"
dateTimePattern="{pattern.text}"
errorText="Invalid input value"/>
</fx:Declarations>
<s:HGroup>
<s:TextInput id="pattern" />
<s:Label text="{dtf.format( new Date())}" />
</s:HGroup>
When I type "y-MM-dd HH:mm:ss.SSS#" in {pattern} , I am not seeing anything between the dot and the pound sign. Does SSS only work for parsing?
Well, that's my solutions then:
<fx:Declarations>
<s:DateTimeFormatter id="dtf"
dateTimePattern="{pattern.text}"
errorText="Invalid input value"/>
</fx:Declarations>
<s:HGroup includeIn="start" bottom="5" left="5">
<s:TextInput id="pattern" />
<s:Label text="{dtf.format( new Date()) + (new Date().milliseconds + 1000).toString().substr(1)}" />
</s:HGroup>
And the pattern would be "y-MM-dd HH:mm:ss."
Try using the mx DateFormatter formatter rather than spark DateTimeFormatter.
The format strings for date formatting in DateFormatter may are slightly different than other time/date formatters but milliseconds (Q) is supported and does work.
With Apache Flex 4.10 (and above) this code:
protected function traceDate():void
{
var df:DateFormatter = new DateFormatter()
df.formatString="YYYY-MM-DD HH:NN:SS.QQQQ#";
trace(df.format(new Date()));
}
Produces a time date string like so:
2013-11-30 09:40:11.0528#
End the date string with "." or ":"
example if the date string is "2018-04-19 16:46:49.766"
then make it "2018-04-19 16:46:49.766" + "."
or
"2018-04-19 16:46:49.766" + ":"

Get and save value from Dataservice Flex

I'm trying to learn Flex, I setup a simple Air application with PHP server as dataserice...
In my php class there is a function counttotal that return a simple int value.
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:demologicaclass="services.demologicaclass.*"
width="682" height="397" showStatusBar="false" initialize="init()">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexEvent;
protected var count:int = 0;
protected function init():void
{
counttotalResult.token = logicaservice.counttotal();
count = counttotalResult.lastResult as int;
}
protected function get_count():void
{
Alert.show(count as String);
}
.....
.....
<s:Label id="countitems" left="10" bottom="39" width="221" height="21"
fontSize="20"
fontWeight="bold" text="{counttotalResult.lastResult as String}"/>
<s:Button right="10" bottom="39" label="Controlla" click="get_count();"/>
In the label I got the correct value, but I can't save and show the value into/from a simple variable...
That's because using the keyword as will make Flex to try to cast a type to another, with a risk that the cast fails. Here, you try to cast a String as an integer, which basically means you do the following :
take 'blabla' and check if it's an integer. If it is, put its value in
count, otherwise put null in it.
What you want to do is transtype (not sure about the word, though) a String to an integer. To do this, use the following syntax :
count = int(Number(counttotalResult.lastResult));
The above means
Take lastResult, and convert it into a Number, and then into an int.
The conversion can fail (but it wont, as long as lastResult is the string representation of a valid number), and the syntax could be shorter, but in a nutshell, that's the difference between casting a type to another, and converting a type to another.

DataSet.WriteXml() - how to "drop" some fields

I've 2 questions:
First, I've a dataset with 5 tables. I've made the relationships of tables and generating an XML from this dataset like this:
StreamWriter xmlDoc = new StreamWriter("myxml.xml", false);
ds.WriteXml(xmlDoc);
xmlDoc.Close();
Some of the fields in each table in dataset are primary keys and I dont want to show them in XML. If I exclude them from tables, I cant make relationships. Can anybody give me some idea that how to write dataset to XML "droping" the key fields (columns in datatables)? For example, here is the XML generating at the moment:
<?xml version="1.0"?>
<o>
<sp spname="SP1" spid="8">
<event spid="8" eventname="Event1" eventId="482">
<bm bmname="BM1" bmid="2" bmeid="826" eventid="482">
<att bmeid="826" val="3.00" attname="Att1" atttype="Type1" attid="23172"/>
<att bmeid="826" val="3.50" attname="Att2" bettype="Type1" attid="23173"/>
</bm>
</event>
</sp>
</o>
but I want this XML to be generated like this (all id attributes should be "dropped" as all ids are for relationships and should not be added in XML):
<?xml version="1.0"?>
<o>
<sp spname="SP1">
<event eventname="Event1">
<bm bmname="BM1" bmid="2">
<att val="3.00" attname="Att1" atttype="Type1" />
<att val="3.50" attname="Att2" bettype="Type1" />
</bm>
</event>
</sp>
</o>
And now 2nd question:
I've given name to my dataset as "o" so its generating the xml as you can see above. I want to add some attributes to <o> node like current datetime. I mean I want <o> node to be genrated as <o generatedDate="09/13/2011" generatedTime="03:45 PM">. How can I achieve it?
Thanks,
You can hide the column to exclude it from the XML-File:
dataSet.Tables["TableName"].Columns["ColumnName"].ColumnMapping = MappingType.Hidden;
One option is to use LINQ to XML to alter the document. Another option would be to pass the XML into an XSLT transformer, which can parse the XML and output the desired results.
Transforming a DataSet using XSLT:
DataTable table = new DataTable();
System.IO.StringWriter writer = new System.IO.StringWriter();
//notice that we're ignoring the schema so we get clean XML back
//you can change the write mode as needed to get your result
table.WriteXml(writer, XmlWriteMode.IgnoreSchema, false);
string dataTableXml = writer.ToString();
As for displaying it in a readable format, I would suggest passing the XML into an XSL transformer, which you can then use to parse the XML and manipulate the output as needed.
Applying an XSLT Transform to a DataSet
http://msdn.microsoft.com/en-us/library/8fd7xytc%28v=vs.71%29.aspx#Y289
Here's a simple example I created to explain how you would use the XSL transformer. I haven't tested it, but it should be pretty close:
DataSet ds = new DataSet();
StringBuilder sbXslOutput = new StringBuilder();
using (XmlWriter xslWriter = XmlWriter.Create(sbXslOutput))
{
XslCompiledTransform transformer = new XslCompiledTransform();
transformer.Load("transformer.xsl");
XsltArgumentList args = new XsltArgumentList();
transformer.Transform(new XmlDataDocument(ds), args, xslWriter);
}
string dataSetHtml = sbXslOutput.ToString();
Formatting XML as HTML using XSLT
Here's an example of using XSLT to transform XML into an HTML table. It should be fairly easy to adopt so you can use it with your serialized DataSet.
Let's say this is your DataSet, serialized to XML:
<RecentMatter>
<UserLogin>PSLTP6\RJK</UserLogin>
<MatterNumber>99999-2302</MatterNumber>
<ClientName>Test Matters</ClientName>
<MatterName>DP Test Matter</MatterName>
<ClientCode>99999</ClientCode>
<OfficeCode/>
<OfficeName/>
<Billable>true</Billable>
<ReferenceId/>
<LastUsed>2011-08-23T23:40:24.13+01:00</LastUsed>
</RecentMatter>
<RecentMatter>
<UserLogin>PSLTP6\RJK</UserLogin>
<MatterNumber>999991.0002</MatterNumber>
<ClientName>Lathe 1</ClientName>
<MatterName>LW Test 2</MatterName>
<ClientCode/>
<OfficeCode/>
<OfficeName/>
<Billable>true</Billable>
<ReferenceId/>
<LastUsed>2011-07-12T16:57:27.173+01:00</LastUsed>
</RecentMatter>
<RecentMatter>
<UserLogin>PSLTP6\RJK</UserLogin>
<MatterNumber>999991-0001</MatterNumber>
<ClientName>Lathe 1</ClientName>
<MatterName>LW Test 1</MatterName>
<ClientCode/>
<OfficeCode/>
<OfficeName/>
<Billable>false</Billable>
<ReferenceId/>
<LastUsed>2011-07-12T01:59:06.887+01:00</LastUsed>
</RecentMatter>
</NewDataSet>
Here's an XSLT script that transforms the DataSet to HTML:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<table border="1">
<tr>
<th>User Login</th>
<th>Matter Number</th>
...
</tr>
<xsl:for-each select="NewDataSet/RecentMatter">
<tr>
<td>
<xsl:value-of select="UserLogin"/>
</td>
<td>
<xsl:value-of select="MatterNumber"/>
</td>
...
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
I would suggest after generating the XML, use LINQ to XML to filter out / add attribute to desired nodes. This filtering and adding attribute is a separate step then generating the XML from data set and should be handled after the XML is generated from data set as that would lead to better design.

How to import unusual data formats into R?

Format consist of lines, every line has set of key="value" elements.
Format example:
X="1" Y="2" Z="who are you?"
Y="4" Z="bla bla..."
X="42"
I would like to import this data into R, table or data.frame, where key defines column.
The following code parses the file you provided in a 'melted' form:
data<-NULL
stream<-file("path");open(stream) #or stream<- textConnection(' X="1" Y="2" Z="who are you?" Y="4" Z="bla bla..." X="42"')
while(length(ele<-c(scan(stream,what="string",n=1,sep="="),scan(stream,what="string",n=1,sep=" ")))>0){
data<-rbind(data,ele);
}
close(stream);
print(data);
Now crystallizing:
sapply(unique(data[,1]),function(key) data[data[,1]==key,2])

flex3 Format date without timezone

I'm receiving a date from a server in milliseconds since 1-1-1970. I then use the DateFormatter to print the date to the screen. However, Flex adds timedifference and thus it displays a different time than what I got from the server. I've fixed this by changing the date before printing to screen. But I think that's a bad solution because the date object doesn't hold the correct date.
Does anyone know how to use the dateFormatter to print the date, ignoring the timezone?
this is how I did it:
function getDateString(value:Date):String
{
var millisecondsPerMinute:int = 1000*60;
var newDate:Date = new Date(value.time - (millisecondsPerMinute*value.timezoneOffset));
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = "EEEE DD-MM-YYYY LL:MM AA";
return dateFormatter.format(newDate);
}
Maybe there is something I'm missing but this seems to work for me.
<?xml version="1.0"?>
<!-- formatters\FormatterDateField.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- Declare a DateFormatter and define formatting parameters.-->
<mx:DateFormatter id="dateFormatter"
formatString="EEEE DD-MM-YYYY LL:NN:SS AA"/>
<mx:Label text="Millis (1220836618601 == Monday 08-09-2008 01:16:58 AM):"/>
<mx:TextInput id="dob" text="1220836618601"/>
<mx:Label text="Formatted date UTC: "/>
<mx:TextInput id="formattedDate"
text=""
editable="false"/>
<mx:Label text="Formatted date local: "/>
<mx:TextInput id="formattedDateLoc"
text=""
editable="false"/>
<!-- Format and update the date.-->
<mx:Button label="Format Input"
click="
var d :Date = new Date(parseInt(dob.text));
formattedDate.text=dateFormatter.format(d.toUTCString());
formattedDateLoc.text=dateFormatter.format(d);
"/>
</mx:Application>
Suggesting that instead of passing the date object (which is timezone dependant) into the dateFormatter, pass in the date object's UTC String instead. I didn't find anything that would suggest that the DateFormatter does anything to the timezone, so there shouldn't be any need to try to compensate for the timezone, especially when the date object already provides a method for getting the UTC.
function getDateString(value:Date):String
{
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = "EEEE DD-MM-YYYY LL:MM AA";
return dateFormatter.format(value.toUTCString());
}
In Flex Hero 4.5 you can use the new Spark DateTimeFormatter:
<s:DateTimeFormatter dateTimePattern="HH':'mm':'ss" id="dateFormatterUTC" useUTC="true" />
<s:Label text="{dateFormatterUTC.format(new Date())}" />
The most simple of fixes is to have as many objects as you can (and properties of objects) be strings. The timezoneOffset solution works fine, but the timezoneOffset for many US cities changes twice during the year. The best rule -- everything is a string.

Resources