I just set up a short toy learning ColdFusion page on a server. The page makes a call out to a cffunction, which gets the current date, determines the year, and then returns a boolean reflecting whether or not the current year is a leap year. This information is displayed on the main page in plain text.
page.cfm
<html>
<head>
<cfinclude template="./func.cfm" />
</head>
<body>
<cfset yearList = "2000;2001,2002/2003,2004,2005;2006/2007,2008,2009;2010,2011,2012" >
<cfloop index="year" list=#yearList# delimiters=",;/" >
<cfset isLeapYear = #My_IsLeapYear(year)# >
<cfif isLeapYear is True>
<cfoutput>
#year# is a leap year!
</cfoutput>
<cfelse>
<cfoutput>
#year# is not a leap year.
</cfoutput>
</cfif>
<br>
</cfloop>
</body>
</html>
func.cfm
<cffunction name="My_IsLeapYear" output="false" access="public" returnType="boolean">
<cfargument name="year" type="numeric" required="true" default="" />
<cfset var isLeapYear = (DaysInYear(CreateDate(arguments.year,1,1)) EQ 366) />
<cfreturn isLeapYear>
</cffunction>
Trying to access this page caused a horrific memory leak and took down the server where it was hosted. I'm at a loss. Any thoughts?
The memory leak was caused to a strange external issue. Thanks for the comments and such.
I think this is a faster way to check this:
<cfset yearList = "2000;2001,2002/2003,2004,2005;2006/2007,2008,2009;2010,2011,2012" >
<cfoutput>
<cfloop index="year" list="#yearList#" delimiters=",;/" >
<p>#year# is <cfif !(val(year) MOD 4 EQ 0)>not </cfif>a leap year!</p>
</cfloop>
</cfoutput>
Avoids the more expensive calls to DaysInYear(). You just need to check if the value of year is a number divisible by 4.
Update
Point taken re: calculation. As for the original function, You can just return the result of the comparison. No need to create a function local variable.
<cffunction name="My_IsLeapYear" output="false" access="public" returnType="boolean">
<cfargument name="year" type="numeric" required="true" default="" />
<cfreturn (DaysInYear(CreateDate(arguments.year,1,1)) EQ 366) />
</cffunction>
and in page.cfm, you can change this code:
<cfset isLeapYear = #My_IsLeapYear(year)# >
<cfif isLeapYear is True>
to a simpler call:
<cfif My_IsLeapYear(year)>
since that function will only return a Boolean value.
Related
I am using MonkehTweet Coldfusion wrapper for Twitter Authentication. I have everything up working, but i cannot get my head around posting multiple images using the PostUpdateWithMedia function. I am relatively new to coldfusion, and learning it along the way. A simple call to PostUpdateWithMedia(status="", media="") would post to Twitter with an image, but how can i use this to post multiple images. The PostUpdateWithMedia function from MonkehTweet is,
<cffunction name="postUpdateWithMedia" access="public" output="false" hint="Updates the authenticating user's status. Request must be a POST. A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates.">
<cfargument name="status" required="true" type="String" hint="The text of your status update. URL encode as necessary. Statuses over 140 characters will be forceably truncated." />
<cfargument name="media" required="true" type="string" hint="Up to max_media_per_upload files may be specified in the request, each named media[]. Supported image formats are PNG, JPG and GIF. Animated GIFs are not supported." />
<cfargument name="possibly_sensitive" required="false" type="boolean" default="false" hint="Set to true for content which may not be suitable for every audience." />
<cfargument name="in_reply_to_status_id" required="false" type="String" hint="The ID of an existing status that the update is in reply to." />
<cfargument name="lat" required="false" type="String" hint="The location's latitude that this tweet refers to." />
<cfargument name="long" required="false" type="String" hint="The location's longitude that this tweet refers to." />
<cfargument name="place_id" required="false" type="String" hint="A place in the world. These IDs can be retrieved from geo/reverse_geocode." />
<cfargument name="display_coordinates" required="false" type="String" hint="Whether or not to put a pin on the exact coordinates a tweet has been sent from." />
<cfargument name="checkHeader" required="false" type="boolean" default="false" hint="If set to true, I will abort the request and return the response headers for debugging." />
<cfargument name="timeout" required="false" type="string" default="#variables.instance.timeout#" hint="An optional timeout value, in seconds, that is the maximum time the cfhttp requests can take. If the time-out passes without a response, ColdFusion considers the request to have failed." />
<cfset var strTwitterMethod = '' />
<cfset arguments["media[]"] = arguments.media />
<cfset structDelete(arguments,'media') />
<cfset strTwitterMethod = getCorrectEndpoint('api') & 'statuses/update_with_media.json' />
<cfreturn genericAuthenticationMethod(timeout=getTimeout(), httpURL=strTwitterMethod,httpMethod='POST', parameters=arguments, checkHeader=arguments.checkHeader) />
</cffunction>
I have tried passing in multiple files as,
PostUpdateWithMedia(status="", media="", media=""); but it didnot work. But, I am passing in the multiple media arguments wrong. Can someone help me with how to pass in multiple media arguments.
Unfortunately, MonkehTweet does not include support for the Twitter API media/upload endpoint, which is required for multi-image Tweets - it only supports the deprecated statuses/update_with_media, which still works, but only supports a single image. I also noticed that the code still refers to 140 character Tweets, so it probably has not been updated for some time. I'm not aware of an alternative ColdFusion wrapper for the API, either, so this is something you would need to build for yourself.
<c:set var="xmlDocumentId" value="${id}" scope="request" />
<s:set var="xmlDocumentId" value="%{id}" scope="request" />
are formatting id based on locale, setting xmlDocumentId to "12,345" while:
<c:out value="${id}" />
<s:property value="%{id}" />
are outputting "12345".
Any ideas how to break this behavior?
Because you are getting value with getText or <s:text> tag your long value gets formatted according to locale. To prevent this from happening convert your long to string.
With <s:set> tag you can call toString() method directly in value attribute.
<s:set var="xmlDocumentId" value="id.toString()" scope="request" />
For the concrete formatting algorithm take a look at java.text.MessageFormat class and its subformat method.
Once you know how to format numbers in Java, in Struts2 <s:property/> tag you can use getText() to format your number in the desired way, for example :
<s:property value="getText('{0,number,#,##0}',{id})"/>
Try this
<s:text name="id" > <s:param name="value" value="id"/> </s:text>
i want just a simple while-loop in JSF.
Something like :
<c:set var="i" value="0"/>
<c:while #{act.observation[i].value !=null}>
<td style="width: 12%;">#{act.observation[i]} /></td>
<c:set var="i" value="${i + 1}" />
Of course i know there is nothing like c:while and i have tried c:forEach and ui:repeat, but couldn't figure out how this could have worked, especially with xml paths (rims) that i am using.
Any ideas?
Try something like this:
<ui:repeat value="#{act.observation}" var="observ">
#{observ}<br/>
</ui:repeat>
Where observation is your list of items you want to print.
Hello I am a young Software developer,
and I struggled the last 5 days with my code.
Here is my code in JSP:
<s:iterator value="getListeDanach()" status="stat">
<li>
<s:url id="URL_ListeDanach" action="uebersicht_umblaettern">
<s:param name="angeklickteSeitenzahl" value="getListeDanach()[#stat.index]" />
<s:bean name="org.apache.struts2.util.Counter" var="counter">
<s:param name="last" value="3" />
</s:bean>
<s:iterator value="#counter" status="stat1">
<s:property value="#stat1.index" />
<s:param name="%{optionaleParamName4}" value="#optionaleParamValue4" />
</s:iterator>
</s:url>
<s:a href="%{URL_ListeDanach}" cssClass="naviTab">
<s:property value="getListeDanach()[#stat.index]" />
</s:a>
</li>
</s:iterator>
My problem is, the first Iteration works great but the 2nd Iteration works half. In the 2nd case the property works, but the param doesn´t work! Al Variables are available. If i take the param Tag of the 2nd Iteration and place it in the first, it works great! But that isn´t what I want.
This is not an answer.
Here's the JSP, cleaned up, and using more S2 functionality. It was impossible to read the original.
<s:iterator value="listeDanach" status="stat" var="outerItem">
<li>
<s:url id="URL_ListeDanach" action="child">
<s:param name="angeklickteSeitenzahl" value="outerItem" />
<%-- What are you trying to do here? --%>
<s:bean name="org.apache.struts2.util.Counter" var="counter">
<s:param name="last" value="3" />
</s:bean>
<%-- What are you trying to do here? There's nothing to iterate over. --%>
<s:iterator value="#counter" status="stat1">
<s:property value="#stat1.index" />
<s:param name="%{optionaleParamName4}" value="#optionaleParamValue4" />
</s:iterator>
</s:url>
<s:a href="%{URL_ListeDanach}">
<s:property value="outerItem" />
</s:a>
</li>
</s:iterator>
In the bean i have a loop with 3 "rounds", in the 2nd iterator i use the var=counter to iterate three times over the property and over the dynamic parameter.
The property shows in HTMl in every loop of the first iterator this result : 0 1 2;
This is how it should work(the property is just there, to test the functionality of the 2nd itarator.)
But in the 2nd case, the parameter-Tag is fully ignored or something like that. For those who want to know the logic behind the code. It is a side navigation bar. listeDav or = list behind the actual number, and listeDanach= list after the actual number. 1 2 3 4 [5] 6 7 8 9.... When the param Tag in the 2nd itarator functions well, I would make the param tag dynamically with the iterated index.
SO in short, what I want is: Every time the first Iterator has his loop, I want to create dynamic parameters. This parameters are defined in the JSP before and are fully supported! I want to use the index "#stat1.index" to make it work.
Something like this :
s:param name="%{optionaleParamName[#stat1.index]}" value="#optionaleParamValue[#stat1.index]" />.....
i have already defined the String behind "#optionaleParamValue[0], behind #optionaleParamValue[1] and behind #optionaleParamValue[2] and soo on... ... and all this is for reusing the actual JSP.
As you can mention, a side navigation bar, can be used in many other cases in the programm.
Greetings
A triple job: I have to do a job with tree task. We have three tasks:
Fetch pages
Parse HTML
Store data... And yes - this is a true Perl-job!
I have to do a parser-job on all 6000 sub-pages of a site in suisse. (a governmental site - which has very good servers ).
see http://www.educa.ch/dyn/79362.asp?action=search and
(if you do not see approx 6000 results - then do a search with .
A detailed page is like this:
[link text][1]
Ecole nouvelle de la Suisse Romande
Ch. de Rovéréaz 20 Case postal 161
1000 Lausanne 12 Website
info#ensr.ch Tel:021 654 65 00
Fax:021 654 65 05
another detailed pages shows this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta name="generator" content="DigiOnline GmbH - WebWeaver 3.4 CMS - "><title>educa.ch</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><link rel="stylesheet" href="101.htm"><script src="102.htm"></script><script language="JavaScript"><!--
var did='d79376';
var root=new Array('d200','d205','d73137','d1566','d79376','d');
var usefocus = 1;
function check() {
if ((self.focus) && (usefocus)) {
self.focus();
}
}
// --></script></head><body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onload="check();"><table cellspacing="0" cellpadding="0" border="0" width="100%"><tr><td width="15" class="popuphead"><img src="/0.gif" alt="" width="15" height="16"></td><td width="99%" class="popuphead">Adresse - Schulen in der Schweiz</td><td width="20" class="popuphead" valign="middle"><img src="../pics/print16x13.gif" alt="Drucken" width="16" height="13"></td><td width="20" class="popuphead" valign="middle"><img src="../pics/close21x13.gif" alt="Schliessen" width="21" height="13"></td></tr><tr bgcolor="#B2B2B2"><td colspan="4"><img src="/0.gif" alt="" width="1" height="1"></td></tr></table><div class="leerzeile"> </div><div class="leerzeile"><img src="/0.gif" alt="" width="15" height="8">Auseklis - Schule für lettische Sprache und Kultur</div><div class="leerzeile"> </div><div><img src="/0.gif" alt="" width="15" height="8">Mutschellenstrasse 37</div><div><img src="/0.gif" alt="" width="15" height="8"></div><div><img src="/0.gif" alt="" width="15" height="8">8002 Zürich</div><div class="leerzeile"> </div><div><img src="/0.gif" alt="" width="15" height="8">latvia.yourworld.ch</div><div><img src="/0.gif" alt="" width="15" height="8">schorderet#inbox.lv</div><div class="leerzeile"> </div><div><img src="/0.gif" alt="" width="15" height="8">Tel:<img src="/0.gif" alt="" width="6" height="8">+41786488637</div><div><img src="/0.gif" alt="" width="15" height="8">Fax:<img src="/0.gif" alt="" width="4" height="8"></div><div> </div></body></html>
I want to do this job with ** HTML::TokeParser or HTML::TokeParser** or *HTML::TreeBuilder::LibXML * but i have little experience with HTML::TreeBuilder::LibXML
Which one would you prefer for this job: Note - I want to store the results in a MySQL-DB. Best things would be to store it immitiately after parsing:
so we have three tasks:
Fetch pages
Parse HTML
Store data
First item: Use LWP::UserAgent to fetch. There are many examples in this forum of using that module to post data and get the resulting pages. BTW we can use Mechanize instead if we prefer.
Second: Parse the page as eg with HTML::TokeParser or some other module to get at only the data we need.
Third: Store the data straight away into a database. There is no need to take an intermediate step and write a temporary file.
hmmm - the first and the second question - how to fetch and how to parse.
Hard to be too specific as your question is very general. I've retrieved pages using LWP and used TokeParser to extract data and store the output in a database many times. I haven't used Mech, but by all accounts it is simpler than LWP.
Creating a user agent using LWP can be as simple as:
my $ua = LWP::UserAgent->new();
you will need to consider things like re-directs, proxies and cookies or passwords depending on your requirements.
To follow re-directs:
$ua = LWP::UserAgent->new(
requests_redirectable => ['GET', 'HEAD', 'POST' ]
);
To store cookies:
$ua->cookie_jar( {} );
To set up a proxy:
$ua->proxy("http", "http://localhost:8888"); # Fiddler
To add a password for authentication:
$ua->credentials( 'www.myhostingplace.com:443' , 'Realm' , 'userid', 'password');
To get content from a page for local processing:
$url = 'http://www.someurl.com'
my $response = $ua->get($url);
if ( $response->is_error() ) {
# Do some error stuff
}
my $content = $response->content();
To parse the content using TokeParser:
my $stream = new HTML::TokeParser(\$content);
while ( my $t = $stream->get_token() ) {
if ( $t->[0] eq 'S' and $t->[1] eq 'input' ) {
if ( uc( $t->[2]{ 'name' } ) eq 'SEARCHVALUE' ) {
my $data = $t->[2]{ 'value' };
# Do something with data
}
}
}
The data is passed into TokeParser as a reference; I then walk through the stream using get token. Each HTML element is passed into an array which you can examine to determine what you should do next.
In the above example I want to search for input tags with an attribute name of 'SEARCHVALUE' and then store the 'value' attribute. The HTML fragment might look something like this:
<input type="hidden" name="SEARCHVALUE" value="Spock" />
When I hit the start of the input tag ($t->[0] eq 'S' and $t->[1] eq 'input') I examine the "name" attribute of the tag (t->[2]{ 'name' }) to see if it matches the value I am searching for; if it does I store the value attribute of the tag ($t->[2]{ 'value' }) in a variable. I can then do whatever I like with the value including storing it in a database.
You can do a lot with TokeParser and in some cases it can be simpler than using regular expressions to carve up the page but it can also be a little challenging to get your head around. If you are trying to extract a simple pattern from the return HTML content then a regular expression can be just as good.
If you have a lot of this to do then I recommend "Perl and LWP" by Sean Burke from O'Reilly. It has been endlessly helpful for me in my web scraping endeavours.
Hope this helps you get started at least.