text
stringlengths
8
267k
meta
dict
Q: Copy/paste menu translation into swedish content in UISearchBar I am building an application for a Swedish client. We didnt do any changes to the project setup and developed the application in xcode. The client is right now coming back and pointing that the "copy / paste" dialog box that comes up in the UISearchBar is also in English. They want this to be in Swedish. Can you please let me know on where this change/ setting needs to be implemented?
{ "language": "en", "url": "https://stackoverflow.com/questions/7511654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error in styles.xml I've placed a styles.xml file in res/values folder and it gives me this error. error: Error retrieving parent for item: No resource found that matches the given name 'Widget'. Here is my code; <resources> <style name="Widget.SeekBar"> <item name="android:indeterminateOnly">false</item> <item name="android:progressDrawable">@+android:drawable/bar1</item> <item name="android:indeterminateDrawable">@+ndroid:drawable/bar2</item> <item name="android:minHeight">5dip</item> <item name="android:maxHeight">5dip</item> <item name="android:thumb">@+android:drawable/scroll1</item> <item name="android:thumbOffset">8px</item> <item name="android:focusable">true</item> </style> the error occurs on the line == style name="Widget.SeekBar" Could you help me please? A: its shold be like this you need parent Widget than you can put child of it. needed first. <?xml version="1.0" encoding="utf-8"?> <resources> <style name="Widget"></style><style name="Widget.SeekBar"> <item name="android:indeterminateOnly">false</item> <item name="android:progressDrawable">@drawable/bar1</item> <item name="android:indeterminateDrawable">@drawable/bar2</item> <item name="android:minHeight">5dip</item> <item name="android:maxHeight">5dip</item> <item name="android:thumb">@+android:drawable/scroll1</item> <item name="android:thumbOffset">8px</item> <item name="android:focusable">true</item> </style> </resources> A: <item name="android:indeterminateDrawable">@+ndroid:drawable/bar2</item> should read <item name="android:indeterminateDrawable">@+android:drawable/bar2</item>
{ "language": "en", "url": "https://stackoverflow.com/questions/7511656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is packet forwarding possible on Android? Our requirement is to develop an Android App &/or service that does the following. Listen to http (port 80) requests/packets sent from the device (by any app). forward them to a different server and not to the host that they are meant to go to. Can someones please indicate whether this is possible and if yes, then how? A: As android is a Linux system you might want to check redirection by using its iptables. However I assume that you might need root rights to do so. A: It's possible on android versions 4.0 or greater with VPNService. Have a look at the ToyVpn example provided by google. It's not nice for the user as they get a popup and a constant icon on the notification bar, but it's possible. If you only want port 80 you will have to decode the ip and tcp headers in your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: fb:comments scrollable under a fixed footer on iOS? We are building a small web page that lives in a UIWebView in an iPad app. This webview has a fixed footer at the bottom and a scrollable div in the middle. Up until now we had a good solution for this, using iscroll4 to scroll the div. When that div contained only text and images, iscroll worked like a charm. But when we add a fb:comments tag into that scrollable div, bad things happen. We've tried a number of different scrolling and/or fixed-position libraries including iscroll4, touch-scroll, and scrollability. None of them seem to work with fb:comments. The most common symptom is that any portion of the fb:comments that was below the original portion of the scrolling area does not show, even when scrolled into view. It's like the iframe size is fixed at the time FB expands fb:comments. If this is a correct analysis, how can I get the iFrame to expand out to whatever size it wants? Or, other suggestions as to what could be going wrong? I feel quite hamstrung as this is running in an iPad app in a UIWebView, and I have no handy developer tools like I do on Chrome (where the problem does not manifest). Mike
{ "language": "en", "url": "https://stackoverflow.com/questions/7511662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can obj.__dict__ be inspected if the class has a __dict__ variable? I am interested in whether there is a way to introspect a Python instance infallibly to see its __dict__ despite any obstacles that the programmer might have thrown in the way, because that would help me debug problems like unintended reference loops and dangling resources like open files. A simpler example is: how can I see the keys of a dict subclass if the programmer has hidden keys() behind a class of its own? The way around that is to manually call the dict keys() method instead of letting inheritance call the subclass's version of the method: # Simple example of getting to the real info # about an instance class KeyHidingDict(dict): def keys(self): return [] # there are no keys here! khd = KeyHidingDict(a=1, b=2, c=3) khd.keys() # drat, returns [] dict.keys(khd) # aha! returns ['a', 'b', 'c'] Now my actual question is, how can I see the __dict__ of an instance, no matter what the programmer might have done to hide it from me? If they set a __dict__ class variable then it seems to shadow the actual __dict__ of any objects inherited from that class: # My actual question class DunderDictHider(object): __dict__ = {'fake': 'dict'} ddh = DunderDictHider() ddh.a = 1 ddh.b = 2 print ddh.a # prints out 1 print ddh.__dict__ # drat, prints {'fake': 'dict'} This false value for __dict__ does not, as you can see, interfere with actual attribute setting and getting, but it does mislead dir() by hiding a and b and displaying fake as the object's instance variable instead. Again, my goal is to write a tool that helps me introspect class instances to see “what is really going on” when I am wondering why a set of class instances is taking so much memory or holding so many files open — and even though the situation above is extremely contrived, finding a way around it would let the tool work all the time instead of saying “works great, unless the class you are looking at has… [description of the exceptional situation above].” I had thought I would be able to infallibly grab the __dict__ with something like: dict_descr = object.__dict__['__dict__'] print dict_descr(ddh, DunderDictHider) But it turns out that object does not have a __dict__ descriptor. Instead, the subtype_dict() C function seems to get separately attached to each subclass of object that the programmer creates; there is no central way to name or fetch the descriptor so that it can be manually applied to objects whose class shadows it. Any ideas, anyone? :) A: I'm not sure I'm happy with how simple this is: >>> class DunderDictHider(object): ... __dict__ = {'fake': 'dict'} ... >>> ddh = DunderDictHider() >>> ddh.a = 1 >>> ddh.b = 2 >>> >>> print ddh.a 1 >>> print ddh.__dict__ {'fake': 'dict'} The problem is that the class is cheating? Fix that! >>> class DictUnhider(object): ... pass ... >>> ddh.__class__ = DictUnhider >>> print ddh.a 1 >>> print ddh.__dict__ {'a': 1, 'b': 2} And there it is. This completely fails though, if the class defines any slots. >>> class DoesntHaveDict(object): ... __slots__ = ['a', 'b'] ... >>> dhd = DoesntHaveDict() >>> dhd.a = 1 >>> dhd.b = 2 >>> >>> print dhd.a 1 >>> dhd.__class__ = DictUnhider Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __class__ assignment: 'DoesntHaveDict' object layout differs from 'DictUnhider' >>> A: This one is based on Jerub answer in this topic: What is a metaclass in Python? You can achieve what you're looking for with metaclasses. First you need to create a metaclass: def test_metaclass(name, bases, dict): print 'The Class Name is', name print 'The Class Bases are', bases print 'The dict has', len(dict), 'elems, the keys are', dict.keys() return dict of course the prints are not necessery. Then let me introduce your new DunderDictHider: class DunderDictHider(object): __metaclass__ = test_metaclass __dict__ = {'fake': 'dict'} Now you have access to all initialized elems by repr(DunderDictHider) The output (with print repr(DunderDictHider) line): The Class Name is DunderDictHider The Class Bases are (<type 'object'>,) The dict has 3 elems, the keys are ['__dict__', '__module__', '__metaclass__'] {'__dict__': {'fake': 'dict'}, '__module__': '__main__', '__metaclass__': <function test_metaclass at 0x1001df758>} Each time you can try if '__dict__' in repr(DunderDictHider) to know whether this class tries to hide its __dict__ or not. Remember, that repr output is a string. It can be done better, but that's the idea itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: iOS >> UILabel: How to Create Lines Separator Relating to Words Count I use a UILabel that is defined in IB as including 2 lines The text itself is coming from the code: [self.myUILabel setText:[someDictionaryThatHoldsNSStrings objectForKey:someDictionaryKey]]; There are always 4 words in the string; I want to make sure that in any case there will always be 2 words in the first line and 2 words in the second line but using Word Wrap doesn't do the trick since the length of the word is deferent depending on the strings. How do I define that the UILabel will always hold 2 words in the first line and 2 words in the second line? A: Instead of trying to find the length of the words and finding the size for the words, you can add a newline(\n) character after the two words and display it in the label without altering the label's size or lineBreakMode. - (NSString *)formatSentenceIntoTwoLines:(NSString *)sentence { sentence = [sentence stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSArray *words = [sentence componentsSeparatedByString:@" "]; NSString *word_1 = [words objectAtIndex:0]; NSString *word_2 = [words objectAtIndex:1]; NSString *word_3 = [words objectAtIndex:2]; NSString *word_4 = [words objectAtIndex:3]; NSString *firstTwoWords = [word_1 stringByAppendingFormat:@" %@", word_2]; NSString *lastTwoWords = [word_3 stringByAppendingFormat:@" %@", word_4]; NSString *formattedSentence = [firstTwoWords stringByAppendingFormat:@"\n%@", lastTwoWords]; return formattedSentence; } Use the above method to format the string. The code seems too big. I write it in this way just to make it understandable. You can still simplify it as you want. And make sure the numberOfLines of label set to 2(label will show only two lines) or 0(for dynamic number of lines). label.numberOfLines = 2; // 0 if there is going to be dynamic number of lines A: Try putting a line break between the second and third word. Make sure to checkout this post because sometimes there are some problems getting the label to recognize the line break based on the source of the string. Another simple option would be to use two UILabels, one for the first two words and a second placed underneath it for the next two words. A: I think this post could help you, for breaking lines : How to add line break for UILabel? And this one could help you if you want to count words (maybe in case your string is obtained dynamically) : What is the most efficient way to count number of word in NSString without using regex? You should set the numberOfLines property of your UILabel to 0. (unlimited number of lines). After that, I think you should count the words in your NSString (with NSScanner or this method), and add a "\n" character dynamically after the second word. Hope this helps, Jérémy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checksum function is depended on Unicode? if its in unicode so the results : ( notice the N ) select CHECKSUM(N'2Volvo Director 20') ---341465450 select CHECKSUM(N'3Volvo Director 30') ---341453853 select CHECKSUM(N'4Volvo Director 40') ---341455363 but if its regular : select CHECKSUM('2Volvo Director 20') ---1757834048 select CHECKSUM('3Volvo Director 30') ---1757834048 select CHECKSUM('4Volvo Director 40') ---1757834048 Can you please explain me why in the first situation - it gives me different and in the second it gives me the same ? there is a lead article about it which says : However the CHECKSUM() function evaluates the type as well as compares the two strings and if they are equal, then only the same value is returned. A: This seems to be collation dependant. DECLARE @T TABLE ( SQL_Latin1_General_CP1255_CI_AS varchar(100) COLLATE SQL_Latin1_General_CP1255_CI_AS, Latin1_General_CI_AS varchar(100) COLLATE Latin1_General_CI_AS ) INSERT INTO @T SELECT '2Volvo Director 20','2Volvo Director 20' UNION ALL SELECT '3Volvo Director 30','3Volvo Director 30' UNION ALL SELECT '4Volvo Director 40','4Volvo Director 40' UNION ALL SELECT '5Volvo Director 50','5Volvo Director 50' UNION ALL SELECT '6Volvo Director 60','6Volvo Director 60' SELECT CHECKSUM(SQL_Latin1_General_CP1255_CI_AS) AS SQL_Latin1_General_CP1255_CI_AS, CHECKSUM(Latin1_General_CI_AS) AS Latin1_General_CI_AS FROM @T Returns SQL_Latin1_General_CP1255_CI_A Latin1_General_CI_AS ------------------------------ -------------------- -1757834048 -341465450 -1757834048 -341453853 -1757834048 -341455363 -1757834048 -341442609 -1757834048 -341448488 CHECKSUM is documented as being more collision prone than HashBytes. I'm not sure specifically why the CP collation has this behaviour for these inputs though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to sort my objects list by date which is returned from server by a ajax call I send an Ajax call to server, then server returns me the xml data which contain a list of objects. Each object in the list contain a "date" attribute. In the success function of the Ajax call, I would like to populate each object in a row of a html table, but before this, I would like to sort the objects by date ascending order based on the "date" attribute of each object. I am wondering what is the efficient way to do this? $.ajax({ type : "GET", url : MY_URL_1, dataType : "xml", success : function(xml) { $(xml).find("DOCUMENT").each(function() { var eachXMLdata = $(this); var date = eachXMLdata.children("DATE").text(); // I can check each object's date here console.log('date:'+date); /*** How to sort the object by date??****/ //I will show each object in a row of a html table here // ... }); } }); As you saw above, I used the .each() function in Ajax success() function to loop through each object and will show each object in a row of a html table. A: Well , If you do have to do it on client side , construct Date objects with the text , and then you can the getTime() function to get the milliseconds since epoch , which should be easily comaparable . Refer below for the Date object API http://www.w3schools.com/jsref/jsref_obj_date.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7511691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSSavePanel, CGImageDestinationFinalize and OS X sandbox I'm using NSSavePanel to let user select image to save to in my app. Everything worked fine until I enabled app sandboxing and entitlements. The problem occurs with selection of an already existing file. My code is like this: // Create a URL to our file destination and a CGImageDestination to save to. CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((CFURLRef)[savePanel URL], (CFStringRef)newUTType, 1, NULL); CGImageDestinationAddImage(imageDestination, cgimage, (CFDictionaryRef)metaData); const bool result = CGImageDestinationFinalize(imageDestination); It works when selecting new file to save the image, but when I select existing file it creates strange named file besides existing file and fails to overwrite the contents of destination url. And even worse, I get no error in return and cannot detect the failure. Is this a bug in CoreGraphics or in my code? Is there any workaround for this issue? A: Finally I have discovered combination of core graphics calls to overwrite an already existing image working in sandboxed environment: CGDataConsumerCreateWithURL followed by CGImageDestinationCreateWithDataConsumer. So it seems CGImageDestinationCreateWithURL is broken (at least in OS X Lion 10.7.1) with sandbox enabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect j2me mobile device screen orientation at LWUIT? I want to know how to detect screen orientation like portrait or landscape mode at J2ME LWUIT. Can LWUIT detect screen orientation automatically or need to write code manually? A: Shai Almog said this in the forum, talking about screen orientation Shai Almog said... We don't explicitly support orientation, the phone sends an event of screen size change and it supports orientation for us. we know the size has changed but we don't know the orientation has changed. The developer can't control orientation changes since this is done automatically based on events to the canvas. http://lwuit.blogspot.com/2008/05/new-video-from-chen-of-lwuit-on-devices.html I think it can help you. I am developing an app with LWUIT now, using the LWUIT resource editor, and the screen orientation is detected automatically. Anyway you must look for Display in API http://lwuit.java.net/nonav/iodocs/index.html, there are some methods that you can use for the orientation, like Display.canForceOrientation() or Display.lockOrientation(). A: What about Display.getInstance().isPortrait()
{ "language": "en", "url": "https://stackoverflow.com/questions/7511697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to verify that code reviewed patch file is exactly what is committed into SVN repository We have a code review process in place where a developer sends out a patch file with his changes to the team. After reviewing it, he is instructed to commit or make changes and resend. How can we ensure that what has been "committed" is exactly what has been "approved" - i.e., if he makes subsequent changes without approval and commits those, how can I detect those? I have the original 'patch file' at my end, but: * *How can I 'generate' something similar between the two committed versions and *Is it viable to compare those two files? A: The easiest way is that The reviewer commit the changes he approved. I've seen some old fashion team (a while ago) where only the project manager could commit to production repository. The thing is, as he has to commit too much stuff he didn't really check anything so that was a bit pointless. A: The simplest solution would be to put such patches to a branch which mean the developer will check in the code on the branch. Than a reviewer can check the code and merge the code back to a particular integration line. This makes sure the code checked in is exactly what has been checked. Furthermore this approach has the advanctage the suggestion which have been made will be documented in the version control as well. A: Reviewer should be a committer as well to make sure he commits the same he reviewed and approved. A: I am guessing you could do this by applying the patch on the old revision and then comparing the same against the latest version of code for difference. You could use svn diff for this. You probably wanna take a look at this answer: How to make svn diff produce file that patch would apply, when svn cp or svn mv was used?
{ "language": "en", "url": "https://stackoverflow.com/questions/7511703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: return product price using LINQ, what return type to use in function? I'm just getting started with LINQ and I'm trying to select and return a product price from database, like so: public int GetPricePerKg(Product prod) { var result = from p in dc.Products where p.pk_product_id == prod.pk_product_id select p.product_price_kg; return result; } This gives me the error: Cannot implicitly convert type 'System.Linq.IQueryable<int?>' to 'int' What's the best way to handle this? I need the price (which is an int in this case) and do some calculations with it in another place A: Well, you've selected a query - that could in theory match 0, 1 or more records. What do you want to do in each situation? Also, it looks like product_price_kg is int? - what do you want to do if it's null? You might want: public int GetPricePerKg(Product prod) { return dc.Products.Where(p => p.pk_product_id == prod.pk_product_id) .Select(p => p.product_price_kg) .Single() .Value; } ... but that will throw an exception if either there isn't exactly one matching product or the price property is null. You can still use a query expression if you want - but I tend not to for simple cases where you then want to add a method call at the end. The query expression equivalent is: return (from p in dc.Products where p.pk_product_id == prod.pk_product_id select p.product_price_kg).Single().Value; Alternatively, you can use the version of Single() which takes a predicate, like this: return dc.Products.Single(p => p.pk_product_id == prod.pk_product_id) .product_price_kg.Value; There are no doubt other variations - they'll all do the same thing - pick whichever one you find most readable. EDIT: Other options instead of Single are: * *First (cope with 1 or more) *FirstOrDefault (cope with 0, 1 or more) *SingleOrDefault (cope with 0 or 1) For the OrDefault versions you'd need to work out what to do if you didn't match any products. A: you need to do (if you only want the first match back) public int GetPricePerKg(Product prod) { var result = (from p in dc.Products where p.pk_product_id == prod.pk_product_id select p.product_price_kg).FirstOrDefault(); return result; } A: Both John Skeet and saj are right in their answers. Here's just another alternate syntax more in line with the code you posted: public int GetPricePerKg(Product prod) { var result = from p in dc.Products where p.pk_product_id == prod.pk_product_id select p.product_price_kg; return result.FirstOrDefault(); } A: you have to use FristOrDefault() extension method public int GetPricePerKg(Product prod) { var result = (from p in dc.Products where p.pk_product_id == prod.pk_product_id select p.product_price_kg).FirstOrDefault(); return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQLite password is available in memory using ADO.Net I have a .net 4.0 app that connects to an encrypted SQLite database via the ADO driver. Something I have noticed is that when connecting the connection string and thus database password is available to view in memory, meaning that users can in fact find out of the database password. Has anybody out there had any experience with this? found a workaround or fix? Thanks for your time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Microsoft Access Does not return Values I have written a program to save attendance of employees.The database engine is MS Access. when I execute a query form the C# program using Data-Adapter it does not return values, but when I'm executing the same query in Access it gives results. I have used one table join in the query OdbcConnection conn = new OdbcConnection(Variables.ConnectionString); conn.ConnectionTimeout = 50; if (conn.State != ConnectionState.Open) conn.Open(); string query = "SELECT l.matchine_number, e.actual_emp_number, e.user_name, e.location_name, l.date_time FROM tbl_log l " + "RIGHT OUTER JOIN tbl_enroled_users AS e ON e.enroled_emp_number = l.enroled_number " + "WHERE " + "l.matchine_number LIKE '*" + txtMatchineNumber.Text + "*' AND " + "e.actual_emp_number LIKE '*" + txtEmpNumber.Text + "*' AND " + "e.user_name LIKE '*" + txtName.Text + "*' AND " + "e.location_name LIKE '*" + txtLocation.Text + "*' AND " + "l.date_time >= #" + dtFrom.Value.ToString("M/d/yyyy") + " 12:00:00 AM# AND " + "l.date_time <= #" + dtTo.Value.ToString("M/d/yyyy") + " 11:59:59 PM# " + "ORDER BY l.matchine_number, e.actual_emp_number, e.user_name, e.location_name, l.date_time"; OdbcDataAdapter adptr = new OdbcDataAdapter(query, conn); DataTable dt = new DataTable(); adptr.Fill(dt); if (conn.State != ConnectionState.Closed) conn.Close(); Please Help A: Try first with a simple query like SELECT l.date_time FROM tbl_log l; to see if your connection is right, if this works then something is wrong with your query. A: without any error-messages or the generated query-string it's just guessing. but my idea is that the wildcards you're using are not correctly interpreted. Try to change * into % and see if it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: create new project using appfuse i use following command in http://appfuse.org/display/APF/AppFuse+QuickStart mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes -DarchetypeArtifactId=appfuse-basic-struts-archetype -DarchetypeVersion=2.1.0 -DgroupId=com.mycompany -DartifactId=myproject -DarchetypeRepository=http://oss.sonatype.org/content/repositories/appfuse it gives me error Required goal not found: archetype:generate in org.apache.maven.plugins:maven-archetype-plugin:1.0-alpha-7 I need some help to create new project using appfuse thanks A: use -U parameter in command line
{ "language": "en", "url": "https://stackoverflow.com/questions/7511713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to trim few bytes of a byte array? I have a long byte array. I need to eliminate the initial 16 bytes. Is there a shortcut do it? A: Check out Array.Copy For example: var array = //initialization int bytesToEliminate = 16; int newLength = array.Length - bytesToEliminate; //you may need to check if this positive var newArray = new byte[newLength]; Array.Copy(array, bytesToEliminate, newArray, 0, newLength); A: This is not the most efficient thing, but will do the trick: // using System.Linq; long[] array = ...; long[] newArray = array.Skip(16).ToArray();
{ "language": "en", "url": "https://stackoverflow.com/questions/7511714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Call to iterating object from iterator How can I call for iterating object from iterating block? # "self" is an Object, and not an iterating object I need. MyClass.some.method.chain.inject{|mean, i| (mean+=i)/self.size} I mean I need to do this: @my_object = MyClass.some.method.chain @my_object.inject{|mean, i| (mean+=i)/@my_object.size} A: This answer is a copy of James Kyburz's answer to a similar question There is no this in ruby the nearest thing is self. Here are some examples to help you on your way #example 1 not self needed numbers is the array numbers = [1, 2, 3] numbers.reduce(:+).to_f / numbers.size # example 2 using tap which gives access to self and returns self # hence why total variable is needed total = 0 [1, 2, 3].tap {|a| total = a.reduce(:+).to_f / a.size } # instance_eval hack which accesses self, and the block after do is an expression # can return the average without an extra variable [1, 2, 3].instance_eval { self.reduce(:+).to_f / self.size } # => 2.0 So far I prefer example 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7511716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with "NOT IN" in a simple SQL query I need to find all id's from the OldTable that doesn't exist in the NewTable Why won't this query find the id? SELECT old_id FROM OldTable WHERE old_id NOT IN ( SELECT id FROM NewTable) By them selves they return this --Returns the id 18571 SELECT old_id FROM OldTable WHERE old_id = 18571 --Returns nothing SELECT id FROM NewTable WHERE id = 18571 Am I missing something obvious here? Both columns are of type int and primary keys. SOLVED The id column had null's in them, I was just being ignorant =/ These works: SELECT old_id FROM OldTable EXCEPT SELECT id FROM NewTable SELECT * FROM old_table ot WHERE NOT EXISTS ( SELECT * FROM new_table nt WHERE nt.id = ot.old_id) These doesn't work: SELECT old_id FROM OldTable LEFT JOIN NewTable ON old_id = id WHERE id IS NULL SELECT old_id FROM OldTable WHERE old_id NOT IN ( SELECT id FROM NewTable) A: SELECT * FROM old_table ot WHERE NOT EXISTS ( SELECT * FROM new_table nt WHERE nt.new_key = ot.old_key ); A: The difference can be attributed to the presence of nulls. Consider these two simplified queries, noting the predicate for both is NULL = 1 which evaluates to UNKNOWN which is handled differently by NOT EXISTS and NOT IN respectively: SELECT * FROM OldTable WHERE NULL NOT IN (SELECT 1 FROM OldTable); SELECT * FROM OldTable WHERE NOT EXISTS (SELECT * FROM OldTable WHERE NULL = 1); The first returns no rows because NOT IN (subquery) evaluated to FALSE. The first returns all rows because NOT EXISTS (subquery) evaluated to TRUE. Conclusion: avoid nulls. A: I don't know why your query doesn't give you the desired result, but I do know that using NOT IN is not very efficient. You would be better of using a joins: SELECT old_id FROM OldTable LEFT JOIN NewTable ON old_id = id WHERE id IS NULL A: SELECT old_id FROM OLDTable WHERE id not in (SELECT id from NewTable); You are using old_id in where condition in the first query and you are using id in second query A: select oldtable.id as orginal, newtable.id as new from oldtable left outer join newtable on oldtable.id =newtable.id where new is null AFAIK (and i am not an expert - check my rep ;-) left outer join is a good technique for this.. it will may perform a not in and does not require a sub-select @onedaywhen kindly points out that this is not always the case e.g. in SQL Server EXISTS() can be more efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Converting ArrayList to String and converted String back to ArrayList I am in a situation where I need to send the arraylist in the network but I need to convert it in the form of string. Now at the destination I want to convert this String to ArrayList to access the individual elements. Please tell me how I can convert the converted String(from ArrayList) back to ArrayList. A: ArrayList of what? If the elements are strings or integers - simply join them using some unique separator and split back to array on the other side. If you want to send an ArrayList of arbitrary Serializable objects, you will have to serialize it, e.g. using Java serialization. However this will produce byte[] array rather than a String. If you are constrained to text protocol, you would then gonna have to use Base64 encoding or similar. A: That depends on whether it is possible to provide an exact string representation of the objects in your array list. The next question would be: why does it need to be a string represenation of the arraylist? That said, if it really needs to be a string representation, JSON might help you, i.e. you convert the array list to a JSON represenation and back. There are a multitude of JSON frameworks out there like GSON, JSON-simple etc. A: private string ArrayListToString(System.Collections.ArrayList list) { string CStr = ""; foreach (string str in list) { CStr += str; CStr += "<b>"; } return CStr; } private System.Collections.ArrayList ArrayListToString(string CStr) { System.Collections.ArrayList list = new System.Collections.ArrayList(); string[] seperator = { "<b>" }; string[] words = CStr.Split(seperator, StringSplitOptions.RemoveEmptyEntries); foreach (string str in words) { list.Add(str); } return list; } A: I would rather not use program language specified binary serialization. Will get stuck by some versioning problem future. You can use JSON format, use JSONArray.toString and JSONArray.fromObject(String) for serial/deserial If you need performance on speed and space, I suggest Google Protocol Buffers , it is a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats. Protocol buffers have many advantages over XML for serializing structured data. Protocol buffers: * are simpler * are 3 to 10 times smaller * are 20 to 100 times faster * are less ambiguous * generate data access classes that are easier to use programmatically
{ "language": "en", "url": "https://stackoverflow.com/questions/7511719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS one month free, than subscription only I am developing news reader app, and client wants to have monthly subscription. This is easy enough, but he wishes to have one month of free trial for each user. So after user downloads app for the first time, he has one month of free use and after that period, he has to pay subscription fee (auto renewable subscription). I am stuck on how to implement this. Any ideas? Preferably without need to connect to my server and handle user registrations and trials from there. Thanks! A: If you handle in on the client side, then whatever scheme you manage to design, the user can restart with a new free trial period very easily: s/he only has to delete and reinstall the app. Since this will erases any local app data, you won't have any way to know whether s/he has already use the trial offer. You will have to handle that server side. A: When you select Auto-Renewable Subscriptions you'll add Duration Information. When you adding duration set Offer a marketing opt-in incentive? option to YES. You'll get Option Box for how many days or months or year you want subscription. Check this free subscription answer here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Setting a button's size according to a dynamic custom view's size * *CalendarBackground is a custom view which implements onDraw() and onMeasure(). Its size is dynamic, calculated in onMeasure(). *CalendarView is another custom view which extends the following RelativeLayout. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <lc.test.CalendarBackground android:id="@+id/calBg" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/prevMonth" android:text="@string/prev_month" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout> *The button prevMonth's position & size should be decided by CalendarBackground, so I need to change its size after CalendarBackground.onMeasure() is invoked. I know how to change a button's size by setting its LayoutParams pragmatically, but I don't know where should I put these codes? It cannot be in CalendarView's constructor, because the code there is invoked before CalendarBackground.onMeasure()... Thanks a lot! As I cannot answer my own question, I put the answer here: I got it. Override the onLayout method of the CalendarView class, and set the button's size there. This is the code of CalendarBackground.onMaesure: @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //Get canvas width and height wCalendar = MeasureSpec.getSize(widthMeasureSpec); hCalendar = 7*MeasureSpec.getSize(heightMeasureSpec)/10; setMeasuredDimension(wCalendar, hCalendar); } This is code of CalendarView.onLayout: @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(prevMonth.getLayoutParams()); lp.width = (right - left)/7; lp.height = (bottom - top)/7; prevMonth.setLayoutParams(lp); } The result is exactly what I want. This onLayout is invoked after CalendarBackground.onMeasure(). However, I observed another question. That is the execution sequence: 4 times CanlendarBackground.onMaesure(), then CalendarView.onLayout(), then another 4 times CanlendarBackground.onMaesure(), then another CalendarView.onLayout(), then CanlendarBackground.onDraw(). Is there anything wrong with my code? I mean this sequence doesn't make sense. CanlendarBackground.onMaesure() is invoked 8 times, and CalendarView.onLayout() is invoke 2 times, although the execution result is what I want. A: There is size interdependence. Therefore depending on the device the size of the view will change. You have to modify the android manifest file for that. Have a look at developers.android... website
{ "language": "en", "url": "https://stackoverflow.com/questions/7511726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ advanced feature for non-cpu hardware in the blog of renderscript http://android-developers.blogspot.com/2011/03/renderscript.html it has mentioned that The advanced C++ features are very difficult to run on non-cpu hardware. so I would like to ask what are the 'advanced features' that this paragraph refers to ? thanks A: I'd consider two things hard: virtual functions, and exceptions. These affect program flow in a complex way. GPU's are rather simple in that respect, they don't even like branches. Note that function pointers are also hard, and you do have those in C. In fact, you'd have more of them: qsort() needs a function pointer, but std::sort doesn't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with date('Y-m-d H:i:s',$usr_profile->getCreatedAt()) getting error? i am trying to parse my MYSQL date in to the format Y-m-d H:i:s and get error: //theses lines ok echo $now = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME'])."<br/>"; echo $nowday = date('d',$_SERVER['REQUEST_TIME'])."<br/>"; echo $nowmonth = date('m',$_SERVER['REQUEST_TIME'])."<br/>"; echo $userdate = $usr_profile->getCreatedAt()."<br/>"; echo $newdate = date('Y-m-d H:i:s',$userdate)."<br/>"; //line 67 error echo $usermonth = date('m',$newdate)."<br/>"; //line 68 error 2011-01-21 08:44:07 Notice: A non well formed numeric value encountered in /home/helloises/github_mira/rainbow_code/phoenix/plugins/rainbowCodePlugin/modules/profile/templates/homeSuccess.php on line 67 1970-01-01 00:33:31 Notice: A non well formed numeric value encountered in /home/helloises/github_mira/rainbow_code/phoenix/plugins/rainbowCodePlugin/modules/profile/templates/homeSuccess.php on line 68 01 i dont understand... i need to check if the difference between two dates (now and userdate) is greater than 24 hours i tried a few things like strtotime, create_date,format_date, DateTime() but to now avail please help? thank you A: You could try wrapping $newdate in strtotime: $newdate = date('Y-m-d H:i:s', strtotime($userdate))."<br/>"
{ "language": "en", "url": "https://stackoverflow.com/questions/7511737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'Using' must end with a matching 'End Using' i am trying to use a Html.RenderPartial but getting an error: 'Using' must end with a matching 'End Using'. View: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<mvc2Test.Models.Employee>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Create </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Create</h2> <% Html.RenderPartial("ViewUserControl1"); %> </asp:Content> Partial View: <% using (Html.BeginForm()) {%> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%: Html.LabelFor(model => model.EmployeeID) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.EmployeeID) %> <%: Html.ValidationMessageFor(model => model.EmployeeID) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.NationalIDNumber) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.NationalIDNumber) %> <%: Html.ValidationMessageFor(model => model.NationalIDNumber) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.ModifiedDate) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.ModifiedDate, String.Format("{0:g}", Model.ModifiedDate)) %> <%: Html.ValidationMessageFor(model => model.ModifiedDate) %> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> A: The error message suggests that the code is parsed as VB, rather than C#. Did you perhaps accidentally specify a wrong language for the partial view? A: i got it i forgot to put this line of code on top of the view: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<mvc2Test.Models.Employee>" %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7511744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is best practice for global error/exception handling in ASP.NET MVC? I've seen two methods of implementing global error handling in an ASP.NET MVC 3 application. One method is via the Application_Error method in Global.asax.cs. For example (Error Handling in global.asax): public class SomeWebApplication : System.Web.HttpApplication { // ... other methods ... protected void Application_Error() { // ... application error handling code ... } } The other method is via a [HandleError] action filter attribute registered in the RegisterGlobalFilters method, again in Global.asax.cs. Which is the better way to approach this? Are there any significant disadvantages to either approach? A: [HandleError] is the way to go since it keeps everything simple and responsibility is clear. This action filter is a specific ASP.NET MVC feature and therefore is the official way of handling errors. It's also quite easy to override the filter to add custom functionality. Application_Error is the old way to do it and doesn't really belong in MVC. The [HandleError] attribute works fine as long as you remember to tag your controllers (or the base controller) with it. Update: Created a blog entry: http://blog.gauffin.org/2011/11/how-to-handle-errors-in-asp-net-mvc/
{ "language": "en", "url": "https://stackoverflow.com/questions/7511752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Issue with toggling dd Currently I’m using dt and dd to display some data. What I’m doing here is initially set the dd to display: none and when the dt is clicked display the associate dd. My HTML markup is <dt > <h1>click here</h1> </dt> <dd style="display: none;"> <h1> DD Data </h1> </dd> <dt > <h1>click here</h1> </dt> <dd style="display: none;"> <h1> DD Data </h1> </dd> jQuery I'm using is $('dt').live('click', function () { var dd = $(this).next(); if (!dd.is(':animated')) { dd.slideToggle(); $(this).toggleClass('opened'); } What I want to do now is to allow one dd to display at a time. When if there is one dd is displaying and if another dt is clicked, i want to close the currently opened dd and display the dd which associate with the clicked dt. Any help will be appreciate A: You could do: $('dt').live('click', function () { var nextDD = $(this).next('dd'); $('dd').hide(); nextDD.show(); }); Fiddle here: http://jsfiddle.net/ktYgB/ A: $('dt').live('click', function () { var dl = $(this).closest('dl'); var dd = $(this).next(); if (!dd.is(':animated')) { $('dd', dl).hide(); // hide all dd's first dd.slideToggle(); $(this).toggleClass('opened'); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7511753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Join between different data types In a particular scenario I have a lookup table with MachineNumber (Varchar) and its MachineID (Int). In my transaction table I refer to the Machine number using lookup table's MachineID. Requirement: Can I have the MachineID field type set as Varchar in the transaction table whereas retaining its type as Int in the lookup table? Reason, for some Machines the MachinNumber is not stored in the Lookup table and I need to store the actual MachineNumber provided by the user in the Transaction table itself and as the Machine number is alphanumeric I want to change the type of this referenced field from Int to Varchar. In a nutshell in the transaction table the MachineID field should contain both MachineID (referenced from the lookup table) and actual Machine Number (provided by the user and stored directly here) Question: Is it a good practice to have different types for these referenced fields or is it a common practice, what will be the effect on the queries with Join between these two tables? Thanks, Alind A: As a general rule, using natural data as the key is preferred, if of course you it is guaranteed to be present and unique in all cases. In your case, if you can use the actual machine id (varchar), then do so, and make that the key for your lookups etc. I will add that I once worked for a company that had EFTPOS terminals transacting with our server. We decided to use the convenient unique EFTPOS terminal ID, but we had problem when they broke down and were swapped out by a repair guy from the bank. The new terminal had a different ID, but to use was "the same" terminal. Our problems were compounded when the terminal was repaired and put back into the field at another client location - with the same original terminal id! This initially caused us no end of hassle. We ended up using an artificial id, and sotred the current physical terminal id as an attribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange warning behavior with gcc and signed/unsigned comparisons I have the following code : unsigned int a; if (a > numeric_limits<int>::max()) do_stuff(); When compiling, gcc complains about warning: "comparison between signed and unsigned" OK, I understand But, with the following code : unsigned int a; if (a > (numeric_limits<int>::max())) do_stuff(); The warning is no longer displayed and I really don't know why... Is there any logical reason for such a behavior or am I doing something wrong?! A: It's because it is a bug. See bug 50012 A: I do not currently have access to a C++ compiler to test this, but I think this might work without any warnings: unsigned int a; if (a > numeric_limits<unsigned int>::max()) do_stuff(); A: The answer lies in the way gcc handles int and unsigned int. unsigned int and int both store a 2 byte value. The difference between them is that unsigned int does not support negative values. It can only store values from 0-65,535. When GCC sees a comparison between int and unsigned int it converts the int to a positive number. e.g if the value of the int is -2 it will convert it to 2. But if the int is preceded by the () operator . (int). GCC interprets it as a positive number (but still converts it) and doesn't give a warning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to call derived class virtual method? I created these classes: public abstract class Node { public virtual NodeModel CreateModel() { throw new NotImplementedException(); } } public class Folder : Node { public virtual FolderModel CreateModel() { // Implementation } } public class Item : Node { public virtual ItemModel CreateModel() { // Implementation } } Then in my program I have a List of Node which only contains Item and Folder objects. When I loop on the list and try to call the CreateModel() method, this is always the Node class method which is called (therefore throwing the exception). I cannot change CreateModel() to abstract as the return type is different depending on the derived type. I was wondering if it is possible to have a different return type. I also want to avoid generics. The fact is that Intellisense is showing me the upper class method when playing around with an instance of it. If I remove the virtual implementation from the upper class, then it displays the base class implementation. This is where I thought it is actually possible. So how can I force the program to call the upper class method? EDIT: The answer was actually simple and was right under my nose. The return type does not matter as it will inherits from the return type defined in the base class abstract CreateModel(). I just marked the method as abstract in my base class and it works just fine. I don't know why I got confused at some moments because now it seems pretty obvious to me. Thanks everybody for helping me out. A: It looks to me like your base class should be generic, with your derived classes specifying the appropriate type argument. public abstract class Node<T> where T : NodeModel { public abstract T CreateModel(); } public class Folder : Node<FolderModel> { public override FolderModel CreateModel() { // Implementation } } public class Item : Node<ItemModel> { public override ItemModel CreateModel() { // Implementation } } Now you have a single method, overridden appropriately - instead of method hiding which was always going to get confusing. EDIT: If you want to be able to refer to these without generics, you could always create a non-generic interface, like this: public interface INode { NodeModel CreateModel(); } public abstract class Node<T> : INode where T : NodeModel { public abstract T CreateModel(); // Explicit interface implementation so we can implement INode.CreateModel // with a different return type. Just delegate to the strongly-typed method. NodeModel INode.CreateModel() { return CreateModle(); } } A: C# does not support covariance in function return types. Anyway, you only need to specify the return type of CreateModel() as something else than NodeModel when other parts are relying on them to be more specific, e.g. when FolderModel extends NodeModel with more methods. If you are only iterating over a list of Node objects and call CreateModel() it is not needed, just declare Folder.CreateModel() with NodeModel return type, even though it returns a FolderModel. A: Here's a version where class inheritance is used instead of generics: public abstract class Node { public virtual NodeModel CreateModel() { throw new NotImplementedException(); } } public class FolderModel : NodeModel { // blah } public class Folder : Node { public virtual NodeModel CreateModel() { var node = new FolderModel(); blah; return node; // FolderModel derives from NodeModel } } public class ItemModel : NodeModel { // blah } public class Item : Node { public virtual NodeModel CreateModel() { var node = new ItemModel(); blah; return node; // ItemModel derives from NodeModel } } public foo(Node node) { var model = node.CreateModel(); } The type of model depends on type of node. Manipulating the specific parts of the model must somehow be part of virtual node methods that know the inners of each specific model. A: public abstract class Node { public virtual NodeModel CreateModel() { throw new NotImplementedException(); } } public class Folder : Node { public virtual FolderModel CreateModel() { // Implementation } } This is not method overriding but it's over loading. Node node=new Folder(); node.CreateModel();//Of Folder To do this you have to override CreateModel in derived(Folder) class
{ "language": "en", "url": "https://stackoverflow.com/questions/7511782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: clojure/lein: How do I include a java file in my project? I have a java file with a single class and I want to include it in my lein project. Where do I put it and how do I import it? (I tried putting it in the src directory under the package path but it tells me ClassNotFound) So the java file has this package declaration: package com.thebuzzmedia.imgscalr; and has this class: public class Scalr { I put it in ~/src/com/thebuzzmedia/imgscalr/Scalr.java and tried to import it from the repl thusly: (import '(com.thebuzzmedia.imgscalr Scalr)) And I get this: com.thebuzzmedia.imgscalr.Scalr [Thrown class java.lang.ClassNotFoundException] What am I missing? A: Since I do not have the reputation to comment on the above answers, I am left with no recourse but to leave my own, ever-so-slightly different answer. The correct syntax (as of Leiningen 2.1.3) is: (defproject ... :java-source-paths ["src/main/java/" "foo/bar/baz/"] ... ) A: Where to place Java sources really depends on which build system you're using. If you're using Leiningen, you have to configure the source paths: (defproject my-project "0.0.1-SNAPSHOT" [...] :java-source-paths ["src/java" "test/java"]) Then you can import Java classes at those source locations in your code or at the REPL like you were already trying to do. A: As of Leiningen 2.X, :java-source-path has been replaced with :java-source-paths, whose value is now specified as a vector rather than a string. Example: (defproject my-project "0.0.1-SNAPSHOT" [...] :java-source-paths ["src/main/java" "src/main/test"] ...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7511789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Echo ' *' PHP When I do this: echo '<li></li>'; in php inside a <ul>, it breaks the rest of the php and results in '; ?> showing up on my site. I'm trying to list journal entries and I've done it many times before, but it just doesn't seem to work now, which is very strange. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php mysql_connect("localhost", "root"); mysql_select_db("lunatic"); ?> <title>Lunatic Cowboys - Gæstebog</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link rel="stylesheet" href="css/reset.css" /> <link rel="stylesheet" href="css/text.css" /> <link rel="stylesheet" href="css/960.css" /> <link rel="stylesheet" href="css/style.css" /> </head> <body> <div id="headercont" class="container_12"> <div id="header" class="grid_12"></div> <div id="navigation" class="grid_12"> <ul> <li><a href="index.html">Forside</a></li><li> -</li> <li><a href="historie.html">Historie</a></li><li> -</li> <li><a href="klubben.html">Klubben</a></li><li> -</li> <li><a href="vedtaegter.html">Vedtægter</a></li><li> -</li> <li><a href="dansetider.html">Dansetider</a></li><li> -</li> <li><a href="instruktoer.html">Instruktør</a></li><li> -</li> <li><a href="kalender.html">Kalender</a></li><li> -</li> <li><a href="galleri.html">Galleri</a></li><li> -</li> <li><a href="http://lunaticcowboys.blogspot.com/" target="_blank">Blog</a></li><li> -</li> <li><a href="gaestebog.html">Gæstebog</a></li><li> -</li> <li><a href="links.html">Links</a></li><li> -</li> <li><a href="kontakt.html">Kontakt</a></li> </ul> </div> </div> <div id="contcont" class="container_12"> <div id="content" class="grid_12"> <h1 id="overskrift">Gæstebog</h1> </div> <div id="guestbook" class="grid_7"> <h2>Se hilsner</h2> <ul> <?php $eQuery = mysql_query("SELECT * FROM guestbook"); while($entries = mysql_fetch_assoc($eQuery)){ echo "<li></li>"; } ?> </ul> </div> <div id="add" class="grid_5"> <h2>Skriv en hilsen</h2> <form id="guestbookform" method="post" action="add.html"> <fieldset> <label for="name">Navn: </label> <input type="text" id="name" name="name"/><br /> <label for="email">Email: </label> <input type="text" id="email" name="email"/><br /> <label for="klub">Klub: </label> <input type="text" id="klub" name="klub"/><br /> <label for="msg">Hilsen: </label> <textarea name="msg" id="msg" rows="8" cols="39" onfocus="this.value=null;">Skriv din hilsen her</textarea><br /> <input type="button" onClick="javascript:addGreeting()" value="Send hilsen!" /> </fieldset> </form> </div> <div id="copyright" class="grid_12"> <p>2011© Copyright Lunatic Cowboys<br />Udvikling og design af <a href="http://alexkotsc.co.cc">Alexander Kotschenreuther</a></p> </div> </div> <script language="javascript" type="text/javascript"> function addGreeting(){ var aReq; try{ // Opera 8.0+, Firefox, Safari aReq= new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ aReq = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ aReq = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } var name = document.getElementById('name').value; var email = document.getElementById('email').value; var klub = document.getElementById('klub').value; var msg = document.getElementById('msg').value; aReq.onreadystatechange = function(){ if(aReq.readyState == 4){ document.getElementById('add').innerHTML = aReq.responseText; } } aReq.open('GET', 'add.php' + '?name=' + name + '&email=' + email + '&klub=' + klub + '&msg=' + msg, true); aReq.send(null); } A: I think I have figured it out. PHP is not handling the request - no PHP code is being executed. If you view the source of the page, you will find that your entire PHP code is visible on the page. Are you running this on a PHP enabled web server, and is the web server configured to pass the file extension you are using to PHP? Is the file a .php file or a .html file? EDIT If you want Apache to get PHP to handle .html files, add these lines to a .htaccess, or put them in httpd.conf and restart Apache: AddHandler application/x-httpd-php .html AddHandler application/x-httpd-php .htm A: now there's no <ul> tag before or after the php code that is said to becausing the problem - maybe this is the wrong thing?
{ "language": "en", "url": "https://stackoverflow.com/questions/7511791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kerberos constrained delegation with protocol transition in java on linux I am not able to find any examples of how constrained delegation with protocol transition is done using JAAS/GSS api's on linux. Appreciate any pointers on this. A: I guess, there is only support for credential delegation. You cannot specify the explicit target hosts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to access non static cloned arrayList for use in static method in Java As part of an assignment Im trying to access a cloned array list from another class so I can utilize it. But when attempting to do so I get the following error "non-static method getConnections() cannot be refrenced from a static context". This is the code I'm using to access the cloned array. It is in the context of working out the best way to take flights from one destination to another. public boolean determineRoute(City from, City to, ArrayList<City> flightRoute) { ArrayList<City> Connections = new ArrayList<City>(); Connections = City.getConnections(); return true; } And this is how the code for that class begins. It does start as static but as far as i can see it should only affect the first method how can I tell java that this method should not be considered static so I can access the cloned list from the non static class?? import java.util.*; public class Lab9_Ex2_Main { //////// START-UP ///////// public static void main(String[] args) { new Lab9_Ex2_Main(); } I have left out a lot of the code as I think it may not be right from me to put every thing up. But should you need more to get a clearer picture I will happily add more of the code. This is the code from another class which contains a cloned array which im attempting to access. import java.util.*; // Class: City // Purpose: To represent a place in the world that you can fly from/to. public class City { private String name; // The name of the City private ArrayList<City> connectsWith; // Which cities are connected to this one public City(String cityName) { name = cityName; connectsWith = new ArrayList<City>(); } // Method: addConnection // Purpose: To note that you can catch a flight to the destination, from this city // Passed: // destination - The City which you can fly to. public void addConnection(City destination) { if (destination != null && destination != this) connectsWith.add(destination); } // Method: getConnections // Purpose: To retrieve a list of cities you can reach from this one. // Note: You are given a clone, (to avoid a privacy leak), and can manipulate it however // you like. E.g. you could delete elements. public ArrayList<City> getConnections() { return (ArrayList<City>) connectsWith.clone(); } public String getName() { return name; } public String toString() { return name; } } A: City actually doesn't provide a static getConnections() method, since that doesn't make sense. The connections depend on an actual City instance and if you have access to one you can call getConnections() on it, even from a static method. This is the comment on the array list that is cloned in getConnections(): // Which cities are connected to this one Note that this means you just can't get the connections without specifying this city (the one you get the connections for) and thus just can't call that method on the City class only. Comment on the method itself: Purpose: To retrieve a list of cities you can reach from this one. Assuming your determineRoute(...) method might be static, it could look like this: public static boolean determineRoute(City from, City to, ArrayList<City> flightRoute) { ArrayList<City> connections = new ArrayList<City>(); connections = to.getConnections(); //or from.getConnections(); what ever makes sense //connections is not used, so I assume you want to put them into flightRoute flightRoute.addAll(connections); return true; } Your determineRoute(...) logic seems quite odd. I assume you want to actually calculate the route between the from and the to city, which you are not doing right now. Fixing that, however, is an exercise for you. You could then call that method in your main method (which has to be static) like this: public static void main(String... args) { City berlin = new City("Berlin"); City beijing = new City("Beijing"); //fill the connections here ArrayList<City> route = new ArrayList<City>(); boolean success = determineRoute(berlin, beijing, route); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: same random sorting in javascript I have got "slides" div and "slidecontrols" div. slidecontrols div contains thumbnail and title of slides and it's displaying title and raising opacity when activate one slide. slides and slidecontrols are in array on javascript and appending to page with jquery. I need to randomize sorting of slides every page refresh but when randomizing slides and slidecontrols there is problem appears.. think like : slides : 1, 2, 3, 4, 5 slidecontrols : 1a, 2a, 3a, 4a, 5a after randomizing : slides : 3, 2, 1, 5, 4 slidecontrols : 4a, 2a, 5a, 1a, 3a but I want this sorting after randomizing : slides : 3, 2, 1, 5, 4 slidecontrols : 3a, 2a, 1a, 5a, 4a A: You don´t have to randomize both. You have to randomize the slides and then sync the slidecontrols with them instead ;) A: Try this, though there are some temp variabls var a = [1, 2, 3, 4, 5]; var b = ['1a', '2a', '3a', '4a', '5a']; var temp = []; var i = 0; a.sort(function() { return temp[temp.length] = (Math.random() - 0.5); }); b.sort(function() { return temp[i++]; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7511799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Runtime error when using vector iterator I'm having a problem with the following code: for(int j = 0; j < ensembleTemp.size(); j++) { ensemble[ensembleTemp[j]].clear(); ensemble[ensembleTemp[j]].insert(ensemble[j].begin(), ensembleTemp.begin(), ensembleTemp.end()); } ensembleTemp is a vector<int> and ensemble is a vector<vector<int>>. I have the following, error: vector insert iterator outside range. What's my mistake? A: You're using the wrong index for the first parameter of insert, it (presumably) should be for(int j = 0; j < ensembleTemp.size(); j++) { ensemble[ensembleTemp[j]].clear(); ensemble[ensembleTemp[j]].insert( ensemble[ensembleTemp[j]].begin(), ensembleTemp.begin(), ensembleTemp.end()); } The first parameter to insert should be an iterator for the vector being inserted into. In addition ensemble.size() must be greater than ensembleTemp[j] for all j. A: Are you sure ensemble.size() is greater than 'j'? and greater than ensembleTemp[j]?
{ "language": "en", "url": "https://stackoverflow.com/questions/7511800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fatal error: Uncaught CurlException SSL connection timeout in facebook api 3.0.0 in base.facebook.php i am getting same ssl error for all version of php-sdk i have increased timeout value but strill same problem but when i tried same sample code on different server it working well. i think there is might be something server related issue like version of lib curl or openssl can you help me ? A: I had the same issue two weeks ago with two computers running on Archlinux with curl 7.24. Curl use SSL version 3 by default but it looks like on my computers the curl to https://graph.facebook.com ended up in a timeout whereas it worked when I specifically asked curl to use SSL version 3. So here how I solved the issue : In the Facebook PHP SDK, in base_facebook.php, replace : public static $CURL_OPTS = array( CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_USERAGENT => 'facebook-php-3.1', ); By : public static $CURL_OPTS = array( CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_USERAGENT => 'facebook-php-3.1', CURLOPT_SSLVERSION => 3, );
{ "language": "en", "url": "https://stackoverflow.com/questions/7511802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problems with FrameLayout i'm adding programatically 3 textviews into a framelayout that haves a camera view. The three textviews are writting in the same position, but i want to put each textview bottom to another (using framelayout) I dont know how to do it, i can't find any examples or info about doing this with framelayout programatically, and also i didnt find the way to do it with setlayoutparams, because that method doesn't have x/y parameters or something like that. here is the code: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); cv = new CustomCameraView(this.getApplicationContext()); FrameLayout rl = new FrameLayout(this.getApplicationContext()); setContentView(rl); rl.addView(cv); tv1=new TextView(getApplicationContext()); tv2=new TextView(getApplicationContext()); tv3=new TextView(getApplicationContext()); rl.addView(tv1); rl.addView(tv2); rl.addView(tv3); tv1.setText("Test1"); tv2.setText("Test2"); tv3.setText("Test3"); } A: Make a linearLayout, add the textViews to this LinearLayout , and add this linearLayout to your FrameLayout. Use the orientation of LinearLayout vertical. use LinearLayout.setOrientation(LinearLayout.VERTICAL), method for setting orientation to vertical.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple technique to upsample/interpolate video features? I'm trying to analyse audio and visual features in tandem. My audio speech features are mel-frequency cepstrum co-efficients sampled at 100fps using the Hidden Markov Model Toolkit. My visual features come from a lip-tracking programme I built and are sampled at 29.97fps. I know that I need to interpolate my visual features so that the sample rate is also 100fps, but I can't find a nice explanation or tutorial on how to do this online. Most of the help I have found comes from the speech recognition community which assumes a knowledge of interpolation on behalf of the reader, i.e. most cover the step with a simple "interpolate the visual features so that the sample rate equals 100fps". Can anyone pooint me in the right direction? Thanks a million A: Since face movement is not low-pass filtered prior to video capture, most of the classic DSP interpolation methods may not apply. You might as well try linear interpolation of your features vectors to get from one set of time points to a set at a different set of time points. Just pick the 2 closest video frames and interpolate to get more data points in between. You could also try spline interpolation if your facial tracking algorithm measures accelerations in face motion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing copied and pasted code/text detection? I've a bunch of legacy javascript files looking really similar. I'd like to implement a copied/pasted code detection tool, but I was unable to find a description of an algorithm... I'm already using sonar with the javascript plugin to detect this kind of code, but I'd like to have a finer-grained control over the detection... Is there any "standard" algorithm for this problem ? Is there any library to perform this analysis (python or java...)? thanks. A: You could take a look to CloneDigger, it is designed to detect clones in python or java code, but the algorithm is described here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to convert JSON string to array What I want to do is the following: * *taking JSON as input from text area in php *use this input and convert it to JSON and pass it to php curl to send request. this m getting at php from get of api this json string i want to pass to json but it is not converting to array echo $str='{ action : "create", record: { type: "n$product", fields: { n$name: "Bread", n$price: 2.11 }, namespaces: { "my.demo": "n" } } }'; $json = json_decode($str, true); the above code is not returning me array. A: If you are getting json string from URL using file_get_contents, then follow the steps: $url = "http://localhost/rest/users"; //The url from where you are getting the contents $response = (file_get_contents($url)); //Converting in json string $n = strpos($response, "["); $response = substr_replace($response,"",0,$n+1); $response = substr_replace($response, "" , -1,1); print_r(json_decode($response,true)); A: your string should be in the following format: $str = '{"action": "create","record": {"type": "n$product","fields": {"n$name": "Bread","n$price": 2.11},"namespaces": { "my.demo": "n" }}}'; $array = json_decode($str, true); echo "<pre>"; print_r($array); Output: Array ( [action] => create [record] => Array ( [type] => n$product [fields] => Array ( [n$name] => Bread [n$price] => 2.11 ) [namespaces] => Array ( [my.demo] => n ) ) ) A: If you are getting the JSON string from the form using $_REQUEST, $_GET, or $_POST the you will need to use the function html_entity_decode(). I didn't realize this until I did a var_dump of what was in the request vs. what I copied into and echo statement and noticed the request string was much larger. Correct Way: $jsonText = $_REQUEST['myJSON']; $decodedText = html_entity_decode($jsonText); $myArray = json_decode($decodedText, true); With Errors: $jsonText = $_REQUEST['myJSON']; $myArray = json_decode($jsonText, true); echo json_last_error(); //Returns 4 - Syntax error; A: this my solution: json string $columns_validation = string(1736) "[{"colId":"N_ni","hide":true,"aggFunc":null,"width":136,"pivotIndex":null,"pinned":null,"rowGroupIndex":null},{"colId":"J_2_fait","hide":true,"aggFunc":null,"width":67,"pivotIndex":null,"pinned":null,"rowGroupIndex":null}]" so i use json_decode twice like that : $js_column_validation = json_decode($columns_validation); $js_column_validation = json_decode($js_column_validation); var_dump($js_column_validation); and the result is : array(15) { [0]=> object(stdClass)#23 (7) { ["colId"]=> string(4) "N_ni" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(136) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } [1]=> object(stdClass)#2130 (7) { ["colId"]=> string(8) "J_2_fait" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(67) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } A: You can convert json Object into Array & String. $data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}'; $b=json_decode($data); $i=0; while($b->{'resultList'}[$i]) { print_r($b->{'resultList'}[$i]->{'displayName'}); echo "<br />"; $i++; } A: If you want to convert to an object then: $data = json_decode($yourJson); if you want to convert to an array then: $data = json_decode($yourJson,TRUE); A: If you pass the JSON in your post to json_decode, it will fail. Valid JSON strings have quoted keys: json_decode('{foo:"bar"}'); // this fails json_decode('{"foo":"bar"}', true); // returns array("foo" => "bar") json_decode('{"foo":"bar"}'); // returns an object, not an array. A: <?php $str='{ "action" : "create", "record" : { "type": "$product", "fields": { "name": "Bread", "price": "2.11" }, "namespaces": { "my.demo": "n" } } }'; echo $str; echo "<br>"; $jsonstr = json_decode($str, true); print_r($jsonstr); ?> i think this should Work, its just that the Keys should also be in double quotes if they are not numerals. A: Make sure that the string is in the following JSON format which is something like this: {"result":"success","testid":"1"} (with " ") . If not, then you can add "responsetype => json" in your request params. Then use json_decode($response,true) to convert it into an array. A: There is a problem with the string you are calling a json. I have made some changes to it below. If you properly format the string to a correct json, the code below works. $str = '{ "action" : "create", "record": { "type": "n$product", "fields": { "nname": "Bread", "nprice": 2.11 }, "namespaces": { "my.demo": "n" } } }'; $response = json_decode($str, TRUE); echo '<br> action' . $response["action"] . '<br><br>'; A: Try this: $data = json_decode($your_json_string, TRUE); the second parameter will make decoded json string into an associative arrays. A: Use json_decode($json_string, TRUE) function to convert the JSON object to an array. Example: $json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; $my_array_data = json_decode($json_string, TRUE); NOTE: The second parameter will convert decoded JSON string into an associative array. =========== Output: var_dump($my_array_data); array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } A: If you ever need to convert JSON file or structures to PHP-style arrays, with all the nesting levels, you can use this function. First, you must json_decode($yourJSONdata) and then pass it to this function. It will output to your browser window (or console) the correct PHP styled arrays. https://github.com/mobsted/jsontophparray A: Use this convertor , It doesn't fail at all: Services_Json // create a new instance of Services_JSON $json = new Services_JSON(); // convert a complexe value to JSON notation, and send it to the browser $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); $output = $json->encode($value); print($output); // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] // accept incoming POST data, assumed to be in JSON notation $input = file_get_contents('php://input', 1000000); $value = $json->decode($input); // if you want to convert json to php arrays: $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE); A: You can change a string to JSON as follows and you can also trim, strip on string if wanted, $str = '[{"id":1, "value":"Comfort Stretch"}]'; //here is JSON object $filters = json_decode($str); foreach($filters as $obj){ $filter_id[] = $obj->id; } //here is your array from that JSON $filter_id; A: <?php $str='{ "action" : "create", "record": { "type": "n$product", "fields": { "n$name": "Bread", "n$price": 2.11 }, "namespaces": { "my.demo": "n" } } }'; $json = json_decode($str,true); echo '<pre>'; print_r($json); this should Work,just that the Keys should also be in double quotes if they are not numerals. output:- Array ( [action] => create [record] => Array ( [type] => n$product [fields] => Array ( [n$name] => Bread [n$price] => 2.11 ) [namespaces] => Array ( [my.demo] => n ) ) ) It will convert Json String To Array A: You can use this to get an object of your JSON data by setting it as object before you decode the data. This only works if you send the object as a JSON string $data = (object)json_decode($_POST['data'])
{ "language": "en", "url": "https://stackoverflow.com/questions/7511821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "161" }
Q: Report Builder 1.0 recommended system requirements I can't seem to find this on MSDN but can anyone tell me the recommended system requirements for running Report Builder 1.0? A: From MSDN: The client computer must have the Microsoft .NET Framework 3.5 installed. The .NET Framework provides the infrastructure for running ClickOnce applications. You must use Microsoft Internet Explorer 6.0 or later. http://msdn.microsoft.com/en-us/library/ms365173(v=SQL.100).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7511827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I don't understand 'closest()' still... Please clarify I am struggling with jQuery's closest() selector. I've made a jsfiddle of what I think should work... but it clearly doesn't. Why not? the HTML <div class="button">button</div> <div class="return_window"></div> and the incredibly complex JS $('.button').click(function(){ $(this).closest('.return_window').html('hi'); }); What don't I understand about this illusive .closest() selector?? Those div's look pretty close to me. I've read the documentation but I don't know what it is.. Resig's documentation or whoever writes it seems to be on a different dimension to me. Any pointers greatly appreciated. A: closest is used to climb up the DOM tree, rather than look sideways at sibling elements. In simple terms, it will look at the parent element, and the parent of that, and so on, until it reaches what it's looking for (or the top of the DOM tree). For example: <div class="grandparent"> <div class="parent"> <div id="child"></div> <div class="grandparent"></div> </div> </div> The following jQuery will select the outer div, rather than the sibling div: $(".child").closest(".grandparent"); closest is the opposite of find, which looks down the DOM tree. To select siblings, you can use the siblings method. A: Closest searches PARENTS of the element - not siblings near the elements. It's called closest because it finds the closest parent of a particular type (selector) to the element. The .parents() get all the parents. I use it all the time. Like: <form> <div> <p> <input type="button" onClick="alert($(this).closest('form'));"> </p> </div> </form> From deep inside I can quickly find the parent form, ignoring all the intervening elements. If you want the nearest sibling do: $(this).prevAll('.return_window').last(); $(this).nextAll('.return_window').first(); This will give you the two closest siblings above and below, and it's on you to figure out which is closer. A: closest looks up the DOM, if the start point is not inside the one you are looking for it wont find it. I modded your code to show this: http://jsfiddle.net/uRgEw/2/ maybe you are looking for this: $('.button').click(function(){ alert('hi'); $(this).closest('.container').find('.return_window').html('hi'); }); with HTML of: <div class="container"> <div class="return_window"> </div> <div class="button">button</div> </div> this will let you go up and back down with a good degree of flexibility. as done here: http://jsfiddle.net/uRgEw/5/ A: In your case use next() not closest() as closest() looks up the tree BEGINNING with the current element: $('.button').click(function(){ $(this).next('.return_window').html('hi'); }); A: .closest() finds the closest ancestor that matches your selector. closest() starts with itself, then its parent, or its parents' parent, or so on. what you have there are siblings. you should use .siblings() if you want to find elements that share the same parent, or are next to each other. A: <div class="return_window"> <div class="button">button</div> </div> In your example the above would be the HTML that would work. It finds the closest ancestor. You could use something like: $(this).next('.return_window').html('hi') With the HTML you've provided. A: closest walks from the current selected element to the root, using parentNode, and find the first element which matches the given selector: function closest(element, selector) { while (element != null) { if (matchesSelector(element, selector)) { return true; } element = element.parentNode; } return null; } For example, we have HTML like: <div id="d1" class="a"> <div id="d2" class="b"> <div id="d3" class="a"> <span id="target"></span> </div> </div> </div> and we need some closest selector, the output would be: * *closest(target, '.a') -> #d3 *closest(target, 'div') -> #d3 *closest(target, '.b') -> #d2
{ "language": "en", "url": "https://stackoverflow.com/questions/7511831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: java get property only exist in child class class Parent { } class Child extends parent { String something; //get and set } Parent parent = getChildObject(); //without casing getChildObject() to Child object. i cannot do child.getSomething(); Can i do something like parent.getProperty("something"); to get the value? A: The correct way to do this is: if (parent instanceof Child) { String something = ((Child) parent).getSomething(); } You can also do this by using reflection, but that is a lot more complicated. A: Sure, use could always use reflection. But it will be very slow. A: Generally speaking, what you are trying to do is not a good idea and you should try to avoid it. If there is no way around it then the answer provided by nfechner is the correct one. A: Not sure I understand the question. But anyway...this is usually done by declaring an abstract method in the superclass and having the subclass(es) provide their own implementation. For instance, abstract class Foo{ abstract String getString(); } class Bar extends Foo{ @Override String getString(){ return "bar"; } } It's important to note that this will require the superclass to be abstract.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to check the state of 3G in my app: Actually i had used the following code to check the wifi is active or not (its working fine). I just want to confirm that can i use the same code to check the 3G active state: public boolean checkwifi() { ConnectivityManager connec = (ConnectivityManager) this.getSystemService(this.CONNECTIVITY_SERVICE); android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI); android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); // Here if condition check for wifi and mobile network is available or not. // If anyone of them is available or connected then it will return true, otherwise false; if (wifi.isConnected()) { return true; } else if (mobile.isConnected()) { return true; } return false; } A: Yes - this code should work. I've got an extra bit of functionality you may want to implement: public static boolean isOnline(Context context) { //ConnectivityManager is used to check available network(s) ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null; } This does the same as your code - it will tell you if you are online via any method (3G or WiFi), but it's a bit more concise. ** EDIT ** Here's the source for that method - it will return null if no active network connection or will return a NetworkInfo object for a current connection: /** * Return NetworkInfo for the active (i.e., connected) network interface. * It is assumed that at most one network is active at a time. If more * than one is active, it is indeterminate which will be returned. * @return the info for the active network, or {@code null} if none is active */ public NetworkInfo getActiveNetworkInfo() { enforceAccessPermission(); for (NetworkStateTracker t : mNetTrackers) { NetworkInfo info = t.getNetworkInfo(); if (info.isConnected()) { return info; } } return null; } A: to check if your connection(WIFI or Mobile ) is On or Off , try this : boolean connected = false; ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) { //we are connected to a network connected = true; } else connected = false;
{ "language": "en", "url": "https://stackoverflow.com/questions/7511836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to expose read-only collection another type of private collection? Here is my problem: there is a class that contains a inner collection (or list, or array, or something like this) of some some class and It must expose a public read-only collection of items, which are properties (or fields) of relative items in inner collection. For example: //Inner collection consists of items of this class class SomeClass { public int _age; //This property is needed for exposing public string Age { get { return this._age.ToString(); } } } //Keeps inner collection and expose outer read-only collection class AnotherClass { private List<SomeClass> _innerList = new List<SomeClass> (); public ReadOnlyCollection<string> Ages { get { //How to implement what i need? } } } I know a simple way to do this by the use of a pair of inner lists, where the second keeps values of needed properties of first. Something like this: //Inner collection consists of items of this class class SomeClass { public int _age; //This property is needed for exposing public string Age { get { return this._age.ToString(); } } } //Keeps inner collection and expose outer read-only collection class AnotherClass { private List<SomeClass> _innerList = new List<SomeClass> (); private List<string> _innerAgesList = new List<string> (); public ReadOnlyCollection<string> Ages { get { return this._innerAgesList.AsreadOnly(); } } } But I dislike this overhead. May be there is some way to do what I want with exposing interfaces. Help me, please! Hurra! It seems that the best solution has been found. Due to the post of Groo this problem found its almost universal answer. Here is It (we need to add two entity): public interface IIndexable<T> : IEnumerable<T> { T this[int index] { get; } int Count { get; } } class Indexer <Tsource, Ttarget> : IIndexable<Ttarget> { private IList<Tsource> _source = null; private Func<Tsource, Ttarget> _func = null; public Indexer(IList<Tsource> list, Func<Tsource, Ttarget> projection) { this._source = list; this._func = projection; } public Ttarget this[int index] { get { return this._func(this._source[index]); } } public int Count { get { return _source.Count; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<Ttarget> GetEnumerator() { foreach (Tsource src in this._source) yield return this._func(src); } } With them, our implementation looks like this: //Inner collection consists of items of this class class SomeClass { public int _age; //This property is needed for exposing public string Age { get { return this._age.ToString(); } } } //Keeps inner collection and expose outer read-only collection class AnotherClass { private List<SomeClass> _innerList = new List<SomeClass> (); private Indexer<SomeClass, string> _indexer = null; public AnotherClass () { this._indexer = new Indexer<SomeClass, string > (this._innerList, s => s.Age); } public IIndexable<string> Ages { get { return this._indexer; } } } Thank Groo and the rest who answered. Hope, this helps someone else. A: The overhead is not so significant if you consider that ReadOnlyCollection is a wrapper around the list (i.e. it doesn't create a copy of all the items). In other words, if your class looked like this: class AnotherClass { private ReadOnlyCollection<string> _readonlyList; public ReadOnlyCollection<string> ReadonlyList { get { return _readonlyList; } } private List<string> _list; public List<string> List { get { return _list; } } public AnotherClass() { _list = new List<string>(); _readonlyList = new ReadOnlyCollection<string>(_list); } } Then any change to the List property is reflected in the ReadOnlyList property: class Program { static void Main(string[] args) { AnotherClass c = new AnotherClass(); c.List.Add("aaa"); Console.WriteLine(c.ReadonlyList[0]); // prints "aaa" c.List.Add("bbb"); Console.WriteLine(c.ReadonlyList[1]); // prints "bbb" Console.Read(); } } You may have issues with thread safety, but exposing IEnumerable is even worse for that matter. Personally, I use a custom IIndexable<T> interface with several handy wrapper classes and extension method that I use all over my code for immutable lists. It allows random access to list elements, and does not expose any methods for modification: public interface IIndexable<T> : IEnumerable<T> { T this[int index] { get; } int Length { get; } } It also allows neat LINQ-like extension methods like Skip, Take and similar, which have better performance compared to LINQ due to the indexing capability. In that case, you can implement a projection like this: public class ProjectionIndexable<Tsrc, Ttarget> : IIndexable<Ttarget> { public ProjectionIndexable (IIndexable<Tsrc> src, Func<Tsrc, Ttarget> projection) { _src = src; _projection = projection; } #region IIndexable<Ttarget> Members public Ttarget this[int index] { get { return _projection(_src[index]); } } public int Length { get { return _src.Length; } } #endregion #region IEnumerable<Ttarget> Members // create your own enumerator here #endregion } And use it like this: class AnotherClass { private IIndexable<string> _readonlyList; public IIndexable<string> ReadonlyList { get { return _readonlyList; } } private List<SomeClass> _list; public List<SomeClass> List { get { return _list; } } public AnotherClass() { _list = new List<SomeClass>(); _readonlyList = new ProjectionIndexable<SomeClass, string> (_list.AsIndexable(), c => c.Age); } } [Edit] In the meantime, I posted an article describing such a collection on CodeProject. I saw you've implemented it yourself already, but you can check it out nevertheless and reuse parts of the code where you see fit. A: Why don't you just return IEnumerable? If you have access to LINQ (.NET 3.5) then just use a select() public IEnumerable<string> Ages{ get{ return _innerList.Select(s => s.stringProperty); } } A: in this case I normaly just use IEnumerable - if the collection is readonly and you don't need the Index-functionality you can just do somehting like this: public IEnumerable<string> Ages { get { return this._innerList.Select(someObj => someObj.Age).ToArray(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: what is the best way to change a gem locally and then revert changes I want to write some puts statements to gem files, but I am afraid that I may forget to revert my changes. But I still want the ability to change gems locally and then restore their original versions. I am using bundler and gemsets for different rails projects. One way to do so is to store which gem i changed, uninstall it and then reinstall it. Other way is to create a temporary gemset, import all gems needed, make changes to it, and then destory the temporary gemset. what are other ways to change gems locally and fast, and to get the original gem once done with debugging? A: use a version control system like git or subversion. It allows you to make a savepoint on your files, make some changes, and rollback to an earlier version if something goes wrong. There are many other features, but it would be too long to describe here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Duplicate: XPath expressions with default namespace I'm currently writing a C# class that allows me to construct entities from an OData feed. Don't ask why, I just need it at the moment :) The snippet of the XML looks like this: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <entry xml:base="http://demo.tenforce.acc/Api.svc/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom"> <id>http://demo.tenforce.acc/Api.svc/Items(387)</id> <title type="text"></title> <updated>2011-09-22T07:35:54Z</updated> <author> <name /> </author> <link rel="edit" title="Item" href="Items(387)" /> <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Children" type="application/atom+xml;type=feed" title="Children" href="Items(387)/Children" /> <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Parent" type="application/atom+xml;type=entry" title="Parent" href="Items(387)/Parent" /> <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Attachments" type="application/atom+xml;type=feed" title="Attachments" href="Items(387)/Attachments" /> <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Predecessors" type="application/atom+xml;type=feed" title="Predecessors" href="Items(387)/Predecessors" /> <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Successors" type="application/atom+xml;type=feed" title="Successors" href="Items(387)/Successors" /> <category term="TenForce.Execution.Api2.Objects.Item" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> <content type="application/xml"> <m:properties> <d:Id m:type="Edm.Int32">387</d:Id> </m:properties> </content> </entry> I've created a code snippet that loads the entire xml string into an XmlDocument, and generates a XmlNamespaceManager as well to have access to the various namespaces. I'm trying to select the <category> element from the XML but I can't seem to get the Xpath expression right. I've tried the following: * *//entry/category *descendant::xmlns:cateogry *//d:category *//m:category *//category *//xml:category But none seem to be selected the node in question. A: Oh never mind, i've found the solution. I had to add the namespace for the atom elements.... var manager = new XmlNamespaceManager(_mDocument.NameTable); manager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices"); manager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"); manager.AddNamespace("atom", "http://www.w3.org/2005/Atom"); This allowed me to select the <category> element by using //atom:category
{ "language": "en", "url": "https://stackoverflow.com/questions/7511848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 7 - Playing streaming video On WP7 platform (using C# and Silverlight) I try to play an online stream into a MediaElement... Here is the C# code: (...) WebClient wc = new WebClient(); wc.OpenReadCompleted += (s, e) => { try { mediaElement.SetSource(e.Result); } catch (Exception we) { System.Diagnostics.Debug.WriteLine(we.Message); } }; wc.OpenReadAsync(new Uri(url, UriKind.Absolute)); (...) Here is the XAML source code: <MediaElement Height="316" HorizontalAlignment="Left" Margin="6,6,0,0" Name="mediaElement" VerticalAlignment="Top" Width="450" AutoPlay="False" /> The url is type of http://.../Manifest and the format is a one supported by the platform. When SetSource is called then an exception is raised with the following message "Stream must be of type IsolatedStorageFileStream". What do I do wrong? Thanks in advance for some help Cheers A: MSDN says: Passing a generic stream to SetSource(System.IO.Stream) is not supported in Silverlight for Windows Phone. However, the IsolatedStorageFileStream class, which derives from Stream, is suppoted on Silverlight for Windows Phone. Instead, consider setting the MediaElement.Source property directly to the stream uri. There's no reason to "download" it first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generate a code from user e-mail to generate a link and then send I am developing an app that enables existing users to invite their friends via e-mail. During the invitation process I generate a code to use in a link that the invited person clicks on to register. Currently I am using the default hashcode generated from the their e-mail string, however this is probably pretty obvious and insecure. I am considering using this: Random random = new Random(); Integer code = random.nextInt() But my instance of Random would need to be a singleton across my whole app ? And each time the app/jvm was restarted it would be "reset" thus making possible collisons where the same number is generated twice ? Edit Actually the default hashcode isn't that bad, an attacker would need to know that someone has been invited and what their e-mail was, and attempt to generate link in correct time frame (where invite is active). A: You can append a (current) date/time string to the email address to make it unique. A: Hash algorithms can't guarantee a unique hash, but what you can do is give an input that can be unique. Try combining the email with a salt value or something like that. This way you guarantee that the hash is unique.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Location or Alternatives for Zends getRequest()->isPost() i was wondering about where Zends functionality comes from when inside of a controller i call $this->getRequest()->isPost() It works, but i do not find where this "isPost()" function comes from. I just noticed it because i don't have intellisense for that. Question is: Is this merely some fallback function that "newbie users" use apart from a better alternative? Or is it perfectly valid using it? Thanks :) A: It is the official way to go, you can use it. Check the source code of Zend_Controller_Request_Http::isPost() to see what it really is doing, if you'd like :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7511857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get real path of application from pid? How can I get the process details like name of application & real path of application from process id? I am using Mac OS X. A: If the PID is the PID of a "user application", then you can get the NSRunningApplication of the app like that: NSRunningApplication * app = [NSRunningApplication runningApplicationWithProcessIdentifier:pid ]; And to print the path of the executable: NSLog(@"Executable of app: %@", app.executableURL.path); the app bundle itself is here NSLog(@"Executable of app: %@", app.bundleURL.path); However this won't work with system or background processes, it's limited to user apps (those typically visible in the dock after launch). The NSRunningApplication object allows to to check if the app is ative, to hide/unhide it and do all other kind of neat stuff. Just thought I mention it here for completeness. If you want to work with arbitrary processes, then the accepted answer is of course better. A: It's quite easy to get the process name / location if you know the PID, just use proc_name or proc_pidpath. Have a look at the following example, which provides the process path: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <libproc.h> int main (int argc, char* argv[]) { pid_t pid; int ret; char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; if ( argc > 1 ) { pid = (pid_t) atoi(argv[1]); ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf)); if ( ret <= 0 ) { fprintf(stderr, "PID %d: proc_pidpath ();\n", pid); fprintf(stderr, " %s\n", strerror(errno)); } else { printf("proc %d: %s\n", pid, pathbuf); } } return 0; } A: You can use the Activity Monitor - http://en.wikipedia.org/wiki/Activity_Monitor Or in the Terminal App you can use: ps xuwww -p PID PIDis the process id you are looking for More help on 'ps`command you can find with man ps A: Try use lsof example: lsof -p 1066 -Fn | awk 'NR==2{print}' | sed "s/n\//\//" output: /Users/user/Library/Application Support/Sublime Text 2/Packages A: I would like to make a better ssh-copy-id in bash only!! For that, i have to know where is sshd to ask him his actual config. On some system i have multiple sshd and which is not my friend. Also on some macOS the ps command didn't show the full path for sshd. lsof -p $PPID | grep /sshd | awk '{print $9}' this return /usr/sbin/sshd after i could ask for sudo /usr/sbin/sshd -T | grep authorizedkeysfile this return, on some system authorizedkeysfile .ssh/authorized_keys so i have to put in .ssh/authorized_keys
{ "language": "en", "url": "https://stackoverflow.com/questions/7511864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: converting variable like string content to real variable in python I have string variable which contains "variable" like content as shown below. str1="type=gene; loc=scaffold_12875; ID=FBgn0207418; name=Dvir\GJ20278;MD5=4c62b751ec045ac93306ce7c08d254f9; length=2088; release=r1.2; species=Dvir;" I need to make variables out of the string such that the variables name and values goes like this type="gene" loc="scaffold_12875" ID="FBgn0207418" name="Dvir\GJ20278" MD5="4c62b751ec045ac93306ce7c08d254f9" length=2088 release="r1.2" species="Dvir" Thanks for the help in advance. A: Don't do this. You could, but don't. Instead make a dictionary whose keys are the names: result_dict = {} items = str1.split(';') for item in items: key, value = item.strip().split('=') result_dict[key] = value A: Or you could do this class Namespace(object): pass for item in str1.split(';'): key, value = item.strip().split('=', 1) setattr(Namespace, key, value) You can then access your variables like so Namespace.length
{ "language": "en", "url": "https://stackoverflow.com/questions/7511865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Extracting table from html into htmltable in asp.net vb (htmlagilitypack) I am trying to grab a html table from a remote page and display the contents of this table in a htmltable on my site. I am using htmlagility pack. So far here is my code: Imports HtmlAgilityPack Partial Class ContentGrabExperiment Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'fetch the remote html page Dim web As New HtmlWeb() Dim html As HtmlAgilityPack.HtmlDocument = web.Load("http://www.thesite.com/page.html") 'Create table Dim outputTable As New HtmlTable Dim tableRow As New HtmlTableRow Dim tableCell As New HtmlTableCell 'Target the <table> tag For Each table As HtmlNode In html.DocumentNode.SelectNodes("//table") 'Target the <tr> tags within the table For Each row As HtmlNode In table.SelectNodes("//tr") 'Target the <td> tags within the <tr> tags For Each cell As HtmlNode In row.SelectNodes("//td") 'Set the value to that of the <td> tableCell.InnerText = cell.InnerHtml 'Add the cell to the row tableRow.Cells.Add(tableCell) Next 'Add row to the outputTable outputTable.Rows.Add(tableRow) Next Next 'Add the table to the page PlaceHolderTable.Controls.Add(outputTable) End Sub End Class From this I was expecting to get the full table with innertext from the page, as a htmltable which I can then manipulate. What I get out of this code is: <table> <tr> <td>&amp;nbsp;</td> </tr> </table> Please can someone point out where I am going wrong with my syntax. Any help much appreciated! A: 1) You only have one TableRow and one TableCell. You will need to create a new one for each row/cell. You can re-use the variables but you will need to "New" an object into them. 2) You might need to select ./tr and ./td to get only rows and cells in the current table / row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to access server using cmd( \\Server\Volume\File) I need to get folder names in my server, as you know when you start cmd.exe it has default path name like "C:\Documents and ....". I can get folder names which are in my "C:/" by typing dir *.* /b /o:n > index.txt. so I have this; C:\Documents and Settings\Name>dir *.* /b /o:n > index.txt I need this if there is a way; \\Server\Volume\File>dir *.* /b /o:n > index.txt sorry for my broken english, any help wellcome. A: You could map the drive and then browse that directory: net use Z: \\Server\Volume cd /d Z:\ dir Hope this helps :) A: Use: pushd \\Server\Volume dir popd
{ "language": "en", "url": "https://stackoverflow.com/questions/7511884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: namespaces in application settings I am migrating an old application to a newer .NET-version. The current application stores arrays with user settings into the registry. In the new application I want to change this mechanism into .NET Application settings (app.config), but I have only figured out so far how to store one-dimensional values in there, for example... My.Settings.myName1 = "John Doe" My.Settings.myMail1 = "john.doe@somemaildomain.com" My.Settings.myName2 = "Lorem Ipsum" My.Settings.myMail2 = "lorem.ipsum@somemaildomain.com" I guess it is possible somehow to work not only with single values, but with arrays, too, which ideally could be accessed by a namespace, something like this: REM just demo code to display what i want, no idea if something like this works... My.Settings.myContacts(1).Name = "John Doe" My.Settings.myContacts(1).Mail = "john.doe@somemaildomain.com" My.Settings.myContacts(2).Name = "Lorem Ipsum" My.Settings.myContacts(2).Mail = "lorem.ipsum@somemaildomain.com" Is something similar possible? If not, is there another way how to work with multidimensional values / arrays in the .NET Application settings? A: .NET app settings are key, value pair only. If you want multidimensional values in app.config you should look at implementing your own custom config section. See http://msdn.microsoft.com/en-us/library/2tw134k3.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7511887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ellipse representing horizontal and vertical error bars with R In R, how to use ellipses to represent error bars (standard deviation) for x and y variables if only summary data, i.e. mean and SD for different data sets, are available. Any feedback is appreciated. A: You can write your own function like this one: draw_ellipse = function (mean_x, mean_y, sd_x, sd_y) { ellipse <- function (x) { sin(acos(x)) } t = seq(-1, 1, length.out = 100) el_y = sd_y*ellipse(t) newx = mean_x + sd_x * t polygon(c(newx, rev(newx)), c(mean_y + el_y, rev(mean_y - el_y)), col = "grey", border = NA) } You can use it very easily using apply(): x = runif(10) y = runif(10) sd_x = abs(rnorm(10, 0.1, 0.02)) sd_y = abs(rnorm(10, 0.05, 0.01)) plot(x, y) df = data.frame(x, y, sd_x, sd_y) apply(df, 1, function (x) { draw_ellipse(x[1], x[2], x[3], x[4]) }) points(x, y, pch = 3) Solution for plotting ellipses with different colors: draw_ellipse = function (mean_x, mean_y, sd_x, sd_y, colidx) { ellipse <- function (x) { sin(acos(x)) } t = seq(-1, 1, length.out = 100) el_y = sd_y*ellipse(t) newx = mean_x + sd_x * t polygon(c(newx, rev(newx)), c(mean_y + el_y, rev(mean_y - el_y)), col = as.character(colors[colidx]), border = NA) } x = runif(10) y = runif(10) sd_x = abs(rnorm(10, 0.1, 0.02)) sd_y = abs(rnorm(10, 0.05, 0.01)) plot(x, y) colors = rainbow(length(x)) df = data.frame(x, y, sd_x, sd_y, colidx = 1:length(x)) apply(df, 1, function (x) { draw_ellipse(x[1], x[2], x[3], x["sd_y"], x["colidx"]) }) points(x, y, pch = 3) A: You might like the function car::ellipse , i.e., the ellipse() function in the car package. A: The ellipse function in the ellipse package will take summary information (including correlation) and provide the ellipse representing the confidence region.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Displays only the last row in foreach statement if($query->num_rows()>0) { foreach($query->result() as $row) { $slNo = $row->sl_no; //echo "</br>"; $sql1 = "SELECT * FROM main_stock_outward WHERE product_id='$slNo' AND request_id='$requestId'"; //echo "</br>"; $query1 = $this->db->query($sql1); if (!($query1->num_rows() > 0)) { echo "hi"; echo $sql2 = "SELECT a.sl_no,a.product_name,a.barcode,b.request_qty,b.deliver FROM stock_product a, stock_request b WHERE b.pos_id='$posNum' AND b.ordered_date like '$requestIssueDate%' AND b.request_id='$requestId' AND a.sl_no='$slNo' AND b.deliver='0' AND a.barcode=b.product_barcode ORDER BY request_qty DESC"; $query2 = $this->db->query($sql2); //return $query2; $arr_data['query3']=array('sales' => $query2); //$query3 = array( // 'sales' => $query2); } } print_r($arr_data['query3']); return $query2; } as shown in the code again.I am able to display only the last row it is not able to display the rows ? A: if($query->num_rows()>0) { foreach($query->result() as $row) { $slNo = $row->sl_no; //echo "</br>"; $sql1 = "SELECT * FROM main_stock_outward WHERE product_id='$slNo' AND request_id='$requestId'"; //echo "</br>"; $query1 = $this->db->query($sql1); if (!($query1->num_rows() > 0)) { echo "hi"; echo $sql2 = "SELECT a.sl_no,a.product_name,a.barcode,b.request_qty,b.deliver FROM stock_product a, stock_request b WHERE b.pos_id='$posNum' AND b.ordered_date like '$requestIssueDate%' AND b.request_id='$requestId' AND a.sl_no='$slNo' AND b.deliver='0' AND a.barcode=b.product_barcode ORDER BY request_qty DESC"; $query2 = $this->db->query($sql2); //return $query2; $arr_data['query3']**[]** =array('sales' => $query2); //$query3 = array( // 'sales' => $query2); } } print_r($arr_data['query3']); return $query2; } you have missed to make the array, I have modified the line - $arr_data['query3'] =array('sales' => $query2); as $arr_data['query3'][] =array('sales' => $query2); I think your problem will solve by this. A: Because you are doing it wrong. You are assigning every result to the same variable. Try this instead: $arr_data[]=array('sales' => $query2); and the: print_r($arr_data);
{ "language": "en", "url": "https://stackoverflow.com/questions/7511892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find dom elements containing text and other dom elements inside I'm trying to apply a class to all elements which contain text or which contain text and other dom elements inside. At least there must be some sort of text inside the element. This div should get the class: <div class="theClass">Some text</div> This div should get the class too: <div class="theClass">Some text<div class="theClass more">More text</div></div> But this one should only give the child div the class: <div class=""><div class="theClass more">More text</div></div> At the moment i'm using the :hasText selector which i found here finding elements with text using jQuery. jQuery.expr[':'].hasText = function(element, index) { // if there is only one child, and it is a text node if (element.childNodes.length == 1 && element.firstChild.nodeType == 3) { return jQuery.trim(element.innerHTML).length > 0; } return false; }; But it only returns elements which contain text. I like to have elements which contain text and other elements (if there are any). Thanks! A: I don't get it fully but could it be like this: <div ><div class="more">More text</div></div> <div >Some text<div class="more">More text</div></div> jQuery.expr[':'].hasText = function(element, index) { // if there is only one child, and it is a text node if (element.firstChild != null) { if (element.firstChild.nodeType == 3) { return jQuery.trim(element.innerHTML).length > 0; } } return false; }; $('div:hasText').addClass('theClass') You get: <div><div class="more theClass">More text</div></div> <div class="theClass">Some text<div class="more theClass">More text</div></div> A: i was trying like this. // content - children == no.of. text nodes. $.fn.islooseTextInside = function(c){ jq = this; jq.each(function(){ var $th = $(this); //no text nodes if(($th.contents().length - $th.children().length) == 0){ $th.children().islooseTextInside(); } //only text nodes if($th.contents().length && $th.children().length == 0){ applyClass($th) } //both are present if(( $th.contents().length - $th.children().length ) > 0 ){ applyClass($th) $th.children().islooseTextInside(); } }) function applyClass(o){ o.addClass('theClass') } } $("body div").islooseTextInside(); Sample HTML: <body> <div>Some text</div> <div>Some text<div>Some text</div></div> <div><div>Some text</div></div> </body> A: With some help of Nicola Peluchetti I managed to fix it with the following functions, but it's still not the best! jQuery.fn.cleanWhitespace = function() { textNodes = this.contents().filter( function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); }) .remove(); return this; } jQuery.expr[':'].hasText = function(element, index) { // if there is only one child, and it is a text node $(element).cleanWhitespace(); if (element.firstChild != null) { if (element.firstChild.nodeType == 3) { return jQuery.trim(element.innerHTML).length > 0; } } return false; }; So first clean all the whitespaces because <div> <img src="noimage"></div> would be a text element to if you don't clean it (because of the space). You should make the function call itself again when the firstChild isn't a nodeType 3.. but i'm working on it. Will post the solution here!
{ "language": "en", "url": "https://stackoverflow.com/questions/7511900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to link a soap request and response in mule 3 I need to send a file to a external web service. When the response is 1, the file should be deleted, else the file should be kept. I use the file connector to send the file, and insert a record into Oracle. When the file is sent out, the key is the message id of the file connect. I want to keep the message id so that I can update the record using this id when the response is back. I tried to use MessagePropertiesTransformer to add a custom property, but the response doesn't preserve it. Is there any way to keep the message id? My config: <?xml version="1.0" encoding="UTF-8"?> <mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:stdio="http://www.mulesoft.org/schema/mule/stdio" xmlns:cxf="http://www.mulesoft.org/schema/mule/cxf" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc" xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml" xsi:schemaLocation=" http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/3.1/mule-file.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/3.1/mule.xsd http://www.mulesoft.org/schema/mule/stdio http://www.mulesoft.org/schema/mule/stdio/3.1/mule-stdio.xsd http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/3.1/mule-cxf.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/3.1/mule-jdbc.xsd http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/3.1/mule-xml.xsd "> <spring:bean id="jdbcDataSource" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-method="shutdown"> <spring:property name="driverName" value="oracle.jdbc.driver.OracleDriver"/> <spring:property name="url" value="jdbc:oracle:thin:user/pass@ip:1521:orcl"/> </spring:bean> <file:connector name="output" outputAppend="true" outputPattern="#[function:datestamp]-#[header:originalFilename]" /> <file:connector name="input" streaming="false" recursive="true" autoDelete="false"> <service-overrides messageFactory="org.mule.transport.file.FileMuleMessageFactory" /> </file:connector> <jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource"> <jdbc:query key="outboundInsertStatement" value="INSERT INTO TEST_MESSAGE (message_id, filename, done) VALUES (#[message:id], #[header:originalFilename], #[string:0])"/> </jdbc:connector> <mulexml:namespace-manager includeConfigNamespaces="true"> <mulexml:namespace prefix="ns1" uri="http://www.iec.ch/TC57/2008/schema/message"/> <mulexml:namespace prefix="soapenv" uri="http://schemas.xmlsoap.org/soap/envelope/"/> <mulexml:namespace prefix="ns1" uri="http://www.iec.ch/TC57/2008/schema/message"/> <mulexml:namespace prefix="fullmodel" uri="iesb.dongfang.com"/> </mulexml:namespace-manager> <flow name="fileTestFlow1"> <file:inbound-endpoint path="D:/data/in" moveToDirectory="D:/data/out" moveToPattern="#[message:id]-#[header:originalFilename]" connector-ref="input"/> <component class="com.component.FileNameExtract"/> <message-properties-transformer scope="outbound"> <add-message-property key="test" value="#[message:id]"/> </message-properties-transformer> <jdbc:outbound-endpoint queryKey="outboundInsertStatement"/> <cxf:jaxws-client clientClass="com.ws.IESBService" port="IESBServiceEndpoint" wsdlLocation="classpath:IESBService.wsdl" operation="requestInfo"/> <outbound-endpoint address="http://ip:8888/axis2/services/iESBService/" exchange-pattern="request-response"> </outbound-endpoint> <xml-entity-decoder-transformer/> <logger message=" #[header:test] !" level="INFO"></logger> </flow> </mule> UPDATE: I tried "session" scope and I think it works. New config: <?xml version="1.0" encoding="UTF-8"?> <mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:stdio="http://www.mulesoft.org/schema/mule/stdio" xmlns:cxf="http://www.mulesoft.org/schema/mule/cxf" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc" xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml" xsi:schemaLocation=" http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/3.1/mule-file.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/3.1/mule.xsd http://www.mulesoft.org/schema/mule/stdio http://www.mulesoft.org/schema/mule/stdio/3.1/mule-stdio.xsd http://www.mulesoft.org/schema/mule/cxf http://www.mulesoft.org/schema/mule/cxf/3.1/mule-cxf.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/3.1/mule-jdbc.xsd http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/3.1/mule-xml.xsd "> <spring:bean id="jdbcDataSource" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-method="shutdown"> <spring:property name="driverName" value="oracle.jdbc.driver.OracleDriver"/> <spring:property name="url" value="jdbc:oracle:thin:user/pass@ip:1521:orcl"/> </spring:bean> <file:connector name="output" outputAppend="true" outputPattern="#[function:datestamp]-#[header:originalFilename]" /> <file:connector name="input" streaming="false" recursive="true" autoDelete="false"> <service-overrides messageFactory="org.mule.transport.file.FileMuleMessageFactory" /> </file:connector> <jdbc:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource"> <jdbc:query key="outboundInsertStatement" value="INSERT INTO TEST_MESSAGE (message_id, filename, done) VALUES (#[message:id], #[header:originalFilename], #[string:0])"/> <jdbc:query key="outboundUpdateStatement" value="update TEST_MESSAGE set done='1' where message_id=#[header:SESSION:test] "/> </jdbc:connector> <mulexml:namespace-manager includeConfigNamespaces="true"> <mulexml:namespace prefix="ns1" uri="http://www.iec.ch/TC57/2008/schema/message"/> <mulexml:namespace prefix="soapenv" uri="http://schemas.xmlsoap.org/soap/envelope/"/> <mulexml:namespace prefix="ns1" uri="http://www.iec.ch/TC57/2008/schema/message"/> <mulexml:namespace prefix="fullmodel" uri="iesb.dongfang.com"/> </mulexml:namespace-manager> <flow name="fileTestFlow1"> <file:inbound-endpoint path="D:/data/in" moveToDirectory="D:/data/out" moveToPattern="#[message:id]-#[header:originalFilename]" connector-ref="input"/> <component class="com.component.FileNameExtract"/> <message-properties-transformer scope="outbound"> <add-message-property key="test" value="#[message:id]"/> </message-properties-transformer> <logger message="first #[message:id] " level="INFO"></logger> <jdbc:outbound-endpoint queryKey="outboundInsertStatement"/> <cxf:jaxws-client clientClass="com.ws.IESBService" port="IESBServiceEndpoint" wsdlLocation="classpath:IESBService.wsdl" operation="requestInfo"/> <outbound-endpoint address="http://ip:8888/axis2/services/iESBService/" exchange-pattern="request-response"> </outbound-endpoint> <xml-entity-decoder-transformer/> <jdbc:outbound-endpoint queryKey="outboundUpdateStatement"/> <logger message="second #[header:SESSION:test] " level="INFO"></logger> </flow> </mule> When I copy the file one by one, it's ok, but when I copy more than five files to the directory, some records can't be updated. Executing SQL statement: 0 row(s) updated A: Set your JDBC outbound endpoint to request-response in order to ensure the flow will execute in a single thread. With your current configuration, the 2 in-only JDBC requests are "detached" from the flow and executed in parallel from it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Return a concrete implementation in a list I know this doesnt compile but why shouldnt it? public interface IReportService { IList<IReport> GetAvailableReports(); IReport GetReport(int id); } public class ReportService : IReportService { IList<IReport> GetAvailableReports() { return new List<ConcreteReport>(); // This doesnt work } IReport GetReport(int id){ return new ConcreteReport(); // But this works } } A: Try change to this IList<? extends IReport> GetAvailableReports() A: It's because of covariance. You can get it to work in .NET 4 (read the link). A: I recently ran into this problem myself, and found that using IEnumerable instead of List solves the problem. It was quite a frustrating issue, but once I found the source of the problem, it made sense. Here's the test code I used to find the solution: using System.Collections.Generic; namespace InheritList.Test { public interface IItem { string theItem; } public interface IList { IEnumerable<IItem> theItems; // previously has as list... didn't work. // when I changed to IEnumerable, it worked. public IItem returnTheItem(); public IEnumerable<IItem> returnTheItemsAsList(); } public class Item : IItem { string theItem; } public class List : IList { public IEnumerable<IItem> theItems; // List here didn't work - changed to IEnumerable public List() { this.theItems = returnTheItemsAsList(); } public IItem returnTheItem() { return new Item(); } public IEnumerable<IItem> returnTheItemsAsList() { var newList = new List<Item>(); return newList; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display issue on HTC Flyer I have developed an application and created the xml files in different layout : * *layout-large *layout-large-1024x600 *layout-normal *layout-normal-480x320 *layout-normal-640x360 *layout-normal-640x480 *layout-normal-800x480 *layout-small *layout-small-320x240 *layout-small-400x240 I have tested the application on five different android devices and it works ok on 4 of it. On the HTC Flyer (resolution 1024x600) the result is not ok. The icon are too little not in the right place... In the eclipse graphical layout preview of the 1024x600 resolution, the result is ok. I don't understand why the result on the Flyer is not ok. I have all the image in the drawable-hdpi folder. Any help would be appreciated ! A: The problem was that I defined the 600x1024 7.0 display as HDPI instead of MDPI. Now it works OK.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to access Session information on service layer? Is there a way I can share Http/Wicket Session information to the service layer without introducing servlet api/Wicket dependency? I'll provide some context to why am I asking this question, just in case I'm missing something and asking the wrong question. I've got several entities that have groups of attributes that can be validatable. Being validatable means there are fields indicating the validation value, the user who made the validation and the date it was validated in. This is how these entities are modelled: @Embeddable public class ValidationBean<T> implements Serializable { private T validated; private String user; private Date date; // Constructors, getters, setters ahead. // ... } @Entity @Table(name="SOME_TABLE") public class SomeEntity implements Serializable, SomeInterface { // Some attributes which conform validation group 1 public String attribute11; public String attribute12; public String attribute13; private ValidationBean<Integer> validationBean1 = new ValidationBean<Integer>(); // Some attributes which conform validation group 2 public String attribute21; private ValidationBean<String> validationBean2 = new ValidationBean<Integer>(); // Constructors, various attribute getters with JPA annotations // ... @Embedded @AttributeOverrides(/*various overrides, each entity/validation group has its own validation column names...*/) public ValidationBean<Integer> getValidationBean1() { return validationBean1; } @Embedded @AttributeOverrides(/*various overrides, each entity/validation group has its own validation column names...*/) public ValidationBean<Integer> getValidationBean2() { return validationBean2; } } ValidationBean's user and date fields are automatically modified in the presentation layer when a change in the validated field is detected. All of this is working correctly. Now, I'm trying to find an elegant & general solution that integrates with the current modelling to the following requirement: When any of the attributes in a validation group gets its value changed, and the related ValidationBean.validated doesn't change, user and date must also be modified with the current user's id and the current date. There are, as I see it, two alternatives; putting that logic in the presentation layer, or in business/service layer * *Putting it in the presentation layer would have an efficieny advantage. Entities are stored in session so that the DB doesn't have to be queried again to check for field changes. But unfortunately, some entities have some of their fields ajax-updated and it would be hard to tell if the entity really changed. Apart from not being the presentation layer's responsability to fulfill this requirement. *Putting it in the service layer seems the best alternative, and I've already found a possible way to handle this properly. I've come up with @PreUpdate. It would be easy to implement a @PreUpdate method on the @Entities to compare the values in DB with the values about to be updated, and modify the related ValidationBeans accordingly. The problem here, and I suppose it's a common problem, is that in the business layer, I don't have where to get the user id from. The current user Id is stored in the Session, which belongs to the presentation layer. So, any tips, comments, recommendations on how can I share http session information to the service layer (not necessarily Wicket-specific), or even alternatives to fulfill this requirement will be welcome. UDPATE : Following gkamal's suggestion, I'll try to integrate spring-security in the less intrusive way I can, just to take advantage of SecurityContext. I'd also appreciate tips on this matter. A: The common approach used to solve this is to introduce a SecurityContext class that holds the details of the current user as a static thread local variable. The variable is initialized (from the httpsession) by the security filter or some other filter and cleared after the request processing is complete. The SecurityContext class will itself be part of the business layer which provides a set / get methods and hence doesn't have any web layer dependency.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What are the differences of that iterations? What are the differences of that iterations: var recordId; for(recordId in deleteIds){ ... } and for(var recordId in deleteIds){ ... } It says implicit definition(what is it), is there a performance difference between them? A: An "implicit declaration" is a variable that is assigned a value before it is declared using a var. The scenario leaves the variable declared in the largest possible scope (the "global" scope). However, in both your code examples, recordId is declared before it is assigned (var recordId), so there's no problem. As to your other question, no, there is no noticeable performance difference. A: the two samples are equivalent, however the first may come from following a recommended pattern in JavaScript which is declaring all variables at the top of every function. Sample: var recordId, i = 0; for(recordId in deleteIds){ ... i++; } More explanation on this can be found here JSLint error: Move all 'var' declarations to the top of the function
{ "language": "en", "url": "https://stackoverflow.com/questions/7511920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to pre-load an existing form with a data from db? i have a problem here,so here's my code <div id="educmaininfo"> <?php foreach($cv->getEducation($_GET['cvid']) as $r){ echo "<a href='#' id='editeducation'>Edit</a>&nbsp;|&nbsp;"; echo "<input type='hidden' name='cvid' value='".$r['ResumeID']."' />"; echo "<input type='hidden' name='educid' value='".$r['EducationID']."'/>"; echo "<a href='#' id='deleteeducation'>Delete</a><br />"; echo "Date From = ".$r['DateFrom']."<br />"; echo "Date To = ".$r['DateTo']."<br />"; echo "Title =".$r['Title']."<br />"; echo "Summary =".$r['Summary']."<br />"; echo "Place Organization =".$r['PlaceOrganization']."<br />"; echo "Emphasis of Study =".$r['EmphasisOfStudy']."<br />"; echo "Study Details =".$r['StudyDetails']."<br />"; echo "Qualifications =".$r['Qualifications']."<br /><br />"; } ?> </div> as you can see that code above, I added 2 hidden stuff, the cvid and the educid. my question is, how to load this form below <div id="educajaxinfo" style="display:none"> <table> <form id="educdetails" method="post" action=""> <input type="hidden" name="cvid" id="cvid" value="<?php echo $v['ResumeID']; ?>" /> <tr><td>Date From:</td><td><input type="text" name="datefromeduc" id="datefromeduc" value="" /></td></tr> <tr><td>Date To:</td><td><input type="text" name="datetoeduc" id="datetoeduc" value="" /></td></tr> <tr><td>Title:</td><td><input type="text" name="titleeduc" id="titleeduc" value="" /></td></tr> <tr><td>Summary:</td><td><textarea name="summaryeduc" id="summaryeduc" rows="10" cols="50"></textarea></td></tr> <tr><td>Place Organization:</td><td><input type="text" name="pog" id="pog" value="" /></td></tr> <tr><td>Emphasis of study:</td><td><input type="text" name="eos" id="eos" value=""></td></tr> <tr><td>Study Details:</td><td><textarea name="studyeduc" id="studyeduc" rows="10" cols="50" ></textarea></td></tr> <tr><td>Qualifications:</td><td><textarea name="qualificationseduc" id="qualificationseduc" rows="10" cols="50"></textarea></td></tr> <tr><td><input type="submit" name="update" value="<?php if($count < 3){ echo 'Add';}else{ echo 'Update';}?>" /></td></tr> </form> </table> </div> with the existing data from the db table, that matches the cvid and educid ? the flow goes like this, if user clicks the edit link, it should redirect him to the form with the values loaded in the input forms...if in pure php i can do this by just doing something like e.g edit.php?cvid=cvid&educid=educid how to do it in ajax way? A: Use jQuery to call a PHP script that returns JSON encoded data. Then use the “success” callback function to inject the data into your form. A: Use the jquery function like following a href='#' onClick=test (echo $cvid ,echo $educid ) id='editeducation'>Edit function test(cvid,educid) { jQuery.post('edit.php?cvid=cvid&educid=educid',function(response){ jQuery('#educajaxinfo').html(response); }); } include the appropriate jquery min file to use above function. on edit.php get the two id's and prepare a whole html then it will be shown in #educajaxinfo div
{ "language": "en", "url": "https://stackoverflow.com/questions/7511929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Type Erasure and Overloading? Can anyone explain in simple terms why in the below class, when I pass in a String, Integer or UUID, only the method overload taking Object as a parameter is used? public final class SkuHydratingConverter implements Converter<Object, Sku> { @Autowired private SkuService skuService; /** * Default implementation, that errs as we don't know how to convert from * the source type. */ public Sku convert(Object source) throws IllegalArgumentException { throw new IllegalArgumentException("Could not convert to Sku"); } public Sku convert(String source) throws IllegalArgumentException { return convert(Integer.valueOf(source)); } public Sku convert(Integer source) throws IllegalArgumentException { return skuService.get(source); } public Sku convert(UUID source) throws IllegalArgumentException { return skuService.get(source); } } Originally I'd wanted to implement Converter<?, ?> three times in the one class, but I soon discovered that's not possible. A: The overloading mechanism works in compile time, that is, which method to call is decided when compiling the classes, not when you run the program. Since runtime types can't (in general) be known at compile time, a snippet like this Object o = "some string"; method(o); will result in a call to a method that takes an Object as argument, as Object is the compile-time type of o. (This has nothing to do with type-erasure or generics.) A: Only method that you are actually implementing for Converter is convert(Object source), because you gave type-parameter Object in: Converter<Object, Sku> Two other convert-methods with String and UUID arguments you can call only when you use instance directly (not via interface). These two method do not override anything, they overload. Converter con = new SkuHydratingConverter(); con.convert(new String());//calls convert(Object), it does not know about any other method SkuHydratingConverter con2 = new SkuHydratingConverter(); con2.convert(new String()); //calls convert(String), because it is one with best matching type of argument. A: As others explained this is not related to erasure but the fact that convert(Object source) is bound at compile time. If you put an @Override before each you will get error in the rest, showing that only that method is overriding the super-class method. What you need is runtime checking of actual type: public Sku convert(Object source) throws IllegalArgumentException { if (source instanceof String) { return convert((String) source); } else if (source instanceof ...) { } else // none match, source is of unknown type { throw new IllegalArgumentException("Could not convert to Sku, unsuported type " + source.getClass()); } } } The other convert methods should be private.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is the Secure Canvas URL required for Localhost apps in development I am developing an application in my local machine. I let users invite their Facebook friends with a Facebook request Dialogue. The friends then click the link in their Facebook and are directed to the canvas page and then redirected out of Facebook to my local site. Do I need to have an SSL certificate and if so how can I have one when I am developing locally so I can test my site? A: From Facebook Oct.1 deadline blog post, SSL is not required for sandbox apps. So you can continue to develop apps without SSL certificate as long as you enable sandbox in your app. A: In my case, temporary DISABLE secure browsing setting in 'Account Setting'. http://gyazo.com/39e4dd5087636ebc3024d2285ab3e33a.png A: Forward works great for developing facebook apps locally, supports SSL too. https://forwardhq.com/in-use/facebook A: You need a certificate before October 1st, otherwise your canvas landing page will be blocked by Facebook. If you develop locally and need a SSL cert just for test, see the following trick for IIS: http://weblogs.asp.net/scottgu/archive/2007/04/06/tip-trick-enabling-ssl-on-iis7-using-self-signed-certificates.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7511932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: itk x and y component of the gradient of an image I would like to calculate the x and y component of the gradient of a 2D image. As in MATLAB is calculated with [dT2,dT1] = gradient(T); ReaderType::Pointer T_g // image FilterType::Pointer gradientFilter = FilterType::New(); gradientFilter->SetInput( T_g->GetOutput()); gradientFilter->Update(); With this sentence, I get the result, but I want to have the x-component and the y-component gradientFilter->GetOutput() Is there any method to extract it? I am looking for it but I have no positive result! Thanks so much Antonio A: The output of the gradientFilter will be a vector image. I assume from your description it's a 2d image! ImageType::IndexType index; index[0]=xcoord; index[1]=ycoord; gradientFilter->GetOutput()->GetPixel(index)[0]; // will return first component of xcoord,ycoord A: http://www.vtk.org/Wiki/ITK/Examples http://www.vtk.org/Wiki/ITK/Examples/ImageProcessing/NthElementImageAdaptor template class itk::NthElementImageAdaptor< TImage, TOutputPixelType > Presents an image as being composed of the N-th element of its pixels. It assumes that the pixels are of container type and have in their API an operator[]( unsigned int ) defined. Additional casting is performed according to the input and output image types following C++ default casting rules. Wiki Examples: All Examples Extract a component of an itkImage with pixels with multiple components Process the nth component/element of a vector image
{ "language": "en", "url": "https://stackoverflow.com/questions/7511939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I convert this "array of bytes" to PDF in ROR (Ruby)? Over the web service, I am returned an array of bytes. Part of which looks like the following... How do I get this back to a file? (It started as a pdf) rg1uje94ppbarWm6azwlDCJeHFFJuXlMN532v46qiyi2u/WNVHCgl10DFe64oZVSFKHN7pZ6qaulNHULZJjix33PWhzPLBVwcbptx5Husx+a7Y4q3T76KBu7pfjvXeav1emibcBSG2mMFakTv0Ho7LvYsVf57hzUq8ptL752worpSKa3L0s9IJ6Z6qIlFzDaXW4ml+3WCWvaHhUW2H+6xfFSuhjHzL8pKmd5t3aI8vsun16YY1VwLw9ivAGX+GUPRVBOTYpVqgLikJhKB7Fkpn5SJSATFAQGoviYGsw7A+B2hA0dpVlisUf0mvC2LjYwfEhcUPGmvwG3sRpGJkUPtzXWx+5a2UaTOtytnLR9qwFbXKf8s2DxS9dR/p+/rwjb9mr24p7E2e8e/ZWNP7dpX7V7xJWpLAxu67lOYhixHFPRZff6063L5q8yGXtOc/J/YP5sSev6l8trGk+c+WNXSa5+b7PfpqY/WJbkefxp4Xe5RfaHqx6oqU/o9ObBdjn3MDm3MzkvFmrvWaXfPavC9s6/8gZZdMeI3cPyp8n/nBSnpjXYUwelZlyKm+ek7Pl8YfhXM4c6uTwxhPyJvZscfRnzaSd7cwWLTs3zj8ucXWe7TGzR+NGXumfk7HqVXCAkrJVS/T+uNDXKHSh5viMpPuTzW+vXu7vIj7eOXLT47XX1vYynzBdcaGx1qo0qrEijTL81UcSZRrFwS7Zv72L/paRvgswpPVdNKe/Qq9hT2R/XQXC8De/HaGVqkC1rkqFIxCto1vzFn1+1xGpOgu+fG/I7P7NBiqm+Ri823b7edVvMEvoIuVLjvjJ7Mv3nTRcV2ZKn+CeR06xqGtHnfN6XVCyyiRx8d2DdxbM0Whz19Imd928mSGz9KpLbXZ0NZhaNX7e08BjbR4fsO+fcdZ7fnhMz0FN2rEnplApbV+aLRt/zHFc15fDpt3/6Kz77vjM+aGNgjJ/eaCpseryirwPdcHuovZPLr3sVRnp2XZwpwH5hwrK0u3vB Ive tried a few things, the closest is as follows (though I am unsure by the output if it is correct): File.open(pdf_filename, 'w' ) do |output| byteArray.each_byte do | byte | output.print byte puts byte end end which returns in the console the following but does not create a valid file ( I assume these numbers are the bytes in Integer (base10)form or something?) : 77 52 79 89 57 etc.. A: I am no expert.. I am learning ruby myself at the moment (looking at questions on SO to vary techniques a bit ;-) but have you tried: File.open(pdf_filename, 'wb' ) do |output| byteArray.each_byte do | byte | output.print byte puts byte end end or maybe even (I really don't know if that will work) I don't have Ruby installed here to test: File.open(pdf_filename, 'wb') { |output| output << byteArray } I got this info from here (among other places): http://strugglingwithruby.blogspot.com/2008/11/ruby-file-access.html Binaries files are just the same; you just add a b to the second parameter of the open method. Depending on your byte array format, you may need to use the unpack method. File.open(pdf_filename, 'wb' ) do |output| output << byteArray.unpack("m") end See the following for possible parameters in the unpack method: http://www.codeweblog.com/ruby-string-pack-unpack-detailed-usage/
{ "language": "en", "url": "https://stackoverflow.com/questions/7511941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I disable a horizontal mouse scroll with JS? I am building a one page site that uses javascript to navigate vertically and horizontally across the page to see different content. I want the user to be able to scroll up and down but not horizontally (currently the user can scroll horizontally in FireFox and see content they shouldn't be able to see unless they use the navigation. Unfortunately I can't use overflow-x: hidden; because it interferes with the smooth-scroll JS I am using. I did find some script (below) to disable any mouse wheel movement but I only want to disable the horizontal movement. Can anyone help? document.addEventListener('DOMMouseScroll', function(e){ e.stopPropagation(); e.preventDefault(); e.cancelBubble = false; return false; }, false); A: I ran into this same problem as well, the "overflow-x:hidden" CSS trick is nice, but it doesn't work for the horizontal scrolling capability of the Mac Mouse (FF only). The code you have works fine, but obviously kills both vertical and horizontal scrolling. I think the extra bit you need there is to check the "e.axis" property. Here's what I have: document.addEventListener('DOMMouseScroll', function(e) { if (e.axis == e.HORIZONTAL_AXIS) { e.stopPropagation(); e.preventDefault(); e.cancelBubble = false; } return false; }, false); Hope that helps! A: Well, your code work only in firefox, so here is a more universal solution, but it's also kill the vertical scroll and so far I couldn't figure out how to stop that. if(window.addEventListener){ window.addEventListener('DOMMouseScroll',wheel,false);} function wheel(event){ event.preventDefault(); event.returnValue=false;} window.onmousewheel=document.onmousewheel=wheel; A: After some experimentation, this bit of code works $(window).bind('mousewheel', function(e){ if(e.originalEvent.wheelDeltaX != 0) { e.preventDefault(); } }); $(document).keydown(function(e){ if (e.keyCode == 37) { e.preventDefault(); } if (e.keyCode == 39) { e.preventDefault(); } }); This prevents the OSX magic mouse, track pad and default arrow keys from causing horz scrolling in safari, chrome and ff as of their latest release. I can make no claim to this being the best solution, but it works. I fear it may cause performance issues as its comparing the x-axis delta of wheel scroll to 0. A: You can do it simply with css styles. <body style=" overflow-x:hidden; "> <style> body { overflow-x:hidden; } </style>
{ "language": "en", "url": "https://stackoverflow.com/questions/7511949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Assembly Language: Memory Bytes and Offsets I am confused as to how memory is stored when declaring variables in assembly language. I have this block of sample code: val1 db 1,2 val2 dw 1,2 val3 db '12' From my study guide, it says that the total number of bytes required in memory to store the data declared by these three data definitions is 8 bytes (in decimal). How do I go about calculating this? It also says that the offset into the data segment of val3 is 6 bytes and the hex byte at offset 5 is 00. I'm lost as to how to calculate these bytes and offsets. Also, reading val1 into memory will produce 0102 but reading val3 into memory produces 3132. Are apostrophes represented by the 3 or where does it come from? How would val2 be read into memory? A: You have two bytes, 0x01 and 0x02. That's two bytes so far. Then you have two words, 0x0001 and 0x0002. That's another four bytes, making six to date. The you have two more bytes making up the characters of the string '12', which are 0x31 and 0x32 in ASCII (a). That's another two bytes bringing the grand total to eight. In little-endian format (which is what you're looking at here based on the memory values your question states), they're stored as: offset value ------ ----- 0 0x01 1 0x02 2 0x01 3 0x00 4 0x02 5 0x00 6 0x31 7 0x32 (a) The character set you're using in this case is the ASCII one (you can follow that link for a table describing all the characters in that set). The byte values 0x30 thru 0x39 are the digits 0 thru 9, just as the bytes 0x41 thru 0x5A represent the upper-case alpha characters. The pseudo-op: db '12' is saying to insert the bytes for the characters '1' and '2'. Similarly: db 'Pax is a really cool guy',0 would give you the hex-dump representation: addr +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F +0123456789ABCDEF 0000 50 61 78 20 69 73 20 61 20 72 65 61 6C 6C 79 20 Pax is a really 0010 63 6F 6F 6C 20 67 75 79 00 cool guy. A: val1 is two consecutive bytes, 1 and 2. db means "direct byte". val2 is two consecutive words, i.e. 4 bytes, again 1 and 2. in memory they will be 1, 0, 2, 0, assuming you're on a big endian machine. val3 is a two bytes string. 31 and 32 in are 49 and 50 in hexadecimal notation, they are ASCII codes for the characters "1" and "2".
{ "language": "en", "url": "https://stackoverflow.com/questions/7511951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Service Stack Hello World tutorial: exception EndpointHost.Config is null I am following the service stack "Hello World" tutorial from http://www.servicestack.net/ServiceStack.Hello/ . But when I am trying to start the asp.net application it says "Value can't be null. Parameter Name: EndpointHost.Config". The full exception text is: [ArgumentNullException: Der Wert darf nicht NULL sein. Parametername: EndpointHost.Config] [ConfigurationErrorsException: ServiceStack: AppHost does not exist or has not been initialized. Make sure you have created an AppHost and started it with 'new AppHost().Init();' in your Global.asax Application_Start()] ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory..cctor() in C:\src\ServiceStack\src\ServiceStack\WebHost.EndPoints\ServiceStackHttpHandlerFactory.cs:45 [TypeInitializationException: Der Typeninitialisierer für "ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory" hat eine Ausnahme verursacht.] [TargetInvocationException: Ein Aufrufziel hat einen Ausnahmefehler verursacht.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230 System.Activator.CreateInstance(Type type, Boolean nonPublic) +67 System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +1051 System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +111 System.Web.Configuration.HttpHandlerAction.Create() +57 System.Web.Configuration.HandlerFactoryCache..ctor(HttpHandlerAction mapping) +19 System.Web.HttpApplication.GetFactory(HttpHandlerAction mapping) +96 System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +125 System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 My global class is: public class Global : System.Web.HttpApplication { /// Web Service Singleton AppHost public class InfoAppHost : AppHostBase { //Tell Service Stack the name of your application and where to find your web services public InfoAppHost() : base("Services", typeof(InfoService).Assembly) { } public override void Configure(Funq.Container container) { } } protected void Application_Start(object sender, EventArgs e) { //Initialize your application var appHost = new InfoAppHost(); appHost.Init(); } } But it seems to never get called. Compiling the example project from the homepage works fine - but I would like to follow the example from the homepage. Any ideas how to solve this problem ? A: I've deleted my test project and tried the tutorial once again. When creating the Global.asax file I've deleted the whole class and made another class Global in this file. It seems Application_Start never got called in this class. A: The problem as you might have guessed is that appHost.Init() hasn't run. Try wrapping it in a try/catch and logging any errors that might have been thrown. A: We had the same problem and solved it by setting "Activate 32-bit-applications" to true in the extended ApplicationPool Settings. (sorry, only have a german Windows so the Settings names are rough guesses) A: Took me a while to figure out what I was doing wrong to cause this issue... this happened to me because I accidentally dragged the Global.asax file into a subfolder in my project. A: I found that this error is caused by the WebApiConfig. The example is using ServiceStack and does not not need ASP.NET Web API. That line needs to be commented out inthe Gloabal.asax.cs file. protected void Application_Start() { AreaRegistration.RegisterAllAreas(); // ** comment out ** WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); new ProteinTrackerAppHost().Init(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7511954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: sorting in XPath using Java I am using XML in my project for data to be Insert/Update/Delete & Searching. currently i am using XPath for doing the above operations from my JAVA application. How can i sort the data[ascending/descending] while reading from XML file using XPath. Can anyone tell me the best way to full-fill this requirement. It's an urgent. A: Here is my suggestion: * *XPath will give you a list of elements in the form of an array of Nodes. *Now this becomes a typical case of sorting an array (hence you can use any of those many sorting algorithms ), but not so straightforward as the elements of the array will be Nodes and you need to compare two nodes. *U will have to write a function where in you will pass two array elements (Nodes). This fn will return true/false depending on comparison of two nodes. *In this function, extract the values based on which the sorting is to be done. Compare those two values and return true/false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Winforms - Notifying/Publishing events in a control hierarchy I have a hierarchy of controls like - MainForm (has menus / toolbars) |____TabContainer |_____TabPages |_____TreeView...etc. Now, after the data has been loaded in the TreeView and user selects a particular Node element - I want to notify the MainForm as well as some controls up in the hirarchy from the TreeView and change the controls(s) state accordingly based on the NodeClicked event. I am maintaining a static EventMgr class where I publish all events and the the controls which are interested in particular events, listen to it. I know there are better ways to design such that Unit Testing becomes easy ? Any ideas ? A: Implementing the Delegates will be a better option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scroll to certain position for 'single' pages In my WordPress site, on single pages, I'd like the scroll bar to automatically scroll to a certain position (say, 400px from the top). The reason is because I have a video player under the header that shows on every page. When the user clicks on a post from the home page, I want the post to come up in the single page without the user having to scroll down. I'm guessing I can use the scroll.to function but am unsure how to go about it. Does anyone have an idea how I can go about this? A: If you don't want to actually 'slide' down the page. You could just use anchors to link to a page, and a point on that page: http://www.webmasterslibrary.com/articles/readArticle.jsp?cid=anchors
{ "language": "en", "url": "https://stackoverflow.com/questions/7511962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate help document (or chm) from dotnet comments I was reading some technical material of dotnet and then i came to know that there is a way by which we can generate good help document from dotnet comments Can anyone please help me to know that how to generate help document from comment in dotnet. whether this is microsoft utility or third party component? A: you can use nDoc: NDoc the usual good practice is to setup your projects to generate XML files and also, as my suggestion, to set treat al warnings as errors; in this way your code will be cleaner and no errors and no warnings allowed and you will be notified at compile time if any public method or property or class does not have the XML comment. After that NDoc does all the job for you ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7511964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLite3 Database file - Corrupted/Encrypted only on Linux I am currently writing a Python script to interact with an SQLite database but it kept returning that the database was "Encrypted or Corrupted". The database is definitely not encrypted and so I tried to open it using the sqlite3 library at the command line (returned the same error) and with SQLite Manager add-on for Firefox... I had a copy of the same database structure but populated by a different instance of this program on a windows box, I tried to open it using SQLite Manager and it was fine, so as a quick test I loaded the "Encrypted or Corrupted" database onto a USB stick and plugged it into the windows machine, using the manager it opened first time without issues. Does anyone have any idea what may be causing this? EDIT: On the Linux machine I tried accessing it as root with no luck, I also tried chmoding it to 777 just as a test (on a copied version of the DB), again with no luck A: Does your Linux box have the same version of SQLite as your Windows box? An old version of SQLite may not be able to recognize files that use newer features. For example, WAL journal mode. To prevent older versions of SQLite from trying to recover a WAL-mode database (and making matters worse) the database file format version numbers (bytes 18 and 19 in the database header) are increased from 1 to 2 in WAL mode. Thus, if an older version of SQLite attempts to connect to an SQLite database that is operating in WAL mode, it will report an error along the lines of "file is encrypted or is not a database". A: You should check the user privileges, the user on linux may not have enough privileges.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pythonic way to replace text with xml nodes I'm wondering if anyone can come up with a more 'pythonic' solution to the problem I'm currently trying to solve. I've got a source XML file that I'm writing an XSLT generator for. The relevant part of the source XML looks like this: ... <Notes> <Note> <Code>ABC123</Code> <Text>Note text contents</Text> ... </Note> <Note> ... </Note> ... </Notes> ... And I have some objects anaologous to these: from lxml.builder import ElementMaker #This element maker has the target output namespace TRGT = ElementMaker(namespace="targetnamespace") XSL = ElementMaker(namespace="'http://www.w3.org/1999/XSL/Transform', nsmap={'xsl':'http://www.w3.org/1999/XSL/Transform'}) #This is the relevant part of the 'generator output spec' details = {'xpath': '//Notes/Note', 'node': 'Out', 'text': '{Code} - {Text}'} The aim is to generate the following snippet of XSLT from the 'details' object: <xsl:for-each select="//Notes/Note"> <Out><xsl:value-of select="Code"/> - <xsl:value-of select="Text"/></Out> </xsl:for-each> The part I'm having difficulty doing nicely is replacing the {placeholder} text with XML nodes. I initially tried doing this: import re text = re.sub('\{([^}]*)\}', '<xsl:value-of select="\\1"/>', details['text']) XSL('for-each', TRGT(node, text) select=details['xpath']) but this escapes the angle bracket characters (and even if it had worked, if I'm being fussy it means my nicely namespaced ElementMakers are bypassed which I don't like): <xsl:for-each select="//Notes/Note"> <Out>&lt;xsl:value-of select="Code"/&gt; - &lt;xsl:value-of select="Text"/&gt;</Out> </xsl:for-each> Currently I have this, but it doesnt feel very nice: start = 0 note_nodes = [] for match in re.finditer('\{([^}]*)\}', note): text_up_to = note[start:match.start()] match_node = self.XSL('value-of', select=note[match.start()+1:match.end()-1]) start = match.end() note_nodes.append(text_up_to) note_nodes.append(match_node) text_after = note[start:] note_nodes.append(text_after) XSL('for-each', TRGT(node, *note_nodes) select=details['xpath']) Is there a nicer way (for example to split a regex into a list, then apply a function to the elements which were matches) or am I just being overly fussy? Thanks! A: note_nodes=re.split(r'\{(.*?)\}',details['text']) # ['', 'Code', ' - ', 'Text', ''] note_nodes=[n if i%2==0 else XSL('value-of',select=n) for i,n in enumerate(note_nodes)]
{ "language": "en", "url": "https://stackoverflow.com/questions/7511968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery tabs...collapsible when out of focus I'm using jquery tabs (http://jqueryui.com/demos/tabs/mouseover.html) as dropdown menu for my work. First Tab, I use for 'Home' and make the content to be hide. My question is, how i can make the content of the tab collapsible when lost focus on tabs content, right now when i want to make all tabs collapsible, i had to hover to 'Home' tab. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7511969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to insert hash into hash in Perl I have a simple hash defined somewhere in the main file our %translations = ( "phrase 1" => "translation 1", # ... and so on ); In another file I want to add some more translations. That is, I want to do something like this: push our %translations, ( "phrase N" => "blah-blah", # .... "phrase M" => "something", ); Of course this code wouldn't work: push doesn't work with hashes. So my question is: what is a simple and elegant way to insert a hash of values into an existing hash? I wouldn't want to resort to $translations{"phrase N"} = "blah-blah"; # .... $translations{"phrase M"} = "something"; since in Perl you're supposed to be able to do things without too much repetition in your code... A: You can assign to a hash slice: @translations{@keys} = @values; or using data from another hash: @translations{keys %new} = values %new; A: %translations = ( "phrase N" => "blah-blah", # .... "phrase M" => "something", %translations ); A: Hash::Merge is another option: https://metacpan.org/module/Hash::Merge also - don't worry too much about optimization in copying hashes - if it becomes a problem, look into it then. Just try and write good clear readable and maintainable code first of all. A hash of several thousand keys with string values is not large! what you haven't specified in your question, is whether there will be any collision of keys (i.e. could there ever be two 'Phrase 1's read from the files...? A: %translations = (%translations, %new_translations); A: You can assign to a hash slice using the keys and values functions. As long as the hash isn't modified between the calls, keys will return the keys in the same order that values returns the values. our %translations = ( "phrase 1" => "translation 1", ); { # Braces just to restrict scope of %add my %add = ( "phrase N" => "blah-blah", "phrase M" => "something", ); @translations{keys %add} = values %add; } # Or, using your alternate syntax: @translations{keys %$_} = values %$_ for { "phrase N" => "blah-blah", "phrase M" => "something", }; A: I know, it's already said. But I want highlight an aspect: Following overwrites existing values in you hash: %translations = ( %translations, "phrase N" => "blah-blah", "phrase M" => "something" ); Following does not: %translations = ( "phrase N" => "blah-blah", "phrase M" => "something", %translations ); Example 1 my %translations = ( a => 'first', b => 'second'); %translations = (%translations, a => 'at first', c => 'third'); Now you have: "a" => "at first" # its overwritten by the new value "b" => "second" "c" => "third" Example 2 my %translations = ( a => 'first', b => 'second'); %translations = (a => 'at first', c => 'third', %translations); Now you have: "a" => "first" # the old value is not overwritten "b" => "second" "c" => "third"
{ "language": "en", "url": "https://stackoverflow.com/questions/7511970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: display lines in AS3 I am baffled by this function, which is called prior to this with parameters 22 and 58 for xVal ad yVal respectively. It doesn't display anything when the swf is compiled and tested, and it's error free. The code is in the document class: private function mLine(xVal : int, yVal : int) { var rCol = 0x0000FF; var incr = Math.round((Math.random() * 20) + 8); lns.push(new Shape()); var i = lns.length - 1; this.addChild(lns[i]); lns[i].graphics.moveTo(xVal, yVal); lns[i].graphics.lineStyle(10, rCol); lns[i].graphics.lineTo(xVal, yVal + 20); lns[i].name = incr; trace("lns[" + i + "] x is " + lns[i].x); // outputs 'lns[0] x is 0' trace("xVal is " + xVal); // outputs 'xVal is 22' trace("yVal is " + yVal); //outputs 'yVal is 58' trace(stage.contains(lns[i])); // outputs 'true' } A: Assuming you have declared private var lns = []; somewhere, it draws a blue line (20px straight down from the given position). It doesn't display anything That means you probably don't have an object of that class on the stage. In your document class, you should use addChild to display an instance of the class containing mLine. mLine needs to be called somehow obviously. You could do this in the class' constructor, but you'd need to remove the last trace statement to avoid a null pointer error, because stage would be null then. Edit: Missed that you said it is in the Document class. So, try and see if drawing anything else works. The problem doesn't seem to be with this function. A: Your code seems like it should work. I have rewrote it to conform better to ActionScript 3 best practices private function drawLine(xVal:int, yVal:int):void { var lineColor:uint = 0x0000FF; var lineShape:Shape = new Shape(); //lineShape.name = String(Math.round((Math.random() * 20) + 8)); lineShape.graphics.lineStyle(10, lineColor); lineShape.graphics.moveTo(xVal, yVal); lineShape.graphics.lineTo(xVal, yVal + 20); addChild(lineShape); lines.push(lineShape); } The x and y properties of your shape will both be zero because you never set them. you are just drawing lines inside the shape at the xVal and yVal. You could do the same thing like this: private function mLine(xVal:int, yVal:int) { var lineColor:uint = 0x0000FF; var lineShape:Shape = new Shape(); //lineShape.name = String(Math.round((Math.random() * 20) + 8)); lineShape.graphics.lineStyle(10, lineColor); lineShape.graphics.moveTo(0, 0); lineShape.graphics.lineTo(0, 20); lineShape.x = xVal; lineShape.y = yVal; addChild(lineShape); lines.push(lineShape); } Not sure why its not showing up at all for you though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access the properties on a XML Node via linq? I read through this post. I have this XML: <?xml version="1.0" encoding="utf-8" ?> <Export version="" srcSys="" dstSys="" srcDatabase="" timeStamp=""> </Export> This is what i tried, but with no luck: var xml = XElement.Parse(BuyingModule.Properties.Resources.Export); Func<XElement, string, string> GetAttribute = (e, property) => e.Elements("property").Where(p => p.Attribute("name").Value == property).Single().Value; var query = from record in xml.Elements("Export") select record; var prop = GetAttribute(query.FirstOrDefault(), "version"); How do i access to properties of the "Export" Node? I need to set those properties A: The Export element doesn't have a properties element, which is what your GetAttribute method is trying to find. My guess is you actually want: var element = xml.Element("Export"); // Just get the first element var version = (string) element.Attribute("version"); It's not clear to me why you've used a query expression and a delegate here - it's just things more complicated than you need. But Attribute(XName) is probably what you were missing...
{ "language": "en", "url": "https://stackoverflow.com/questions/7511973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Objective-C – ShareKit customize Twitter navigation bar Does anyone know how to customize the Twitter navigation bar in ShareKit? (change colors and add image) Cheers, Peter A: In SHKTwitterForm.m add the line given below inside - (void)viewDidAppear:(BOOL)animated self.navigationController.navigationBar.tintColor = [UIColor redColor]; You can tweak this class to customize more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Too many timeouts in android? i have an Http client in my android app that changes messages with a server. lately 2 out of every 3 ( approx) messages i send to the server get timed out is that normal? Thanks in advance! Omri A: Try finding the source for the timeout. It's definitely not normal to get a timeout on a simple request/response. Did you try timing how long it takes for the request to reach your server? How long does it take it for your server to issue the response? How long does it take for the client to receive this response? You can add print outs to the server and client after syncing their clocks, showing the time of each of these steps. Then find the problem in your code (probably) that causes these delays.
{ "language": "en", "url": "https://stackoverflow.com/questions/7511989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sql Server Reporting Services Web Service access problem from a Silverlight Application I hope you can help me with this one... :) I have a .net application which holds a Silverlight component. I also have Sql Server 2008 R2 with Reporting Services installed. The SSRS has been added to the Silverlight App as a Web Service Reference. The above is all running on one development machine (so no cross domain stuff I think, I'm new to SSRS and Web Services). The issue im having is - when I call/try to access the SSRS web service .asmx (http://localhost/ReportServer_sql2008r2/ReportService2010.asmx) from the SSRS web service reference class in the Silverlight App, I get the following error message:- 'An error occurred while trying to make a request to URI 'http://localhost/ReportServer_sql2008r2/ReportService2010.asmx'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.' My thoughts on the error message - I think the stuff about cross domain policy is irrelevant, as this set up is all on one machine. Other than that I don't know what to look for. I searched on this for 2 days and even started reading about Code Access Security, CAS, but not sure if that is the source of the problem. Any any thoughts would be much appreciated. If you need more info no problem. Thanks Rob A: If this error is happening on the client, it might be relevant to know how you are accessing the SL page. If you are accessing it by domain, ie: http://Mycompanyname.com/, then the "localhost" reference can be considered cross site
{ "language": "en", "url": "https://stackoverflow.com/questions/7511996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Tabs problem in Tablet fragment Like for list view there is ListFragment.So is there anyway to so that i can put tabs inside one fragment like TabActivity? A: You can use a TabHost inside a fragment, see the Google IO app, it does this for the session details fragment: http://code.google.com/p/iosched/source/browse/android/src/com/google/android/apps/iosched/ui/SessionDetailFragment.java
{ "language": "en", "url": "https://stackoverflow.com/questions/7512001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActiveMQ with C# and Apache NMS - Count messages in queue I'm using ActiveMQ to send and receive messages using a C# app. However I'm having some difficulty just getting a count of the messages in the queue.. Here's my code: public int GetMessageCount() { int messageCount = 0; Uri connecturi = new Uri(this.ActiveMQUri); IConnectionFactory factory = new NMSConnectionFactory(connecturi); using (IConnection connection = factory.CreateConnection()) using (ISession session = connection.CreateSession()) { IDestination requestDestination = SessionUtil.GetDestination(session, this.QueueRequestUri); IQueueBrowser queueBrowser = session.CreateBrowser((IQueue)requestDestination); IEnumerator messages = queueBrowser.GetEnumerator(); while(messages.MoveNext()) { messageCount++; } connection.Close(); session.Close(); connection.Close(); } return messageCount; } I thought I could use the QueueBrowser to get the count, but the IEnumerator it returns is always empty. I got the idea of using QueueBrowser from this page, but maybe there is another way I should be doing this? Update: The solution to the 'infinite loop' issue I found when going through the enumerator was solved by accessing the current message. It now only goes through the loop once (which is correct as there is only one message in the queue). New while loop is: while(messages.MoveNext()) { IMessage message = (IMessage)messages.Current; messageCount++; } A: I don't have an ActiveMq with me right now so I can not try it but I think the problem is you are not starting the connection. Try like this : using (IConnection connection = factory.CreateConnection()) { connection.start (); using (ISession session = connection.CreateSession()) { //Whatever... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7512004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Auto expand the element height, if content is bigger in multiple elements css I have this: http://jsfiddle.net/UHrLH/1/ I set the height on the box element to auto, but min-height is 200px; Now if i try to make more content in the first box, the height expands but it creates a big white space under it. I do not want that, i want to have the box under eachother like you can see above, where the height on all boxes is 200px See the issue here: http://jsfiddle.net/UHrLH/2/ A: http://jsfiddle.net/chricholson/UHrLH/10/ This will give you boxes inline but unfortunately the pairs will not extend to match the height of it's partner. To do this you will need to use tables or a javscript overwrite to capture the height. Also, bear in mind display: inline-block will not work on divs in IE7 and below, it would work on a span though: http://www.quirksmode.org/css/display.html#t03 A: http://jsfiddle.net/UHrLH/11/ I have added an additional div if that is ok for you... <div class="box_Container">
{ "language": "en", "url": "https://stackoverflow.com/questions/7512006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: add class to parent if child exists hi im using codeigniter to generate a form the form error only shows if there is an error for that field i to use twitter-bootstrap for styling so i need a way to add a class of error to both the div (with class="clear fix") and the input if (span class="help-inline") exists as child. would prefer not to use query so it will degrade properly but any option would be good any help would be great. hope that makes sense. code is below thanks <?php echo form_open('login'); ?> <fieldset> <div class="clearfix"> <?php echo form_label('Email Address: ', 'email_address');?> <div class="input"><?php echo form_input('email_address', set_value('email_address'), 'id="email_address" class="xlarge" autofocus ');?> <?php echo form_error('email_address', '<span class="help-inline">', '</span>'); ?> </div> </div><!-- /clearfix --> <div class="clearfix"> <?php echo form_label('Password: ', 'password');?> <div class="input"><?php echo form_input('password', '', 'id="password" class="xlarge"');?> <?php echo form_error('password', '<span class="help-inline">', '</span>'); ?> </div> </div><!-- /clearfix --> <div class="actions"> <?php echo form_submit('submit', 'Login', 'class="btn primary"'); ?> </div> </fieldset> <?php echo form_close(); ?> rendered html(if error is triggered) <form action="http://unetics.site/index.php/login" method="post" accept-charset="utf-8"> <div style="display:none"> <input type="hidden" name="csrf_test_name" value="c0856f469b1f498480881a8512042ccf" /> </div> <fieldset> <div class="clearfix"> <label for="email_address">Email Address: </label> <div class="input"> <input type="text" name="email_address" value="" id="email_address" class="xlarge" autofocus /> <span class="help-inline">The Email Address field is required.</span> </div> </div><!-- /clearfix --> <div class="clearfix"> <label for="password">Password: </label> <div class="input"><input type="text" name="password" value="" id="password" class="xlarge" /> <span class="help-inline">The Password field is required.</span> </div> </div><!-- /clearfix --> <div class="actions"> <input type="submit" name="submit" value="Login" class="btn primary" /> </div> </fieldset> </form> A: I'd suggest using: $('.help-inline').closest('.clear-fix').addClass('error').end().prev('input').addClass('error'); JS Fiddle demo. JS Fiddle demo, with your rendered html (note that I've changed the jQuery closest() to: closest('.clearfix')). Or: $('.clear-fix').each( function(){ if ($(this).has('.help-inline')){ $(this).addClass('error'); $(this).find('input').addClass('error'); } }); JS Fiddle demo. JS Fiddle demo, with your rendered html (note that I've changed the jQuery selector to: $('.clearfix')).
{ "language": "en", "url": "https://stackoverflow.com/questions/7512016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Php Contact Form Subject Field I have this on my contact.php file: '.JText::_('PLG_LABEL_NAME').' <input type="text" name="name" id="name" value="'.$_POST['name'].'" /> <br /> <br /> '.JText::_('PLG_LABEL_EMAIL').' <input type="text" name="email" id="email" value="'.$_POST['email'].'" /> <br /> <br /> '.JText::_('PLG_LABEL_SUBJECT').' <input type="text" name="subject" id="subject" value="'.$_POST['subject'].'" /> <br /> <br /> Which of these two or where do i add these codes? <?php if($this->item->params->get('itemTitle')): ?> <?php echo $this->item->title; ?> Thanks in advance by the way. It's outside of the scope file. The file containing the item is in item.php and it has this line to get the item title and display it as <?php if($this->item->params->get('itemTitle')): ?> <!-- Item title --> <h2 class="itemTitle"> <?php echo $this->item->title; ?> A: Like this? $html .= '<label for="contact_subject">'; $html .= '&nbsp;'. JText::_( 'Subject' ).':'; if ($this->item->params->get('itemTitle')) $html .= $this->item->title; $html .= '</label>';
{ "language": "en", "url": "https://stackoverflow.com/questions/7512017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save images into Database I'd like to know if there's a way to save Images (of the type .gif) to the sqllite-database. If yes how should my DatabaseAdapter look like. Also is there a performance issue? A: There's nothing special in storing image to SQLite. Just create table with BLOB record type and do smth like: protected long saveBitmap(SQLiteDatabase database, Bitmap bmp) { int size = bmp.getRowBytes() * bmp.getHeight(); ByteBuffer b = ByteBuffer.allocate(size); bmp.copyPixelsToBuffer(b); byte[] bytes = new byte[size]; b.get(bytes, 0, bytes.length); ContentValues cv=new ContentValues(); cv.put(CHUNK, bytes); this.id= database.insert(TABLE, null, cv); } Probably you migth want to save image chunk by chunk, since there's limits/recommended BLOB size (don't really recall how much) A: You should use BLOB in your database: Check this tutorial... But I think you should download and store image in HashMap, which will make it simpler. Code: Stroring var imageMap = new HashMap<String, byte[]>(); var imageUrl = "http://i.stack.imgur.com/TLjuP.jpg"; var imagedata = GetImage(imageUrl); imageMap.put("img",imagedata); Retrieving var imageData = imageMap.get("img"); var imageStream = new ByteArrayInputStream(imageData); var image = BitmapFactory.decodeStream(imageStream); GetImage private byte[] GetImage(String url) { try { var imageUrl = new URL(url); var urlConnection = imageUrl.openConnection(); var inputStream = urlConnection.getInputStream(); var bufferedInputStream = new BufferedInputStream(inputStream); var byteArrayBuffer = new ByteArrayBuffer(500); int current = 0; while ((current = bis.read()) != -1) { byteArrayBuffer.append((byte)current); } return byteArrayBuffer.toByteArray(); } catch (Exception e) { Log.d("ImageManager", "Error: " + e.toString()); return null; } } Hope it helps you. A: Check this tutorial, it should show you what you need. Another useful link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7512019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: custom webdav implementation in IIS, gives 405 on PROPFIND I have created a custom webdav implementation with a HttpHandler, to serve files in a database via webdav protocol to a client. On Cassini, my VS Development server I can access this without problems. Now I am trying to debug this site in IIS, and that doesn't work. I have the IIS 7.5 Webdav module uninstalled. Some snippets of my web.config: <system.web> ... <httphandlers> <add type="Test.WebDAVHandler, Test" verb="*" path="*"></add> </httphandlers> ... </system.web> <system.webserver> <modules runAllManagedModulesForAllRequests="true"> <remove name="WebDAVModule"> </remove> </modules> <validation validateIntegratedModeConfiguration="true"> <defaultdocument enabled="true"> <files> <add value="example.aspx"></add> </files> </defaultdocument> <handlers accessPolicy="Read,Write,Execute,Script"> <remove name="WebDAV"> <add name=".NET Runtime" verb="*" path="*" preCondition="classicMode,runtimeVersionv2.0,bitness64" requireAccess="None" resourceType="Unspecified" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" modules="IsapiModule"> </add> </handlers> </validation> </system.webserver> When I connect to this site by using the Map network drive option of Windows 7 and inspect the requests using Fiddler, I see that the after some authentication, the client does the following request: OPTIONS localhost/explorer and gets the following (shortened) response. HTTP/1.1 200 OK Allow: OPTIONS, TRACE, GET, HEAD, POST I am missing some allowed verbs here, like PROPFIND. The next request the client does is a PROPFIND. The server responds with a 405 Method not allowed. I looked at the request tracing, and the DefaultDocumentModule is causing this error. When I disable this module, the DirectoryListingModule causes this 405. Does anyone have a clue how to fix this, so that I can use webdav with my custom handler?
{ "language": "en", "url": "https://stackoverflow.com/questions/7512022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java EE Servlet/filter/phase listener difference and order of processing I want to know what the order of processing requests is and what's the difference between servlet (@WebServlet), filter (@WebFilter), phase listeners etc. These methods have very similar headers (doGet/doFiler). A: The processing of a request in regard to filtering and then processing by a servlet is described here: http://download.oracle.com/docs/cd/B32110_01/web.1013/b28959/filters.htm Thus you'd mainly use a servlet do deliver content and maybe alter request/response using filters. Filters can be used to implement a pipes and filters or a decorator design pattern. (Though they can also deliver content by themselves and don't forward delegation to final processing by a servlet at all.) So much to the servlet request processing. PhaseListeners are a higher abstraction level concept. They don't belong to the servlet spec but to the Java Server Faces Concepts building ontop of servlets. They can be used to track the phases your JSF Components go through during a request and thus are the alternative for filters when you want to influence behaviour/rendering of JSF components during a request. A litte example for the usage of phase listeners can be found here: http://www.softwareengineeringsolutions.com/thoughts/frameworks/JSF.Techniques-PhaseListeners.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7512024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Stored Procedures To Run Automatically I have an asp.NET framework 4 web form website with user login capabilities etc etc... Im using visual studio 2010. Each user has 3 login attempts once the log in attempts has passed 3, their account is locked. The only way to unlock these accounts is via the admin panel. however a need a stored procedure or trigger that sets all the login attempts to zero each day. This way the login attempts wont be accumulative, just a daily counter. How would this be done? A: If you storing login attempts count in any table for each user then you can create one job which runs every day and make attempt count to 0 for each user. If you have no idea about how to create job then please refer this link : Job in SQL 2005 Job in SQL 2000 A: You can use the SQL Server Agent to schedule a job. http://msdn.microsoft.com/en-us/library/ms189089.aspx Add a step that simply sets the login attempts field to 0 for every user, and schedule it to run daily. A: If you have control over your SQL Server, then have a look at running a SQL Agent Job or writing a Windows Service. If you are outsourced to Azure, you can wrap your SProc in a Service call and use the Task Scheduler Service. Also, look here and here A: As the other answers say, you can create a job for SQL Server Agent, and have it execute once a day. However, I generally distrust this kind of solution - if the Agent job fails for some reason, you could end up locking people out of the application and never know about it. I'd recommend storing the attempts in a "login_attempts" table, with a time stamp, and writing your query to filter out attempts older than 24 hours.
{ "language": "en", "url": "https://stackoverflow.com/questions/7512025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL find name doubles and sum values I have one table records with the columns: |rec.id|rec.name|user.name|hours| and the values respectively: |1 |google |Admin | 12 | |2 |yahoo |Admin | 1 | |3 |bing |Manager | 4 | What i want to do is take all of the records with the same user.id and sum there hours together in SQL. Perhaps its the early mornign but i cant seem to figure out a way of doing this. I thought about using sql to find the duplicates but thats only going to return a number and not what i want to do with them. This sounds like a really simple thing so sorry in advance. A: select user_name, sum(hours) from your_table group by user_name; A: You would group on the user name and use the sum aggregate on the hours: select [user.name], sum(hours) as hours from TheTable group by [user.name]
{ "language": "en", "url": "https://stackoverflow.com/questions/7512028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF Channel construct performance issue I have a strange situation, and I hope someone has experienced this scenario, and can help me. I have a WCF service hosted on IIS. From one client (Windows XP Pro SP3), a simple call takes less than a second, but from another client (also win xp pro sp3 but must be with another config somehow), it takes 7 seconds to make the first call in the application. What I do in the app, is instanciating the service, and making a simple call. I have tried to do diagnostics. When I look at the client service log, I can see that the construct of the channel takes about 2 seconds. Open Client base takes about 2 seconds and running the method in the service takes about 2 seconds. Then I close the service. If I make the call again, it take 0 seconds, like on the other machine. If I close the application, the first run takes 7 seconds again. From the slow PC calls to ASMX service on the same IIS allways run fast, but I want to use WCF. I use basic IIS authentication, and I am adding credentials runtime with the code below. But I do the same thing, on both PC's, so... I must be configuration somehow. MyServiceClient client = new MyServiceClient(); ClientCredentials loginCredentials = new ClientCredentials(); loginCredentials.UserName.UserName = "theuser"; loginCredentials.UserName.Password = "thepass"; var defaultCredentials = client.Endpoint.Behaviors.Find<ClientCredentials>(); client.Endpoint.Behaviors.Remove(defaultCredentials); //remove default ones client.Endpoint.Behaviors.Add(loginCredentials); //add required ones client.Endpoint.Address = new System.ServiceModel.EndpointAddress(GetSVCUrl()); client.InnerChannel.OperationTimeout = new TimeSpan(0, 0, 60); client.Endpoint.Binding.OpenTimeout = new TimeSpan(0, 0, 60); Configuration is set with <security mode="TransportCredentialsOnly"> <transport clientCredentialType="Basic" realm="" /> </security> I have googled a lot on the issue and have tried different configsettings related to proxy etc, but without any real breakthrough. I hope someone can give me a hint in the right direction. Thanks! Morten, Denmark
{ "language": "en", "url": "https://stackoverflow.com/questions/7512034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using LINQ query syntax with custom Maybe monad implementation I am trying to write a simple Maybe monad in C#. I want to be able to use the LINQ query syntax with it. This is what I have come up with so far: using System; using System.Collections.Generic; abstract class Maybe<A> { public abstract Maybe<B> SelectMany<B>(Func<A, Maybe<B>> f); public abstract Maybe<B> Select<B>(Func<A, B> f); } class Just<A> : Maybe<A> { private readonly A a; public Just(A a) { this.a = a; } override public Maybe<B> SelectMany<B>(Func<A, Maybe<B>> f) { return f(a); } override public Maybe<B> Select<B>(Func<A, B> f) { return new Just<B>(f(a)); } override public string ToString() { return "Just " + a; } } class Nothing<A> : Maybe<A> { override public Maybe<B> SelectMany<B>(Func<A, Maybe<B>> f) { return new Nothing<B>(); } override public Maybe<B> Select<B>(Func<A, B> f) { return new Nothing<B>(); } override public string ToString() { return "Nothing"; } } static class Program { public static void Main(string[] args) { Maybe<int> m = new Just<int>(12); Maybe<int> n = new Nothing<int>(); Maybe<int> result = from m0 in m from n0 in n select m0 + n0; Console.WriteLine(result); } } And this is the error message: prog.cs(48,25): error CS1501: No overload for method `SelectMany' takes `2' arguments prog.cs(5,28): (Location of the symbol related to previous error) Compilation failed: 1 error(s), 0 warnings Can anyone please guide me on what I should do to be able to use query syntax with my Maybe implementation? Thanks. A: SelectMany must should be declared as an extension in a static class, for example: public static class Maybe { public static Maybe<B> SelectMany<B>(this Maybe<A> maybe, Func<A, Maybe<B>> f) { return f(a); } ... } EDIT: you still need a piece. With this should work: public static Maybe<V> SelectMany<T, U, V>(this Maybe<T> m, Func<T, Maybe<U>> k, Func<T, U, V> s) { return m.SelectMany(x => k(x).SelectMany(y => new Just<V>(s(x, y)))); } You need this because: from m0 in m from n0 in n select m0 + n0 would be translated in: m.SelectMany(m0 => n, (m, n0) => m0 + n0); Instead, for example: var aa = new List<List<string>>(); var bb = from a in aa from b in a select b; is translated in aa.SelectMany(a => a);
{ "language": "en", "url": "https://stackoverflow.com/questions/7512035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how to send the data from a TextField/TextView to another view? I have 3 TextFields and 1 TextView in my first view (proj1) now i want to show the data from these Fields to the next view on the click of a button-"Done!". How do i do this? I know its a very basic question, but i've just started off with iphone app dev, any help would be really helpfull. A: You can get the value of a textfield with the text property and set the value of the textview with setText [textview setText:[textfield text]] Posting from my android, hope formatting is fine. A: Take a look at this: http://www.iphonedevsdk.com/forum/iphone-sdk-development/54859-sharing-data-between-view-controllers-other-objects.html A: It's definitely a big answer. Instead let me post a link - How to share data i.e. pass data between different View Controllers and other Objects
{ "language": "en", "url": "https://stackoverflow.com/questions/7512037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamically grouping/nesting flat data in a TreeView I would like to take a flat list of objects and present them in a TreeView using custom groups. public enum DocumentType { Current, Inactive, Transition, Checkpack, TechLog, Delivery } public enum Status { Approved, Rejected, Pending } public class Document { public string Name { get; set; } public DateTime Created { get; set; } public string CreatedBy { get; set; } public DateTime Modified { get; set; } public string ModifiedBy { get; set; } public DocumentType Type { get; set; } public Status Status { get; set; } } For example... The user might want to see this list, with the top level group being "Status" and the second level being "Name". This all needs to be configurable from the UI, and I'm struggling to find the best way to achieve it. I've had a brief look at the CollectionViewSource object, but couldn't find a good way to get it to dynamically build a TreeView. My gut feeling is that i'll need to do some clever templating in XAML - this is as far as i've got... <Window.Resources> <DataTemplate x:Key="DocumentTemplate"> <DockPanel> <TextBlock Text="{Binding Name}" /> </DockPanel> </DataTemplate> <HierarchicalDataTemplate x:Key="GroupTemplate" ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource DocumentTemplate}"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> </Window.Resources> <Grid> <TreeView ItemsSource="{Binding Documents.View.Groups}" ItemTemplate="{StaticResource GroupTemplate}"/> </Grid> public CollectionViewSource Documents { get { var docs = new CollectionViewSource(); docs.Source = DocumentFactory.Documents; docs.GroupDescriptions.Add(new PropertyGroupDescription("CreatedBy")); return docs; } } Of course this only displays the Top-level group ("CreatedBy"). After reading a question below, I managed to come up with a better question... My question: Is it possible to have a generic HierarchicalDataTemplate for a TreeView that displays custom groups applied to a CollectionViewSource. A: Honestly this should be marked as a bug in WPF. I too tried and found that Documents.View.Groups throws binding error on View property being null. Also <TextBlock Text="{Binding Path=Name}" /> is correct in the GroupTemplate but not in the DocumentTemplate. Note that Groups are of special type GroupItem where Name is one such property that holds the value on which grouping has taken place. On the other hand in DocumentTemplate, we should refer the property that we need to display on the leaf nodes items e.g. in my example I used Employee.FirstName (I grouped on Gender). <DataTemplate x:Key="DocumentTemplate"> <DockPanel> <TextBlock Text="{Binding FirstName}" /> </DockPanel> </DataTemplate> Now for binding to take effect I had to introduce a converter which simply returns Groups. public class GroupsConverter : IValueConverter { public object Convert(object value, ...) { return ((CollectionViewSource)value).View.Groups; } .... } And tree view binding was changed this way... <TreeView x:Name="treeView" ItemsSource="{Binding Path=Documents, Converter={StaticResource GroupsConverter}}" ItemTemplate="{StaticResource GroupTemplate}" /> Then this worked for me. Does this help you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7512041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Binding the background colour of a control using a trigger in WPF/XAML Okay, first off I have no experience of WPF whatsoever so please bear with me and apologies if my terminology is a little wayward... ;) The following code snippet is part of a WPF application that I have inherited. The trigger governs whether mandatory fields on a particular form are highlighted or not. The code works but the highlighting seems to apply to the control and the border (??) which contains it. <ItemsControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:cal="clr-namespace:Caliburn.PresentationFramework.ApplicationModel;assembly=Caliburn.PresentationFramework" x:Class="company.product.Jobs.JobParametersEditor" IsTabStop="False"> <ItemsControl.ItemTemplate> <DataTemplate> <DockPanel MinHeight="30"> <TextBlock Text="{Binding DisplayName, Mode=OneWay}" DockPanel.Dock="Left" VerticalAlignment="Center" MinWidth="120" Margin="6,0" /> <Border> <Border.Style> <Style TargetType="{x:Type Border}"> <Setter Property="Background" Value="{x:Null}" /> <Style.Triggers> <DataTrigger Binding="{Binding IsValid}" Value="False"> <Setter Property="Background" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> </Border.Style> <ContentControl cal:View.Model="{Binding ValueEditor}" ToolTip="{Binding ToolTip}" IsTabStop="False" MinHeight="19" VerticalAlignment="Center" HorizontalAlignment="Stretch" /> </Border> </DockPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> The result is a bit clunky so I would like to restrict the highlighting to the control only but I can't figure out how to do it. I've tried moving the trigger so that it applies to the ContentControl instead of the Border but that didn't work and fiddling about with border margins, padding and thickness hasn't had any effect either. Could anybody enlighten me as to how to accomplish this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7512051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJS drag/drop a CompositeSprite I want to set draggable on a CompositeSprite using Ext JS 4.0. There are examples on how I can set draggable a single sprite (draggable: true), but it doesn't work for CompositeSprite. If I write: compositeSprite.setAttributes({ draggable: true }); the result is each sprite in compositeSprite can be dragged separately. I need them to be dragged together. I have also tried to use dd property which contains Ext.dd.DragSource, but I can't apply Ext.dd.DragSource to Sprites. (There are no examples on the net, only for grid and tree). Any thoughts?
{ "language": "en", "url": "https://stackoverflow.com/questions/7512054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }