text
stringlengths
8
267k
meta
dict
Q: HTTP handlers in IIS6 or IIS7 classic mode I'm currently struggling with httphandlers in IIS. I'm developing a website in .NET4 in VS2010 and Cassini. In this website, i have a gallery, whose pictures are loaded through my handler. For example http://mywebsite.com/Gallery/123/Pic1.jpg My HTTP Handler gets the id 123 and returns the picture from the database (simplified). So, everything works fine in Cassini (VS integrated webserver) and in IIS7 in "integrated mode". Pictures are loaded like they should. But I have to deploy this site on a shared hoster, who is using IIS6. After many searching and own logging, I found out, the the request isn't routed to my handler, and so I get a 404 from IIS. My definition which is enough for IIS7 integrated mode: <system.web> <handlers> <add verb="*" path="Gallery/*/*" type="[coorect Type spec]" /> </handlers> </system.web> For IIS7 in classic mode I had to add <system.webServer> <handlers> <add name="ImageHandler" verb="*" path="Galler</*/*" type="[type]" modules="IsapiModule" scriptProcessor="c:\windows\Microsoft.net\framework\v4.0.30319\aspnet_isapi.dll"/> </handlers </system.webServer> This last config only works whith the stuff in the module and scriptprocessor attributes... But this config doesn't work in IIS6.... Can anyone help me ? A: The issue is that IIS6 typically decides what ISAPI handler to pass the request to by using the file extension. So it sees .jpg and tries to serve a static file from that path. This is also what IIS7 refers to as classic mode. And you'll note you are referencing aspnet_isapi.dll in your configuration because it needs to be told what should handle this. Once you've passed it into aspnet_isapi, the asp.net http handling pipeline kicks in and you can execute your handler. The easiest fix would be to find a host that supports IIS7. Failing that, you could see if they have any url rewriting options. With that, you could rewrite things so that you append an .ashx on the url, which will let IIS6 grab it and put it into the asp.net pipeline and your handler would fire. You could also see if they allow wildcard mappings, but that is a very tall order for most shared hosts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: COUNT causes error in db2 from PHP When I run this query I get the following error: Column MANUFACTURER or expression in SELECT list not valid. The query runs fine if I remove the COUNT function. Any ideas? (this query is a bit of a mock so it might not make perfect sense) SELECT MANUFACTURER , PART_NUMBER , COUNT(1) AS CNT FROM ( SELECT AWPART AS PART_NUMBER , MANF AS MANUFACTURER FROM STKMP INNER JOIN PRICING AS P ON AWPART = P.JCPART AND R.CODE = 1 WHERE PART_NUMBER LIKE '%A2%') AS T Modifying the last line as follows produces the same effect. WHERE PART_NUMBER LIKE '%A2%') AS T GROUP BY MANUFACTURER A: Typically COUNT() is only meaningful if you have a GROUP BY clause. Perhaps you meant to add this to the end (after the AS T?): GROUP BY MANUFACTURER, PART_NUMBER;
{ "language": "en", "url": "https://stackoverflow.com/questions/7621276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I have a method and I want to return three different values to my main method Lets say I have this program below. Now I want to pass both the users first name AND last name into the method without calling it again and changing the parameter and making the user retype there first name and last name again. I know I can make two different methods for finding the first name and last name but I was wondering if there was a way to do this is just one method. import java.util.Scanner; public class Document3 { public static void main(String[] args) { String name; name = getName("lastName"); //But how would I get my lastName WITHOUT recalling the method with "lastName" in the parameters? System.out.println(name); //I want to also get the other name into in my main method somehow } public static String getName(String nameOption) { Scanner x = new Scanner(System.in); String firstName = ""; String lastName = ""; String nameChoice = ""; System.out.print("Please enter your first name: "); firstName = x.nextLine(); System.out.print("\nPlease enter your last name: "); lastName = x.nextLine(); if (nameOption.equals("firstName")) { nameChoice = firstName; } if (nameOption.equals("lastName")) { nameChoice = lastName; } return nameChoice; //how do I return both variables (firtName and lastName) and how would I access them } } A: Create a small wrapper class which holds the values you want to return, and return an instance of that class. class Name { final String firstName; final String lastName; Name(String first, String last) { firstName = first; lastName = last; } } How to use it: public static void main(String[] args) { Name name = getName(); String first = name.firstName; String last = name.lastName; } public static Name getName() { Scanner x = new Scanner(System.in); System.out.print("Please enter your first name: "); String firstName = x.nextLine(); System.out.print("\nPlease enter your last name: "); String lastName = x.nextLine(); return new Name(firstName, lastName); } A: You can create another class called Fullname which contains two attribute , first name and last name. Then inside your getName function, return the Fullname object. A: Yes, return an object, a map, or an array (ew). Java doesn't have a way to return multiple values without wrapping them up into a single object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I configure hadoop mapreduce so that the log of my mapreduce class can output to a file? I modified the $HADOOP_HOME/conf/log4j.properies But it is not working as what I expect. How to solve this problem? A: Check if you have other log4j.properties files in your classpath. A problem with log4j is that the only the last log4j.properties it reads from the classpath will be actually used. So if you have other log4j.properties files in the classpath, then one of those might be getting picked up. Try to merge all these log4j.properties files and it should work. Also please post the content of the log4j.properties files if you can. There can be a problem there as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Razor View Engine Not Searching Area View Locations I am using the default RazorViewEngine, and Area layout configuration, however when i naviagate to a link which uses a view within the area. I get a error stating the View could not be found and searched in the following locations: ~/Views/Applications/Details.cshtml ~/Views/Applications/Details.vbhtml ~/Views/Shared/Details.cshtml ~/Views/Shared/Details.vbhtml What I find odd is that it looks as though the view engine does not attempt to search the areas location. What adjustments do I need to make to have the view engine search for views in its area. Here is the related code I used to define my area. Global.asax.cs protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteRegistrar.RegisterRoutesTo(RouteTable.Routes); } ApplicationAreaRegistration.cs private void RegisterRoutesTo(RouteCollection routes) { routes.MapRoute("Application_default", AreaName + "/{action}/{applicationId}", new { controller = "Applications", action = "Index", applicationDomainId = UrlParameter.Optional }, new { applicationId = @"\d+" }); } Index.cshtml @Html.RouteLink(item.Name, "Application_default", new { applicationId = item.Id, action = "Details" }) Physical Directory Layout Areas \ \Application \Controllers -ApplicationsController.cs \Views -Details.cshtml -ApplicationAreaRegistration.cs A: Are you certain that RegisterRoutesTo() in ApplicationAreaRegistration.cs is being invoked? It seems that the Route to your area has not been registered. I would suggest moving your MapRoute back into the override of RegisterArea in ApplicationAreaRegistration.cs. A: Your MapRoute seems to be an issue. Try adding an area declaration routes.MapRoute("Application_default", AreaName + "/{action}/{applicationId}", new { area= "Application", controller = "Applications", action = "Index", applicationDomainId = UrlParameter.Optional }, new { applicationId = @"\d+" }); Also, just double check the various overloads available for Html.RouteLink - you may want to add the area the RouteValues collection `new {area="Application", applicationId = item.Id, action = "Details"}` when using RouteLink outside an area
{ "language": "en", "url": "https://stackoverflow.com/questions/7621286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Binding to datagrid and null object I display products within a datagrid for fast editing. Each product may have some different prices. I have created a Price class which has as properties my prices. To display the price for delivery i use <DataGridTextColumn Header="Delivery" Binding="{Binding Path=Price.Delivery}" /> No problem. The problem is when editing and Price is NULL. Then it crashes somehow... It should be dead easy but couldn't find a solution yet. (apart from having always instantiated price class)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why isn't has_many working on these Mongoid models? I have these models: class Feed include Mongoid::Document field :name field :host field :user_name ... has_many :stores end class Store include Mongoid::Document field :name field :store_id field :dealfeeds, type: Array ... belongs_to :feed end But when I try to add a store through feeds, I get these errors: >> Feed.stores << Store.new NoMethodError: undefined method `stores' for Feed:Class >> Feed[:stores] << Store.new NoMethodError: undefined method `[]' for Feed:Class A: Ah, silly me. These are operations on an instance not on a class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache ReWrite rule for & to & Already doing this rewrite rule RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^.*$ https://www.%{SERVER_NAME}%{REQUEST_URI} Now the requested url is https://www.example.com/abc.php?a=&amp;b=abc&amp;c=def&amp;d=0&amp;e=1 to https://www.example.com/abc.php?a=&b=abc&c=def&d=0&e=1 A: add the NE tag at the end of the rule (No Escape): RewriteRule (...) [NE]
{ "language": "en", "url": "https://stackoverflow.com/questions/7621304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I batch rewrite an SVN log? I need to do a search/replace over the names of users making changes to my SVN repository; we're making some organizational changes so I need to change 'fantasticMan' as the author of various changes in the log to 'authorA' (just an example). My idea was to svn dump and then do a search/replace over the dump file. The problem is that after the first checkout, it only gets to revision 1; when I was doing an svnadmin load command I got this message: svnadmin: Dumpstream data appears to be malformed. I suspect that there are some checksums in the log to ensure the integrity of the dumpfile so I can't just do a search and replace over the dumpfile. How do I make changes on the author names of a repository? (If there's a way to do this without having to dump the repository and then reload the dump, I'd prefer that solution.) A: Is there a way to change a SVN users username through the entire repository history? Using svndumptool works best. A.H.'s way would take me much longer. A: You can use svnadmin setrevprop for that. In Linux speak: svnadmin setrevprop -r1 MyRepoDir svn:author <(echo -n NewAuthor) So the next question will be: How the get the old author: svnlook author -r1 MyRepoDir So you will basically iterate from revision 1 up to "youngest" and map each author on the way. I hope for you, that you don't have as many revisions as some Apache repositories. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: If mysql results = 1 then . Is not working? Hello I wanna check to see if there is all ready a user in the db with the same username before adding it to the db ... but I'm getting a white page. $sql2="SELECT * FROM users WHERE username='$user' "; $result2=msyql_query($sql2,); if (mysql_num_rows($result2)==0) { echo "A account is all ready here" ; } else{ That's the main bit were it checks. Here is my full code: include('config.php'); ini_set('display_errors',1); error_reporting(E_ALL); print_r ($_SESSION) ; if ($_SESSION['number_three'] == 3 ) { $user = mysql_real_escape_string($_POST['username']); $pass = mysql_real_escape_string($_POST['password']); $email = mysql_real_escape_string($_POST['email']); $avatar = mysql_real_escape_string($_POST['avatar']); $starter = mysql_real_escape_string($_POST['starter']); $gender = mysql_real_escape_string($_POST['gender']); $_SESSION['start'] = $starter; $sql = "SELECT * FROM pokemon WHERE pic='$_SESSION[start]'"; $result = mysql_query($sql) or die(mysql_error()); $values = mysql_fetch_array($result); $sql2="SELECT * FROM users WHERE username='$user' "; $result2=mysql_query($sql2,); if (mysql_num_rows($result2)==0) { echo "A account is all ready here" ; } else{ $_SESSION['test'] = $values['name']; mysql_query("INSERT INTO users (username, password, email, avatar, gender) VALUES ('$user','$pass','$email','$avatar','$gender' ) ") or die(mysql_error()); mysql_query("INSERT INTO user_pokemon (pokemon, belongsto, slot) VALUES ('".$_SESSION['test']."','$user','1' ) ") or die(mysql_error()); unset($_SESSION['number_three']); } else { echo " You do not ment to be here ! Go Away !"; } } If I take the top part of the code out in the first bit script works but does not check if user is already in the db..... with the script has it is now I'm getting white page with the top bit of code in first post code bit also I am not getting any errors.... A: $result2=mssql_query($sql2,); You're calling mssql_query, not mysql_query. A: mssql_query? Try mysql_query instead. A: Use PDO with exception throwing: try { $PDO = new PDO($dsn, $username, $password, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)); //use $PDO->query(); Errors will be thrown and you'll be able to see them. This way you don't have to check the boolean return values on queries. } catch(PDOException $error) { echo $error->getMessage(); } A: I'm not sure if this is the only problem, but first off, on the line where you make that second query, you're calling mssql_query rather than mysql_query, which is the query function for Microsoft SQL Server databases, and wouldn't know how to get results back from MySQL. A: * *Try adding E_STRICT if you have older PHP than 5.4.0. *Add or die (mysql_error()); to know if there's an error in the query. *Try using if (!mysql_num_rows($result2)) or if (mysql_num_rows($result2) < 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get event from Google Calendar in Java? I use this code for getting Google calendars list: // Create a CalenderService and authenticate CalendarService myService = new CalendarService("exampleCo-exampleApp-1"); myService.setUserCredentials("[email protected]", "mypassword"); // Send the request and print the response URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full"); CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class); System.out.println("Your calendars:"); System.out.println(); for (int i = 0; i < resultFeed.getEntries().size(); i++) { CalendarEntry entry = resultFeed.getEntries().get(i); System.out.println("\t" + entry.getTitle().getPlainText()); } This code return me calendars list, but I need to get all events from this calendar about today. How can I do that? A: If you are using the sample program to start with please use ..../private/full to get the events from Calendar. For example: "https://www.google.com/calendar/feeds/[email protected]/private/full"); A: Assuming you're using the official GData API: Try using the getFeed(Query query, …) overload with a CalendarQuery - that seems to let you specify the range for the start time of an event. A: You can also use a this default URL, instead of specifying [email protected], "https://www.google.com/calendar/feeds/default/private/full" And I think you should use CalendarEventFeed Object instead of CalendarFeed See this code snippet below: CalendarQuery myQuery = new CalendarQuery(feedUrl); myService.setUserCredentials(p.getgUser(), p.getgPassword()); DateTime dt = new DateTime(); myQuery.setMinimumStartTime(DateTime.now()); myQuery.setMaximumStartTime(dt); CalendarEventFeed resultFeed = myService.query(myQuery, CalendarEventFeed.class); Then traverse the contents of resultFeed ..... CalendarEventFeed resultFeed = calendarData for (int i = 0; i<calendarData.getEntries().size(); i++) { CalendarEventEntry entry = calendarData.getEntries().get(i); .....
{ "language": "en", "url": "https://stackoverflow.com/questions/7621309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BUG?? ImageView causing background image to stretch I am trying to write an xml representing the following GUI: -------------------- | <text>| | <text>| | | |<pic> | -------------------- in the background I want to have an image.... I wrote the following: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" android:background="@drawable/image1" > <RelativeLayout android:id="@+id/widget48" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:background="@color/transparent" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:layout_alignParentTop="true" android:layout_alignParentRight="true" > </TextView> <TextView android:id="@+id/description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:layout_below="@+id/title" android:layout_alignParentRight="true" android:padding="10dp" > </TextView> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> </LinearLayout> with the following xml the background image looks fine, but the ImageView is not located where I want it to be... after adding the following: android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" to the ImageView the background image is stretched and looks ugly.... How do I set the image to the bottom-left without causing the background to get stretched??? THANKS! First of all thanks for trying to help.... Tried your last suggestion try to change both the relative layout and linear to : android:layout_width="wrap_content" android:layout_height="wrap_content" still no success... I made the code even easier - removed the outer layout, <RelativeLayout android:id="@+id/widget48" android:layout_width="wrap_content" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android" android:background="@drawable/single_detail" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:paddingTop="50px" android:paddingRight="25px" android:textStyle="bold" android:textColor="#0000FF" > </TextView> <TextView android:id="@+id/description" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/title" android:layout_alignParentRight="true" android:paddingTop="10px" android:paddingRight="25px" android:textColor="#0000FF" > </TextView> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" /> </RelativeLayout> still same problem as seen in the images.... other ideas?? I am hopeless...... :) HELP!!!! PLEASE!!!! A: if you want the image to be the backgroud of the layout just put it in android:background=in the relative layout but if you want to use the imageView you can change android:scaleType= in the image view so it won't stretch A: Here is an example to the problem: GOOD: BAD:
{ "language": "en", "url": "https://stackoverflow.com/questions/7621313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find the text of an element in XML that contains a namespace with GPath Hey I would like to find a given text in an xml that looks like this: <s:Envelope xmlns:s="http://..."> <s:Body> <About_ServiceResponse xmlns="http://...> <About_ServiceResult xmlns:a="http://> <a:businessServiceVersionStructureField> <a:BusinessServiceVersionStructureType> <a:businessServiceDBVersionNameField>V001</a:businessServiceDBVersionNameField> <a:businessServiceVersionNameField>Some Service^V100</a:businessServiceVersionNameField> </a:BusinessServiceVersionStructureType> </a:businessServiceVersionStructureField> </About_ServiceResult> </About_ServiceResponse> </s:Body> </s:Envelope> So in this example i would like to find the text: "Some Service". I have tried with Xpath but could not get that to work. I have also tried with Gpath and all i could get there was all of the texts in one long String. How would you do this in GPath or/and XPath? A: Try this XPath: //*[contains(text(), 'Some Service')] It will return all elements which contain text node with Some Service A: After registering the bindings of the prefixes to the corresponding namespaces, use: /*/s:Body /s:About_ServiceResponse /s:About_ServiceResult /a:businessServiceVersionStructureField /a:BusinessServiceVersionStructureType /a:businessServiceVersionNameField /text() When this XPath expression is evaluated against the following XML document (the provided one is severely malformed and I had to spend considerable time to make it well-formed): <s:Envelope xmlns:s="http://..."> <s:Body> <About_ServiceResponse xmlns="http://..."> <About_ServiceResult xmlns:a="http://"> <a:businessServiceVersionStructureField> <a:BusinessServiceVersionStructureType> <a:businessServiceDBVersionNameField>V001</a:businessServiceDBVersionNameField> <a:businessServiceVersionNameField>Some Service^V100</a:businessServiceVersionNameField> </a:BusinessServiceVersionStructureType> </a:businessServiceVersionStructureField> </About_ServiceResult> </About_ServiceResponse> </s:Body> </s:Envelope> Exactly the wanted text node is selected: Some Service^V100 In case you want to select the element that is the parent of this text node, use: /*/s:Body /s:About_ServiceResponse /s:About_ServiceResult /a:businessServiceVersionStructureField /a:BusinessServiceVersionStructureType /a:businessServiceVersionNameField XSLT - based verification: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s="http://..." xmlns:a="http://"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:copy-of select= "/*/s:Body /s:About_ServiceResponse /s:About_ServiceResult /a:businessServiceVersionStructureField /a:BusinessServiceVersionStructureType /a:businessServiceVersionNameField /text() "/> ======= <xsl:copy-of select= "/*/s:Body /s:About_ServiceResponse /s:About_ServiceResult /a:businessServiceVersionStructureField /a:BusinessServiceVersionStructureType /a:businessServiceVersionNameField "/> </xsl:template> </xsl:stylesheet> When this transformation is applied against the same XML document (above), the selected nodes are output (using "=======" as delimiter): Some Service^V100 ======= <a:businessServiceVersionNameField xmlns:a="http://" xmlns="http://..." xmlns:s="http://...">Some Service^V100</a:businessServiceVersionNameField> A: Using Groovy with XmlSlurper/GPathResult def xml = ''' <s:Envelope xmlns:s="http://foo"> <s:Body> <About_ServiceResponse xmlns="http://bar"> <About_ServiceResult xmlns:a="http://baz"> <a:businessServiceVersionStructureField> <a:BusinessServiceVersionStructureType> <a:businessServiceDBVersionNameField>V001</a:businessServiceDBVersionNameField> <a:businessServiceVersionNameField>Some Service^V100</a:businessServiceVersionNameField> </a:BusinessServiceVersionStructureType> </a:businessServiceVersionStructureField> </About_ServiceResult> </About_ServiceResponse> </s:Body> </s:Envelope>''' def envelope = new XmlSlurper().parseText(xml) envelope.declareNamespace(s:'http://foo', t:'http://bar', a:'http://baz') assert 'Some Service^V100' == envelope.'s:Body'. 't:About_ServiceResponse'. 't:About_ServiceResult'. 'a:businessServiceVersionStructureField'. 'a:BusinessServiceVersionStructureType'. 'a:businessServiceVersionNameField'.text() assert 'Some Service^V100' == envelope.'Body'. 'About_ServiceResponse'. 'About_ServiceResult'. 'businessServiceVersionStructureField'. 'BusinessServiceVersionStructureType'. 'businessServiceVersionNameField'.text() Since the element names in your sample are unique, it can be done with or without registering the namespaces. A: Using Groovy XmlSlurper. def xml = new XmlSlurper().parseText(yourXml).declareNamespace(ns1: 'http://..',ns2:'http://..') def theText = xml?.'ns1:Body'?.'ns2:About_ServiceResponse'?.'ns3.About_ServiceResult'?.businessServiceVersionStructureField?.businessServiceVersionNameField.text();
{ "language": "en", "url": "https://stackoverflow.com/questions/7621321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby find next Thursday (or any day of the week) What is the best way to calculate the Date, Month, and Year of the next Thursday (or any day) from today in Ruby? UPDATE In order to create dummy objects, I'm trying to figure out how to calculate a random time. In all, I'd like to produce a random time between 5 and 10 PM on the next Thursday of the week. A: date = Date.today date += 1 + ((3-date.wday) % 7) # date is now next Thursday A: This SO answer is also short and simple https://stackoverflow.com/a/7930553/3766839 def date_of_next(day) date = Date.parse(day) delta = date > Date.today ? 0 : 7 date + delta end date_of_next "Thursday" A: DateTime.now.next_week.next_day(3) As @Nils Riedemann pointed out: Keep in mind that it will not get the next thursday, but the thursday of the next week. eg. If tomorrow was thursday, it won't return tomorrow, but next week's thursdays. Here is an excerpt of some code I've written recently which handles the missing case. require 'date' module DateTimeMixin def next_week self + (7 - self.wday) end def next_wday (n) n > self.wday ? self + (n - self.wday) : self.next_week.next_day(n) end end # Example ruby-1.9.3-p194 :001 > x = DateTime.now.extend(DateTimeMixin) => #<DateTime: 2012-10-19T15:46:57-05:00 ... > ruby-1.9.3-p194 :002 > x.next_week => #<DateTime: 2012-10-21T15:46:57-05:00 ... > ruby-1.9.3-p194 :003 > x.next_wday(4) => #<DateTime: 2012-10-25T15:46:57-05:00 ... > A: Aside from getting next Thursday as the others described, Ruby provides easy methods to get the month and year from any date: month = date.month year = date.year Inside of Rails you can easily get next Thursday as such: next_thur = Date.today.next_week.advance(:days=>3) UPDATE Thanks to @IvanSelivanov in the comments for pointing this out. You can skip a step by doing: next_thur = Date.today.next_week(:thursday) A: IMO the chronic library is awesome for stuff like this. The Ruby code would be: def date_of_next(day) Chronic.parse('next #{day}') end
{ "language": "en", "url": "https://stackoverflow.com/questions/7621322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Objective-C release, autorelease, clarification needed I am pretty sure this is correct, but if possible could you confirm [[self doublyLinkedList] add:[n1 autorelease]]; and [[self doublyLinkedList] add:n1]; [n1 release]; will both produce the same retainCount for the n1, once the pool is drained A: Although both methods will eventually result in the same retain count, explicitly calling release will be more efficient because the object will not have to be added to and removed from the auto-release pool. A: Yes, result will be the same in both cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple static variable scopes within same application? What is the best way to set up multiple static scopes within the same application? I have structs that serve as wrappers over accessing an array. Here's an example: class FooClass{ static int[] BarArray; } struct FooStruct{ public int BarArrayIndex; public int BarArrayValue { get { return FooClass.BarArray[BarArrayIndex]; } set { FooClass.BarArray[BarArrayIndex] = value; } } } For performance reasons, I don't want to store a reference to BarArray in every instance of FooStruct, hence I declared the array static. However, it's possible that in the future I'll have to work with multiple different BarArrays at the same time (where different instances of the struct should point into different arrays). Is there a way to achieve that without having to store an additional reference in every instance of the structs and not using a static variable neither? If not, what's the best way to use multiple static instances while making the whole application feel as "one application" for the end-user? A: You seem to think that holding a reference to an array means copying the array .. ie that each instance of your struct would contain a copy of the array? This is not the case. All the struct would contain is a reference to the array ... a pointer. There would only exist one instance of the array in memory. I'm not sure this is gaining you any performance points. A: You can't. The point of static is to have one instance over the whole application. Have a look at Dependency Injection instead. It should fulfill your usecase perfectly fine and is the prefered way of handling such a problem. A: It's not only memory. Every time I create a new instance or copy it (pass it to a method etc.) it'll add some cpu time overhead as well. That's the main thing I'd like to minimize Then make them class objects. Then you only have to pass a reference around and you can add a ref to the array without penalty. (And No, using 1M small objects on the heap is not a perfromance issue). But I seriously doubt that copying small structs was singled out by a profiler. It sounds like you're guessing where the bottleneck is. A: static class FooClass{     private static int[][] barArrays; public static int[] getBarArray(int instanceIndex) { return barArrays[instanceIndex]; } } struct FooStruct{ private int instanceIndex;     public int BarArrayIndex;     public int BarArrayValue {       get { return FooClass.getBarArray[instanceIndex][BarArrayIndex]; }       set { FooClass.getBarArray[instanceIndex][BarArrayIndex] = value; }     } } This is a generalization of the Singleton pattern. By the way, the performance penalty for each instance of FooStruct to hold on to a common instance of FooClass is absolutely trivial. A: The best you could do at this moment is to add a factory method to the FooClass, responsible for returning an instance of the BarArray. class FooClass { int[] GetBarArray() { } } For now, implement this method to return a static object. If somewhere in future you decide to change the policy of creating the array, you just reimplement the factory method. A: If you just want to have multiple static Variables use a new AppDomain for every Context. But i'm not sure if this is the right soultion for your Problem (See other Answers). EDIT: Tutorials and Helpful http://msdn.microsoft.com/en-us/library/system.appdomain.aspx http://www.beansoftware.com/NET-Tutorials/Application-Domain.aspx I don't understand Application Domains
{ "language": "en", "url": "https://stackoverflow.com/questions/7621330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I index a tree in MongoDB? I need to create a tree with tens of levels and thousands of nodes, and then find a given document by field inside that tree. Is it possible to index that field in the whole tree? And what would the query to find that document look like? A: You want to store a graph, use a graph database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I programmatically generate Heroku-like subdomain names? We've all seen the interesting subdomains that you get automatically assigned when you deploy an app to Heroku with a bare "heroku create". Some examples: blazing-mist-4652, electric-night-4641, morning-frost-5543, radiant-river-7322, and so on. It seems they all follow a adjective-noun-4digitnumber pattern (for the most part). Did they simply type out a dictionary of some adjectives and nouns, then choose combinations from them at random when you push an app? Is there a Ruby gem that accomplishes this, perhaps provides a dictionary which one could search by parts of speech, or is this something to be done manually? A: Engineer at the Heroku API team here: we went with the simplest approach to generate app names, which is basically what you suggested: keep arrays of adjectives and nouns in memory, pick an element from each at random and combine it with a random number from 1000 to 9999. Not the most thrilling code I've written, but it's interesting to see what we had to do in order to scale this: * *At first we were picking a name, trying to INSERT and then rescuing the uniqueness constraint error to pick a different name. This worked fine while we had a large pool of names (and a not-so-large set of apps using them), but at a certain scale we started to notice a lot of collisions during name generation. To make it more resilient we decided to pick several names and check which ones are still available with a single query. We obviously still need to check for errors and retry because of race conditions, but with so many apps in the table this is clearly more effective. It also has the added benefit of providing an easy hook for us to get an alert if our name pool is low (eg: if 1/3 of the random names are taken, send an alert). *The first time we had issues with collisions we just radically increased the size of our name pool by going from 2 digits to 4. With 61 adjectives and 74 nouns this took us from ~400k to ~40mi names (61 * 74 * 8999). *But by the time we were running 2 million apps we started receiving collision alerts again, and at a much higher rate than expected: About half of the names were colliding, what made no sense considering our pool size and amount of apps running. The culprit as you might have guessed is that rand is a pretty bad pseudorandom number generator. Picking random elements and numbers with SecureRandom instead radically lowered the amount of collisions, making it match what we expected in first place. With so much work going to scale this approach we had to ask whether there's a better way to generate names in first place. Some of the ideas discussed were: * *Make the name generation a function of the application id. This would be much faster and avoid the issue with collisions entirely, but on the downside it would waste a lot of names with deleted apps (and damn, we have A LOT of apps being created and deleted shortly after as part of different integration tests). *Another option to make name generation deterministic is to have the pool of available names in the database. This would make it easy to do things like only reusing a name 2 weeks after the app was deleted. Excited to see what we'll do next time the collision alert triggers! Hope this helps anyone working on friendly name generation out there. A: There are several possibilities. You can generate a random string. If you want to use real words, you need a dictionary. Then you can create a result generating a permutation of words and digits. Another nice alternative is the one adopted by Ruote. Ruote relies on rufus-mnemo to generate an unique name for each process. rufus-mnemo provides methods for turning integer into easier to remember ‘words’ and vice-versa. You can generate an unique id for the record, then convert it into a word. A: I've created a gem to do this: RandomUsername Similar gems are Bazaar and Faker. A: Thanks to @m1foley I am using your gem https://github.com/polleverywhere/random_username Generate random name: num_size = 2 # you can change this value to change number size temp_num = (Array.new(num_size) { rand(10).to_s }).join app_url = RandomUsername.adjective + '-' + RandomUsername.noun + '-' + temp_num Explanation: * *At first generate two digit number *then generate an adjective *then generate a noun *finally concatenate with dash(-): adjective + noun + temp_num Some generated name: # caring-plateau-07 # teal-summer-32 # vivid-snowflake-25 # outrageous-summer-95
{ "language": "en", "url": "https://stackoverflow.com/questions/7621341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: MY cssjson code not is not effecting my div <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="styles/common.css"> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script type='text/javascript'> $(function() { $.getJSON('http://api.jo.je/justgiving/jsonp.php?d=expedition-aconcagua&callback=?', {}, function (data) { $('#title').html(data.title); $('#target').html(data.donations_target); $('#raised').html(data.donations_total); $('#percent').html(data.percentage_complete); $('#charity').html(data.charity); $('#charity_details').html(data.charity_details); $('#charity_logo').html(data.charity_logo); var donations = ""; $.each(data.donations, function(index, value) { if (index < 3) { donations = donations + "<strong>" + value.person + "</strong>" + value.amount + "<br />" + value.message + "<br />"; } }); $('#donations').html(donations); var cssjson = { ".percentage_bar_complete":{ "width":"data.percentage_complete" } } var styleStr = ""; for(var i in cssjson){ styleStr += i + " {\n" for(var j in cssjson[i]){ styleStr += "\t" + j + ":" + cssjson[i][j] + ";\n" } styleStr += "}\n" } }) }); </script> </head> <body> <h2><span id='title'></span></h2> <h3><span id='charity'></span></h2> <div><img src="<span id='charity_logo'></span>" /><span id='charity_logo'></span></div> <h3>Target <span id='target'></span>, <span id='raised'></span> raised</h3> <h4>Percentage Complete - <span id='percent'></span>%</h4> <div class="percentage_bar"> <div class="baseline"> <p>0%</p> </div> <div class="total"> <p>100%</p> </div> <br clear="all" /> <div class="percentage_bar_bg"> <div class="percentage_bar_complete"> </div> </div> </div> <h3>Most recent donations</h3> <div id='donations'></div> I am having difficulty getting the CSS part of the JSON to work. The intention is to have two div layers one top of the other, the bottom with a width of 100% to indicate the empty bar and the other with a percent width drawn from the JustGiving JSON feed "percentage_complete". However the CSSJSON code I have added does not seem to working. Any help would be greatly appreciated. The page as it is can be viewed here http://www.adam-poole.co.uk/test/jg.html A: var cssjson = { ".percentage_bar_complete":{ "width":"data.percentage_complete" } } you are setting the width property to the value of (string) "data.percentage_complete" instead of the value of the variable data.percentage_complete. remove the double quotation marks around the variable name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute shell commands synchronously in PHP I need to run multiple scripts(5 scripts) via cmd, I want to make sure unless and until the first script finishes the second should not initiate. Thus after first script completes then only second should being then third one and so on.. Currently I am using the following code to do this exec ("php phpscript1.php "); exec ("php phpscript2.php "); exec ("php phpscript3.php "); exec ("php phpscript4.php "); exec ("php phpscript5.php "); I think these scripts run asynchronously, any suggestion guys so that these scripts can be run synchronously. A: If I'm getting you right, you're executing php scripts from inside a php script. Normally, php waits for the execution of the exec ("php phpscript1.php"); to finish before processing the next line. To avoid this, just redirect the output to /dev/null or a file and run it in background. For example: exec ("php phpscript1.php >/dev/null 2>&1 &");. A: PHP exec will wait until the execution of the called program is finished, before processing the next line, unless you use & at the end of the string to run the program in background. A: Check out the exec function syntax on php.net. You will see that exec does not run anything asynchronously by default. exec has two other parameters. The third one, return_var can give you a hint if the script ran successfully or any exception was fired. You can use that variable to check if you can run the succeeding scripts. Test it and let us know if it works for you. A: In my opinion, it would be better to run cronjobs. They will execute synchronously. If the task is "on-the-fly", you could execute the command to add this cronjob. More information about cronjobs: http://unixgeeks.org/security/newbie/unix/cron-1.html http://service.futurequest.net/index.php?_m=knowledgebase&_a=viewarticle&kbarticleid=30 A: Both exec and system wait for the script to execute unless you don't fork. Check.php <?php echo "here ".__LINE__."\n"; exec ("php phpscript1.php"); echo "here ".__LINE__."\n"; system("php phpscript2.php"); echo "here ".__LINE__."\n"; ?> phpscript1.php <?php echo "=================phpscript1.php\n"; sleep(5); ?> phpscript2.php <?php echo "=================phpscript2.php\n"; sleep(5); ?> Check.php execute script1 for 5 seconds then display next line number and then execute script2 by printing the next line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: Do you use onPostCreate() method? According to the documentation, Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown. It is not advised to use this method. However, I use it to tweak some elements after onCreate. I see that some people use it to do something between onResume() and they are advised not to do this as they cannot rely on this method (due to its bad documentation). So, can I use the tweaking here (it does not rely on onResume at all)? Do you ever use this method and when/why? A: onPostCreate can be useful if you are making your own "super-class" extension of Activity with functionality that all your activities shall share. using onPostCreate as a callback method from subclass' onCreate will notify that all creation is finished. Example: If you have activities sharing the same layout, then you can use the onPostCreate to add onClickListeners etc If you are overriding onPostCreate, it is best to make the call to super.onPostCreate at the end of your implementation. A: Google uses onPostCreate() in their example project for Navigation Drawer. ActionBarDrawerToggle needs to sync after orientation change lets say :) @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } So I think onPostCreate() should be used only in some specific situations... A: This is an extension to the second answer: Imagine you are trying to implement BaseActivity which doesn't set any layout in OnCreate method. public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } } Then imagine you have some other Activity (extends the BaseActivity) which sets some layout : public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } activity_main.xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/my_btn" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> So the the very first time when you can use your button in BaseActivity is onPostCreate method: public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); Button btn = (Button) findViewById(R.id.myBtn); //this is the when you can initialise your button } } Using BaseActivity is a common practice in making good apps! A: As the documentation states, onPostCreate is mostly intended for framework use. The question is: What do you intend to do in onPostCreate() that you can't do in onCreate() or onResume() (i.e. what exactly does "tweaking some elements" mean)? I am not using it, as I see no reason to do so - all I need to do can be done in onCreate or onResume. However Google itself uses it in it's TabActivity for instance. A: I use onPostCreate() when i need to change the view programmatically. Because call findViewById() not work when i use in onCreate. A: There might be situations you will be needing to use it. specially with the newer APIs. A scenario that it might be useful is during rotation change, or return state to an activity that has a progress bar inside the action bar. you will need to set it false inside it onPostCreate() @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setProgressBarIndeterminateVisibility(false); } A: You can check the execution sequence in ActivityThread#performLaunchActivity. Then you will find that onPostCreate() is the final lifecycle method thad has been executed after the onCreate(),onStart(),OnRestoreInstanceState() of an activity. And after that,onResumewill be executed. A: Since none of the answers made a point on onRestoreInstanceState(Bundle), I want to make a point here. This method will be called, If an app is forcefully removed from the memory and then started by the user again. So that we can use this method to retain activity state, Incase if the user previously removed the app forcefully from memory. A: According to the event name 'Post' meaning, i always use it for checking Elements size might be changed during onCreated, especially while Elements or layouts should be changed after screen rotated. A: it just called after onCreate, Since my program isn`t very complex, it works well. It is useful to do something in common in the base class after the child class has inflate its layout
{ "language": "en", "url": "https://stackoverflow.com/questions/7621349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Ruby on Rails - Import data from csv file from url I am creating a simple app in Ruby on Rails. Need to import data from cvs files at finance.google.com (an example http://www.google.com/finance/historical?q=NYSE:SMH). The program then stores this data for all 500 companies of S&P500 on a daily basis into a database. What's the proper way to do this? A: Simplest way could be this, it's almost just like reading a file: require "open-uri" url = "http://www.google.com/finance/historical?q=NYSE:SMH" url_data = open(url).read() # favorite way of parsing csv goes here EDIT: that was the approach from a script. For a Rails approach you could write a Rake task to do this, and run it periodically via a scheduled task. A: Please check this gist, pretty sure it will resolve your issue https://gist.github.com/victorhazbun87/9ac786961bbf7c235f76
{ "language": "en", "url": "https://stackoverflow.com/questions/7621352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Event handler not firing anymore I have been at work this afternoon trying to use a backgroundworker to read from an pretty large xml File Located in my assembly. It has worked pretty well up till the point I decided to rename the backgroundworker's objectname. After I built my solution, it told me it was a success. After running my program and testing it, I noticed that the backgroundworker's DoWork Event refuses to fire at all. When I added the code below to the Backgroundworker's RunWorkerCompleted event, all i got was a messagebox containing a big fat nothing. MessageBox.Show(e.Result + " " + e.Error); Renaming it back to what it was also didn't help. I wrote all the code myself, so there are no third party applications involved here. Here is the code I used to set up the workings with the backgroundworker private volatile List<string> listItems = new List<string>(); private BackgroundWorker _populateListItems = new BackgroundWorker(); private string currentConnection; #endregion public frmSettings() { InitializeComponent(); //I will be able to track how far the list is populated with the following command. _populateListItems.WorkerReportsProgress = true; //This will fire if there is an error in the xml file. _populateListItems.WorkerSupportsCancellation = true; //Assign the job to be done for the backgroundworker _populateListItems.DoWork +=new DoWorkEventHandler(_populateListItems_DoWork); _populateListItems.ProgressChanged += new ProgressChangedEventHandler(_populateListItems_ProgressChanged); //When the worker is finished, the following event will fire: All UI controls will be updated. _populateListItems.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_populateListItems_RunWorkerCompleted); _populateListItems.RunWorkerAsync(); } void _populateListItems_ProgressChanged(object sender, ProgressChangedEventArgs e) { prgProgress.Value = e.ProgressPercentage; lblProgress.Text = e.ProgressPercentage.ToString() + "%"; } private void _populateListItems_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //The operation is completed/Cancelled/Erroneous. The list will now be populated with the available information. MessageBox.Show(e.Result + " " + e.Error); foreach (string item in listItems) { liConnections.Items.Add(item); } //This shows the user which connection is currently used. lblCurrentSelection.Text = currentConnection; } private void _populateListItems_DoWork(object sender, DoWorkEventArgs e) { try { //The following lines of code are the variables that are going to be used. // xReadSettings will make the XmlReader xRead Ignore whitespaces and comments, if any. // assemblyExecuted will get information from which assembly gets Executed. // filename Will get the filename of the settings.xml file that is going to be used. // SettingsStream will open the stream for reading and writing, using the GetManifestResourceStream() method from the currently executed assembly. XmlReaderSettings xReadSettings = new XmlReaderSettings(); Assembly assemblyExecuted = Assembly.GetExecutingAssembly(); string filename = String.Format("{0}.Settings.xml", assemblyExecuted.GetName().Name); Stream settingsStream = assemblyExecuted.GetManifestResourceStream(filename); xReadSettings.IgnoreComments = true; xReadSettings.IgnoreWhitespace = true; //Finally the xmlReader object is created using the settingstream, and its settings. //While the stream reads, it checks whether the nodes accessed are elements of the xml file. //if it is an element that is accessed, then we check whether the element which is accessed is a connection string to the database //if it is a connectionstring to the database, we will check if the connection has a name. //if it has a name, we get the name attribute, and add it to our list. The list is volatile, so it will be up to date, because this //background thread is updating it. //To Update the progress of the backgroundworker, we need to know the amount of elements in the XML File. Xpath will be used for this. XmlDocument xdoc = new XmlDocument(); xdoc.Load(settingsStream); XmlNodeList nodes = xdoc.SelectNodes("*"); //Xpath - select all. int totalElementsToRead = nodes.Count; int totalElementsRead = 0; using (XmlReader xRead = XmlReader.Create(settingsStream, xReadSettings)) { while (xRead.Read()) { if (xRead.NodeType == XmlNodeType.Element) { if (xRead.Name == "ConnectionString") { if (xRead.HasAttributes) { string attribute = xRead.GetAttribute("name").ToString(); listItems.Add(attribute); } } if (xRead.Name == "CurrentConnection") { xRead.Read(); //gets the value of <CurrentConnection> currentConnection = xRead.Value.Trim(); } totalElementsRead++; _populateListItems.ReportProgress(totalElementsRead / totalElementsToRead * 100); } } } } catch { _populateListItems.CancelAsync(); } } Pardon the theory in the comments behind it. I'm explaining it the best way that i can. My question is though, can anyone see perhaps where this has gone wrong? Why the event suddenly does not fire? It is supposed to fill a list up with items from my xml file (untouched, was working before rename). Running a step-through debug also proved it was skipping my doWork event handler. A: I think the problem is that you are calling RunWorkerAsync from the constructor and the ProgressChanged fails due to the form not being visible yet. Try moving the call to RunWorkerAsync to the form's Show event handler. OK, so the problem was an exception inside the DoWork event handler that was being eaten up by the try..catch block. To sum up the issues with your code: * *try..catch block that eats up all exceptions and makes debugging difficult. *Call RunWorkerAsync from inside the form constructor. *Access UI thread objects from the worker thread without proper synchronization/locking. *Call CancelAsync from inside the DoWork event handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is ids.xml used for? Just a quick question, what is the ids.xml used for when developing an Android app? I saw an example on the android resources webpage which contained: <resources> <item name="snack" type="id"/> </resources> What would this be used for? A: Another application for id.xml is in respect to layouts and library projects. Let's say you specify a generic list of options in a library (dialog) layout <CheckedTextView android:id="@+id/checked_option_one"... <CheckedTextView android:id="@+id/checked_option_two"... ... and handle these views in a generic (dialog) fragment optionOneCheck = (CheckedTextView)rootView.findViewById(R.id.checked_option_one); optionTwoCheck = (CheckedTextView)rootView.findViewById(R.id.checked_option_two); If you remove any of the view declarations from a copy of the layout in a main project, you will get a "no such field" error exception at runtime. The compiler doesn't complain, but at runtime the id isn't actually there/known. Declaring the ids in id.xml and using <CheckedTextView android:id="@id/checked_option_one"... ... avoids the runtime error A: id.xml is generally used to declare the id's that you use for the views in the layouts. you could use something like <TextView android:id="@id/snack"> for your given xml. A: ids.xml has the following advantage: all ids were declared, so compiler can recognize them. If something like this: <TextView android:id="@+id/text1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignBelow="@id/text2" android:text="...."/> <TextView android:id="@+id/text2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="...."/> Can result in compiling error because text2 was refered before declared A: ids.xml is much more powerful. You can predefine values like <item name="fragment_my_feature" type="layout"/> <item name="my_project_red" type="color"/> not only id. Actually you can use more resource types: https://developer.android.com/guide/topics/resources/more-resources It's extremely helpful to predefine some layouts, colors etc. in root module for multi-module app. You can keep actual layouts, colors, etc. in specific app module which has root module as dependency. A: When creating views dynamically, predefining id's in ids.xml gives the posibility to reference a newly created view. After you use the setId(id) method you can access the view as if it had been defined in XML. This blog post has a nice example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: How to install PIL with Freetype? I wanted to put django-simple-captcha in my project but it cannot create images for the CaptchaField. It says "No module named _imagingft" I am using Ubuntu 11.04 I installed libfreetype6 and libfreetype6-dev by apt-get install then I downloaded PIL 1.1.6 and changed FREETYPE_ROOT = "/usr/local/include" then I built PIL python setup.py build then install it python setup.py install I still cannot import _imagingft and my page still does not display the captcha image. it only shows captcha <input box> A: OK it works now, all I did was to redo everything and not install zlib,jpeglib,freetype via aptitude Sorry I posted it as comment, I didn't knew I can already answer my own question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: update statement not executing I am trying to write an UPDATE query that can check for a null value in one of the fields. I have three conditions, two are mandatory, of three fields. itemCode and itemCheckDigit will always exist, itemSuffix is possibily Null. There may be multiple records where itemCode and itemCheckDigit together are equal to other records, itemSuffix is the unquie identifier, only one instance will exist though where itemSuffix is Null and it will never be duplicated. UPDATE item SET itemImageFileName = ''' + @fileName + ''' WHERE (itemCode = ''' + @itemCode5 + ''') AND (itemCheckDigit = ''' + @itemCkDigit + ''') AND (itemSuffix IS NULL); This is what I think I would like to do, but it is not working. A: Your problem is that you are wrapping tick marks around your parameters in your statement so when it's evaluated it looking for stuff from the item table where itemCode is 'toy' (note the single quotes) The string concatenation you are doing is how one would, poorly, add parameters to their dynamic queries. Instead, take the tick marks out like so UPDATE item SET itemImageFileName = @fileName WHERE (itemCode = @itemCode5 ) AND (itemCheckDigit = @itemCkDigit) AND (itemSuffix IS NULL); To handle optional search parameters, this article by Bill Graziano is excellent: Using Dynamic SQL in Stored Procedures. I find that is strikes a good balance between avoiding the query recompilations of setting the recompile option on and avoiding table scans. Please to enjoy this code. It create a temporary table to simulate your actual item table and loads it up with 8 rows of data. I declare some parameters which you most likely wont' need to do as the ado.net library will do some of that magic for you. Based on the values supplied for the first 3 parameters, you will get an equivalent match to a row in the table and will update the filename value. In my example, you will see the all NULL row will have the filename changed from f07.bar to f07.bar.updated. The print statement is not required but I put it in there so that you can see the query that is built as an aid in understanding the pattern. IF NOT EXISTS (SELECT * FROM tempdb.sys.tables T WHERE T.name like '%#item%') BEGIN CREATE TABLE #item ( itemid int identity(1,1) NOT NULL PRIMARY KEY , itemCode varchar(10) NULL , itemCheckDigit varchar(10) NULL , itemSuffx varchar(10) NULL , itemImageFileName varchar(50) ) INSERT INTO #item -- 2008+ --table value constructor (VALUES allows for anonymous table declaration) {2008} --http://technet.microsoft.com/en-us/library/dd776382.aspx VALUES ('abc', 'X', 'cba', 'f00.bar') , ('ac', NULL, 'ca', 'f01.bar') , ('ab', 'x', NULL, 'f02.bar') , ('a', NULL, NULL, 'f03.bar') , (NULL, 'X', 'cba', 'f04.bar') , (NULL, NULL, 'ca', 'f05.bar') , (NULL, 'x', NULL, 'f06.bar') , (NULL, NULL, NULL, 'f07.bar') END SELECT * FROM #item I; -- These correspond to your parameters DECLARE @itemCode5 varchar(10) , @itemCkDigit varchar(10) , @itemSuffx varchar(10) , @fileName varchar(50) -- Using the above table, populate these as -- you see fit to verify it's behaving as expected -- This example is for all NULLs SELECT @itemCode5 = NULL , @itemCkDigit = NULL , @itemSuffx = NULL , @fileName = 'f07.bar.updated' DECLARE @query nvarchar(max) SET @query = N' UPDATE I SET itemImageFileName = @fileName FROM #item I WHERE 1=1 ' ; IF @itemCode5 IS NOT NULL BEGIN SET @query += ' AND I.itemCode = @itemCode5 ' + char(13) END ELSE BEGIN -- These else clauses may not be neccessary depending on -- what your data looks like and your intentions SET @query += ' AND I.itemCode IS NULL ' + char(13) END IF @itemCkDigit IS NOT NULL BEGIN SET @query += ' AND I.itemCheckDigit = @itemCkDigit ' + char(13) END ELSE BEGIN SET @query += ' AND I.itemCheckDigit IS NULL ' + char(13) END IF @itemSuffx IS NOT NULL BEGIN SET @query += ' AND I.itemSuffx = @itemSuffx ' + char(13) END ELSE BEGIN SET @query += ' AND I.itemSuffx IS NULL ' + char(13) END PRINT @query EXECUTE sp_executeSQL @query , N'@itemCode5 varchar(10), @itemCkDigit varchar(10), @itemSuffx varchar(10), @fileName varchar(50)' , @itemCode5 = @itemCode5 , @itemCkDigit = @itemCkDigit , @itemSuffx = @itemSuffx , @fileName = @fileName; -- observe that all null row is now displaying -- f07.bar.updated instead of f07.bar SELECT * FROM #item I; Before itemid itemCode itemCheckDigit itemSuffx itemImageFileName 1 abc X cba f00.bar 2 ac NULL ca f01.bar 3 ab x NULL f02.bar 4 a NULL NULL f03.bar 5 NULL X cba f04.bar 6 NULL NULL ca f05.bar 7 NULL x NULL f06.bar 8 NULL NULL NULL f07.bar after itemid itemCode itemCheckDigit itemSuffx itemImageFileName 1 abc X cba f00.bar 2 ac NULL ca f01.bar 3 ab x NULL f02.bar 4 a NULL NULL f03.bar 5 NULL X cba f04.bar 6 NULL NULL ca f05.bar 7 NULL x NULL f06.bar 8 NULL NULL NULL f07.bar.updated
{ "language": "en", "url": "https://stackoverflow.com/questions/7621364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Searching (x,y) pair in sequence I would like to find match (x,y) in string. Is the following seem good ? Or better alternative you can suggest. Please note that between (x,y) pairs several white spaces or commas may exists in mystring. #!/usr/bin/env python import re mystring="(3,4) , (2, 4),(5,4), (2,3), " tmp= re.findall(r'\(\d+,\d\)+', mystring) print tmp for i, v in enumerate(tmp): if v =="(5,4)": print "match found" Thank you. A: Instead of re.findall(r'\(\d+,\d\)+', mystring) Use re.findall(r'\(5,4\)', mystring) and it will only find the pair you want A: Why not search for the pair you want? Also, you can use \s to match whitespace. import re def find_pair(x, y, mystring): return re.findall(r'\(\s*?%d,\s*?%d\s*?\)+' % (x, y), mystring); print find_pair(2, 4, "(3,4) , (2, 4),(5,4), (2,3), ") A: No regex needed: ast.literal_eval(mystring).count((5,4)) or if (5,4) in ast.literal_eval(mystring): print('Found!')
{ "language": "en", "url": "https://stackoverflow.com/questions/7621366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Radio button checked using jQuery I'm trying to alert some stuffs when a radio button is checked but my code isn't working. Does anyone have any idea why? <html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $("input[@name='crkbrd']").change(function(){ if ($("input[@name='crkbrd']:checked").val() == 'Upload') { alert("Upload Your Own Ad"); } else if ($("input[@name='crkbrd']:checked").val() == 'Edit') { alert("Edit Your Ad Here"); } else { alert("You haven't chosen anything"); } }); }); </script> </head> <body> <input type="radio" id="rb1" name="crkbrd" value="Upload" /> Upload Your Own Ad<br /> <input type="radio" id="rb2" name="crkbrd" value="Edit" /> Edit Your Ad Here </body> </html> A: Remove the @ in the name selectors. JQuery uses CSS selectors, which is in this format:  • elementselector[attribute=value] Use one of the following selectors instead: input[name=crkbrd] input[name="crkbrd"] input[name='crkbrd'] You should have got this error message when you ran your code: Syntax error, unrecognized expression: [@name='crkbrd']
{ "language": "en", "url": "https://stackoverflow.com/questions/7621371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I change the date format of a DataBinder.Eval in asp.net? I'm trying to figure out how to change the datetime format so just the date will show up. <asp:Repeater ID="RepeaterActions" runat="server"> <ItemTemplate> <li> <span class="historyDate"><%#DataBinder.Eval(Container.DataItem, "ActionListDate")%></span> <span class="historyName"><%#DataBinder.Eval(Container.DataItem, "LeadActionName")%></span><br /> <span class="historyNotes"><%#DataBinder.Eval(Container.DataItem, "ActionListNote")%></span> </li> </ItemTemplate> </asp:Repeater> I'm guessing it's something in between the <% %>, but I'm not sure. My code behind is: <pre> protected void RepeaterActionsFill() { string sql = @" select a.ActionListDate, a.LeadListID, a.ActionListNote, l.LeadActionName from ActionLists as a INNER JOIN LeadActions as l ON a.LeadActionID = l.LeadActionID where a.LeadListID = " + Convert.ToInt32(Request["id"].ToString()); RepeaterActions.DataSource = DBUtil.FillDataReader(sql); RepeaterActions.DataBind(); } </pre> Currently, it comes accross looking like this: And what I'm looking for is for the time stamp to be gone there. Any help is appreciated. EDIT: Here is what I was looking for: <asp:Repeater ID="RepeaterActions" runat="server"> <ItemTemplate> <li> <span class="historyDate"><%#DataBinder.Eval(Container.DataItem, "ActionListDate", "{0:M/d/yy}")%></span> <span class="historyName"><%#DataBinder.Eval(Container.DataItem, "LeadActionName")%></span><br /> <span class="historyNotes"><%#DataBinder.Eval(Container.DataItem, "ActionListNote")%></span> </li> </ItemTemplate> </asp:Repeater> A: give the format e.g: <%# DataBinder.Eval(Container.DataItem, "ActionListDate", "{0:d/M/yyyy hh:mm:ss tt}") %> A: <%# string.Format("{0:ddd MMM yyyy}", Eval("ActionListDate"))%> A: I put this in the code behind: public string makeShortDate(object oDate) { if (oDate is DBNull) { return ""; } else { DateTime dDate = Convert.ToDateTime(oDate); string sDate = dDate.ToShortDateString(); return sDate; } } And use this in the XHTML: Text='<%# makeShortDate ( DataBinder.Eval(Container.DataItem, "MyDate")) %>' You can modify this for any type. A: Can't test this code right now but something along the lines of? <%#DataBinder.Eval(Container.DataItem, "ActionListDate").ToString("dd/MM/yyyy") %> A: also you can change your tsql to the following or just remove the Convert.ToInt32() string sql = string.Format(@"select a.ActionListDate, a.LeadListID, a.ActionListNote, l.LeadActionName from ActionLists as a INNER JOIN LeadActions as l ON a.LeadActionID = l.LeadActionID where a.LeadListID = {0};", Request["id"]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7621373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: How to get current method name not from the current Thread at runtime using reflection? class Foo{ static void fooMethod1(){ // do something } static void fooMethod2(){ // do something } static void fooMethod3(){ // do something } } class bar{ public static void main(String[]args){ Foo.fooMethod1(); Foo.fooMethod2(); Foo.fooMethod3(); } } Using reflection, how to know (without knowing method name) that fooMethod1 || 2 || 3 is called (not from the current Thread)? A: Given that you aren't writing some kind of debugging tool, perhaps you should have your threads talk to each other? Perhaps using an observer? To me, that seems like a much more straight forward, simple and easy-to-understand solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: php curl posting to server where script is hosted doesn't work I'm trying to use curl to post data to a script which is posted on the same server however it gives me this error: <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>401 - Unauthorized</title> </head> <body> <h1>401 - Unauthorized</h1> </body> </html> It works fine on localhost, what settings do I need to change to make it work on the server though? A: 401 - unauthorized probably means there is a password protection in place for the path you are trying to upload to. You'll need to remove the protection, or change your script so curl sends the correct credentials.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving SQLite database from android phone to emulator I have my app with some data. I'd like to test my sqlite database (from my phone) in Android emulator. I'm 99% sure It was working some time ago using the same method. I know where are my database files, I know how to use PUSH and PULL DDMS features. Maybe something change in new SDK? This is how I'm moving my SQLite database from phone to androim emulator. * *I've got rooted phone and created android emulator in eclipse. My database file is in /data/data//databases/file.db I can copy this file from my phone to my desktop. * *I've got sqlite database file, I can open it in (for example) SQLite Manager. I see my database structure with data. Everything is OK. *Now, I'm moving my database file to android emulator. I've got my app already installed. I'm using "Push a file onto the device" from DDMS. OK. It works. My file was uploaded to emulator. But. When I'd like to see my database schema using emulator, this is what I get: Error: database disk image is malformed (this is error from adb console). My app can't see this database. Doing the same thing on my phones - no problems. Is there a bug in android emulator or maybe I'm doing something wrong. I'm using rooted phone with 2.3.4 (CM7.1-RC1). My emulator is using API level 10 (2.3.3). A: Ok this isn't an answer to solve your problem directly, but instead of copying your database from your phone to the emulator, wasting countless hours of hair pulling, why don't you create some test scripts to fill your database upon installing the app? That way you just push the new version to your phone, run it, and you are set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: helpers for all controllers under a namespace? I have an admin namespace. Is there a standard way to create a helper file that is automatically available for every controller in the namespace? A: If you have all your controllers in the namespace inherit from a different controller than the others in your application, say Admin::AdminBaseController, then this becomes simple. Just add the following line to that controller: helper :all
{ "language": "en", "url": "https://stackoverflow.com/questions/7621380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: restrict xulrunner network access I have a xulrunner application that uses browser component to display HTML content. For security reasons I would like to restrict that browser to be able to only access a certain url mask. I would like to restrict any networking to intranet only, something like "*.company.com". But not only page navigation, XHR, CSS, script and all the netwoking. Does any body know how to implement this? Any XPCOM components that I could use for it? A: The easiest way to do this would be through a proxy auto-configuration file (assuming that your application doesn't actually need to use a proxy). So you would set network.proxy.type preference to 2 (use PAC file) and network.proxy.autoconfig_url to chrome://.../proxy.js. With proxy.js being something along the lines of: function FindProxyForURL(url, host) { if (shExpMatch(host, "*.company.com")) { return "DIRECT"; } return "SOCKS localhost:19191"; } So any requests to *.company.com won't use a proxy whereas requests to other hosts will be directed to a localhost port which is hopefully closed - so these requests will not succeed. This is a hack of course but one that is simple enough and works well in most scenarios. The proper (but more complicated) way of doing this would be using content policies. You need to implement nsIContentPolicy in an XPCOM component and register that component in the content-policy category. This will make sure that the shouldLoad() method of your component will be called for each URL to be loaded - you can return Ci.nsIContentPolicy.REJECT_REQUEST to block the load.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a dropdown list to the browser through google chrome extension? Is it possible to add a dropdown menu to chrome browser through a google chrome extension so the user can chose an option lets say color and then the extension can apply that color to the background or something else? Note I am interested in adding a dropdown to the chrome browser. A: You can't change browser's menu. You can: * *add icon with optional popup to the toolbar (browser action), *add icon to the url bar (page action), *add item to page's context menu. That's the only changes you can make to browser's interface. Based on your task I would go with browser action with popup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a click event to Zynga's new Canvas Scrolling API In case you missed it on HN, Zynga open sourced a great tiling / scrolling API for Canvas. https://github.com/zynga/scroller How can I add a click event to each cell for this? Exact code isn't required just the idea of where to start. I haven't spent enough time with Canvas yet, but I think this is a good place to start. I want to be able to get the cell that's clicked and query inside it. like context.click(function(e) { alert(e.hasSpecificAttribute); }) A: I haven't worked with this before, but from the few minutes I just spent with it I think you will have to calculate the cell yourself. If you run the demos they have (publicly hosted by someone here http://qwan.org/scroller/demo/), you'll notice that the canvas version is different from the DOM-based options. The DOM-based options actually use div elements, so you could easily pick out the cell using classes and/or id's. The canvas version seems to use one large canvas, though. Their demo page displays the current scroll values that are affecting the horizontal and vertical offset. You should be able to just grab those, and combine them with the location that the user clicked within the parent container as well as the width and height of each cell to determine which cell was clicked on. For instance: var x_cell = Math.floor((scroll_x + click_x) / cell_width); var y_cell = Math.floor((scroll_y + click_y) / cell_height); Note however that this won't really let you query the pixels on the canvas in that cell. Cells in this API seem to be an abstract concept that aren't really part of the structure of the canvas (ie. there aren't many little canvas elements). So, you might then want to use the cell coordinates to determine a region of the canvas that you can use getImageData() on. This would be very straightforward, and would just be context.getImageData(x_cell * cell_width, y_cell * cell_height, cell_width, cell_height);.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Concurrency between many machines running the same web app on the server side This is a pretty open question. I was wondering: how can you handle concurrency if you have a web application that is hosted on many computers on the server side? For example, how can you manage a simple stack if you have an ASP .NET application running on different machines with each one having its own memory? Is there something I'm missing? Thanks A: If I understand the question correctly: how do multiple Web servers co-ordinate to return responses? In general a farm of Web servers will serve up exactly the same HTML to clients when a particular request arrives. If there's a need to store state - suppose the user posts back a form with data, or session state is used to keep track of a shopping cart - then you'll need some shared mechanism to do that. There's plenty of ways to share state between multiple instances of a Web server: * *A database can store data that needs to be persisted indefinitely, such as user profile information *Similarly, a key-value store (like the Windows Azure table storage) can be used for permanent storage, with advantages in performance over less flexibility when querying *Shared session state (using a database or central session state server) can store moderately-persistent data that's local to the current session Things can get complex, though: * *If data is cached, you may need to have a mechanism to expire the cache on each Web server *Eventually, contention over shared session storage or database storage can negate the advantages of multiple Web servers To get around this some systems use the principle of "eventual consistency", where, for instance, a profile update might not be replicated immediately to every server in a cluster. Not-quite-fresh data is sometimes regarded as good enough. As you can tell this is a complex subject and I've only really skated around the edges of it. The good news is that generally you won't need to bother as unless you're creating a very large or complex site most modern server hardware can handle many tens of requests per second without breaking into a sweat. It's only when you start to move above a few dozen simultaneous requests per second that Web farms start to be necessary. A: Jeremy McGee's answer covers most of the important points. One other angle is that many web farm setups use "sticky sessions" where one session stays with a particular server. It is a great compromise between allowing scale and having to build, buy or configure lots of state management across your web server pool. The big problem kicks in when you have to scale the underlying data store out. There be dragons. A: You use reverse ajax (Comet) in different channels like using the web server Meteor. Facebook and Twitter use the same asynchronous event methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parse XML String with Regex.Matches in C# i have a very strange problem which i cannot solve at the moment. i try to parse a xml string with Regex.Matches to get all xml Nodes with a specific name. it worked until now. i have a xml input string with exactly 30 xml nodes named "row" for some freaky reason my code returns me 26 nodes.. i have actually NO idea why there are 4 missing. Heres my code to parse the data: public static List<String> getXMLNodeContentFromSQLQueryString(String queryString, String rowName) { List<String> returnVal = new List<string>(); MatchCollection matchCollection = Regex.Matches(queryString, "<" + rowName + ">.*?</" + rowName + ">"); foreach (Match match in matchCollection) { String splitted = match.ToString(); splitted = splitted.Replace("<" + rowName + ">", "").Replace("</" + rowName + ">", ""); returnVal.Add(splitted); } if (returnVal.Count == 0) returnVal.Add(""); return returnVal; } heres the xml string "<?xml version=\"1.0\"?>\r\n<EADATA version=\"1.0\" exporter=\"Enterprise Architect\">\r\n\t<Dataset_0><Data><Row><OperationID>5</OperationID><Object_ID>135</Object_ID><Name>applyForward</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{84137450-8053-46eb-ACD5-574741233ABC}</ea_guid></Row><Row><OperationID>6</OperationID><Object_ID>135</Object_ID><Name>applyBackward</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{416E8BF3-9D6D-4fb3-8C32-05E4E6B8EDDD}</ea_guid></Row><Row><OperationID>12</OperationID><Object_ID>240</Object_ID><Name>copy</Name><Scope>Public</Scope><Type>EObject</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{E57518A9-9A91-4b0f-9311-F7AF3177F809}</ea_guid></Row><Row><OperationID>13</OperationID><Object_ID>240</Object_ID><Name>embedSDMInEAnnotation</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{44F4A863-86CB-4889-B179-3F4BA1F68D8D}</ea_guid></Row><Row><OperationID>18</OperationID><Object_ID>273</Object_ID><Name>configure</Name><Scope>Public</Scope><Type>EBoolean</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>0. Integrator creates GraphTriple and sets roots\r\n1. Adds the given graph triple to the translator\r\n2. Iterates over composite structure of input model and fills unprocessedNodes and unprocessedEdges (other collections are initially empty although this could be different in incremental mode)</Notes><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{B22FDBFE-C033-4ff5-81FB-2ED133A55F62}</ea_guid></Row><Row><OperationID>19</OperationID><Object_ID>273</Object_ID><Name>translate</Name><Scope>Public</Scope><Type>TranslationResult</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>136</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{2DFA0837-F09F-40f5-A4BD-CD3857D2D712}</ea_guid></Row><Row><OperationID>21</OperationID><Object_ID>165</Object_ID><Name>determineLNCC</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>Iterate through all rules of the given TGG and consider edges in the following way:\r\nforall edges e in rule r\r\n-&amp;gt; s(e) or t(e) are context elements\r\n-&amp;gt; e is set to create\r\n=&amp;gt; add quadruple containing the types of s(e), t(e), the name of e and the encoded equivalent if s, t or both are context elements.</Notes><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{0E021F1A-5CE7-4f68-B737-D2C11AA200ED}</ea_guid></Row><Row><OperationID>22</OperationID><Object_ID>273</Object_ID><Name>determineCandidateRulesForNode</Name><Scope>Public</Scope><Type>CandidateRules</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>1. Look up in table for operational rules that translate type(node).</Notes><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>352</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{7BE07512-219E-40f3-BB81-B1C5B5B15211}</ea_guid></Row><Row><OperationID>24</OperationID><Object_ID>135</Object_ID><Name>isAppropriate</Name><Scope>Public</Scope><Type>EOperation</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>1. check if core match exists in input graph starting from given entry node\r\n2. check if DEC is satisfied (call external method)\r\n3. process context on demand\r\n4. return the corresponding perform* EOperation or null if check failed.</Notes><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>183</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{EC74C95A-0D42-4b5d-98C6-0E3273664A8D}</ea_guid></Row><Row><OperationID>25</OperationID><Object_ID>273</Object_ID><Name>updateProcessedSets</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Notes>1. Determines the corresponding graph elements to the translated objects in the given ruleResult (also edges for translated references!!!)\r\n2. Adds these graph elements to the set of processed elements\r\n3. Be careful not to manipulate the set of unprocessed elements!</Notes><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>3</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{CE58DEC9-E683-4d49-8A92-986698AD7ABD}</ea_guid></Row><Row><OperationID>26</OperationID><Object_ID>165</Object_ID><Name>buildCandidateRulesLookupTable</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{BC2520AA-DB89-4280-ACE6-F6A8711EDC61}</ea_guid></Row><Row><OperationID>28</OperationID><Object_ID>273</Object_ID><Name>determineCandidateRulesForEdge</Name><Scope>Public</Scope><Type>CandidateRules</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>4</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>352</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{1070078F-FF2E-49ca-9432-2D50C026A0D6}</ea_guid></Row><Row><OperationID>29</OperationID><Object_ID>288</Object_ID><Name>eInvoke</Name><Scope>Public</Scope><Type>java.lang.Object</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{A1D00185-AE82-493e-AAAC-E916D2DD98D3}</ea_guid></Row><Row><OperationID>38</OperationID><Object_ID>240</Object_ID><Name>CREATE</Name><Scope>Public</Scope><Type>BindingOperator</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>4</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>115</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{42E99307-46D4-444b-886B-FBA399DF29F6}</ea_guid></Row><Row><OperationID>39</OperationID><Object_ID>240</Object_ID><Name>BACKWARD</Name><Scope>Public</Scope><Type>ApplicationTypes</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>5</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>272</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{D0F76449-7205-4f9c-A03D-C68F72A669C4}</ea_guid></Row><Row><OperationID>27</OperationID><Object_ID>165</Object_ID><Name>determineEntryNode</Name><Scope>Private</Scope><Type>TGGObjectVariable</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>128</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{12E442A3-491E-4dc2-9171-728084C3746F}</ea_guid></Row><Row><OperationID>30</OperationID><Object_ID>434</Object_ID><Name>invokeOperationWithSingleArg</Name><Scope>Public</Scope><Type>EObject</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>288</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{DDE51358-F82B-4100-A5D1-12154D533B41}</ea_guid></Row><Row><OperationID>31</OperationID><Object_ID>165</Object_ID><Name>deriveOperationalRules</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>3</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{30584C3D-773E-4256-BBE9-4FD226E45814}</ea_guid></Row><Row><OperationID>32</OperationID><Object_ID>165</Object_ID><Name>createOperationalRules</Name><Scope>Private</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>4</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{ED7EF05C-D74B-4a0f-897D-DB7612AC5AEB}</ea_guid></Row><Row><OperationID>35</OperationID><Object_ID>240</Object_ID><Name>determineOperationSignature</Name><Scope>Public</Scope><Type>EString</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{999096A0-B224-4446-A8D5-CB581BA2DD20}</ea_guid></Row><Row><OperationID>36</OperationID><Object_ID>165</Object_ID><Name>createPerformOperation</Name><Scope>Private</Scope><Type>Activity</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>5</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>95</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{3414F021-9221-4be2-A133-28E6DAA25ADD}</ea_guid></Row><Row><OperationID>37</OperationID><Object_ID>240</Object_ID><Name>convertDirectionToAppropriateDomain</Name><Scope>Public</Scope><Type>DomainType</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>3</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>198</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{E83E8FA4-1802-4a2a-AF6B-81D5E4BAB83A}</ea_guid></Row><Row><OperationID>40</OperationID><Object_ID>240</Object_ID><Name>FORWARD</Name><Scope>Public</Scope><Type>ApplicationTypes</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>6</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>272</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{403AA3D8-A275-4763-BB64-8BDF6425EA18}</ea_guid></Row><Row><OperationID>42</OperationID><Object_ID>165</Object_ID><Name>createIsAppropriateOperation</Name><Scope>Public</Scope><Type>Activity</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>6</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>95</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{15A6B03B-DDE5-479d-A3DE-FA2A05970DE1}</ea_guid></Row><Row><OperationID>43</OperationID><Object_ID>240</Object_ID><Name>CHECK_ONLY</Name><Scope>Public</Scope><Type>BindingOperator</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>7</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>115</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{16268928-5197-4269-8A3D-5251DD8AA7A6}</ea_guid></Row><Row><OperationID>44</OperationID><Object_ID>240</Object_ID><Name>BOUND</Name><Scope>Public</Scope><Type>BindingState</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>8</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>113</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{5529869A-FE95-489e-BB61-BB1F46EBAB87}</ea_guid></Row><Row><OperationID>45</OperationID><Object_ID>240</Object_ID><Name>UNBOUND</Name><Scope>Public</Scope><Type>BindingState</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>9</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>113</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{A3CFAA93-BE84-4602-BAC7-AF42DE44F4AE}</ea_guid></Row><Row><OperationID>46</OperationID><Object_ID>240</Object_ID><Name>SUCCESS</Name><Scope>Public</Scope><Type>EdgeGuard</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>10</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>104</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{41D81F5E-E224-4171-A7B5-08BAD5D650E3}</ea_guid></Row><Row><OperationID>47</OperationID><Object_ID>240</Object_ID><Name>FAILURE</Name><Scope>Public</Scope><Type>EdgeGuard</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>11</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>104</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{8D2A6AF2-70C9-4d51-ADF2-CBD72BE0D8C1}</ea_guid></Row><Row><OperationID>48</OperationID><Object_ID>240</Object_ID><Name>MANDATORY</Name><Scope>Public</Scope><Type>BindingSemantics</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>12</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>114</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{ADB4946B-AAA6-4ead-97DE-476DE4406DC1}</ea_guid></Row></Data></Dataset_0></EADATA>\r\n" and ideas? thanks SOLVED!!!!!!!!!!!!!!! Still have no idea where the problem was but solved the problem with using XMLReader thanks for you advices heres the code for interested people. public static List getXMLNodeContentFromSQLQueryString(String queryString, String rowName) { List returnVal = new List(); // load contents of file TextReader textReader = new StringReader(queryString); // process file contents XmlDocument domDoc = new XmlDocument(); domDoc.Load(textReader); XmlNodeList nodeList = domDoc.GetElementsByTagName(rowName); foreach (XmlNode node in nodeList) { returnVal.Add(node.InnerXml); } return returnVal; } A: In each of the non returned rows (the Rows with OperationIDs of 18, 21, 24, and 25), there is one or more "\r\n" in the text, which causes the Regex to not match. Getting rid of them, or replacing them temporarily will return all 30 rows. However, using an XML parser as you now have is definitely the right way to go. A: Instead of using Regex, Add this namespace using System.Xml.Linq; using System.Xml.XPath; and then: var x1 = XDocument.Parse(str); var rows = x1.XPathSelectElements("//Row"); A: This might help someone. Using Linq to XML string xmlString = "<?xml version=\"1.0\"?>\r\n<EADATA version=\"1.0\" exporter=\"Enterprise Architect\">\r\n\t<Dataset_0><Data><Row><OperationID>5</OperationID><Object_ID>135</Object_ID><Name>applyForward</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{84137450-8053-46eb-ACD5-574741233ABC}</ea_guid></Row><Row><OperationID>6</OperationID><Object_ID>135</Object_ID><Name>applyBackward</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{416E8BF3-9D6D-4fb3-8C32-05E4E6B8EDDD}</ea_guid></Row><Row><OperationID>12</OperationID><Object_ID>240</Object_ID><Name>copy</Name><Scope>Public</Scope><Type>EObject</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{E57518A9-9A91-4b0f-9311-F7AF3177F809}</ea_guid></Row><Row><OperationID>13</OperationID><Object_ID>240</Object_ID><Name>embedSDMInEAnnotation</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{44F4A863-86CB-4889-B179-3F4BA1F68D8D}</ea_guid></Row><Row><OperationID>18</OperationID><Object_ID>273</Object_ID><Name>configure</Name><Scope>Public</Scope><Type>EBoolean</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>0. Integrator creates GraphTriple and sets roots\r\n1. Adds the given graph triple to the translator\r\n2. Iterates over composite structure of input model and fills unprocessedNodes and unprocessedEdges (other collections are initially empty although this could be different in incremental mode)</Notes><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{B22FDBFE-C033-4ff5-81FB-2ED133A55F62}</ea_guid></Row><Row><OperationID>19</OperationID><Object_ID>273</Object_ID><Name>translate</Name><Scope>Public</Scope><Type>TranslationResult</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>136</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{2DFA0837-F09F-40f5-A4BD-CD3857D2D712}</ea_guid></Row><Row><OperationID>21</OperationID><Object_ID>165</Object_ID><Name>determineLNCC</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>Iterate through all rules of the given TGG and consider edges in the following way:\r\nforall edges e in rule r\r\n-&amp;gt; s(e) or t(e) are context elements\r\n-&amp;gt; e is set to create\r\n=&amp;gt; add quadruple containing the types of s(e), t(e), the name of e and the encoded equivalent if s, t or both are context elements.</Notes><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{0E021F1A-5CE7-4f68-B737-D2C11AA200ED}</ea_guid></Row><Row><OperationID>22</OperationID><Object_ID>273</Object_ID><Name>determineCandidateRulesForNode</Name><Scope>Public</Scope><Type>CandidateRules</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>1. Look up in table for operational rules that translate type(node).</Notes><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>352</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{7BE07512-219E-40f3-BB81-B1C5B5B15211}</ea_guid></Row><Row><OperationID>24</OperationID><Object_ID>135</Object_ID><Name>isAppropriate</Name><Scope>Public</Scope><Type>EOperation</Type><ReturnArray>0</ReturnArray><Concurrency>Sequential</Concurrency><Notes>1. check if core match exists in input graph starting from given entry node\r\n2. check if DEC is satisfied (call external method)\r\n3. process context on demand\r\n4. return the corresponding perform* EOperation or null if check failed.</Notes><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>183</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{EC74C95A-0D42-4b5d-98C6-0E3273664A8D}</ea_guid></Row><Row><OperationID>25</OperationID><Object_ID>273</Object_ID><Name>updateProcessedSets</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Notes>1. Determines the corresponding graph elements to the translated objects in the given ruleResult (also edges for translated references!!!)\r\n2. Adds these graph elements to the set of processed elements\r\n3. Be careful not to manipulate the set of unprocessed elements!</Notes><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>3</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{CE58DEC9-E683-4d49-8A92-986698AD7ABD}</ea_guid></Row><Row><OperationID>26</OperationID><Object_ID>165</Object_ID><Name>buildCandidateRulesLookupTable</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>1</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{BC2520AA-DB89-4280-ACE6-F6A8711EDC61}</ea_guid></Row><Row><OperationID>28</OperationID><Object_ID>273</Object_ID><Name>determineCandidateRulesForEdge</Name><Scope>Public</Scope><Type>CandidateRules</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>4</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>352</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{1070078F-FF2E-49ca-9432-2D50C026A0D6}</ea_guid></Row><Row><OperationID>29</OperationID><Object_ID>288</Object_ID><Name>eInvoke</Name><Scope>Public</Scope><Type>java.lang.Object</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{A1D00185-AE82-493e-AAAC-E916D2DD98D3}</ea_guid></Row><Row><OperationID>38</OperationID><Object_ID>240</Object_ID><Name>CREATE</Name><Scope>Public</Scope><Type>BindingOperator</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>4</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>115</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{42E99307-46D4-444b-886B-FBA399DF29F6}</ea_guid></Row><Row><OperationID>39</OperationID><Object_ID>240</Object_ID><Name>BACKWARD</Name><Scope>Public</Scope><Type>ApplicationTypes</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>5</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>272</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{D0F76449-7205-4f9c-A03D-C68F72A669C4}</ea_guid></Row><Row><OperationID>27</OperationID><Object_ID>165</Object_ID><Name>determineEntryNode</Name><Scope>Private</Scope><Type>TGGObjectVariable</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>128</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{12E442A3-491E-4dc2-9171-728084C3746F}</ea_guid></Row><Row><OperationID>30</OperationID><Object_ID>434</Object_ID><Name>invokeOperationWithSingleArg</Name><Scope>Public</Scope><Type>EObject</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>0</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>288</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{DDE51358-F82B-4100-A5D1-12154D533B41}</ea_guid></Row><Row><OperationID>31</OperationID><Object_ID>165</Object_ID><Name>deriveOperationalRules</Name><Scope>Public</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>3</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{30584C3D-773E-4256-BBE9-4FD226E45814}</ea_guid></Row><Row><OperationID>32</OperationID><Object_ID>165</Object_ID><Name>createOperationalRules</Name><Scope>Private</Scope><Type>void</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>4</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{ED7EF05C-D74B-4a0f-897D-DB7612AC5AEB}</ea_guid></Row><Row><OperationID>35</OperationID><Object_ID>240</Object_ID><Name>determineOperationSignature</Name><Scope>Public</Scope><Type>EString</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>2</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>0</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{999096A0-B224-4446-A8D5-CB581BA2DD20}</ea_guid></Row><Row><OperationID>36</OperationID><Object_ID>165</Object_ID><Name>createPerformOperation</Name><Scope>Private</Scope><Type>Activity</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>5</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>95</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{3414F021-9221-4be2-A133-28E6DAA25ADD}</ea_guid></Row><Row><OperationID>37</OperationID><Object_ID>240</Object_ID><Name>convertDirectionToAppropriateDomain</Name><Scope>Public</Scope><Type>DomainType</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>3</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>198</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{E83E8FA4-1802-4a2a-AF6B-81D5E4BAB83A}</ea_guid></Row><Row><OperationID>40</OperationID><Object_ID>240</Object_ID><Name>FORWARD</Name><Scope>Public</Scope><Type>ApplicationTypes</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>6</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>272</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{403AA3D8-A275-4763-BB64-8BDF6425EA18}</ea_guid></Row><Row><OperationID>42</OperationID><Object_ID>165</Object_ID><Name>createIsAppropriateOperation</Name><Scope>Public</Scope><Type>Activity</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>6</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>95</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{15A6B03B-DDE5-479d-A3DE-FA2A05970DE1}</ea_guid></Row><Row><OperationID>43</OperationID><Object_ID>240</Object_ID><Name>CHECK_ONLY</Name><Scope>Public</Scope><Type>BindingOperator</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>7</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>115</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{16268928-5197-4269-8A3D-5251DD8AA7A6}</ea_guid></Row><Row><OperationID>44</OperationID><Object_ID>240</Object_ID><Name>BOUND</Name><Scope>Public</Scope><Type>BindingState</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>8</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>113</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{5529869A-FE95-489e-BB61-BB1F46EBAB87}</ea_guid></Row><Row><OperationID>45</OperationID><Object_ID>240</Object_ID><Name>UNBOUND</Name><Scope>Public</Scope><Type>BindingState</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>9</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>113</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{A3CFAA93-BE84-4602-BAC7-AF42DE44F4AE}</ea_guid></Row><Row><OperationID>46</OperationID><Object_ID>240</Object_ID><Name>SUCCESS</Name><Scope>Public</Scope><Type>EdgeGuard</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>10</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>104</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{41D81F5E-E224-4171-A7B5-08BAD5D650E3}</ea_guid></Row><Row><OperationID>47</OperationID><Object_ID>240</Object_ID><Name>FAILURE</Name><Scope>Public</Scope><Type>EdgeGuard</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>11</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>104</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{8D2A6AF2-70C9-4d51-ADF2-CBD72BE0D8C1}</ea_guid></Row><Row><OperationID>48</OperationID><Object_ID>240</Object_ID><Name>MANDATORY</Name><Scope>Public</Scope><Type>BindingSemantics</Type><ReturnArray>0</ReturnArray><IsStatic>0</IsStatic><Concurrency>Sequential</Concurrency><Abstract>0</Abstract><Synchronized>0</Synchronized><Pos>12</Pos><Const>0</Const><Pure>FALSE</Pure><Classifier>114</Classifier><IsRoot>FALSE</IsRoot><IsLeaf>FALSE</IsLeaf><IsQuery>FALSE</IsQuery><ea_guid>{ADB4946B-AAA6-4ead-97DE-476DE4406DC1}</ea_guid></Row></Data></Dataset_0></EADATA>\r\n"; //s = File.ReadAllText("d:\\test.txt"); //s = "<string>" + s + "</string>"; List<String> returnVal = new List<string>(); string rowName="Row"; try { XElement x = XElement.Parse(xmlString); var rows=x.Descendants(rowName); foreach (var row in rows) { returnVal.Add(row.ToString().Replace("<" + rowName + ">", string.Empty).Replace("</" + rowName + ">", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("> <", string.Empty)); } } catch { } Hope This helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7621406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: select with $('#id ul li') & excluding .class I'm using the following code in a function. $('#id ul li').css('background-image','none'); Is it possible to add a unless statement so it excludes any li with the class .class ? A: Not an "unless" statement, but a :not() statement: $('#id ul li:not(.class)').css('background-image', 'none');
{ "language": "en", "url": "https://stackoverflow.com/questions/7621407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript object instantiation similar to php new $className(); I'm trying to do the equivalent to this but in JS. $className = 'MyClass'; $obj = new $className(); I've tried obvious things but with no luck, currently resorted to using eval as below :/ eval('var model = ' + modelName + '();'); Thanks! A: For global "classes", use: var classname = "Date"; var obj = new window[classname](); window is the global namespace. Variables and methods defined immediately within <script>, without a wrapper are automatically stored in the global namespace. For methods of other "namespaces", use: var classname = "round"; var obj = new Math[funcname](); // Illustrative purposes only, Math doesn't need `new` For private methods which aren't attached to a namespace, there's no solution except for eval or Function: var classname = "nonglobal"; var obj = new (Function(classname))(); You should avoid eval whenever possible, especially if you're working with unknown strings. A: See this SO question for a good anwser: Dynamic Object Creation But basically you want return new window[modelName];
{ "language": "en", "url": "https://stackoverflow.com/questions/7621410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how are google hangout apps served Can someone explain how google hangout apps are served? It seems to me that google downloads the manifest.xml from a public url you specify, then reserves the html in the content tag. How does google prevent the javascript in that content from manipulating the clients cookies for the google hangouts domain? A: The hangout app is served in an iframe with a different domain than the container page. The only way you can effectively communicate with the container page is through the Hangouts API, which uses some special cross-browser tricks to cross the domain barrier. Specifically, the Hangouts API uses Google Gadgets RPC to communicate with the parent page on the Google Hangouts domain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generate a hyperlink for each id I have an HTML page with tens of elements with an id attribute. I want to have an on page navigation in the sidebar. How can I get a bookmark link for each id ? like for each id="N" I need <a href="#N">M</a> but not next to it, all in one separate place. Edit: Even better (assuming I only have inline type of elements, headings in my case): for each <x id="N">M</x> I need <a href="#N">M</a> Edit2: Maybe you have a PHP or JS snippet or a Coda clip ? or a standalone tool. I cannot run Python, Perl, CGI etc <h4 id="Units">Units</h4> <h5 id="Direct Fire Units">Direct Fire Units</h5> These units carry light, bullet based weapons and automatically fire at enemy units in their FoF. They do not harm friendly Units. Shotgun Machine GunSniper Rifle P.S. I'll do the <ul> and <li> myself A: In plain JavaScript (and this took longer than I care to admit...sigh): var navList = document.createElement('ol'); var headers = document.getElementsByTagName('h2'); document.body.insertBefore(navList,headers[0]); for (i=0;i<headers.length;i++){ newLi = document.createElement('li'); newA = document.createElement('a'); newA.href = '#' + headers[i].id; newA.innerHTML = headers[i].innerHTML; newLi.appendChild(newA); navList.appendChild(newLi); } JS Fiddle demo. A: How about something similar. Since your question is not very clear, i would suggest that you edit the example i made and show us what you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTMLUnit and Android: JAXP incompability Trying to connect to "www.google.com" throw a simple HTMLUnit The WebClient class initialization of HTMLUnit failed on incompatibility with android jaxp impl: final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3); HtmlPage page1 = null; try { page1 = webClient.getPage("http://www.google.com/"); } catch (FailingHttpStatusCodeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block .... 09-30 23:05:57.867: ERROR/AndroidRuntime(289): FATAL EXCEPTION: main 09-30 23:05:57.867: ERROR/AndroidRuntime(289): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mygo/com.mygo.HTMLUnitActivity}: java.lang.IllegalStateException: Method 'jsxGet_encoding' was not found for encoding property in com.gargoylesoftware.htmlunit.javascript.host.css.CSSCharsetRule 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.os.Handler.dispatchMessage(Handler.java:99) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.os.Looper.loop(Looper.java:123) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at java.lang.reflect.Method.invokeNative(Native Method) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at java.lang.reflect.Method.invoke(Method.java:521) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at dalvik.system.NativeStart.main(Native Method) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): Caused by: java.lang.IllegalStateException: Method 'jsxGet_encoding' was not found for encoding property in com.gargoylesoftware.htmlunit.javascript.host.css.CSSCharsetRule 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.javascript.configuration.ClassConfiguration.addProperty(ClassConfiguration.java:109) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.parsePropertyElement(JavaScriptConfiguration.java:437) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.parseClassElement(JavaScriptConfiguration.java:384) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.buildUsageMap(JavaScriptConfiguration.java:312) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.(JavaScriptConfiguration.java:147) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.getInstance(JavaScriptConfiguration.java:237) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.(JavaScriptEngine.java:117) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.WebClient.init(WebClient.java:215) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.gargoylesoftware.htmlunit.WebClient.(WebClient.java:189) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at com.mygo.HTMLUnitActivity.onCreate(HTMLUnitActivity.java:22) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-30 23:05:57.867: ERROR/AndroidRuntime(289): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) * *Should I downgrade htmlunit ? (I'm using 2.9). *Any other solution to use htmlunit on Android SDK? Any help will be appreciated. A: I solved by downgrading to htmlunit 2.8
{ "language": "en", "url": "https://stackoverflow.com/questions/7621422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unique job with NSOperationQueue On an iPhone project I have an NSOperationQueue, which handles communication to a server, on my appDelegate object and an upload job as following: @interface UploadOperation : NSOperation - (id)initWithItem:(NSDictionary*)anItem; @end I'm pushing items, with the user's request, to the NSOperationQueue which fire the upload. Everything works great, but I want to prevent the same upload operation to occur more then 1 time. In other words, if the upload was not finish, don't push the same item to the upload queue. Is it possible with NSOperationQueue methods or I'll have to manage it by my own with an "items currently on queue" array? A: First ensure your NSOperation subclass' hash and isEqual: are implemented such that two instances trying to upload the same content are considered equal. Then before adding a new operation, check first to see if there is already an identical operation in the queue by calling containsObject: on the array returned by calling operations on NSOperationQueue. A: You could subclass NSOperationQueue and override the addOperation: method to check and make sure this new operation is one you haven't seen recently (or one that is currently enqueued). You could maintain your own list of recent operations, or use the operation queue's -operations method to return the currently enqueued operations. Then just use your custom operation queue subclass instead. A: It's actually been done for you: https://github.com/mronge/CTUniqueOperationQueue A: You are correct, you need to manage it by using your own array of items that are currently on the queue: NSArray *allQueueItems = ....; NSMutableArray *queueItems = [NSMutableArray array]; for (NSOperation *item in allQueueItems) { [self.operationQueue addOperation:item]; [queueItems addObject:item]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Uploadify with big files (2GB+) I'm using Uploadify to create a file uploader to Amazon S3. I need it to work on files up to 2GB, and show an error if the file is bigger than that. I don't have a finer file granulation, but for a 3.5GB file it works correctly (i.e. shows the error), and for a 10GB file it doesn't even want to select it or trigger any event. (The file open dialog .closes and nothing happens, as if the user didn't select the file in the first place). Is there a bug in the Uploadify code and if it is, how can I make it work?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MYSQL - select max score of each player for each day assuming we have a table like below name | userid | score | datestamp | ----------------------------------------------------- john | 1 | 44 | 2011-06-10 14:25:55 mary | 2 | 59 | 2011-06-10 09:25:51 john | 1 | 38 | 2011-06-10 21:25:15 elvis | 3 | 19 | 2011-06-10 07:25:18 ... marco | 4 | 100 | 2011-03-10 07:25:18 i want to display the high-score of each user in each single day. so for eaxmple if the player john have played ten rounds in the 2001-06-10 i want to display the the best score of that day, and so on for the others players. thank you very much for the time. A: SELECT name, MAX(score) AS hiscore, DATE(datestamp) AS sdate FROM scores GROUP BY userid, sdate ORDER BY sdate DESC But also notice that your table is not even in the first normal form because it lacks an unique key. Also after fixing that, name of players will be repeated, and it will have to be extracted in a separate table for the second normal form. A normalised design will have two tables: player(userid, name) scores(scoreid, userid, score, datestamp) A: Not tested, but what about? select userid, max(score), date(datestamp) from table group by userid, date(datestamp)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to handle list of undefined length with gettext? I'd like to translate strings of the following format: Delete files toto, tata and titi. First idea was to use Delete files %s but then I thought about plural forms. What if some language doesn't put 'and' at the end but, for example, two different words for the last item and the one before it. So here are two questions: * *Do you know a language like that? *Do you know a better way to handle this case? A: This is more complicated. Actually it seems that you need only to choose between singular and plural form (although languages could have multiple plural forms). So basically Do you want to delete this file: %s? or Do you want to delete these files: %s?. I cannot say for all languages but this would be OK in Polish. However, if you want to put quantity (which is rather good idea), you would end up with multiple plural forms: Do you want to delete this file: %s (Czy chcesz usunąć ten plik: {0}? when translated) or Do you want to translate these %n files: %s translated either as Czy chcesz usunąć te %n pliki: %s? or Czy chcesz usunąć tych %n plików: %s?. As for lists, CLDR charts might be a good source of information on how to handle them - look for listPattern. Below I am presenting a fragment from Polish charts: {0} and {1} are placeholders, the list you provided would look like: toto; tata i titi. I am still not totally sure this is what it should like (in Polish I am more inclined to toto, tata i titi) but in theory you could use this information to create a list. In another answer I claimed that it is actually impossible to create such lists in general case (regardless of the language) and people tend to use list view controls for selection or present data as vertical list to avoid problems. Your example would need to be modified to: These file(s) would be deleted: toto tata titi Are you sure? This might be problematic (it might not fit in the screen) but this is what people often do to avoid issues with lists in foreign languages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to have www.site.com and site.com with Orchard Multi-Tenancy module I have successfully set up multi-tenancy in Orchard on a public facing site. If you enter www.tenant.com it works fine in Orchard. However, Orchard's admin for Tenants only allows input for one site. In the instance where a user just types tenant.com, when I tried binding that in landlord site it takes me to the landlord page, not the tenant. Adding a new "tenant" in Orchard Tenants admin will literally create a new site (at least, i get to the setup recipe page) and not take that alternative to the actual tenant site. Any thoughts? A: Sorry to bump a really old question but I am bored and am reading through some Orchard source code and I see this: _shellsByHost = qualified .SelectMany(s => s.RequestUrlHost == null || s.RequestUrlHost.IndexOf(',') == -1 ? new[] {s} : s.RequestUrlHost.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries) .Select(h => new ShellSettings(s) {RequestUrlHost = h})) .GroupBy(s => s.RequestUrlHost ?? string.Empty) .OrderByDescending(g => g.Key.Length); I don't actually have any multi-tenant sites to test this on and am too lazy to set one up but well, looks to me like you can just do "www.test.com, test.com". Maybe someone can clarify this but I think this would be the simplest solution for anyone else encountering this problem. All the best A: That's a good question. What I would do is put a permanent redirect from one of the domains to the one you prefer to be canonical. From an SEO perspective, that's what you should do anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: T-SQL. How create list as comma-separated string in one SELECT? MS SQL 2005. T-SQL. I find many good solutions how split string. But how combine result from inner SELECT as string (for example, with comma-separator)? Code: SELECT b.date, (SELECT o.number FROM order o WHERE o.number = m.number ) AS orderList FROM bank b, movemoney m WHERE b.code = m.code The table 'movemoney' consist of zero or few orders from the table 'order'. How create 'orderList' as string in one SELECT statement? A: You can also put the XML PATH into a subquery in the SELECT if you want. I just prefer this construct: SELECT b.date, SUBSTRING(CAST(foo.bar AS varchar(8000)), 2, 7999) AS orderList FROM bank b JOIN movemoney m ON b.code = m.code OUTER APPLY ( SELECT ',' + concatenatedid FROM order o WHERE o.number = m.number FOR XML PATH ('') ) foo(bar)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating Two Windows Causes Second Created to Bum Out I'm trying to use a hotkey to change a layered window from being transparent to allowing mouse messages to come through. In my main function I call // make hotkey with WM_HOTKEY messages sent to hwnd's window procedure, id 1, // no other keys to work, F5 as hotkey // while checking for errors and it completes successfully. I also do the same // (id of 2) for VK_F7 and it completes successfully. RegisterHotKey (hwnd, 1, 0, VK_F5); RegisterHotKey (hwnd, 2, 0, VK_F7); In my window procedure, I have case WM_HOTKEY: MessageBox (hwnd, "Got here", "Attention", MB_OK); // Other stuff I need to do here I tried adding MOD_CONTROL, but to no avail. This did actually work before. The only difference now is that I realized that two windows would solve the problems I've been having. Last time I only had one, and now I have two window procedures in my application. I made sure it's all going to the right one and everything, but I shouldn'e be limited to just 1 window... The window itself displays, as I set the transparency to 100/255 so it screens the view a bit, and I can see that screen. Changing the key itself does nothing, and the WM_HOTKEY messages are being posted to the queue. I'm going to try manually sending them to the window. edit: ^ with SendMessage() isn't working, going to see if it's getting any messages, and same with the other window while I'm at it. edit: okay I feel like an idiot for saying this, but I had RegisterHotKey going to a null hwnd since I didn't actually create that window yet (I created the one not getting hotkey message first and originally had these right after that). The problem is that even though I can see this window, and if I comment it all out the view is different (no screen), it isn't receiving any messages. edit: I changed the title to something more suitable with this extra info. If this is a generic thing anyone's experienced, I'd be glad to hear. For now, I'm assuming it's my wrapper and creating them manually. major edit: I just tried using raw API instead of my wrapper and it had an error registering the second. I changed the class name and now the classes register and the windows get created. The message box that comes up for hotkeys shows too. I think I forgot to put the showwindow for them though, I'll say how that works in a second (edit: after I restart my computer yet again!!!). Before you ask, I didn't spend too long on my wrapper yet, and yes, it has error checking, but uses a similar system to set/get lasterror() and I didn't check the return values on them since the second one seemed to be created before. A: The problem was that both windows had the same class name. This does confuse me a bit, as I thought they were allowed to, and I shall be adding a static instance counting member to my wrapper then. The final result is that every problem in this area is now fixed :D EDIT: I just had to add this after learning it, but I came upon the knowledge that you can create two windows with the same class name, but they must use the same window procedure. Learning this actually strengthened my understanding of this topic a lot, so if I clear this up for even one other person I'll be happy. /EDIT Just in case you're wondering what the purpose of this was, I'm including a little shot of it. It's hopefully going to turn into something that you can "skin" your screen with. It does stay on top and follow you around now so most of it is done. As you can see, not the nicest computer to work with The console window will be hidden later when I add a way to exit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: event binding in MVVM my code in ViewModel : public void Insert_Click(object sender, RoutedEventArgs e) { System.Windows.MessageBox.Show("Insert_Click"); } code in View : <Button Click="{Binding Insert_Click}" Background="Black" Height="56" Name="btnAdd" Width="57"> </Button> error : Error 1 Click="{Binding Insert_Click}" is not valid. '{Binding Insert_Click}' is not a valid event handler method name. Only instance methods on the generated or code-behind class are valid Please show me the correct code A: The event hook ups will only work for code behind to the control/window if you remove the Binding syntax from the event handler. For MVVM it is a bit different. You can get that to work if you move the handler to the code behind but I suspect you want to use MVVM. Here what you really need is to use the Command pattern <Button Command="{Binding Insert}" Background="Black" Height="56" Name="btnAdd" Width="57"/> and view model public ViewModel() { Insert = new RelayCommand(Insert_Click); } public ICommand Insert { get; private set; } private void Insert_Click() { System.Windows.MessageBox.Show("Insert_Click"); } This is using a framework such as MVVM light
{ "language": "en", "url": "https://stackoverflow.com/questions/7621437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to this with a DataGrid in WPF I have a datagrid in which I need to implement two features and I'm a bit blocked on how to implement them. First, I want to add a row at the end of the grid with the totals of the other rows and I want this row to be fixed so it does not get sorted when the others are. Second, it's a grid with a lot of columns but they can be grouped into different aspects of the data, so I would like to expand and compress some groups of columns to allow the grid to be viewed on the screen. I would like to do something like putting an expander on a set of columns. Any help would be great. Thanks for your time! A: For the first point you need to work with the footer row, putting totals or summaries in the footer row will allow you to always see it with no sort or scroll issue. For the second point, if I got it right, being able to hide a bunch of columns and show them again does not sound trivial or easy without quite some code. Personally whenever a grid needs certain amount of customization I'd like go for commercial grids like DevExpress or Telerik, in any .NET platform like WPF, WinForms ASP.NET or SliverLight those controls pay off very well and very soon considering the rich feature set and possibilities without your precious time spent on grids but actually keeping your focus on the real business. see online demos from DevExpress or Telerik for their cool WPF grids.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to ask the user for an output file in python I have to ask the user for an output file and then append data to it but whenever I try it tells me that the data has no append attribute. I think this is because when I try to open the file it is seeing it as a string and not an actual file to append data too. I have tried multiple ways of doing this but right now I am left with this: Output_File = str(raw_input("Where would you like to save this data? ")) fileObject = open(Output_File, "a") fileObject.append(Output, '\n') fileObject.close() The output that I am trying to append to it is just a list I earlier defined. Any help would be greatly appreciated. A: Your error is at this line: fileObject.append(Output, '\n') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'file' object has no attribute 'append' Use the write method of a file object: fileObject.write(Output+'\n') A: File objects have no append method. You're looking for write. Also, str(raw_input(...)) is redundant, raw_input already returns a string. A: The error message is pretty self-explanatory. This is because file objects don't have append method. You should simply use write: fileObject.write(str(Output) + '\n') A: def main(): Output = [1,2,4,4] Output_File = input("Where would you like to save this data?") fileObject = open(Output_File, 'a') fileObject.write(str(Output)+'\n') fileObject.close() if __name__ == '__main__': main() just use the .write method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling NSRunLoop methods in applicationDidBecomeActive causes system to not respond When my iOS app is activated, on clicking a file the app supports (FTA), I want to display a modal view in applicationDidBecomeActive. Since I want the control back, when the modal view is dismissed, I use NSRunLoop and a flag to detect the view is dismissed. Please see the attached code. When the [NSRunloop runUntilDate] is invoked, my view is displayed but behind the current view and does not respond to keyboard/mouse actions. Any ideas what is happening. [CODE] - (void) applicationDidBecomeActive:(UIApplication *)application { //App activated due to file selection in an email attachment, display modal dialog if (fileSelected) { RSAImportViewController *s = [[RSAImportViewController alloc] initWithNibName:@"RSAImportViewController_iPad" bundle:nil]; UINavigationController* rNC = [[UINavigationController alloc] initWithRootViewController:s]; [rNC setModalPresentationStyle:UIModalPresentationFormSheet]; [rNC setModalTransitionStyle:UIModalTransitionStyleCoverVertical]; [nav presentModalViewController:rNC animated:YES]; // wait for modal view to be dismissed, the modal view is dismissed when ok/cancel // buttons are clicked. while (s.completion == requestRunning) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]; } [s dismissKeyboard]; // Do further processing return; } A: That's not what NSRunLoop methods are for. You should instead set yourself as the delegate of your modal view and make the modal view inform its delegate when it is dismissed — and call any other method as appropriate to do anything you want to do. In RSAImportViewController.h: @class RSAImportViewController @protocol RSAImportViewControllerDelegate -(void)rsaImportViewControllerDone:(RSAImportViewController*)vc; @end @interface RSAImportViewController ... @property(assign) id<RSAImportViewControllerDelegate> delegate; @end In RSAImportViewController.m, whereever you call the dismissModalViewControllerAnimated: method: @implementation RSAImportViewController @synthesize delegate; ... -(void)someMethodInYourCode { ... [self dismissModalViewControllerAnimated:YES]; // call the delegate method to inform we are done (adapt to your needs) [self.delegate rsaImportViewControllerDone:self]; } ... @end And in the AppDelegate: - (void) applicationDidBecomeActive:(UIApplication *)application { { if (fileSelected) { ... rNC.delegate = self; // set 'self' to be informed when the rNC is dismissed [nav presentModalViewController:rNC animated:YES]; } else { [self doFurtherProcessing]; } } -(void)rsaImportViewControllerDone:(RSAImportViewController*)vc { [self doFurtherProcessing]; } -(void)doFurtherProcessing { [s dismissKeyboard]; // and all your other stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook app with ssl certificate Two weeks ago i bought a SSL Certificate for my domain. I have an app in Facebook and for Safari works fine but in Chrome the following message appears: "Error 501 (net::ERR_INSECURE_RESPONSE): Error desconocido." I have set the "Secure Canvas URL" in the configuration of the app in Facebook. What's the problem? I have just checked it out in Internet Explorer and Firefox and works fine. In both browsers enter the game directly. With respect the Certificate and app settings, the certificate is valid for www and the domain, and in app setting i just typed the domain name. Well, the function from Facebook that arise the problem is: FB.Canvas.setAutoResize(); I hope this could be helpful. A: It is a known problem that Chrome handles this less elegant: http://code.google.com/p/chromium/issues/detail?id=87957 But that does not take away the fact that it should work with a valid certificate. Can you checn with a few other browsers, like IE and Firefox? Please get back when those give any indication of the underlying problem. A: This problem happens to me for my app, but only on Chrome on Ubuntu (Chrome on Windows 7 is fine, and Firefox [version 13 at the moment] on Ubuntu is fine), and it only happens when secure browsing is forced on in Facebook (Account settings > Security > Secure browsing). By unchecking Browse Facebook on a secure connection (https) when possible, I no longer receive this problem. Please downvote this answer (a lot, hahaha), because telling users to use a different operating system or to turn off secure browsing is not going to be received well! I'll report back if I come up with a real solution. A: What's the problem? Your SSL cert is invalid or not configured properly. This can happen for example when you use your domain with www in app settings, while the cert is ussued on a domain without www, etc. It can be something else misconfigured also. A: I know it´s an old Thread but I just got a similar problem when facing some Free Hosts that uses shared SSL cert instead of Custom Domain Certs. On setting up your Canvas App, on "Secure Canvas URL", use the URL provided by the HOST instead of your custom URL. Ex: If your host is openshift, they give an URL similar to -> php-blablabla.rhcloud.com. Use this one instead of blablabla.com (which would be the domain you paid for). Hope this helps someone. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why synchronous RPC is bad While reading about Google webtool kit, came across a statement saying 'synchronous RPCs are bad'. Any reason why they are? One good reason i could think of is the response to end user may be impacted by any lag in the remote server or due to networking issues. Can anyone tell what the exact reasons are? Thank you all in advance. A: I guess GWT is talking about synchronous RPC from the javascript code running in the browser to the server. And it's indeed bad, because JavaScript is single-threaded, and doing a lengthy synchronous RPC call from the JavaScript thread makes the browser page not responsive: the GUI is frozen until the RPC call ends. That's why AJAX is asynchronous by default: it allows making asynchronous requests to the server, which lets the browser in a responsive state. When the response comes back, a callback method is called to handle the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I rename duplicates in MySQL using PHP or just a MySQL trying to rename duplicates in MySQL database so far using that code but this only adding 1 at the end of name. So if I have UPDATE phpfox_photo n JOIN (SELECT title_url, MIN(photo_id) min_id FROM phpfox_photo GROUP BY title_url HAVING COUNT(*) > 1) d ON n.title_url = d.title_url AND n.photo_id <> d.min_id SET n.title_url = CONCAT(n.title_url, '1'); Anna Anna Anna Result is Anna Anna1 Anna11 When I got 200 Annas result is Anna1111111111111111111111111111111111111111111....etc how do I do it to rename in the following inc Anna Anna1 Anna2 A: if i didn't miss something you can make a stored procedure that iterates throw your rows using cursors to do that as following: DECLARE counter INT DEFAULT 0; DECLARE num_rows INT DEFAULT 0; DECLARE offset INT; DECLARE title_urlvalue VARCHAR(50); DECLARE no_more_rows BOOLEAN; DECLARE ucur CURSOR FOR SELECT UPDATE phpfox_photo n JOIN (SELECT title_url, MIN(photo_id) min_id FROM phpfox_photo GROUP BY title_url HAVING COUNT(*) > 1) d ON n.title_url = d.title_url AND n.photo_id <> d.min_id; SET offset = 1; SET no_more_rows = TRUE; select FOUND_ROWS() into num_rows; OPEN ucur; uloop: LOOP FETCH ucur if counter >= num_rows then no_more_rows = False; endif INTO title_urlvalue; IF no_more_rows THEN CLOSE ucur; LEAVE uloop; END IF; update title_urlvalue = Concat(title_urlvalue,offset); SET offset = offset + 1; SET counter = counter + 1; END LOOP uloop; close ucur; A: With User-Defined Variables SET @counter:=0; SET @title_url:=''; UPDATE phpfox_photo n JOIN (SELECT title_url, MIN(photo_id) min_id FROM phpfox_photo GROUP BY title_url HAVING COUNT(*) > 1) d ON n.title_url = d.title_url AND n.photo_id <> d.min_id SET n.title_url = IF(n.title_url <> @title_url, CONCAT(@title_url:=n.title_url, @counter:=1), CONCAT(n.title_url, @counter:=@counter+1)); A: Maybe you can use modulo to produce numbering, like this (SQLite example, but should be similar in mysql): SELECT *, (rowid % (SELECT COUNT(*) FROM table as t WHERE t.name = table.name ) ) FROM table ORDER BY name All you need is to translate rowid and modulo function, both availible in mysql. Then you can CONCAT results as you desire. A: UPDATE phpfox_photo n JOIN (SELECT title_url, MIN(photo_id) min_id FROM phpfox_photo GROUP BY title_url HAVING COUNT(*) > 1 ) d ON n.title_url = d.title_url AND n.photo_id <> d.min_id SET n.title_url = CASE WHEN <last char is int> THEN <replace last char with incremented last char> ELSE <string + 1> END
{ "language": "en", "url": "https://stackoverflow.com/questions/7621460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dllregisterserver in iviewers failed When I try to run Oleview I get an error saying that DllRegisterServer failed for IViewer.dll (sorry I wanted to post a screenshot but I can't until I get 10 reputation =p) Oleview will run but like the msg says, you can't look at interfaces which is exactly what I want to do. I found my iviewer.dll and ran regsvr32 on it just fine. So I'm not sure whats up. A: You only need to run it the first time as admin. Make sure you open a tlb file though, so it registers IVIEWERS.DLL as COM server into the registry. After that you can run it as a normal user. This is explained in the Windows SDK readme, by the way. A: Ack, should have done more due diligence. Found this on msdn which explains that you need to run Oleview as admin. Stupid UAC. I tried it out and running as admin works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "65" }
Q: Java Blackberry sending custom made packet i need to recreate this within Java for Blackberry device: char cPacketData[1024]; int thisPacketLength=( X_PACKET_SPACE*12 ) + ( 20*X_PACKET_SPACE ); (*(int *) (cPacketData)) =X_PACKET_START; (*(int *) (cPacketData+X_PACKET_SPACE)) =thisPacketLength; (*(int *) (cPacketData+X_PACKET_SPACE*2)) =X_PACKET_POSITION_DATA; (*(int *) (cPacketData+X_PACKET_SPACE*3)) =positionX; (*(int *) (cPacketData+X_PACKET_SPACE*4)) =positionY; send(mSocket,(const char *)&cPacketData,thisPacketLength,0); I already know that i should use OutputStreamWriter but i don't know how to recreate that packet in Java, can you please help? UPDATE Ok, think i've got it right: char[] payload = new char[100]; int start=9999; payload[3] = (char)((start >> 24) & 0XFF); payload[2] = (char)((start >> 16) & 0XFF); payload[1] = (char)((start >> 8) & 0XFF); payload[0] = (char)((start >> 0) & 0XFF); int len=100; payload[X_PACKET_SPACE+3] = (char)((len >> 24) & 0XFF); payload[X_PACKET_SPACE+2] = (char)((len >> 16) & 0XFF); payload[X_PACKET_SPACE+1] = (char)((len >> 8) & 0XFF); payload[X_PACKET_SPACE] = (char)((len >> 0) & 0XFF); _out.write(payload); Seems to work fine, kinda 'oldsKewl' way of doing - so i would appreciate if you guys have any better option. Just to confirm, it works by doing it this way. A: Resolved Here is how i do it, so that my server side can recv the packets from BB correctly. OutputStream _out = conn.openOutputStream(); packet[3]= (byte)(9999 >>> 24); packet[2]= (byte)(9999 >>> 16); packet[1]= (byte)(9999 >>> 8); packet[0]= (byte)(9999 >>> 0); packet[8]= (byte)(60 >>> 24); packet[7]= (byte)(60 >>> 16); packet[6]= (byte)(60 >>> 8); packet[5]= (byte)(60 >>> 0); packet[13]= (byte)(4 >>> 24); packet[12]= (byte)(4 >>> 16); packet[11]= (byte)(4 >>> 8); packet[10]= (byte)(4 >>> 0); packet[18]= (byte)(_PIN >>> 24); packet[17]= (byte)(_PIN >>> 16); packet[16]= (byte)(_PIN >>> 8); packet[15]= (byte)(_PIN >>> 0); packet[23]= (byte)(1 >>> 24); packet[22]= (byte)(1 >>> 16); packet[21]= (byte)(1 >>> 8); packet[20]= (byte)(1 >>> 0); _out.write(packet,0,60);
{ "language": "en", "url": "https://stackoverflow.com/questions/7621462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I get the span text with incremental id using jQuery? I'm sorry guys I've changed my code to this: <table border="1"> <?php $a = array('apple','banana','grapes','pineapple'); for ($x=0;$x<=3;$x++) { ?> <tr> <td><div class='fruit' ><?php echo $a[$x]; ?></div></td> <td><a href='#' class='viewbutton'>View</a></td> </tr> <?php } ?> </table> Now my problem is how can I get the text inside the <div>? I've tried $(".viewbutton").click(function() { alert ( $('#div_debit').text() ); }); This will return only the first value. How can I get the succeeding values in the array? is it using id? A: As far as I know, there's no CSS or jQuery-specific selector to match for all numeric values (like [0-9] or \d in regexes); correct me, if I'm wrong! But: as you give each <span> the class "fruit", you can just access them with span.fruit. This will return an array, which you can iterate over with each(). this will be set to the current item within that function, so you can check for the desired ID. $('.fruit').each(function(){ // this.id will be your numeric ID of the current item }); Also, if your elements are numbered continuously (e.g. 1, 2, 3, and not 2, 1, 3), you can use the :nth-child-pseudo-selector to access one of the <span>s. If all of this doesn't work for you; e.g. if you need to use the class .fruit somewhere else too, the last option I could think of is that you iterate manually over the elements in JavaScript. for( var x = 0; x <= 3; x++ ) { var e = $('#'+x); // Do something with the element; or add it to an array of all the elements } Edit: If you don't know how many items there will be in the page, but you want to match for every numeric ID, you can use the following. $('*').each(function(){ if( this.id.match(/\d+/) ) { // do something with an element which has a numeric ID } }); of course, its preferrable to use the above example, if you know how many items there will be, because it's probably faster. A: You are, probably, make it wrong. Don't use id as a number like this, prefer put at least a prefix on it. You can use $('span.fruit#1').text() to get the first text span. If you don't put a id, you can use $('span.fruit:nth-child(1)').text().
{ "language": "en", "url": "https://stackoverflow.com/questions/7621463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot convert a row to a DataTable in C# I'm trying to convert a DataRow to a DataTable, but I'm getting errors. I searched and tried all possible solutions, but none worked! I have a method which accepts a DataTable as its parameter (this DataTable has one row exactly). That method will return some information. At first, I tried to convert the DataRow to a DataTable using ImportRow(newtable.ImportRow(row)), but newtable is empty afterward. Then, I tried dt.clone(), but this fills the newtable with just everything, which is not what I was after! Actually the exact thing I was after. private static void BatchFrontSidePrinting(Student St, frmBaseCard frm) { DBINFOPACK UserInfo; DBCARDINFO CardInfo; DataTable newtable = new DataTable("newtable"); foreach (DataRow row in dt.Rows) { try { // here, I'm trying to send one DataRow as a DataTable to the GetInfo() method, // and for the next iteratio , after getting the info I'm removing the row which was just added, // so that for the next iteration, newdatatable is empty. All of the proceeding actions fail !:( newtable.ImportRow(row); // doesn't work! UserInfo = GetInfo(newtable); newtable.Rows.Remove(row); // doesn't work! St = UserInfo.STUDENT; ((frmFrontSideCard)frm).Replica = UserInfo.CARDINFO.Replica; if (UserInfo.CARDINFO.Replica) { Loger.Items.Add("Replication !"); } // print ((frmFrontSideCard)frm).Print = St; // update CardInfo = UserInfo.CARDINFO; CardInfo.SID = UserInfo.STUDENT.ID; CardInfo.BIMAGE = UserInfo.BIMAGE; SetInfo(CardInfo); } catch (Exception exep) { Loger.Items.Add(String.Format("Inside [BatchFrontSidePrinting()] : Student {0} {1}:", St.ID, exep.Message)); } } } A: foreach (DataRow row in dt.Rows) { try { DataTable newtable = new DataTable(); newtable = dt.Clone(); // Use Clone method to copy the table structure (Schema). newtable.ImportRow(row); // Use the ImportRow method to copy from dt table to its clone. UserInfo = GetInfo(newtable); catch (Exception exep) { // } } A: var someRow = newTable.NewRow(); someRow[0] = row[0]; // etc newTable.Rows.Add(someRow); A: It looks like you are using newtable as a temporary container to send each row in dt to the GetInfo method. If so, why not change the GetInfo method to take a DataRow rather than a DataTable that contains a single DataRow? Then you can get rid of newtable and not bother with creating and copying DataRows in the first place. private static void BatchFrontSidePrinting(Student St, frmBaseCard frm) { DBINFOPACK UserInfo ; DBCARDINFO CardInfo; foreach (DataRow row in dt.Rows) { try { // just pass the row UserInfo = GetInfo(row); // rest of the code as before St = UserInfo.STUDENT; ((frmFrontSideCard)frm).Replica = UserInfo.CARDINFO.Replica; if (UserInfo.CARDINFO.Replica) { Loger.Items.Add("Replication !"); } //print ((frmFrontSideCard)frm).Print = St; //update CardInfo = UserInfo.CARDINFO; CardInfo.SID = UserInfo.STUDENT.ID; CardInfo.BIMAGE = UserInfo.BIMAGE; SetInfo(CardInfo); } catch (Exception exep) { Loger.Items.Add(String.Format("Inside [BatchFrontSidePrinting()] : Student {0} {1}:", St.ID, exep.Message)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where should I put the code? I have the models User and StoredItem: class UserData < ActiveRecord::Base has_many :stored_items, :dependent => :destroy end class StoredItem < ActiveRecord::Base belongs_to :user named_scope :lookup, lambda { |id| { :conditions => ['qid = ?', id]}} end I need to have two methods to add and remove the items to StoredItem for current user. I put this code to User model: class UserData < ActiveRecord::Base has_many :stored_items, :dependent => :destroy def save_item(params) if(!self.stored_items.lookup(params[:qid]).exists?) item = self.stored_items.new(:sid => params[:qid], :name => params[:qti], :url => params[:qur], :group_id => params[:title], :rating => Integer(params[:rating])) item.save end end def remove_item(qid) item = self.stored_items.lookup(qid).first() item.destroy end end So here is the StoredItem controller: def save_item @user = UserData.find_by_login(session[:cuser]) @user.save_item(params) # ... end Is it good architectural decision or it will be better to put this code to StoredItem model and pass the current user into it? A: This is a good architectural decision. You need to keep it in the user since the User is the owner of the StoredItem. The user is responsible for its stored items, not the other way around.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to load PyGTK documentation in Eclipse PyDev Plugin in auto-completion? In Eclipse PyDev plugin, all document of default library of python will be load, but document of pygtk doesn't load in Eclipse. Any way to load them to eclipse? A: I don't know if it's your situation, but perhaps you should include pygtk at the forced builtins section of your interpreter properties. Go to the manual and check for the forced builtins section. Look at this page too. A: Make sure that your PYTHONPATH includes pygtk.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java - Saving StringTokenizer into arrays for further processing in other methods I've been coding Perl and Python a lot and this time I got an assignment to code in Java instead. So I'm not too familiar with handling data in Java. My task involves having a input file where I need to check dependencies and then output those with transitive dependencies. Clearer ideas below: Input File: A: B C B: C E C: G D: A Output File: A: B C E G B: C E G C: G D: A B C E G So far this is what I've got (separating the first and second token): import java.util.StringTokenizer; import java.io.*; public class TestDependency { public static void main(String[] args) { try{ FileInputStream fstream = new FileInputStream("input-file"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; while ((strLine = br.readLine()) != null) { StringTokenizer items = new StringTokenizer(strLine, ":"); System.out.println("I: " + items.nextToken().trim()); StringTokenizer depn = new StringTokenizer(items.nextToken().trim(), " "); while(depn.hasMoreTokens()) { System.out.println( "D: " + depn.nextToken().trim() ); } } } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } } Any help appreciated. I can imagine Perl or Python to handle this easily. Just need to implement it in Java. A: This is not very efficient memory-wise and requires good input but should run fine. public class NodeParser { // Map holding references to nodes private Map<String, List<String>> nodeReferenceMap; /** * Parse file and create key/node array pairs * @param inputFile * @return * @throws IOException */ public Map<String, List<String>> parseNodes(String inputFile) throws IOException { // Reset list if reusing same object nodeReferenceMap = new HashMap<String, List<String>>(); // Read file FileInputStream fstream = new FileInputStream(inputFile); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; // Parse nodes into reference mapping while((strLine = br.readLine()) != null) { // Split key from nodes String[] tokens = strLine.split(":"); String key = tokens[0].trim(); String[] nodes = tokens[1].trim().split(" "); // Set nodes as an array list for key nodeReferenceMap.put(key, Arrays.asList(nodes)); } // Recursively build node mapping Map<String, Set<String>> parsedNodeMap = new HashMap<String, Set<String>>(); for(Map.Entry<String, List<String>> entry : nodeReferenceMap.entrySet()) { String key = entry.getKey(); List<String> nodes = entry.getValue(); // Create initial node set Set<String> outSet = new HashSet<String>(); parsedNodeMap.put(key, outSet); // Start recursive call addNode(outSet, nodes); } // Sort keys List<String> sortedKeys = new ArrayList<String>(parsedNodeMap.keySet()); Collections.sort(sortedKeys); // Sort nodes Map<String, List<String>> sortedParsedNodeMap = new LinkedHashMap<String, List<String>>(); for(String key : sortedKeys) { List<String> sortedNodes = new ArrayList<String>(parsedNodeMap.get(key)); Collections.sort(sortedNodes); sortedParsedNodeMap.put(key, sortedNodes); } // Return sorted key/node mapping return sortedParsedNodeMap; } /** * Recursively add nodes by referencing the previously generated list mapping * @param outSet * @param nodes */ private void addNode(Set<String> outSet, List<String> nodes) { // Add each node to the set mapping for(String node : nodes) { outSet.add(node); // Get referenced nodes List<String> nodeList = nodeReferenceMap.get(node); if(nodeList != null) { // Create array list from abstract list for remove support List<String> referencedNodes = new ArrayList<String>(nodeList); // Remove already searched nodes to prevent infinite recursion referencedNodes.removeAll(outSet); // Recursively search more node paths if(!referencedNodes.isEmpty()) { addNode(outSet, referencedNodes); } } } } } Then, you can call this from your program like so: public static void main(String[] args) { try { NodeParser nodeParser = new NodeParser(); Map<String, List<String>> nodeSet = nodeParser.parseNodes("./res/input.txt"); for(Map.Entry<String, List<String>> entry : nodeSet.entrySet()) { String key = entry.getKey(); List<String> nodes = entry.getValue(); System.out.println(key + ": " + nodes); } } catch (IOException e){ System.err.println("Error: " + e.getMessage()); } } Also, the output is not sorted but that should be trivial. A: String s = "A: B C D"; String i = s.split(":")[0]; String dep[] = s.split(":")[1].trim().split(" "); System.out.println("i = "+i+", dep = "+Arrays.toString(dep));
{ "language": "en", "url": "https://stackoverflow.com/questions/7621478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AS3 Make enemy move towards mouse package { import enemies.Enemy; import flash.display.Sprite; import flash.events.*; public class Main extends Sprite { // a place to store the enemy public var enemy:Enemy; private function handleEnterFrame(e:Event):void { tweenIt(enemy.x, mouseX, 2); } private function tweenIt(variable:Number, target:Number, speed:Number):void{ if (variable < target) { variable += speed; } if (variable > target) { variable -= speed; } } // this is the first code that is run in our application public function Main():void { addEventListener(Event.ENTER_FRAME, handleEnterFrame); // we create the enemy and store him in our variable enemy = new Enemy(); // we add the enemy to the stage addChild(enemy) enemy.x = Math.random() * stage.stageWidth; enemy.y = Math.random() * stage.stageHeight; } } } The enemy class has a bitmapped embeded into it. I am using FlashDevelop to program. When I do something like enemy.x+=1 it works, but when I try using my tween it script the enemy stands still no matter what the position of the mouse. Thank you, Blobstah A: I'm not an AS3 developer so I can't help you if anything's wrong with your code, but if you're unsure of how to mathematically move an enemy towards the mouse, here's how. (This isn't the code, just the general jist of what you want to calculate. I'm sure you can convert it to AS3.) First, find the distance between the enemy and your mouse. xDistance = enemyPositionX - mousePositionX; yDistance = enemyPositionY - mousePositionY; Then, find the rotation needed to point the enemy towards the mouse. rotation = atan2(yDistance, xDistance); And lastly, here is what you want to put inside your tweenIt function to move the enemy towards the mouse (at 3 pixels per function call). enemyPositionX -= 3 * cos(rotation); enemyPositionY -= 3 * sin(rotation); And that should be it! I give credit to Be Recursive because it's where I learned how to do this. A: You're passing in the value of the enemy's x position to your tweenIt function, changing that value, then throwing the result away. In other words, variable is a different variable than enemy.x, even though it got its starting value from enemy.x. One way to fix this is by changing the parameter to be a reference the the actual enemy: private function handleEnterFrame(e:Event):void { tweenIt(enemy, mouseX, 2); } private function tweenIt(anEnemy:Enemy, target:Number, speed:Number):void{ if (anEnemy.x < target) { anEnemy.x += speed; } // ... } A: So, To add to the answer of Cameron you can make a more general function to change variables. I will demonstrate a small example below private function tweenIt(anEnemy:Enemy, variableName:String, value:Number):void { anEnemy[variableName] = value; } The above function will update the current value of the variable you want, so if you would type the following: tweenIt(enemy, "width", 200); this would update the width of your enemy-object to 200 :) And this should do the trick :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery tmpl grouping function with support for multiple groups Couldnt find any example on grouping using jquery tmpl() so thought id post what I came up with (that works) in case anyone else was trying to do it. A: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> <style type="text/css"> #lvList { float:left; } .league { background-color: #E8F6FF; } .group { background-color: #FEEAEB; margin-left: 10px; } .team { margin-left: 20px; } </style> </head> <body> <script id="itemtemplate" type="text/x-jquery-tmpl"> {{if !$item.sameasbefore("League") }} <div class="league">League: ${League}</div> {{/if}} {{if !$item.sameasbefore("Group") }} <div class="group">Group: ${Group}</div> {{/if}} <div class="team">${Team}</div> </script> <div id="lvList"></div> <script type="text/javascript"> var Leagues = [ { League: 1, Group: "A", Team: "France" }, { League: 1, Group: "A", Team: "China" }, { League: 1, Group: "B", Team: "Brazil" }, { League: 2, Group: "A", Team: "England" }, { League: 2, Group: "A", Team: "Scotland" }, { League: 2, Group: "B", Team: "India" } ]; var grouping = []; $("#itemtemplate").tmpl(Leagues, { sameasbefore: function (field) { var same = false; if (grouping[field] === this.data[field]) same = true; grouping[field] = this.data[field]; return same; } }).appendTo("#lvList"); </script> </body> </html> A: See the JQuery API docs for the basic usage of templates. I've written an extension to this function, which allows multiple categories to be grouped.Usage: $(JQuery template).tmpl_sort(data,[options,] array of groups)   •   For JQuery template, data and options, see the tmpl API documentation.   •   array of groups should be an array consisting of strings which identify the groups. Code: (function($){ $.fn.tmpl_sort = function(data, options_or_groups, array_groups){ return $.tmpl_sort(this, data, options_or_groups, array_groups); } $.tmpl_sort = function(template, data, options_or_groups, array_groups){ if(typeof array_groups == "undefined"){ array_groups = options_or_groups; options_or_groups = void 0; } array_groups = typeof array_groups == "string" || typeof array_groups == "number" ? [array_groups] : array_groups; if(!(array_groups instanceof Array)) throw new TypeError("$.fn.tmpl_sort: second argument has to be a string or array"); var groups = {}; for(var i=0; i<array_groups.length; i++){ (function(groupname){ var last; groups[groupname] = function(group){ /* === is a strict comparison operator */ return last === (last=group); } })(array_groups[i]); } return template.tmpl(data, groups, options_or_groups) } })(jQuery); Example at http://jsfiddle.net/gBTzU/ var Leagues = [ { League: 1, Group: "A", Team: "France" }, { League: 1, Group: "A", Team: "China" }, { League: 1, Group: "B", Team: "Brazil" }, { League: 2, Group: "A", Team: "England" }, { League: 2, Group: "A", Team: "Scotland" }, { League: 2, Group: "B", Team: "India" } ]; $("#itemtemplate").tmpl_sort(Leagues, ["sameleague", "samegroup"]).appendTo("#lvList");
{ "language": "en", "url": "https://stackoverflow.com/questions/7621483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Performing post through Chrome extension, where does it go? I want the below code to execute when I push the button I have added to my chrome browser through my extension: <script> var formData = new FormData(); var html = document.innerHTML; formData.append("time", "12:00:00"); formData.append("html",document.getElementsByTagName('html')[0].innerHTML); var xhr = new XMLHttpRequest(); xhr.open("POST", "https://www.mywebsite.com/index"); xhr.send(formData); </script> my issues is I have no idea where does this go? background html? manifest? I cant understand how it works even after reading the document about the architecture can anyone help me?. A: This code should go into background page. In order for it to work you need to add https://www.mywebsite.com to domain permissions first. It is all explained here with examples. To catch browser action button click: //background.html chrome.browserAction.onClicked.addListener(function(tab) { var formData = new FormData(); ... }); This will work only if you don't have a popup defined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How throw, try {} catch {} should be used in the real world? I mean, I knew all the language rules about throw, try {} catch {}, but I am not sure if I am using them correctly in the real world. Please see the following example: We have a large piece of scientific code which did all sorts of image processing things, recently we decided to spruce it up and make it more robust. One of the routines which is frequently used is void rotate_in_place(float* image, image_size sz); To make it more robust, we add some sanity check at the beginning of the code: void rotate_in_place(float* image, image_size sz) { // rotate_in_place does not support non-square image; if (sz.nx != sz.ny) throw NonSquareImageError; // rotate_in_place does not support image too small or too large if (sz.nx <= 2 || sz.nx > 1024) throw WrongImageSizeError; // Real rode here ..... } Now the problem is that rotate_in_place() is used in over 1000 places, shall I wrap each call of rotate_in_place() with try{} catch {}, this looks to me will make code incredibly bloated. Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using if (sz.nx != sz.ny) { cerr << "Error: non-squared image error!\n"; exit(0); } In short, I am not so sure about the real benefit of using throw, try, catch, any good suggestions? A: Every site that handles the error needs try-catch block. It all depends on your design, but I doubt you need to handle the error in every rotate_in_place call-site, you probably get away from propagating upwards most of the time. Printing the error and using exit is bad for three reasons: * *You can't handle the error. exit is not handling (unless it's done when the error is absolutely critical, but your function cannot know that — caller might have a way to recover). *You're extending responsibilities of the function with writing to a hard-coded stream, which might not even be available (this is rotate_in_place, not rotate_in_place_and_print_errors_and_kill_the_program_if_something_is_wrong) — this hurts reusability. *You lose all debugging information with this approach (you can generate stack traces from unhandled exceptions, you can't do anything with a function that bails out every time — unhandled exception is a bug, but it's a bug you can follow to the source). A: The general rule for exceptions is, "Does the immediate call site care about what's going on here?" If the call site does care, then returning a status code probably makes sense. Otherwise, throwing makes more sense. Consider it this way -- sure, your rotate in place method has a couple of invalid argument types, in which case you should probably throw std::invalid_argument. It's unlikely that a caller of rotate_in_place wants to deal with or knows how to deal with the case that an image was not square, for example, and therefore that's probably better expressed as an exception. Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using if (sz.nx != sz.ny) { cerr << "Error: non-squared image error!\n"; exit(0); } It's different because if someone later wants to take your function and put it in, say, a GUI application, they don't have to terminate the program based on the error. They can turn that exception into something pretty for the user or something like that. It also has benefits for you right now -- namely that you don't have to pull <iostream> into that translation unit simply to do error writing. I usually use a pattern something like this: int realEntryPoint() { //Program goes here } int main() { //Allow the debugger to get the exception if this is a debug binary #ifdef NDEBUG try #endif { return realEntryPoint(); } #ifdef NDEBUG catch (std::exception& ex) { std::cerr << "An exception was thrown: " << ex.what() << std::endl; } #endif } A: Now the problem is that rotate_in_place() is used in over 1000 places, shall I wrap each call of rotate_in_place() with try{} catch {}, this looks to me will make code incredibly bloated. It will, and it beats the purpose of using exceptions in the first place. Another possibility is do not wrap any try{} catch{} and let the program exit, but how is this different from just using [...] That you can always change the location of exception handling later on. If at some point you find a better place to sensibly handle the error (perhaps recovering from it), then that's the point where you put the catch. Sometimes that's in the very function where you throw the exception; sometimes it's way up in the call chain. Do put a catch-all in main, just in case. Deriving exceptions from standard ones such as std::runtime_error makes doing this a lot easier. A: The point in using exception handling holds in following simple rules: * *As soon as anything bad can happen due to bad user input (internal logic should be handled via assertions/logging), throw an exception. Throw as soon as possible, and as much as possible: C++ exceptions are usually pretty cheap compared to say, .Net ones. *Let an exception propagate if you can't handle the error. This means pretty much always. The thing to remember is: The exception should bubble up to the point where it can be handled. This can mean a dialog box with some formatting of the error, or this can imply that some unimportant piece of logic won't be executed after all, etc. A: Using exceptions allows the caller to decide how to handle an error. If you called exit directly within the function, then the program would exit without the caller being able to decide how to handle the error. Also, with exit, stack objects would not be unwound. :-( A: What you can do is to make rotate_in_place return a boolean if the function call was succesfull. And return the rotated image via a function parameter. bool rotate_in_place(float* image, image_size sz, float** rotated_image) { // rotate_in_place does not support non-square image; if (sz.nx != sz.ny) return false; // rotate_in_place does not support image too small or too large if (sz.nx <= 2 || sz.nx > 1024) return false; // Real rode here ..... return true; } A: It depends. Exceptions are generally meant to be caught/handled. In your case, is it possible to handle the exception (for instance, the user provides a non-square image, so you ask them to try again). However if there is nothing you can do about it, then cerr is the way to go. A: Well, I agree that really using Exceptions results in bloated code. That is the main reason for me not liking them. Anyway, as to your example: The key difference between throwing exceptions and just using exit() is that, since the handling of the exception happens (or is supposed to happen) outside of the program fragment that generated the error/exception, you do not specify how the user of a function/class has to handle the error. By using exceptions you allow different treatments like aborting the program, reporting errors or even recovering from certain errors. TLDNR: If you use exceptions, the exception-generating part of the code does not need to specify how the exceptional case is treated. That happens in the outside program and can be changed depending on how the code is being used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is there a way to kill a PHP program while it's working? Is there a way to kill a PHP program while it's working? I know in Linux/Unix I can do ps -u [username] And it will tell me what processes are running. To stop a process I just enter kill [process #] With PHP is there any way to see what processes are currently running on the remote server and kill an individual program from completion? Ideally using exec()? The reason that I ask is that I am on a shared hosting environment and I work on & test my programs directly on the server... Every now and then I'll do something silly like enter a ridiculous number of loops, accidentally, where it can take several minutes to an hour to actually complete. Seeing that there is virtually no information on the subject, I thought it would be an interesting question to throw out there. Thanks! A: if u have some infinite loop or something, put this while(1){ if(!file_exists("continue.txt")){ die("Stop"); } //Your Code here. } so when u delete that file "continue.txt", your script dies. A: Ask your hosting provider for SSH access and do that in Unix way. Still you can emulate shell access with a system function and friends: exec("ps --no-header -eo pid,user,comm", $output); foreach ($output as $line) { $line = preg_split('#\s+#', trim($line)); echo "PID: $line[0] USER: $line[1] PRG: $line[2]\n"; } Disclaimer: you probably won't be able to kill Apache processes even if you will have shell access. A: You can change set_time_limt settings before the risk of a loop, making the script stop after 10 seconds if you wish. http://php.net/manual/en/function.set-time-limit.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7621490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't input in command prompt when using keytool to generate key pair (public and private keys) and a signing certificate I can't provide any input from my keyboard or from the on-screen keyboard when using keytool to generate key pair (public and private keys) and a signing certificate. This problem occurs only when executing this command not in any other commands. I tried using running command from .bat file but still can't provide any input. The only input i can provide is enter(button). So should i go forward by again providing enter(button)? Note: I am referring Oreilly Android Application Development 2009.pdf Web version: http://androidapps.org.ua/i_sect17_d1e6459.html A: Are you sure you can't provide password? It doesn't show you any character when you type password and it is correct. Did you try print e.g. '123' as password and '456' as re-enter password? Does it say they don't match?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Cannot see the changes from database after adding in android? I have tabs activities. one activity gets data from local database, but when I add information to database through another activity and back to the activity which shows the database contents, I don't see the changes! >> I need to re-run the applications to see the changes ! why and how to solve it ? A: Ahh you probably need to re-bind your adapter, or call notifyDataSetChanged() on your adapter. For instance, in your onResume() method call listView.setAdapter(new MySpecialAdapter()). That way no matter if your program is resumed from your other activity, or some other program, it will refresh the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to have a menu accelerator with plus or minus signs in Swing? I have tried setting the accelerator of a JMenuItem using the following : item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); The menu item shows the shortcut ⌘+ (on a mac) but hitting these two keys won't trigger it. I have the same problem with the minus sign -. Is there any way to have a menu item with any of these signs as a shortcut ? EDIT - Here is a SSCCE : public class MenuWithPlus { public static void main(String[] args) { JFrame frame = new JFrame(); JMenuBar bar = new JMenuBar(); JMenu menu = new JMenu("View"); JMenuItem item = new JMenuItem("Zoom in"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("ZOOM IN TRIGGERED"); } }); menu.add(item); bar.add(menu); frame.setJMenuBar(bar); frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } A: At accelerator code you have to modify to: item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, Event.CTRL_MASK)); A test that I made was add a key event listener on frame and catch de key value for plus (in this case ADD). frame.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { System.out.println(e.getKeyCode()); } }); A: Are you using the +/- keys on the main keyboard vs. the numpad? They're seen as separate keys, so make sure you're using them consistently. I think VK_PLUS is not used for the usual plus key (Shift-= on a US keyboard), but rather either the numpad +, or the + key on some German keyboards. Assuming you have a US keyboard, you might want Shift together with VK_EQUALS. See this old bug and this discussion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get copied value from ctrl+v key event in javascript This method detects ctrl + v event but I couldnt find how to get the value of it ? Thanks in advance, $(".numeric").keydown(function (event) { if (event.shiftKey) { event.preventDefault(); } switch (event.keyCode) { case 86: if (event.ctrlKey) { // detects ctrl + v var value = $(this).val(); alert(value); // returns "" } break; } A: All you have to do it hook into the paste event, let it finish by breaking the callstack and then read the value. It might seem ugly but it is very crossbrowser friendly and saves you creating a lot of crappy code just to read the actual clipboard. $(".numeric").bind('paste', function (event) { var $this = $(this); //save reference to element for use laster setTimeout(function(){ //break the callstack to let the event finish alert($this.val()); //read the value of the input field },0); }); See it in action here: http://jsfiddle.net/Yqrtb/2/ Update: Since i just recently had to do something similar, i thought i'd share my final implementation, it goes like this: $('textarea').on('paste',function(e) { //store references for lateer use var domTextarea = this, txt = domTextarea.value, startPos = domTextarea.selectionStart, endPos = domTextarea.selectionEnd, scrollTop = domTextarea.scrollTop; //clear textarea temporarily (user wont notice) domTextarea.value = ''; setTimeout(function () { //get pasted value var pastedValue = domTextarea.value; //do work on pastedValue here, if you need to change/validate it before applying the paste //recreate textarea as it would be if we hadn't interupted the paste operation domTextarea.value = txt.substring(0, startPos) + pastedValue + txt.substring(endPos, txt.length); domTextarea.focus(); domTextarea.selectionStart = domTextarea.selectionEnd = startPos + pastedValue.length; domTextarea.scrollTop = scrollTop; //do work on pastedValue here if you simply need to parse its ccontents without modifying it }, 0); }); A: It's very much browser dependent. The data is in the event passed to your handler. In safari/chrome, we are listening for the paste event on the input and then doing event.clipboardData.getData('text/plain') in the callback and it seems to work ok. You should use your favorite debugger and put a breakpoint into your paste event handler, and look at the event that is passed in. A: You need a hack. I've detailed one on Stack Overflow a few times before: * *How can I get the text that is going to be pasted in my html text editor? *Pasting into contentedittable results in random tag insertion *JavaScript get clipboard data on paste event (Cross browser) A: It's very simple, code below works fine, in my case takes text contained on clipboard. function onPaste(info) { var copied = event.view.clipboardData.getData("Text"); alert(copied); } In this case variable called copied contains the value that you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Avoid Android Memory Leak when not using Static Image I know this has probably been addressed, however, I am having memory leak issues in my Android app. I have it cycle through a differant picture in the users library every time they push a button. This works fine for the first couple then throws an out of memory exception. I have looked around and though I understood that the pictures are being stored on the heap(?) even after it is not being pointed at. Is there a way I can force this to clean up so I am not getting the error? I have tried the following.... private void setImage() throws RemoteException{ view.setBackgroundDrawable(null); currentBackground = Drawable.createFromPath(backgroundImageService.getCurrentImageLocation()); view.setBackgroundDrawable(currentBackground); } UPDATE:: Update This worked!!! private void setImage() throws RemoteException{ if(currentBackground != null){ currentBackground.recycle(); } currentBackground = BitmapFactory.decodeFile(backgroundImageService.getCurrentImageLocation()); view.setBackgroundDrawable(new BitmapDrawable(currentBackground)); } Thanks A: you can use Bitmap.recycle() if you can change your Drawable with Bitmap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Struts Validation - Combining requiredif and mask I have a requirement in my app where a field is required on certain conditions and then that field should match a particular pattern. Is there a way I can combine the requiredif and mask conditions? I am on struts 1. Here's the validation.xml <form-validation> <global> <constant> <constant-name>char</constant-name> <constant-name>^[a-zA-Z]*$</constant-name> </constant> </global> <formset> <form name="myform"> <field property="city" depends="requiredif"> <arg0 key="city"/> <var> <var-name>field[0]</var-name> <var-value>state</var-value> </var> <var> <var-name>fieldTest[0]</var-name> <var-value>EQUAL</var-value> </var> <var> <var-name>fieldValue[0]</var-name> <var-value>SEATTLE</var-value> </var> </field> </form> </formset> </form-validation> How do I add a mask condition so that it is checked only if the above condition is true? Thanks Sahil A: IMO, don't; leave complex validations to Java code. The overhead of maintaining complex validations in the XML file isn't worth the effort. "requiredif" was deprecated and should be replaced with "validwhen", btw. You can create (relatively) complex validations with "validwhen", but... ew. Much cleaner to do in Java.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vb4android Alternative for Mac OS X Is there any alternative to vb4android for Mac OS X? A: Are you sure you want to develop for Mac OS X and not iOS? Take a look at the new Delphi XE2 which supports Windows, Max OS X and iOS. There is also LiveCode which develops for all platforms. If you are looking to develop apps on portable devices iOS (iPhone,iPod, iPad) and Android then try NS Basic/App Studio and PhoneGap. Or RhoMobile or Appcelerator. They run semi-native apps using javascript. Widget
{ "language": "en", "url": "https://stackoverflow.com/questions/7621510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dependency Injection & its relationship with automated testing via an example Through SO, I found my way to this page: http://www.blackwasp.co.uk/DependencyInjection.aspx There they provide a snippet of C# code to use as an example of code that could benefit from dependency injection: public class PaymentTerms { PaymentCalculator _calculator = new PaymentCalculator(); public decimal Price { get; set; } public decimal Deposit { get; set; } public int Years { get; set; } public decimal GetMonthlyPayment() { return _calculator.GetMonthlyPayment(Price, Deposit, Years); } } public class PaymentCalculator { public decimal GetMonthlyPayment(decimal Price, decimal Deposit, int Years) { decimal total = Price * (1 + Years * 0.1M); decimal monthly = (total - Deposit) / (Years * 12); return Math.Round(monthly, 2, MidpointRounding.AwayFromZero); } } They also include this quote: One of the key problems with the above code is the instantiation of the PaymentCalculator object from within the PaymentTerms class. As the dependency is initialised within the containing class, the two classes are tightly coupled. If, in the future, several types of payment calculator are required, it will not be possible to integrate them without modifying the PaymentTerms class. Similarly, if you wish to use a different object during automated testing to isolate testing of the PaymentTerms class, this cannot be introduced. My question is about the statement in bold: * *Did the author actually mean Unit Testing or is there something about automated testing that I'm missing? *If the author DID intend to write automated testing, how would modifying this class to use dependency injection aid in the process of automated testing? *In either case, is this only applicable when there are multiple types of payment calculators? *If so, is it typically worth implementing DI right from the start, even with no knowledge of requirements changing in the future? Obviously this requires some discretion that would be learned through experience, so I'm just trying to get a baseline onto which to build. A: Did the author actually mean Unit Testing or is there something about automated testing that I'm missing? I read this to mean unit testing. You can run unit tests by hand or in an automated fashion if you have a continuous integration/build process. If the author DID intend to write automated testing, how would modifying this class to use dependency injection aid in the process of automated testing? The modification would help all testing, automated or not. In either case, is this only applicable when there are multiple types of payment calculators? It can also come in handy if your injected class is interface-based and you'd like to introduce a proxy without having to change the client code. If so, is it typically worth implementing DI right from the start, even with no knowledge of requirements changing in the future? Obviously this requires some discretion that would be learned through experience, so I'm just trying to get a baseline onto which to build. It can help from the start, if you have some understanding of how it works and what it's good for. There's a benefit even if requirements don't change. Your apps will be layered better and be based on interfaces for non-value objects (immutable objects like Address and Phone that are just data and don't change). Those are both best practices, regardless of whether you use a DI engine or not. UPDATE: Here's a bit more about the benefits of interface-based design and immutable value objects. A value object is immutable: Once you create it, you don't change its value. This means it's inherently thread-safe. You can share it anywhere in your app. Examples would be Java's primitive wrappers (e.g. java.lang.Integer, a Money class. etc.) Let's say you needed a Person for your app. You might make it an immutable value object: package model; public class Person { private final String first; private final String last; public Person(String first, String last) { this.first = first; this.last = last; } // getters, setters, equals, hashCode, and toString follow } You'd like to persist Person, so you'll need a data access object (DAO) to perform CRUD operations. Start with an interface, because the implementations could depend on how you choose to persist objects. package persistence; public interface PersonDao { List<Person> find(); Person find(Long id); Long save(Person p); void update(Person p); void delete(Person p); } You can ask the DI engine to inject a particular implementation for that interface into any service that needs to persist Person instances. What if you want transactions? Easy. You can use an aspect to advise your service methods. One way to handle transactions is to use "throws advice" to open the transaction on entering the method and either committing after if it succeeds or rolling it back if it throws an exception. The client code need not know that there's an aspect handling transactions; all it knows about is the DAO interface. A: The author of the BlackWasp article means automted Unit Testing - that would have been clear if you'd followed its automated testing link, which leads to a page entitled "Creating Unit Tests" that begins "The third part of the Automated Unit Testing tutorial examines ...". Unit Testing advocates generally love Dependency Injection because it allows them to see inside the thing they're testing. Thus, if you know that PaymentTerms.GetMonthlyPayment() should call PaymentCalculator.GetMonthlyPayment() to perform the calculation, you can replace the calculator with one of your own construction that allows you to see that it has, indeed, been called. Not because you want to change the calculation of m=((p*(1+y*.1))-d)/(y*12) to 5, but because the application that uses PaymentTerms might someday want to change how the payment is calculated, and so the tester wants to ensure that the calculator is indeed called. This use of Dependency Injection doesn't make Functional Testing, either automated or manual, any easier or any better, because good functional tests use as much of the actual application as possible. For a functional test, you don't care that the PaymentCalculator is called, you care that the application calculates the correct payment as described by the business requirements. That entails either calculating the payment separately in the test and comparing the result, or supplying known loan terms and checking for the known payment value. Neither of those are aided by Dependency Injection. There's a completely different discussion to be had about whether Dependency Injection is a Good or Bad Thing from a design and programming perspective. But you didn't ask for that, and I'm not going to lob any hand grenades in this q&a. You also asked in a comment "This is the heart of what I'm trying to understand. The piece I'm still struggling with is why does it need to be a FakePaymentCalculator? Why not just create an instance of a real, legitimate PaymentCalculator and test with that?", and the answer is really very simple: There is no reason to do so for this example, because the object being faked ("mocked" is the more common term) is extremely lightweight and simple. But imagine that the PaymentCalculator object stored its calculation rules in a database somehow, and that the rules might vary depending on when the calculation was being performed, or on the length of the loan, etc. A unit test would now require standing up a database server, creating its schema, populating its rules, etc. For such a more-realistic example, having a FakePaymentCalculator() might make the difference between a test you run every time you compile the code and a test you run as rarely as possible. A: If the author DID intend to write automated testing, how would modifying this class to use dependency injection aid in the process of automated testing? One of the biggest benefits would be to be able to substitute the PaymentCalculator with a mock/fake implementation during the test. If PaymentTerms was implemented like this: public class PaymentTerms { IPaymentCalculator _calculator; public PaymentTerms(IPaymentCalculator calculator) { this._calculator = calculator; } ... } (Where IPaymentCalculator is the interface declaring the services of the PaymentCalculator class.) This way, in a unit test, you would be able to do this: IPaymentCalculator fakeCalculator = new FakePaymentCalculator() PaymentTerms paymentTerms = new PaymentTerms(fakeCalculator); // Test the behaviour of PaymentTerms, which uses a fake in the test. With the PaymentCalculator type hardcoded into PaymentTerms, there would be no way to do this. UPDATE: You asked in comment: Hypothetically speaking, if the PaymentCalculator class had some instance properties, the person developing the unit test would probably create the FakePaymentCalculator class with a constructor that always used the same values for the instance properties, right? So how then are permutations tested? Or is the idea that the unit test for PaymentTerms populates the properties for FakePaymentCalculator and tests several permutations? I don't think you have to test any permutations. In this specific case, the only task of the PaymentTerms.GetMonthlyPaymend() is to call _calculator.GetMonthlyPayment() with the specified parameters. And that is the only thing you need to unit test, when you write the unit test for that method. For example, you could do the following: public class FakePaymentCalculator { public decimal Price { get; set; } public decimal Deposit { get; set; } public int Years { get; set; } public void GetMonthlyPayment(decimal price, decimal deposit, int years) { this.Price = price; this.Deposit = deposit; this.Years = years; } } And in the unit test, you could do this: IPaymentCalculator fakeCalculator = new FakePaymentCalculator() PaymentTerms paymentTerms = new PaymentTerms(fakeCalculator); // Calling the method which we are testing. paymentTerms.GetMonthlyPayment(1, 2, 3); // Check if the appropriate method of the calculator has been called with the correct parameters. Assert.AreEqual(1, fakeCalculator.Price); Assert.AreEqual(2, fakeCalculator.Deposit); Assert.AreEqual(3, fakeCalculator.Years); This way we tested the only thing, which is the responsibility of the PaymentTerms.GetMonthlyPayment(), that is calling the GetMonthlyPayment() method of the calculator. However, for this kind of tests, using a mock would be much more simpler than implementing an own fake. If you're interested, I recommend you to try out Moq, which is a really simple, yet useful Mock library for .NET.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Maven pom error I have example projects from spring core training courses I've been on. They did work on their machines, not on mine though. I am not really expert with maven, but .pom file inside gives this error. I really appreciate any monkey-alike-instructions, I'l do first then understand. Thank you very much in advance. I just want to run them and go through again. Project build error: Non-resolvable parent POM: Failure to transfer com.springsource.training.common:abstractWebProject:pom:1.1.7.RELEASE from https://tbits.springsource.com/repository/snapshot was cached in the local repository, resolution will not be reattempted until the update interval of com.springsource.training.snapshot has elapsed or updates are forced. Original error: Could not transfer artifact com.springsource.training.common:abstractWebProject:pom:1.1.7.RELEASE from/to com.springsource.training.snapshot (https://tbits.springsource.com/repository/snapshot): ConnectException and 'parent.relativePath' points at wrong local POM pom.xml /mvc-1-solution line 1 Maven Problem plus I am having numerous mistakes for missing libraries: Description Resource Path Location Type Project 'mvc-1-solution' is missing required library: 'C:\Users\Blabla\.m2\repository\org\cloudfoundry\cloudfoundry-runtime\0.6.0-BUILD-SNAPSHOT\cloudfoundry-runtime-0.6.0-BUILD-SNAPSHOT.jar' mvc-1-solution Build path Build Path Problem Project 'mvc-1-solution' is missing required library: 'C:\Users\Blabla\.m2\repository\org\hibernate\hibernate-annotations\3.5.3-Final\hibernate-annotations-3.5.3-Final.jar' mvc-1-solution Build path Build Path Problem Project 'mvc-1-solution' is missing required library: 'C:\Users\Blabla\.m2\repository\org\hibernate\hibernate-core\3.5.3-Final\hibernate-core-3.5.3-Final.jar' mvc-1-solution Build path Build Path Problem and many more alike. Their .pom file. <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springsource.training.module</groupId> <artifactId>mvc-1-solution</artifactId> <packaging>war</packaging> <version>3.2.1.RELEASE</version> <parent> <groupId>com.springsource.training.common</groupId> <artifactId>abstractWebProject</artifactId> <version>1.1.7.RELEASE</version> </parent> <repositories> <repository> <id>com.springsource.training.snapshot</id> <name>SpringSource Training Repository - Snapshots</name> <url>https://tbits.springsource.com/repository/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>com.springsource.training.release</id> <name>SpringSource Training Repository - Releases</name> <url>https://tbits.springsource.com/repository/release</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>org.springframework.maven.milestone</id> <name>Spring Maven Milestone Repository</name> <url>http://maven.springframework.org/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>springsource-snapshot</id> <url>http://s3.amazonaws.com/private.maven.springsource.com/snapshot/</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <dependencies> <!-- DBCP --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.3</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> <exclusion> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> </exclusion> <exclusion> <groupId>xerces</groupId> <artifactId>xerces</artifactId> </exclusion> <exclusion> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> </exclusion> <exclusion> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.5.4</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- CloudFoundry --> <dependency> <groupId>org.cloudfoundry</groupId> <artifactId>cloudfoundry-runtime</artifactId> <version>0.6.0-BUILD-SNAPSHOT</version> </dependency> </dependencies> </project> A: Not a solution, but a recipe how to solve it: * *Check each of the repositories you have defined in the Maven POM. For me, the 2 springsource repos are not available at the moment. *I think that the abstractWebProject will be contained in some of these. So the error Project build error: Non-resolvable parent POM: Failure to transfer will be a result of that. *After you may have access to the parent POM, you should check if all the dependencies are resolvable. *If everything fails, get in touch with the training team. If you were on that training, they will try to help you. You should have then the following information ready available: * *The POM you want to use (as in your question) *The file settings.xml in your Maven installation *The version of your Maven isntallation *The file settings.xml in your user directory .m2 (depending on your operating system at different locations). Hope you can get the help you need to solve it. A: "..resolution will not be reattempted until the update interval of com.springsource.training.snapshot has elapsed or updates are forced." --This is due to the first failure trying to download artifacts, need to remove those *.lastUpdated from your repository. For windows: cd %userprofile%.m2\repository for /r %i in (*.lastUpdated) do del %i
{ "language": "en", "url": "https://stackoverflow.com/questions/7621519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Element-wise vector-vector multiplication in BLAS? Is there a means to do element-wise vector-vector multiplication with BLAS, GSL or any other high performance library ? A: There is always std::valarray1 which defines elementwise operations that are frequently (Intel C++ /Quse-intel-optimized-headers, G++) compiled into SIMD instructions if the target supports them. * *http://software.intel.com/sites/products/documentation/hpc/composerxe/en-us/cpp/mac/cref_cls/common/cppref_valarray_intro.htm Both these compilers will also do auto-vectorization * *http://software.intel.com/en-us/articles/getting-code-ready-for-parallel-execution-with-intel-parallel-composer/ *http://gcc.gnu.org/projects/tree-ssa/vectorization.html In that case you can just write #define N 10000 float a[N], b[N], c[N]; void f1() { for (int i = 1; i < N; i++) c[i] = a[i] + b[i]; } and see it compile into vectorized code (using SSE4 e.g.) 1 Yes they are archaic and often thought of as obsolete, but in practice they are both standard and fit the task very well. A: In GSL, gsl_vector_mul does the trick. A: (Taking the title of the question literally...) Yes it can be done with BLAS alone (though it is probably not the most efficient way.) The trick is to treat one of the input vectors as a diagonal matrix: ⎡a ⎤ ⎡x⎤ ⎡ax⎤ ⎢ b ⎥ ⎢y⎥ = ⎢by⎥ ⎣ c⎦ ⎣z⎦ ⎣cz⎦ You can then use one of the matrix-vector multiply functions that can take a diagonal matrix as input without padding, e.g. SBMV Example: void ebeMultiply(const int n, const double *a, const double *x, double *y) { extern void dsbmv_(const char *uplo, const int *n, const int *k, const double *alpha, const double *a, const int *lda, const double *x, const int *incx, const double *beta, double *y, const int *incy); static const int k = 0; // Just the diagonal; 0 super-diagonal bands static const double alpha = 1.0; static const int lda = 1; static const int incx = 1; static const double beta = 0.0; static const int incy = 1; dsbmv_("L", &n, &k, &alpha, a, &lda, x, &incx, &beta, y, &incy); } // Test #define N 3 static const double a[N] = {1,3,5}; static const double b[N] = {1,10,100}; static double c[N]; int main(int argc, char **argv) { ebeMultiply(N, a, b, c); printf("Result: [%f %f %f]\n", c[0], c[1], c[2]); return 0; } Result: [1.000000 30.000000 500.000000] A: I found that MKL has a whole set of mathematical operations on vector, in its Vector Mathematical Functions Library (VML), including v?Mul, which does what I want. It works with c++ arrays, so it's more convenient for me than GSL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Cron job with php How can you do a cron job with php without creating a cron Job on the server cron software Is that even possible ? EDIT as I added in a comment I've seen a script called piwik who does that kind of stuff, e.g. Sends emails without any cron job A: I think the best you could do is make a cron job that periodically checks a file X for cron jobs and runs them. Then all you would have to do is add jobs to X instead of to cron. A: No. You can try online services like http://pingability.com/ Cron is ideal though. A: set_time_out(0); ignore_user_abort(true); while(1){ sleep(1); // sleep one sec every time. //do your stuff here.. //you can use time() with IF to make it execute something only on specific timing. } Not recommended.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: calling a simple WCF Service from jQuery I have a very simple WCF Service called pilltrkr.svc. I'm trying to call this service from jQuery via the following code: var jsondata = JSON.stringify(); $.ajax({ type: "POST", async: false, url: './pilltrakr.svc/DoWork/', contentType: "application/json; charset=utf-8", data: jsondata, dataType: "json", success: function (msg) { alert(msg); }, error: function (XMLHttpRequest, textStatus, errorThrown) { // alert(XMLHttpRequest.status); // alert(XMLHttpRequest.responseText); } }); I am doing this locally (so using localhost). DoWork just returns a string. When I call this function I get a http://localhost:57400/pilltrakr/pilltrakr.svc/DoWork/ 404 Not Found How do I call my WCF Service? I've tried several different variations (after researching). I was able to call this service using the code behind method (client). I'm sure this is a real easy thing to do. Please advise. More code - It seems like every post on Stack includes the interface and the actual class for the service, so I am also putting them here, just in case there is something I'm missing: Interface: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; using System.Web; namespace serviceContract { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "Ipilltrakr" in both code and config file together. [ServiceContract] public interface Ipilltrakr { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] string DoWork(); [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] int addUser(string userName, string userPhone, string userEmail, string userPwd, string acctType); } } class: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using pillboxObjects; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; namespace serviceContract { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "pilltrakr" in code, svc and config file together. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] public class pilltrakr : Ipilltrakr { string Ipilltrakr.DoWork() { return "got here"; } int Ipilltrakr.addUser(string userName, string userPhone, string userEmail, string userPwd, string acctType) { userAccount ua = new userAccount(); int uId; ua.userName = userName; ua.userPhone = userPhone; ua.userEmail = userEmail; ua.userPwd = userPwd; ua.userCreateDate = DateTime.Now; ua.userAccountType = acctType; uId = ua.add(); return uId; } } } web config: <?xml version="1.0"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <connectionStrings> <add name="xxxConnectionString" connectionString="Data Source=xxx;Initial Catalog=xxx;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> </system.web> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_Ipilltrakr" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="http://localhost:57400/pilltrakr/pilltrakr.svc/pilltrakr" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Ipilltrakr" contract="svcPilltrakr.Ipilltrakr" name="BasicHttpBinding_Ipilltrakr" /> </client> <services> <service name="serviceContract.pilltrakr" behaviorConfiguration="MyServiceTypeBehaviors"> <endpoint contract="serviceContract.Ipilltrakr" binding="basicHttpBinding" address="pilltrakr" bindingNamespace="serviceContract"/> <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors"> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" /> </system.serviceModel> </configuration> A: Probably a bit late, but I wrote a couple of blog posts a few years ago about calling WCF from jQuery. This also covers fault handling - which many articles ignore. Part one and Part two. HTH Iain A: I figured out how to finally call my simple WCF service from jQuery. I found some source code after reading this link: http://www.west-wind.com/weblog/posts/2009/Sep/15/Making-jQuery-calls-to-WCFASMX-with-a-ServiceProxy-Client. This link doesn't provide the source but it was another page that referenced this link. Anyway, I downloaded the code and started to compare my code versus this working project that was calling a WCF Service via jQuery. What I found was that my web.config file was way too complicated so I shorted that up considerably. Then I also realized that my methods were not public. So I made them public and then after a few more tweaks (i.e. taking out the namespaces) the page started to return the simple string I was trying to return. <system.serviceModel> <services> <service name="pilltrakr" behaviorConfiguration="MyServiceTypeBehaviors"> <endpoint address="" behaviorConfiguration="pilltrakrAspNetAjaxBehavior" binding="webHttpBinding" contract="Ipilltrakr"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="pilltrakrAspNetAjaxBehavior"> <enableWebScript/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> </system.serviceModel> A: what i found in google, might help you. $(document).ready(function() { $("#sayHelloButton").click(function(event){ $.ajax({ type: "POST", url: "dummyWebsevice.svc/HelloToYou", data: "{'name': '" + $('#name').val() + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { AjaxSucceeded(msg); }, error: AjaxFailed }); }); }); function AjaxSucceeded(result) { alert(result.d); } function AjaxFailed(result) { alert(result.status + ' ' + result.statusText); } [WebMethod()] public static string sayHello() { return "hello "; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do i use X-Accel-Redirect with nginx I have a asp.net website and i have nice urls so the user may see /abc/1/a.jpg the path is docroot/abc/number/number/id.jpg I need asp.net to decode where the real path is. So essentially i do it and instead of rewriting i set the X-Accel-Redirect header and called Reponse.End(); I got a 404 error. This code was in Application_BeginRequest. I tried not doing .End() and just return. I get a asp.net like 404 error. I messed around and gave up so instead of sending the header i called HttpContext.Current.RewritePath to the exact same path. The image now displays but its being handled by asp.net instead of nginx. How do i get nginx to listen to my X-Accel-Redirect headers? What do i need in my config file? my current one looks like this Note that i am in fact putting everything through asp.net. server { server_name www.MYSITE.com static.MYSITE.com; root /var/www/MYSITE; location / { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } A: gah. The problem was nginx config file. I needed to add location /base/path { internal; } The file must be in a directory/location that is marked internal; I notice the content type is incorrect unless set to "". Heres what i did and i am not sure you need the first line HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.ContentType = ""; HttpContext.Current.Response.AddHeader("X-Accel-Redirect", full); HttpContext.Current.Response.End();
{ "language": "en", "url": "https://stackoverflow.com/questions/7621530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery timeout change content I have an issue. I use this code: var test='test'; $('#tip').delay(1000).html(test); That doesn't work, it won't change the text. Although, it works if I do html('test') instead of having a variable there. I've also tried using non jQuery JavaScript: var test='test'; setTimeout("document.getElementById('tip').innerHTML=text", 1000); As earlier, it only works if I directly input the text instead of a variable. But how can I fix so it setTimeout works with variables too? Or is there any ind of work-around? Btw, I use jQuery 1.6.3. EDIT: Sorry, only the standard method (non jQuery) works as supposed when trying to do that without variable. With jQuery it makes it 'test' first, and the delay comes after. A: I've just written a function: (function(text){ setTimeout(function(){ document.getElementById("tip").innerHTML = text; }, 1000); })(text) The timeout is wrapped inside an anonymous function, so that multiple test variables can be used, and don't interfere with each other. Instead of wrapping the text in an anonymous function , you can also name the function, and call it from within a script: funcName("test text").
{ "language": "en", "url": "https://stackoverflow.com/questions/7621536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alternatives to .NET for clients Maybe it is just me, but deploying .NET desktop apps to client machines seems to be a more involved process than with other frameworks. Those I've written and those I've purchased as 3rd party applications seem to require more separate downloads. Whether it be one click downloading, upgrading the .NET framework, or uninstalling/reinstalling a crashing app because some part of the .NET framework or app did not download/install properly. If I want to hire a developer to write a windows based desktop application that is downloaded once, and installs without additional downloads, what other languages can I look too? The app will need its own installer, which I'm guessing the developer should have a license to distribute with their app. One disadvantage I believe I'll be loosing is that .NET developers are probably some of the most affordable. However, I'd like to improve the user install experience. Any feedback is welcome. A: The best way to ensure that the .NET framework is available on client computers is to use an older version of the framework, such as .NET 2.0. Most people or companies ready to pay for software have a version of Windows recent enough (or have Windows Updates turned on). Of course, not all apps are written in .NET. Visual C++/MFC, Delphi and Qt come to mind. Regarding the installer, the free Inno Setup has become extremely popular. WIX is also very popular (and free as well). This one target .MSI installers. I've been developing product applications professionally for 20 years now (OMG!) and I'm extremely careful to deployment considerations such as reducing the required dependencies. For that reason, I've resisted some time to the .NET sirens. But this is the past: Stick to .NET 2.0 and you won't have any problem: Vista and Windows 7 (which means nearly all computers) install it by default (actually v3.0+). WinXP owners have .NET 2.0 if they ever Windows Updated their computers in the past x years. A: To get that sort of install experience you would need to turn to things which compile to native, for example: * *C/C++ *Delphi ALTHOUGH I am not sure what sort of negative experience you had so far with .NET clients... current Windows versions have at least .NET 2 or even .NET 4 pre-installed...
{ "language": "en", "url": "https://stackoverflow.com/questions/7621538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows Phone 7 listbox colorize items? Is there a way to use the listbox with a htmlstring? listbox.items.add("<font color='#efefef' size=2>asd</font>"); ? A: Not natively. But you can do something like this: listbox.Items.Add(new TextBlock() { Text = "Asd", Foreground = Color.FromArgb(0xff, 0xef, 0xef, 0xef), FontSize = 2, });
{ "language": "en", "url": "https://stackoverflow.com/questions/7621541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GA Tracking code on ajax requests? I have this: <!-- Google Code for Tilmeldinger nyhedsbrev Conversion Page --> <script type="text/javascript"> /* <![CDATA[ / var google_conversion_id = 982857669; var google_conversion_language = "da"; var google_conversion_format = "1"; var google_conversion_color = "ffffff"; var google_conversion_label = "e90GCIP3jwMQxe_U1AM"; var google_conversion_value = 0; if (20) { google_conversion_value = 20; } / ]]> */ </script> <script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/982857669/?value=20&label=e90GCIP3jwMQxe_U1AM&guid=ON&script=0"/> </div> </noscript> I inserted it on the page the ajax request to, and in the response I see this script^. But it does not track or count anything? What should I do? A: You can use the GA event's tracking. Here is all info you need: http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html I suggest you to write small function: var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-xxxxxxxx-x']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); function event(category, action, label, value) { _gaq.push(['_trackEvent', category, action, label, value]); } And jsut call event() function. A: The script's not being executed when the AJAX request returns. You can either try and figure out why, or I think the <noscript> bit does most of the work anyway so you could try removing the rest and just placing the image into your page: <img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/982857669/?value=20&label=e90GCIP3jwMQxe_U1AM&guid=ON&script=0"/> This should issue an image request that sends the tracking data to AdWords.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery FullCalendar - delete all events in a selection I am using FullCalendar and I'm using the select: function to allow the user to select one or more days, and then enter a value, which I will later save to a database. I want to clear the existing events in the selection before adding a new one, but I can't access the event property from within select function to then call fullCalendar('removeEvent', );. Any ideas? Thanks! A: The FullCalendar plugin provides a method clientEvents which returns all events that are stored locally at the client (e.g. if the calendar retrieves the data from a json feed, you only get those events that already got downloaded). As you cannot select something that is not visible, all events in the selected area are definitely in this cache. See http://arshaw.com/fullcalendar/docs/event_data/clientEvents/ for more information. This method accepts an optional parameter idOrFilter, used to apply a filter before returning the events. This can be a list of IDs or (more valuable to you) a function. This function gets an event object and returns true (meaning: include this event in the result set) or false (discard it). var eventsToDelete = $('#calendar').fullCalendar('clientEvents', function(event) { // check if event.start >= selection.start && event.start < selection.end ... etc. }); eventsToDelete is now an array that contains all the events you want to delete.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: file corrupt when click download link I try to use php to force the image jpg file download, I have implemented eth following code: html <a href = "filedownload.php?src=uploads/myimage.jpg&download=true>download this file</a> download.php <?php ob_start(); include_once 'functions.php'; if (isset($_GET['download']) && $_GET['download'] == 'true') { $src = sanitizeString($_GET['src']); header('Content-Description: File Transfer'); header('Content-Type: image/jpeg'); header('Content-Disposition: attachment; filename='.basename($src)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: public'); header('Pragma: public'); } ?> Suppose the full path of the image is "www.example.com/smith/topic/uploads/myimage.jpg", I have recieved the right image name and the download window is appeared as well, but the image is corrupt and with 1KB size, any one could tell me why, thanks a lot. A: Here you are example how to use readfile function <?php $file = 'monkey.gif'; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } ?> A: You need some code that actually sends over the file. See e.g. readfile or fpassthru A: Try to use: header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
{ "language": "en", "url": "https://stackoverflow.com/questions/7621565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remote Procedure Call cleanup My situation is the following: I've implemented a simple RPC system in C through which a client can call a remote function to which it passes a command. The command is executed on the remote machine and the string containing the output is returned to the client. So, the function signature is: char* execute(char* command) Inside this function I do a malloc for the result string and return it. The function is published and clients my invoke it. My question is: in which way can I free the allocated char* on the server side after each remote procedure call? Edit: To detail my problem a bit more: the issue here is that after the first rpc call, the server crashes with "glibc detected free() invalid pointer" error. Inside the execute procedure I have something like: char* result = (char*) malloc(STRING_SIZE * sizeof(char)); ... return result; I'm assuming it's trying and failing to free the returned result. A: It depends on which RPC mechanism is used. Some can automatically call freeing functions on returned pointers if the function is marked appropriately. If your RPC library can't do that, you have to change malloc to something else. In single-threaded server, you can simple return pointer to a static buffer, in multithreaded...it depends on the situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Oracle 11g - Check constraint with RegEx I'm using Oracle 11g, and trying to create a table define constraints on the creation. I was trying to add check constraint to validate some information (like e-mail address, phone number, etc...) Is there something in Oracle 11g that would allow me to do something like this? constraint CK_CONSTRAINT_NAME check (EMAIL like 'REGEX') The regEx I wanted to use (grabbed from regexLib) is: ^[a-zA-Z][a-zA-Z0-9_\.\-]+@([a-zA-Z0-9-]{2,}\.)+([a-zA-Z]{2,4}|[a-zA-Z]{2}\.[a-zA-Z]{2})$ I think Oracle 11g (correct me if I'm wrong) doesn't support this format for RegEx... I've seen methods using REGEX_LIKE, but it seems to only work in WHERE clauses. I'd like to keep it as a check constraint and not a trigger or an external function/script. Also, I've read in other threads here, someone saying RegEx' are not a good way of verifying e-mail address format and such information. No reason was given in the comment, and I'd like to know why, if a reason there is! A: A check constraint follows the same syntax rules as conditions for a WHERE clause: alter table foo add constraint check_email check (REGEXP_LIKE(email,'your_regex_goes_here','I')); More details in the manual: * *for Oracle 11 - http://docs.oracle.com/cd/E11882_01/server.112/e41084/conditions007.htm#SQLRF52141 *for Oracle 12 - https://docs.oracle.com/database/121/SQLRF/conditions007.htm#SQLRF52141 Edit: There are however some restrictions on what you can actually use in a check constraint: * *Oracle 11 - http://docs.oracle.com/cd/E11882_01/server.112/e41084/clauses002.htm#SQLRF52205 *Oracle 12 - https://docs.oracle.com/database/121/SQLRF/clauses002.htm#SQLRF52205 A: CREATE TABLE MYTABLE( EMAIL VARCHAR2(30) CHECK(REGEXP_LIKE (EMAIL,'^[A-Za-z]+[A-Za-z0-9.]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$')) ); ALTER TABLE MYTABLE ADD(CONTACT NUMBER(10) CHECK(REGEXP_LIKE(CONTACT,'[0-9]{10}'))); Explanation of Regular Expression ^ #start of the line [_A-Za-z0-9-]+ # must start with string in the bracket [ ], must contains one or more (+) ( # start of group #1 \\.[_A-Za-z0-9-]+ # follow by a dot "." and string in the bracket [ ], must contains one or more (+) )* # end of group #1, this group is optional (*) @ # must contains a "@" symbol [A-Za-z0-9]+ # follow by string in the bracket [ ], must contains one or more (+) ( # start of group #2 - first level TLD checking \\.[A-Za-z0-9]+ # follow by a dot "." and string in the bracket [ ], must contains one or more (+) )* # end of group #2, this group is optional (*) ( # start of group #3 - second level TLD checking \\.[A-Za-z]{2,} # follow by a dot "." and string in the bracket [ ], with minimum length of 2 ) # end of group #3 $ #end of the line
{ "language": "en", "url": "https://stackoverflow.com/questions/7621568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Jquery call function dynamically I have a following scenario that I have to call a function on a jquery object dynamically. The code looks like this : $('div[class]').each(function(){ var class=$(this).attr('class'); // I want to now check if that function with the name of class exists for jquery // object. I need help here. // if that function exists, i need to apply that function to the enumerated object. }); I want to now check if that function with the name of class exists for jQuery object. I need help here. If that function exists, I need to apply that function to the enumerated object. A: I'm writing this of the top of my head so it might not work, but try: if(jQuery.isFunction(jQuery[class])) jQuery[class](this); Edit: if the function is a jquery method then try with: if(jQuery.isFunction(jQuery.fn[class])) { jQuery.fn[class](this); jQuery(this)[class](); // alternative call syntax }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oauth 2.0 - Redirect URL takes user to the canvas page on my website and not to the iframe on Facebook I have looked around and around for hours now and messed about with different pieces of code and I am at a loss. I am only a begginner at PHP so I am learning it as I go along. I get how authorisation works and I have managed to get the app authorised, just once the app has been authorised the application redirects the user to the full canvas page on my website instead of displaying my canvas page in the iframe within Facebook. I can't for the life of me work out how to change this so the redirect redirects to the iframe and not my website. I would really appreciate some help on this matter. (P.s. I know there are similar topics to this and I have read quite a few and have found nothing that has helped me solve my problem) Many Thanks Scott
{ "language": "en", "url": "https://stackoverflow.com/questions/7621576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble on initializing a factory object I am using Ruby on Rails 3.1.0, rspec-rails 2 and Factory gems. I have some trouble related to the validation process when I state a Factory object for an Account class. In the model file I have: class Account < ActiveRecord::Base belongs_to :user attr_accessible :name, ..., :password validates :name, :presence => true ... validates :password, :presence => true end In the factory file I have: FactoryGirl.define do factory :account, do sequence(:name) { |n| "Foo #{n}"} ... password 'psw_secret' association :user end factory :user do auth 'registered' end end When in the spec file I state let!(:account) { Factory(:account) } it works as expected but when I use the following: let!(:user) { Factory(:user, :account => Factory(:account)) } I get this error: Failure/Error: let!(:user) { Factory(:user, :account => Factory(:account)) } ActiveRecord::RecordInvalid: Validation failed: Account password can not be blank, Account is invalid Why I get that error? How can I solve the problem? A: I think you should do it the other way around: @user = Factory(:user) @account = Factory(:account, :user => @user) The relation is defined on account, not on user. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using bake on shared hosting Cakephp I'm trying to get bake working on my subdomain which is under shared hosting. Is there a way we can get this working? I know how to connect to server via ssh shell but then what do I do after that? A: same as local machine cd <path_to_console> cake if you do not know path_to_console ask for host support, also path_to_console may be in environment path then just use cake in all dirs A: First cd to the directory where the cake script is. On a Linux webserver, this would probably be something like ~/cake/console/, if you've put the CakePHP libs outside your web-accessible directories. If you've put everything into your web directory you'll probably have to go somewhere like ~/www/cake/console/. Then simply type ./cake bake and take it from there. You shouldn't have to do anything with environment variables. This is only necessary if you want to be able to run the cake console from any directory. I find it less of a hassle to just cd into the cake console's directory and run it using ./cake.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: facebook canvas page: app behavior dependent of visitor to user's profile The problem: I want to provide a facebook application as canvas page to user A ('the owner'). If user A is seeing the app via in its profile, the app should exhibit behavior Ba. If there is a user B ('the visitor') which is visiting the owners profile and clicking to see the app's canvas page in the owner's profile, the app should exhibit behavior Bb according to the visitor's profile. The visitor (user B) does not have the application in its profile. An analogy would be that an application like bandpage in a band's profile (http://www.facebook.com/hmbmusic?sk=app_178091127385) would have different behavior according to each person visiting the profile. I've been one day researching stuff fb_sig_user and fb_sig_canvas_user and can not come to a conclusion over if it this possible to do something like this or not. Is it possible? Any tips? A: It's possible. Once a user authorizes your app you'll have access to their ID and can make decisions as to who they are. Additionally if you're coming in to your app from different endpoints you can use the URL to make decisions from. You'll need to decode the signed request that's passed to your app to see if the user has added the app yet or not. Start your research with the signed_request and that should get you headed in the right direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detecting when user leaves page in Page_Load event When a user leaves a page it fires of the Page_Load event again. How can I tell in code_behind that this is happening so in can avoid running the custom functions as the code in the Page_Load does not really need to be ran when leaving the page? A: When a user leaves a page it fires of the Page_Load event again What do you mean by leaving a Page? Closing the browser or clicking Back button on browser? Or moving to another Page? Page_Load method is fired when on Loading Page or when Postback occurs on the same Page, but not leaving it. Before you start any operations, you can (and you should) ensure that client is still connected and use HttpResponse.IsClientConnected property. The IsClientConnected property returns false when the following conditions are true: * *The connection to the client was terminated. This can occur if the Close method was invoked, or if the client stopped execution of the Web page or browsed to another page. *The HttpWorkerRequest object that is handling the request is null or the HttpWorkerRequest.IsClientConnected method returns false. If a custom HttpWorkerRequest object handles the request, then the HttpWorkerRequest.IsClientConnected method might be set based on custom criteria. For example, the custom worker request might force a time-out after a period of time. http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx EDIT Switching tabs usually fires normal Postback, to detect it you should use: private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostback) { //this is first load of this page } } A: If I understand the question correctly, you're looking for the IsPostBack property: private void Page_Load() { if (!IsPostBack) { // Any code here will only run the first time the page is loaded } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error with regex in jquery I want to validate my textbox on keypress event. As I am newbie with jquery, I searched on google and found one jquery plugin named 'limitkeypress'. This is my code: $(document).ready(function() { $("#title").limitkeypress({ rexp: /^[A-Za-z]*$/ }); }); Plugin library is: http://brianjaeger.com/process.php It's giving me the following error $("#title").limitkeypress is not a function When I checked the library on jsfiddle it shows me dozens of errors. Is there any other validation library or plugin? EDIT Thanks everyone for your valuable comment. Finally I got the solution. Though I was including file correctly. but don't know Y it was not working. I wrote jQuery.noConflict(); and all the problem is solved. What exactly it work. Please let me know, though I read but doubt still I have doubt. A: regexp is ok: 'buGaGa'.match(/^[A-Za-z]*$/); $("#title").limitkeypress is not a function probably you forget to inlude library or wrong path. Check it in Firebug( Net -> All ) lib must be highlight in black, not red. A: Made a demo: http://jsfiddle.net/tTASy/ plugin seems to work fine. Check your path to the script. if you paste a link to your page we could help you more specifically. A: You can do this in jQuery like this without the plugin.. $("#your_textbox").keypress(function() { var length = this.value.length; if(length >= MIN && length <= MAX) { $("#your_submit").removeAttr("disabled"); $("#your_validation_div").hide(); } else { $("#your_submit").attr("disabled", "disabled"); $("#your_validation_div").show(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7621594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining Arrays in VBA I have a list of customers from last year (in column A) and I have a list of customers from this year (in Column B). I've put the data from these two columns in arrays (using the code below - which is set up as Option Base 1): 'Define our variables and array types' Sub CustomerArray() Dim LastArray() As String Dim CurrentArray() As String Dim BothArray() As String Dim LR As Long Dim i As Integer 'Define LastArray which is customers last year' LR = Cells(Rows.Count, 1).End(xlUp).Row ReDim LastArray(LR - 3) With Range("A1") For i = 1 To LR - 3 LastArray(i) = .Offset(i, 0) Next i End With 'Define CurrentArray which is customers this year' ReDim CurrentArray(LR - 3) With Range("B1") For i = 1 To LR - 3 CurrentArray(i) = .Offset(i, 0) Next i End With End Sub Now I want to compare/combine the Arrays to show a list of customers who appear in both of the two arrays I just defined (last year and this year). I want to create a third array with the customers who appear for both years (and I want to put that in column D of my excel sheet). I'm getting confused on how to write the code which will compare these two arrays (current year and last year). Will I use a conditional If > statement? Each of the arrays have the customers listed alphabetically. I appreicate any help you might be able to give me. Thanks! A: You don't need to mess with arrays or loop at all, keep it simple, try something like this: Sub HTH() With Range("A1", Cells(Rows.Count, "A").End(xlUp)).Offset(, 3) .Formula = "=IF(COUNTIF(B:B,A1)>0,A1,"""")" .Value = .Value .SpecialCells(xlCellTypeBlanks).Delete End With End Sub A: OK. I got a little carried away here, but this does what your are asking (you may have to tune it up to suit your specific needs. To use this code, simply call the Sub "Match Customers". Your original code proposed the use of three arrays. Excel VBA provides some mechanisms to do what you seek which are both easier to use, and possibly more efficient. I went ahead and broke the process out into more discrete chunks of code. While it seems like more code, you will find that each peice might make more sense, and it is much more maintainable. You can also now re-use the individual functions for other operations if needed. I also pulled your range and column indexes out into locally defined constants. This way, if the various row or column references ever need to change, you only have to change the value in one place. It is not necessarily the most efficient way to do this, but is most likely less complicated than using the arrays you originally propose. I have not tested this exhaustively, but it works in the most basic sense. Let me know if you have questions. Hope that helps . . . Option Explicit 'Set your Column indexes as constants, and use the constants in your code. 'This will be much more maintainable in the long run: Private Const LY_CUSTOMER_COLUMN As Integer = 1 Private Const CY_CUSTOMER_COLUMN As Integer = 2 Private Const MATCHED_CUSTOMER_COLUMN As Integer = 4 Private Const OUTPUT_TARGET As String = "D1" Private Const LAST_ROW_OFFSET As Integer = -3 'A Function which returns the list of customers from last year 'as a Range object: Function CustomersLastYear() As Range Dim LastCell As Range 'Find the last cell in the column: Set LastCell = Cells(Rows.Count, LY_CUSTOMER_COLUMN).End(xlUp) 'Return the range of cells containing last year's customers: Set CustomersLastYear = Range(Cells(1, LY_CUSTOMER_COLUMN), LastCell) End Function 'A Function which returns the list of customers from this year 'as a Range object: Function CustomersThisYear() As Range Dim LastCell As Range 'Find the last cell in the column: Set LastCell = Cells(Rows.Count, CY_CUSTOMER_COLUMN).End(xlUp) 'Return the range of cells containing this year's customers: Set CustomersThisYear = Range(Cells(1, CY_CUSTOMER_COLUMN), LastCell) End Function 'A function which returns a range object representing the 'current list of matched customers (Mostly so you can clear it 'before re-populating it with a new set of matches): Function CurrentMatchedCustomersRange() As Range Dim LastCell As Range 'Find the last cell in the column: Set LastCell = Cells(Rows.Count, MATCHED_CUSTOMER_COLUMN).End(xlUp) 'Return the range of cells containing currently matched customers: Set CurrentMatchedCustomersRange = Range(Cells(1, MATCHED_CUSTOMER_COLUMN), LastCell) End Function 'A Function which performs a comparison between two ranges 'and returns a Collection containing the matching cells: Function MatchedCustomers(ByVal LastYearCustomers As Range, ByVal ThisYearCustomers As Range) As Collection Dim output As Collection 'A variable to iterate over a collection of cell ranges: Dim CustomerCell As Range 'Initialize the collection object: Set output = New Collection 'Iterate over the collection of cells containing last year's customers: For Each CustomerCell In LastYearCustomers.Cells Dim MatchedCustomer As Range 'Set the variable to reference the current cell object: Set MatchedCustomer = ThisYearCustomers.Find(CustomerCell.Text) 'Test for a Match: If Not MatchedCustomer Is Nothing Then 'If found, add to the output collection: output.Add MatchedCustomer End If 'Kill the iterator variable for the next iteration: Set MatchedCustomer = Nothing Next 'Return a collection of the matches found: Set MatchedCustomers = output End Function Sub MatchCustomers() Dim LastYearCustomers As Range Dim ThisYearCustomers As Range Dim MatchedCustomers As Collection Dim MatchedCustomer As Range 'Clear out the destination column using the local function: Set MatchedCustomer = Me.CurrentMatchedCustomersRange MatchedCustomer.Clear Set MatchedCustomer = Nothing 'Use local functions to retrieve ranges: Set LastYearCustomers = Me.CustomersLastYear Set ThisYearCustomers = Me.CustomersThisYear 'Use local function to preform the matching operation and return a collection 'of cell ranges representing matched customers. Pass the ranges of last year and this year 'customers in as Arguments: Set MatchedCustomers = Me.MatchedCustomers(LastYearCustomers, ThisYearCustomers) Dim Destination As Range 'Use the local constant to set the initial output target cell: Set Destination = Range(OUTPUT_TARGET) 'Itereate over the collection and paste the matches into the output cell: For Each MatchedCustomer In MatchedCustomers MatchedCustomer.Copy Destination 'Increment the output row index after each paste operation: Set Destination = Destination.Offset(1) Next End Sub A: If you want to compare the two arrays using loops, maybe because you have, for example, picked up all the data into arrays for faster computation rather than interacting with the spreadsheet range object, or you need to compare multiple things from the two arrays to check that the entries match so can't use a .find statement, then this is what you need: -Two loops, one nested inside the other -Three counters, one for each array -One "Exit Loop", "Exit For", "GoTo foundmatch" or similar way of exiting the inner loop -A "Redim Preserve" of the results array -An "If" statement -Finally, one line where you assign the name that appears in both arrays to the results array This is everything that is needed to write it simply as loops - but doesn't give the fastest or best way to do it (Redim Preserve is not the best..). Constructing it should be easy from this list though: the if statement should either be an x=y type for a general usage, or if x>y if you are really really sure that the list being looped in the inner loop really is sorted alphabetically
{ "language": "en", "url": "https://stackoverflow.com/questions/7621598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSMutableURLRequest POST string data with URLencode, return “414 Request-URI Too Large" When I use NSMutableURLRequest to POST string data with URLencode, return “414 Request-URI Too Large”,How I can do? return error message as below: <html> <head><title>414 Request-URI Too Large</title></head> <body bgcolor="white"> <center><h1>414 Request-URI Too Large</h1></center> <hr><center>nginx/1.0.6</center> </body> </html> and I use NSMutableURLRequest Setting as below: NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[urlStr dataUsingEncoding:NSUTF8StringEncoding]]; A: urlstr cannot be both URL and POST data. You must split it at the ? or the first & into URL and POST data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to keep track of the memory usage in C? I have to do a project in C where I have to constantly allocate memory for big data structures and then free it. Does there exista a library with a function that helps to keep track of the memory usage so I can be sure if I am doing things correctly? (I'm new to C) For example, a function that returns: A) The total of memory used by the program at the moment, OR B) The total of memory left, would do the job. I already googled for that and searched in other answers. Thanks! A: Try tcmalloc: you are looking for a heap profiler, although valgrind might be more useful initially. A: Although some people excoriate it, the book "Writing Solid Code" by Steve Maguire has a lot of reasonable ideas about how to track your memory usage without modifying the system memory allocation functions. Basically, instead of calling the raw malloc() etc functions directly, you call your own memory allocation API built on top of the standard one. Your API can track allocations and frees, detect double frees, frees of non-allocated memory, unreleased (leaked) memory, complete dumps of what is allocated, etc. You either need to crib the code from the book or write your own equivalent code. One interesting problem is providing a stack trace for each allocation; there isn't a standard way to determine the call stack. (The book is a bit dated now; it was written just a few years after the C89 standard was published and does not exploit const qualifiers.) Some will argue that these services can be provided by the system malloc(); indeed, they can, and these days often are. You should look carefully at the manual provided for your version of malloc(), and decide whether it provides enough for you. If not, then the wrapper API mechanism is reasonable. Note that using your own API means you track what you explicitly allocate, while leaving library functions not written to use your API using the system services - as, indeed, does your code, under the covers. You should also look into valgrind. It does a superb job tracking memory abuses, and in particular will report leaked memory (memory that was allocated but not freed). It also spots when you read or write outside the bounds of an allocated space, spotting buffer overflows. Nevertheless, ultimately, you need to be disciplined in the way you write your code, ensuring that every time you allocate memory, you know when it will be released. A: If you're worried about memory leaks, valgrind is probably what you need. On the other hand, if you're more concerned just with whether you're data structures are using excessive memory, you might just use the common mallinfo function included as an extension to malloc in many unix standard libraries including glibc on Linux. A: Every time you allocate/free memory, you could log how big your data structure is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }