text
stringlengths
8
267k
meta
dict
Q: Whenever ruby scheduler doesn't work, what am I missing? Cannot make it works ... In my config/schedule.rb I have : set :output, '../log/development.log' every 5.minutes do runner "UserWatchedRepo.update" end Note the log setted, but nothing happen. In my Rails 3.0.10 model file app/models/user_watched_repo.rb I get : class UserWatchedRepo include Mongoid::Document def update conn = FaradayStack.build 'https://api.github.com' User.all.map do |user| nickname = user.nickname resp = conn.get "/users/#{nickname}/watched" resp.body.each do |repo| user.watchlists.build( html_url: "#{repo['html_url']}", description: "#{repo['description']}", fork_: "#{repo['fork']}", forks: "#{repo['forks']}", watchers: "#{repo['watchers']}", created_at: "#{repo['created_at']}", pushed_at: "#{repo['pushed_at']}", avatar_url: "#{repo['owner']['avatar_url']}" ) end user.save! end end end Any idea ? Thank you Luca A: Did you run the whenever command in your console? Your code doesn't actually create a cronjob, it just provides the inputdata for the whenever gem which has to be turned into an actual cronjob. To get this done, you have to cd into your apps root directory and run the following command: whenever --update-crontab YOUR_APP_NAME As far as I know, YOUR_APP_NAME doesn't have to be your actual app name, it has just to be a unique identifier. I consider it good practice though to use your appname to avoid confusion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NAudio - How to send sine wave only to one audio channel on jack I took an existing mono (non-stereo) NAudio example for Visual Studio 2010 from: http://mark-dot-net.blogspot.com/2009/10/playback-of-sine-wave-in-naudio.html and changed it to have two channel stereo audio as shown below: public abstract class WaveProvider32 : IWaveProvider { public WaveProvider32() : this(44100, 2) // Was 44100, 1 { } . . . } When I try to place the correct sample value in the first float in buffer and a zero in the second float in buffer, I was expecting to get a sine wave on the right channel and no audio on the left. I'm seeing the same frequency 10x lower amplitude out of phase sine wave on the left channel vs. the right channel. Is that from some kind of signal bleed through or am I not understanding how the code should work? Here is a sample of how I changed WaveProvider32: public class SineWaveProvider32 : WaveProvider32 { . . . public override int Read(float[] buffer, int offset, int sampleCount) { int sampleRate = WaveFormat.SampleRate; for (int n = 0; n < sampleCount; n += 1) { buffer[n+offset] = (float)(Amplitude * Math.Sin((2 * Math.PI * sample * Frequency) / sampleRate)); buffer[n+offset+1] = (float)(0); sample++; if (sample >= sampleRate) { sample = 0; } } return sampleCount; } } Any advice on what I'm doing wrong? Regards Note: The NAudio project is located at: http://naudio.codeplex.com/ A: Your for loop should have += 2, not += 1. for (int n = 0; n < sampleCount; n += 2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7507347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Add a method to a list instance in python I want to add a method to a single instance of the 'list' class. Example: a = [1,2] a.first = lambda self: return self[0] I know this don't work, but I want something like that works like that. I know its not a good practice, and I know I should do a whole new class, but I think this is possible in Python and haven't figured out how. I am aware of: Dynamically add member function to an instance of a class in Python and Dynamically binding Python methods to an instance correctly binds the method names, but not the method but none of those work with a native list. Thanks! A: Nothing will work with a native list, since you cannot add methods to a type defined in C. You will need to derive from list and add your method to that class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Android widget providers & main application question Alright, i seem to be asking a lot today but i'm pretty much stumped at this part after reading the documentation. Or maybe i'm just doing it wrong. I'm doing an app where the user is able to create a widget from the application itself, which means : 1) I click on my app in the menu screen 2) App boots up, user fills in details 3) User hits create button 4) Data gets saved into a file, probably XML 4) Application closes, widget gets planted on the screen of the device in a 2x2 box. However, when i read through various tutorials and documentation for android, it seems like the widget provider and application are two different entities altogether and it doesn't sound like they can be merged as one (meaning data cannot be transferred). Am i still able to create my application using the original ideation or do i have to change the entire thing drastically? Thanks in advance. A: You can combine an app with widgets in one APK. That's not a problem at all. They also can share data in various ways (shared preferences, files, SQLite, ...). The problem starts with the idea that the widget can be placed via your app. Widgets have to be placed by the user, he has to select the widget from the widget-menu and place it where he wants it. Your whole concept can still be done, and is pretty often - using a ConfigurationActivity. That is pretty much a normal activity that's invoked when the user selects the widget. You can customize that to your likings, including some things that prompt the user to input data, select preferences and so on. After that, you can build your widget with the specifications from that activity in your widget update method. It gets placed by the user, and thats it. A: The wigdet is apart of its application. The user can enter information from a widget and you can use different methods of storing and sharing the information. Such as SharedPreference,SQLITE(RECOMMENDED). You will be able to use either one of this to exchange data the user enters between your widget and main acitivty. EDIT: TO add a widget by a button click instead of the original way. You may need to look through the Android OS and find out how the widget is added from their. And maybe create a method of some sort to do this. I dont think it is a class that allows you to do this. I believe the Android OS is only packaged with this way of longpress on the homescreen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble with updates on a TreeView with data bound XML data via XElement I have a TreeView implemented in WPF that is bound to some XML data via the XElement class. When loading the XML file the first time the binding works fine. All the data populates the tree as expected. The problem occurs when I add and remove elements because nothing happens in the TreeView. Now I've done this before' and I believe I remember not having to do any extra work for this work correctly. At least for the simple case of adding and removing items from the tree. I remember being surprised that this worked without any extra coding effort. I don't have access to that code anymore so I can't just look at what I already did. So I'm kind of stumped as to why I can't get this to work now. My WPF code is as follows. <Window.Resources> <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="ViewEditTreeTemplate"> <StackPanel Orientation="Horizontal" Margin="2"> <Label x:Name="ElementHeaderLabel" Padding="1" VerticalContentAlignment="Center" FontSize="16" Content="{Binding Path=DisplayName}" /> </StackPanel> </HierarchicalDataTemplate> </Window.Resources> <Grid> <TreeView Name="DataTree" ItemTemplate ="{Binding Source={StaticResource ViewEditTreeTemplate}}" Margin="0,0,0,53" /> </Grid> I'm attaching my XML document in the code behind as follows. Keep in mind that this appears to be working since the tree auto populates with the information from the XML data just fine. XElement NewElement = new XElement(XElement.Load(FilePath)); List<XElement> TempList = new List<XElement>(); TempList.Add(NewElement); DataTree.ItemsSource = TempList; In the code behind when I go to add or remove elements I do as follows: // When removing an element Element.Remove(); //Element is of type XElement // When adding an element ParentElement.Add(NewElement); //ParentElement and NewElement are of type XElement I have this strong feeling that when I did this before, I actually didn't have to do anything special. The .Remove() and .Add() routines somehow notified the bindings that the items in .Elements() have changed and the screen updated automatically. Whatever the case, its not working this time around. Does anyone know why? A: Ok, I have a solution to my own problem. I'm not sure why I thought this would originally work without having to do anything special, but that seems to not be the case. To clarify the problem a little more, I was not using the the XElement object as is, I had it wrapped by another class so I could add a few more features to it. This was good though because it turns out I needed the INotifyPropertyChanged interface and to override a few methods in order to get the behavior I wanted. My actual class header looks like this. public class TreeElement : XElement, INotifyPropertyChanged { ... } Since my TreeView was binding on the XElement.Elements() routine, it was not receiving notifications when I added or removed elements. The reason why is because XElement.Elements() is NOT a dependency property. Its a routine. I knew this ahead of time but for some reason I was stubborn and still thought it was going to work. So what I needed to add was the INotifyPropertyChanged interface, and then invoke the NotifyPropertyChanged() routine whenever operations occurred that would cause the data from XElement.Elements() to be changed. Namely, they XElement.Add() and XElement.Remove() routine. There are several more but I'll just talk about these two. These routines are not overridable, but they can be hidden using the "new" key word. Here is the new implementation for those routines. public new void Remove() { XElement parent = this.Parent; base.Remove(); if ((parent != null) && (parent.GetType() == typeof(TreeElement))) { //need to tell parent that they are losing an element ((TreeElement)parent).NotifyPropertyChanged("Elements"); } } public new void Add(object Content) { base.Add(Content); NotifyPropertyChanged("Elements"); } As you can see, even though .Elements() is not a property the NotifyPropertyChanged("Elements") method works just fine at notifying my binding 'ItemsSource="{Binding Path=Elements}"'. So now when I update in the code behind using .Add() or .Remove() my tree auto updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does make track timestamps How does make keep timestamps for files? I am trying to put in place my git repo. I am adding precompiled binaries for files which are mostly not gonna change. Now, when I checkout repo from git then I dont want to compile these c files. I want to use these prebuilt binaries. So, to set up this scheme, I want to know how makefile tracks timestamps. Can anyone help me? Thanks A: make looks at the last-modified times. From the GNU make manual: The make program uses the makefile data base and the last-modification times of the files to decide which of the files need to be updated. And from IEEE Std 1003.1-2008 make manual: The make utility examines time relationships and shall update those derived files (called targets) that have modified times earlier than the modified times of the files (called prerequisites) from which they are derived. You can use touch: touch - change file access and modification times to adjust the timestamps if necessary. A: If you are using make I do not think that you should put these binaries into the repository - simply just enable make to check that they are up to date. You can always rebuildd them. This is especially true if you are not the only person working on the project. You will need to update some of these files in the future and hence recompile them. If you are under the illusion that they are not going to change you might get bitten when things do not work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to disable the loading message in the header of a jQuery Mobile page I want to disable the loading message in the header only when transitioning between jQuery Mobile pages. Alternatively, if I can change the default "loading" text, that would also suffice. I have tried $(document).bind("mobileinit", function(){ $.mobile.hidePageLoadingMsg(); }); also $.mobile.pageLoading( true ); you can see an example here A: See the docs for mobileinit and use loadingMessage to set the default. I believe you can programmatically change it with $.mobile.loadingMessage as well. A: Have you tried setting loadingMessage to false? http://jquerymobile.com/demos/1.0a4/docs/api/globalconfig.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7507357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rubymine install or problems with sqlite3 install? Can anyone help me here - I am pretty sure there's something up with my sqlite3 install and I can't find clear step by step instructions on fixing it? It has manifested itself this time as a Rubymine startup error... Process: rubymine [1351] Path: /Applications/RubyMine 3.2.4.app/Contents/MacOS/rubymine Identifier: com.jetbrains.rubymine Version: ??? (???) Code Type: X86-64 (Native) Parent Process: launchd [739] Interval Since Last Report: 390 sec Crashes Since Last Report: 1 Per-App Interval Since Last Report: 0 sec Per-App Crashes Since Last Report: 1 Date/Time: 2011-09-21 15:01:17.659 -0700 OS Version: Mac OS X 10.5.8 (9L30) Report Version: 6 Anonymous UUID: [i guess i should edit this to make it anonymous] Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000002, 0x0000000000000000 Crashed Thread: 0 Dyld Error Message: Library not loaded: /usr/lib/libsqlite3.0.dylib Referenced from: /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CFNetwork.framework/Versions/A/CFNetwork Reason: no suitable image found. Did find: /usr/lib/libsqlite3.0.dylib: mach-o, but wrong architecture /usr/local/lib/libsqlite3.0.dylib: mach-o, but wrong architecture /usr/lib/libsqlite3.0.dylib: mach-o, but wrong architecture That last bit - the DYLD ERROR MESSAGE bit - I have seen that before recently so I don't think that's a result of any problem with rubymine. Help appreciated A: Okay so this question has the same answer as the question I posed here: Help to fix strange sqlite3 error - dyld: Library not loaded: /usr/lib/libsqlite3.0.dylib They're both ultimately down to somehow having got a messed up install of sqlite3 - however, most of the straightforward ways of installing new versions of sqlite3 didn't fix the problem again. Took an awful lot of googling to figure out the answer to this. So... I'll put the answer in just one place, on the above referenced question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opening a file in Java inside a directory specified by wildcard characters In Java, is it possible to specifiy a directory using a wildcard character, when trying to create a file object as below? File newFile = new File("\temp\*\path"); In this case, the directory is created by some other part of code which I don't have access to, which puts a timestamp in the name. So the problem would be solved if I can put * in place of the timestamp, like File newFile = new File("\temp\dirname-*\path"); // * is timestamp when directory was created. Thanks for any help. A: If you're a programmer, you should learn that statements like "I am sure that a single directory exists at that place" will be true until they are false (and they will be false at some point). Do the work to look in \temp\, verify that there is only one directory, then open the file with the correct path. Then when the precondition isn't true you can throw an exception or display a message. A: Creating it as you described is not possible. It is, however, possible to write an algorithm to search for a File that fits the description. In your case, you would want to create a new File("temp") then recursively search through its children (using the listFiles for any file whose isDirectory method returns true) for a file that is named "path". A: No, it is not possible to use wild cards in file names in Java. You will need to resolve the path yourself, but it is not hard. You might find new java.io.File("/tmp").listFiles(); an interesting place to start.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to make a button call a JavaScript function in XHTML Strict 1.0? In plain old HTML the following code will work: <input type="button" value="click" onClick="function()" /> However; in XHTML Strict 1.0 this code will not validate, saying that "there is no function onClick". I know that this code here will work, <a href="javascript:function()>click</a> But I want the function to occur on the click of a button. A: It's onclick (all lower case) in XHTML, which is case-sensitive. (Reference) So for instance (live copy): <!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> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/> <title>Testing</title> <script type="text/javascript"> function foo() { alert("Hi there"); } </script> </head> <body> <p onclick="foo()">Testing</p> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7507365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use AES-256 encryption on Google App Engine? It looks like I'm limited to 128-bit AES encryption on GAE. The following code throws InvalidKeyException (Illegal key size), looks like this happens when unlimited security policy is not installed. Cipher cipher = Cipher.getInstance("AES"); SecretKey key = new SecretKeySpec(new byte[64], "AES"); // 256 bit key for AES cipher.init(Cipher.ENCRYPT_MODE, key); Anyone know about this? A: According to this, you can use BouncyCastle with GAE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: event listeners vs. event handlers Possible Duplicate: JavaScript Event Listeners vs Event Handlers element.onload vs element.addEventListener(“load”,callbak,false) I've read this question but it's still unclear to what's the difference between <input type="button" onclick="call_function();" /> And $(function() { $("#my_button").click(function() { call_function(); }); }); <input type="button" id="my_button" /> The first one is an event handler and the second one is an event listener, am I right? Is one way better than the other and why? Which one is better at handling graceful degradation? A: Functionally speaking there is no difference. In both cases the method call_function will be invoked when the given button element is clicked. Stylistically though there is a big difference. The latter example is considered more robust by many because it allows the developer to separate out the 3 parts of at HTML page into completely different items * *HTML page: Contains the data of the page *CSS stylesheet: Determines how the data is displayed *Javascript: Provides the behavior This is possible in the second example because the javascript behavior is hooked up independently of the definition of the button. This allows for the HTML to be defined completely independent of the associated javascript. They can be in separate files, written by separate people and for the most part mutated independently. There are some restrictions (like don't change id fields) but overall it gives a large degree of freedom between the logically different pieces of the display. A: Event handler is a function or other chunk of code that is invoked by browser in response to specific event. Event listener, in the given context, is a higher level abstraction introduced by javascript library (jquery here) and what this library will do for you is creating event handler that would call some code that will go over listeners and call them one by one. So jquery hides from you the logic of maintaining a list of listener functions and calling them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: filter dates fields from paradox db using microsoft.jet.oledb.4.0 Hi I'm trying to filter data fields from a paradox database table (from information system on programmed on delphi)... I successfully made the connection with the connection string: Provider =Microsoft.Jet.OLEDB.4.0; Data Source =c:\bddir; Extended Properties =Paradox 5.x; I can even successfully execute queries like select * from mytable But when I'm trying to do queries like: SELECT * FROM entries WHERE date = '2011-1-1' thru a c# application with the cxstr above.. and it said: Data type mismatch in criteria expression any solutions?? I tried things like StrToDate or QuotedStr and it didn't work... :( A: Try SELECT * FROM entries WHERE date = #1/1/11# instead of SELECT * FROM entries WHERE date = '2011-1-1' look here: MS-TechNet A: Finally I got it it's: SELECT * FROM table WHERE year(dateField) >= 2011 AND month(dateField) >= 1 AND day(dateField) >= 1 Hope it helps you!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7507378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can an element inside an iframe capture a key event? I have a canvas element in a simple html document with an attached keydown and keyup listener. This works correctly when I load the document in the browser and start pressing the keys. However, if I load the document in an iframe, nothing happens when I press the keys. It seems the key events never enter the iframe or the document inside the iframe. Is there a way to fix this? A: I found the answer in this question. Setting the focus on the document inside the iframe solves the problem Setting focus to iframe contents A: I found subscribing the event to window.top worked for me, as my game was several iframes deep.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cronjob in every 5 minutes until 17.00 pm Cpanel Minute Hour Day Month Weekday */5 * * * * This code triggers page in every 5 minutes for 24 hours. But i want it until 17.00 pm (or any hour). how can i change it in Cpanel? A: Use the range specification: */5 0-17 * * * You didn't give a starting time, so I assumed midnight (0). Adjust to taste.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Like Button og: image and og:title not being recognised When using the like button, the defined og:image and og:title do not show on facebook page. Link to example .. It's the like button at bottom of the article and not the one at the top of the page: http://www.nflfc.co.uk/main.php?articleId=221&pageId=3&teamId=3 Using the linter I get the following info which all points to everything being ok but no joy... http://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.nflfc.co.uk%2Fmain.php%3FarticleId%3D221%26pageId%3D3%26teamId%3D3 Any help to point me in the right direction into what I am doing wrong will be much appreciated. Adi Thankyou for replying so quickly. I think you are correct in the facebook cache being regional, as I have just had an overseas friend test and it worked fine for him too. I'm concerned how I am writing my code now though with this cache..... <?php $url="http://".$_SERVER['HTTP_HOST'].$SERVER['REQUEST_URI']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en" lang="en"> <head> <title>Nottingham Forest Ladies Football Club - <?php echo $row_pageLayoutSelection['linkTitle']; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta property="og:title" content="NFLFC : <?php echo $row_article2['articleTitle']; ?>" /> <meta property="og:type" content="sports_team" /> <meta property="og:url" content="<?php echo $url; ?>" /> <meta property="og:image" content="http://www.nflfc.co.uk/images/news/<?php echo $row_article2['articleId']; ?>_154x85.jpg" /> <meta property="og:site_name" content="NFLFC : <?php echo $row_article2['articleTitle']; ?>" /> <meta property="fb:app_id" content="xxxxxxx"/> <meta property="fb:admins" content="xxxxxxx" /> Will this dynamic data for individual database articles be ok or will I encounter Facebook cache issue do you think? Thanks again for your help with this, greatly appreciated. Adi A: Facebook caches data when you first add like button to your page. This caches might be regional not sure about that, but it takes 24hr to remove caches sometimes. So make a working template for your like button headers and use them all the time, if lint shows its ok then it ll be ok. (Note:try to like the page from https://developers.facebook.com/tools/debug/ this might fix it, just a superstition) when i liked the post, shows this image http://www.nflfc.co.uk/images/news/221_154x85.jpg and this info on profile NFLFC : Forest Girls 8 v 0 Wollaton Hall It was Wollaton who created the first chance causing Natalie to pull off a good save, but after 7 minutes Jessica Munn put Forest ahead with a clinical finish. Forest without being fluent created other opportunities, but it was a poor clearance by the keeper which led to Leia Ward increasing the lea... A: The caching could be true. i had the problem with a page, renamed the page and all was ok for the new page. Now i tried loading this old page once again to check and it integrated the image just fine. So there IS caching and caching is temporary. But now I have the problem with a brand new page that shouldn't be cached yet. Very frustrating. Image is retrieved from MySQL blob field by asp script. the debugger shows the image and gives no error but the button on the page doesn't take the image. Page: http://www.ffkama.be/html/2_agenda_detail.asp?ps=id51 Image URL: http://www.ffkama.be/root/imager_ag.asp?id=51 Suggestion for FB devs, after a successful debug use on the page, purge cache or cache the debugged page UPDATE: I forgot the code in the HEAD TAG :( One thing is sure, without the 'prefix="og: h t tp://ogp.me/ns# fb: ht tp://ogp.me/ns/fb# website: h t tp://ogp.me/ns/website#"' in the HEAD Tag, the debugger doesn't give an arror and the image shows up in the dubugger but the image won't show up on your page. Then the page is cached and there are only 2 solutions: 1. rename the page 2. wait several days for the cache to expire A: I had a white .png that was not showing up because the background of facebook is white of course. So I changed my og:image to a black logo but it wouldn't refreshed the cached .png. Just simply going to this link fixed it. https://developers.facebook.com/tools/debug/ A: I think the problem is your image size: 221_154x85.jpg is supposed to be a 154x85 pixes image, right? According to the debugger page: All the images referenced by og:image should be at least 200px in both dimensions. Please check all the images with tag og:image in the given url and ensure that it meets the recommended specification. hope it'll help
{ "language": "en", "url": "https://stackoverflow.com/questions/7507387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IIS delays a lot between each response with async requests I have a ASP.NET MVC project running on my developer machine with windows 7 ultimate and iis 7.5. I do the following: var requests = ["http://myserver.com/news/details/113834", "http://myserver.com/tag/details?ids=113834&entityType=23", "http://myserver.com/publish/details?ids=113834&entityType=23", "http://myserver.com/generalproperty/details?ids=113834&entityType=23", "http://myserver.com/category/details?ids=113834&entityType=23"]; var f = new Date().getTime(); $.each(requests, function(k,v) { $.ajax({ url :v, async : true, type :'get', success : function(data) { console.log(new Date().getTime() -f ); }}); }) Then I get the following results(approx) 12, 521,1025,1550, 2067 async result http://martinhansen.no/hostedimages/async.PNG If I switch the async to false I get : 14,32,49,58,68 sync result http://martinhansen.no/hostedimages/sync.PNG Seems somewhere the requests are being queued up and after a while it responds only every 500 ish second. I have made my controllers return blank text instead of the database call, so not the database. Is there a limitation on IIS 7.5 for windows 7? A setting I can change? I'm suspecting a max concurrent requests per user or something similar. And then it "punishes" you by responding every 500 ms only. So that people don't use it as an actual server. Likely? And is there a way to avoid it? A: It have nothing to do with IIS apperantly or IIS on windows 7, I also tried it on a test server and same results. It was because of limitations imposed by sessionstate, see the "Concurrent Requests and Session State" section at the bottom here: http://msdn.microsoft.com/en-us/library/ms178581.aspx However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. But I still don't understand why it don't fire off the next request right after the the first one is seemingly finished. It seems very fake the 500 ms delay. I came over this question How to set the ASP.NET SessionState read-write LOCK time-out? that talks about the lock out time for the session state. System.Web.SessionState.SessionStateModule.LOCKED_ITEM_POLLING_INTERVAL = 500 That's the magic number that I've been searching my code and the interwebs for.. 500! I knew it had to be somewhere. Anyway, to fix this, I added the sessionstate attribute to my controllers with the option of read-only [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)] public class BaseController : Controller{} Read more about it: http://afana.me/post/session-less-controllers-and-TempData-ASPNET-MVC.aspx http://weblogs.asp.net/imranbaloch/archive/2010/07/10/concurrent-requests-in-asp-net-mvc.aspx I still think something is wrong though, why don't the previous request tell the system that it no longer needs a lock on the sessionstate so that the next request can complete? A: How many requests are you sending at once? IIS on Client OSs are limited to 10 simultaneous connections. Above that limit it throws the incoming connection into a queue and processes it when a slot opens up. This has been the case for a long time in an effort by MS to ensure that client OSes aren't used to cannibalize sales of their server OS platforms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Error with Access Stored Query that uses VBA Modules from excel I am trying to run a Stored MS-access Query from excel using VBA. I have created a generic function to preform this task (using ADODB). I can get results with or without parameters. However when I try to run a stored Query that references an Access vba module, excel barfs a runtime error "undefined function MissCat" (which is the name of the custom function the stored query uses). I would have expected this to work as access knows the definition of the function, but now I get the feeling the ADODB interface is trying to interperet the SQL in the stored query without the aid of the VBA module i've created in access. I am jumping through these hoops as most of my users do not have access installed on their machines. Is it possible for me to use the stored query as is (changing the query interface, perhaps)? or is the path of least resistance changing the query such that it doesn't need the custom function (as you can see below it is quite simple, I've used it as a crutch because I don't know SQL very well) here is the function Function MissCat(ProShip As Date, TargetDate As Date) As String If TargetDate >= ProShip Then MissCat = "Meets target" Exit Function End If If TargetDate < Date Then MissCat = "Unrecoverable" Exit Function End If Select Case ProShip - TargetDate Case 1 To 6 MissCat = "Less than one week" Case 7 To 14 MissCat = "1-2 Weeks" Case Else MissCat = "Greater than 2 Weeks" End Select End Function and here is the SQL TRANSFORM Count(Shipset.ID) AS CountOfID SELECT Calendar.[Week Of] FROM Calendar INNER JOIN Shipset ON Calendar.DateSerial = Shipset.ShipDate WHERE (((Calendar.[Week Of])>Date()-(13*7)) AND ((Shipset.ShipDate) Is Not Null) AND ((Shipset.ReqOut)=False) AND ((Shipset.TwoTier)=False)) GROUP BY Calendar.[Week Of] ORDER BY IIf(MissCat([Shipset]![ShipDate],[Shipset]![TargetDate])="Meets Target","Meets Target","Hit") DESC PIVOT IIf(MissCat([Shipset]![ShipDate],[Shipset]![TargetDate])="Meets Target","Meets Target","Hit"); thanks, A: Building on @HansUp's excellent analysis, I wonder if a SWICH() statement would be easier to read e.g. SELECT ProShip, TargetDate, SWITCH ( TargetDate >= ProShip, "Meets target", TargetDate < Date, "Unrecoverable", ProShip - TargetDate < 7, "Less than one week", ProShip - TargetDate < 14, "1-2 Weeks", TRUE, "Greater than 2 Weeks" ) FROM YourTable; I also wonder if the using DATEDIFF('D', TargetDate, ProShip) would be easier to read (i.e. decipher intention) than using arithmetic on DATETIME values. A: Your query will not be able to use the custom VBA function except when it is run from within an Access session. You can substitute nested IIf() function statements for the MissCat function. Two challenges with that approach when the nesting is complex: it's hard to follow the logic; it's easy to screw up the syntax. The general form is IIf(condition, truepart, falsepart) So for the first condition, try this in a temporary procedure you create in Access. Debug.Print IIf(TargetDate >= ProShip, "Meets target", "else") As the next step, replace "else" with an IIf expression for the second condition. Debug.Print IIf(TargetDate >= ProShip, "Meets target", _ IIf(TargetDate < Date, "Unrecoverable", "else")) And so forth. This is what I wound up with as the final grand mess. Debug.Print IIf(TargetDate >= ProShip, "Meets target", _ IIf(TargetDate < Date, "Unrecoverable", _ IIf(ProShip - TargetDate < 7, "Less than one week", _ IIf(ProShip - TargetDate < 15, "1-2 Weeks", "Greater than 2 Weeks")))) After you have the procedure working correctly, copy the nested IIf expression and test it in a new Access query. SELECT ProShip, TargetDate, IIf(TargetDate >= ProShip, "Meets target", IIf(TargetDate < Date, "Unrecoverable", IIf(ProShip - TargetDate < 7, "Less than one week", IIf(ProShip - TargetDate < 15, "1-2 Weeks", "Greater than 2 Weeks")))) AS MissCat FROM YourTable; After looking again at how you used the MissCat function in your original query, I don't think I'd try to substitute this approach directly. I would create a separate query to transform the base data and then adapt the original query to use the new query as one of its data sources.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java/Android: Incorrect number of arguments for type AsyncTask I think there's something wrong with this code. Can someone please check if there are any mistakes in the code? ImageView userPicture = (ImageView) findViewById(R.id.userPicture); private synchronized void downloadAvatar(){ AsyncTask <Bitmap> task = new AsyncTask <Bitmap> (){ @Override public void onPreExecute() { //Do nothing } @Override public Bitmap doInBackground() { URL fbAvatarUrl = null; Bitmap fbAvatarBitmap = null; try { fbAvatarUrl = new URL("http://graph.facebook.com/"+userID+"/picture"); fbAvatarBitmap = BitmapFactory.decodeStream(fbAvatarUrl.openConnection().getInputStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fbAvatarBitmap; } @Override public void taskComplete(Bitmap result) { fbUserAvatar.setImageBitmap(result); } }; task.execute(); } I'm getting an error on the row with this code: AsyncTask <Bitmap> task = new AsyncTask <Bitmap> () The error message is: Incorrect number of arguments for type AsyncTask; it cannot be parameterized with arguments A: AsyncTask takes three arguments: Params, Progress and Result. It should probably be AsyncTask< Bitmap, Void, Void > in your case; and doInBackground should take a Bitmap... args.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-9" }
Q: Android: leaving an app with home button and returning to a different activity when going through a long press on the home button I have an app which has uses bluetooth, and should not be accessible if the bluetooth is turned off on the device. the way I chose to implement this is as follows: * *created a dispatcher activity which is launched when the app is first launched. *this activity checks the status of bluetooth, if bt is off, it send you to noBtScreen, if it is on, it takes you to yesBtScreen the problem is that when the user gets to the noBtScreen and then hits the home button, changes the bt status and comes back to the app (by long pressing the home button and selecting my app) it arrives at the noBtScreen which it shouldn't get to at this point. There are obviously naive ways to fix this, for example, I can check the bt status in the activity's onResume, but I think that there is a "right" solution which should be used here. I've tried some of the activity settings in the manifest file specifically, I tried putting the following flags on the NoBtTask: android:finishOnTaskLaunch android:allowTaskReparenting in combination and not in combination with android:clearTaskOnLaunch android:alwaysRetainTaskState I also tried adding this.finish to the noBtActivity::onStop method, but that didn't help either (what happened then was that I got in once, got out, and when i got in again, nothing happened and i stayed on the home screen, when i tried it again, it indeed took me to the dispatcher activity, it's interesting to see the log for this: 09-21 17:54:49.511: INFO/ActivityManager(115): Starting: Intent { cmp=com.test.elad/.NoBtActivity } from pid 12603 09-21 17:54:49.523: ERROR/Elad(12603): NoBtActivity.onCreate 09-21 17:54:49.527: ERROR/Elad(12603): NoBtActivity.onStart 09-21 17:54:49.527: ERROR/Elad(12603): NoBtActivity.onResume 09-21 17:54:49.765: INFO/ActivityManager(115): Displayed com.test.elad/.NoBtActivity: +248ms 09-21 17:54:51.867: ERROR/Elad(12603): NoBtActivity.onSaveInstanceState 09-21 17:54:51.867: ERROR/Elad(12603): NoBtActivity.onPause 09-21 17:54:51.867: INFO/ActivityManager(115): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.launcher/com.android.launcher2.Launcher } from pid 115 09-21 17:54:51.882: VERBOSE/RenderScript_jni(195): surfaceCreated 09-21 17:54:51.882: VERBOSE/RenderScript_jni(195): surfaceChanged 09-21 17:54:52.277: ERROR/Elad(12603): NoBtActivity.onStop 09-21 17:54:56.183: INFO/ActivityManager(115): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10100000 cmp=com.test.elad/.DispatcherActivity } from pid 115 09-21 17:54:56.265: ERROR/Elad(12603): NoBtActivity.onDestroy A: Put android:noHistory="true" in Manifest for both noBtScreen and yesBtScreen. Here's what the android docs says about noHistory: A value of "true" means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to return to it. EDIT: I have another suggestion that hopefully will work. When you startActivity from your dispatcher Activity, you could pass an extra with the key name "randomExtra" Then in the onResume or onCreate of your other Activities check if intent.hasExtra("randomExtra"), and then if that returns true, then just continue. If it returns false, then do startActivity(new Intent(context, DispatcherActivity.class) A: Call finish() in onUserLeaveHint() callback of the activity. A: Try to specify android:launchMode="singleTask" in manifest for your dispatcher activity. A: First if you are going to put your finish() anywhere it would be in the onPause() method. onPause is called immediately after moving out of the actively showing activity. With that said you need to check these intent flags out... more specifically look at: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_SINGLE_TOP http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY Edit: also here is a flag that is set by the system that you can check to see if the activity was launched from the activity stack history: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY Edit2: WOW I see some really complex answers! The OP needs to do no more than make sure that the activity cannot be called again unless a conditional says so. An Intent flag is plenty to perform this task. Don't over-complicate things!!! A: This may not answer your question exactly, as it suggests a different approach, but hopefully it will at least be useful for other viewers. Here's what I would do: The application initially launches a (BluetoothEnforcerActivity), which is a blank screen. In its onResume(), check the status of Bluetooth. If Bluetooth is not available, show an alert dialog informing the user that Bluetooth must be enabled to continue. The dialog would have the buttons "Quit" and "Try Again". "Quit" would of course exit the dialog and the BluetoothEnforcerActivity (bringing the user back to the home screen). "Try again" would exit the dialog such that BluetoothEnforcerActivity would test for Bluetooth again in onResume(). (If Bluetooth is still not available, just show the dialog again. Make sure there's enough of a pause that the user can tell the dialog closed and re-opened.) If/when Bluetooth is finally available, the BluetoothEnforcerActivity launches the main activity and calls its own finish() method. All that said, don't forget to consider the case where the user disables Bluetooth once they've gotten past the BluetoothEnforcerActivity. A: My suggestion for you is to create a new class that extend from Activity (BTActivity) and make both NoBtActivity and YesBtActivity extend from BTActivity. Now, on BTActivity Override onRestart and check for the bluetooth status in there, if it's on and you are on NoBtActivity, change to YesBtActivity and vice versa. A: Try something lik this: * *Register BroadcastReceiver for android.bluetooth.adapter.action.STATE_CHANGED (check this), it will notify you when the Bluetooth has been turned on or off. *On your onReceive() method of BroadcastReceiver store it's position. You can use sharedpreference for this. *When your noBtScreen comes to foreground, override onResume() method and check for this variable and if the bluetooth is on then startactivity(yesBtScreen) and finish() the noBtScreen. *You can put same check on yesBtScreen and if the bluetooth is off then startactivity(noBtScreen) and finish() the yesBtScreen. A: I made an app that had a login screen at the start. Leaving the application and returning would mean going back to the login screen. This is how I got around it - it required the use of intents to save data. (I have 4 activities - Main Activity, second actvity, login setup activity and login activity) on the main activity i have this: @Override protected void onUserLeaveHint() { super.onUserLeaveHint(); Intent intent = getIntent(); String activity = intent.getStringExtra("activity"); if (activity == null || !activity.equals("first") || !activity.equals("firsttime")){ NavUtils.navigateUpFromSameTask(MainActivity.this); }else { getIntent().removeExtra("activity"); } System.out.println("mainactivity"); } on my second activity i have this: private void returning(){ Intent intent = new Intent(this, MainActivity.class); intent.putExtra("activity","first"); startActivity(intent); } and on my login setup activity I have this (on the onclick for login): Intent i = new Intent(LoginSetup.this, MainActivity.class); i.putExtra("activity","firsttime"); startActivity(i); So every time I move between activities something is stored in the intent extras and when I leave the activity the intent is checked to see if it holding intent data. If the intent is holding no extras then you return to the login screen. hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: WCF Service Method Name in IIS Log Can the IIS logs be configured to output the name of the method called for a WCF service? Right now the logs show only the name of the svc file. Current log: /myservice.svc I would like it to show: /myservice.svc/mymethod A: Unfortunately, there is no way to have the IIS standard logging log the method name called on a service. It only registers the page serviced. You can however enable WCF logging to produce an svclog file that does give complete insight in method invocations and WCF service operations. For details, look at: http://msdn.microsoft.com/en-us/library/ms730064.aspx. Might that be acceptable?
{ "language": "en", "url": "https://stackoverflow.com/questions/7507395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Message Systems and parameters in OOP? In the WinAPI, WndProc has lParam and wParam which are longs. This means you generally have to typecast them into the correct type. I've read that message systems in OOP should not need to cast things and that this is a bad practice. Therefore, in a language like C++, how would a basic message system work, where each message has 2 parameters, or even object pointers, depending on the message, but doing so without typecasting? Thanks A: For the general case I doubt you can do without some typecasting. However, in C++ level design the typecasting can be mostly be centralized. Look up visitor pattern. Cheers & hth., A: The problem with type-casting is that it isn't safe. Boost provides a number of ways to do typecasting in a safe way. If the data that could be sent in your message system is well-defined, limited to a few possible choices, then one could employ a boost::variant object. Variants are kind of like type-safe unions that have built-in visitation support. However, if the set of possible data is more or less arbitrary, then you won't be able to use a variant. You still want to preserve type-safety, so that the person receiving the message cannot cast it to a different type other than the type that it was originally given with. In that case, boost::any is a good choice. Yes, you still have to use an any_cast, but that will fail if it is not of the proper type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom line UITextView I have one UITextView. I can have a UITextView with only one line and with horizontal scrolling only? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7507398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript noob: why can't new objects be created from initializers? OK, I really have read everything I can find trying to get a comprehensive understanding of Javascript. I know this can be done using a constructor function, but I'm trying to understand the language enough to know why this happens... PeepClass = { color: "Yellow", shape: "Chick" }; var peepsA = new Object(PeepClass); var peepsB = new Object(PeepClass); if ( peepsA == peepsB ) document.write( "Why wouldn't these be unique instances?" ); Why doesn't new Object(PeepClass) create unique instances of the PeepClass object? Instead, it results in three references to the same object. A: I guess you want this: var peepsA = Object.create( PeepClass ); Now peepsA is a new object which inherits from the object PeepClass. Btw when you pass an object into new Object(), that same object is returned, ergo, the operation is a no-op. PeepClass === new Object( PeepClass ) which means that the notation new Object( obj ) is meaningless. A: To put it another way, you can initialize an object in two ways: // these are equivalent var o1 = new Object(); var o2 = {}; A: To quote MDN: The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a type that corresponds to the given value. In other words, when you call new Object(PeepClass) what you get back is not an instance of PeepClass, but PeepClass itself. A: Read about new Object([value]) construction in ECMAScript standart. If value is ECMAScript object then it doesn't create a new object, it just return the value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I reference an image that I have created in an table array in Corona (Lua)? Apologies for the incredibly noob question, but I'm new to Lua, very very rusty at any code, stuck and can't find the solution! I'm creating a series of random images on screen using: for count = 1, 6 do r = math.random ( 1, 5 ) mpart[count] = display.newImage ("mpart" .. r .. ".png") mpart[count].y = 680 mpart[count].x = x mpart[count].spawnednew = false x = x + 170 mpart[count]:addEventListener ("touch", onTouch) end How do I know which object is being touched/moved in the function "onTouch", and how do I add a property to it, e.g. mpart[1].spawnednew == true A: Your onTouch function should have an event parameter passed in. The touched image can then be found by in event.target. A: Well first off, lins is spot on about how to reference the touched object: the 'event' parameter of the listener function includes the value 'event.target' As for adding new data to the touched object, that's as simple as 'event.target.moved = true' and now the object has data at object.moved
{ "language": "en", "url": "https://stackoverflow.com/questions/7507412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What kind of Map does a Scala Iterable's "toMap" method return? A Scala Iterable has a toMap method, which returns a Map. What is this map backed by? What are its performance characteristics? Is there any way to specify that toMap should return a HashMap? A: It returns an immutable.HashMap, which is actually an immutable hash array mapped trie. This data structure is essentially a hybrid between a multilevel hashtable and a trie. The worst-case complexity of a hash array mapped trie is O(log n) for all operations, although with a very low constant factor - hash array mapped tries are very shallow, and typically have only a few indirections. You can read more about the performance characteristics here or run a couple of microbencharks. The performance is acceptable in most cases. The toMap always returns a hash trie. If you want a mutable hash table, then do this: import collection._ mutable.HashMap() ++= xs instead of: xs.toMap
{ "language": "en", "url": "https://stackoverflow.com/questions/7507414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: In ObjC, how do I hide implementation a superclass's methods in a subclass? In ObjC, how do I hide implementation a superclass's methods in a subclass? I'm not sure if @private would do the trick, as it appears to only apply to ivars. A: You're right, the @private directive is for instance variables, not methods. To hide a method's implementation, simply omit its declaration from the header file. To suppress warnings, you can use use a category or class extension to declare the method in the .m file. There's no built-in language feature to prevent a subclass from seeing the method, though. Why would you want to do that? A: There are no actually "private" methods in Obj-C; since any message can be sent to any object at runtime, there's no way to prevent someone from sending the message you care about. That said, you can intercept that message in the subclass and not handle it. The simplest way to make a superclass's method inaccessible is to override it in the subclass and do nothing: - (void)someMethodIDontWantToSupport { } A: MARK as in subclass interface file. - (void)someMethodIDontWantToSupport __unavailable;
{ "language": "en", "url": "https://stackoverflow.com/questions/7507417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sanitizing paste event using jQuery in contentEditable div I am trying to sanitize a paste in a contentEditable div. That is, the code should look something like the following: $('#content').bind('paste',function(e) { // Ensure pasted markup is valid }); Ideally, I would be able to parse through the pasted text and re-format it in a way that is appropriate to the site, but I don't know how to do this. Alternatively, I would be comfortable pasting as plain text (as opposed to HTML), but I don't know how to do this either. I am slightly less comfortable with the solution of having a box pop up with a textarea, asking the user to paste into this text area and then putting the text into the content at the previous cursor position. I know how to do this, but want to avoid it. And I am completely uncomfortable with just preventing the user from pasting by using e.preventDefault(). A: There is no direct way in most browsers to access the content pasted before it goes into the DOM. There is, however, a fairly elaborate way to do this that only works for pastes triggered by the keyboard. See my answer here: JavaScript get clipboard data on paste event (Cross browser) A: I've been able to achieve this with the rangy javascript library allowing me to save and restore the caret position after sanitizing the content. https://github.com/timdown/rangy Tested in chrome and safari. $("#content").on('paste', function(){ sanitize(); }); function sanitize(){ setTimeout(function(){ var savedSelection = rangy.saveSelection(); $("#content *").removeAttr("style"); // Do your parsing here. rangy.restoreSelection(savedSelection); }, 0); } A: Could you not verify the content once it is already in the field some how? Let the content paste in, save the original content first and if the new content is not valid, replace it back with the old. It's just a theory but I'm just going to have to experiment too for now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Recovering an APK's code I recently erased my hard drive and lost few weeks of work. Despite committing frequently, I hadn't pushed my changes upstream for a while. I've extracted my app's APK from my phone and I've been trying to recover its code. I'm assuming it's possible since it was a test build (and, consequently, not obfuscated or anything like that). The best result I was able to achieve was by using dex2jar but I still have a lot of code like this: int i = context.getResources().getDimensionPixelSize(2131165184); int j = context.getResources().getDimensionPixelSize(2131165184); screenNameParams.addRule(10); screenNameParams.addRule(1, 2131034138); screenNameParams.setMargins(paramInt, 0, 0, 0); Or even: long l1 = paramLong1; long l2 = paramLong2; long l3 = paramLong3; int i = paramInt; List localList = localClient.getBetween(l1, l2, l3, i); My experience with android-apktool was even worse, since I wasn't even able to get some Java code out of it... which is expected, since it works with smali debugging. I've read all related questions here on SO and I've seen people saying that "it is tough to get the actual source code for the apk unless you're the developer", so there's hope since I'm the developer. Finally, my question is: Is it possible to fully recover an APK's original code, considering it was a test build from eclipse? A: In short, no. It looks like your code was run through ProGuard and obfuscated (as is normal) and so you won't be able to get your original code. In your quote about being the developer, those people are basically saying "it's hard to get the source for an APK unless you already have it because you're the developer" but in this case even though you're the developer, you've lost the source. The only last option I can think of that you might try is to find a hard drive recovery program and use it as soon as possible and see if you can recover your source. Maybe you haven't overwritten those sectors yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android LocationManager not throttling as expected I am experiencing difficulties reliably throttling the gps update rate on the fly. The following approach seems consistent with everything I read, and it will occasionally change the update rate once or twice (to, say, taking one GPS reading every four seconds) but after that it just stays at a rate and will no longer change. private LocationManager _locationMgr; private LocationListener _locationListener; private int _secondsPerUpdate=-1; // Constructor public AshGps(Activity l_activity, int l_secondsPerUpdate) { _locationMgr = (LocationManager) l_activity.getSystemService(Context.LOCATION_SERVICE); _locationListener = new mylocationlistener(); _locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, l_secondsPerUpdate*1000, 0, _locationListener); _secondsPerUpdate = l_secondsPerUpdate; } // Called up to once every three seconds // to change the update rate void ChangeUpdateRate(int l_secondsPerUpdate ) { if( _secondsPerUpdate != l_secondsPerUpdate ) { _locationMgr.removeUpdates(_locationListener); _locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, l_secondsPerUpdate*1000, 0, _locationListener); _secondsPerUpdate = l_secondsPerUpdate; } } // Methods handles the incoming GPS reading 'event' private class mylocationlistener implements LocationListener { @Override public void onLocationChanged(Location location) { ... A: The time period per update is a suggestion to Android. It will not always be honored. Quoting the documentation: This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mstest - /resultsfile doesnt work when /testsettings switch is used I need to specify the location of the MSTest log file. I was doing this just fine with /resultfile:path but we needed the global timout, etc from the .settings file so i added the /testsettings:testfile.testsettings switch. Now that ive done that, MSTest no longer creates the log. Any ideas? Ive tried specifying /resultfile switch after /testsettings
{ "language": "en", "url": "https://stackoverflow.com/questions/7507431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to deal with nested XML structure in JavaScript? I have the following nested XML structure <forum> <title>Title1</title> <id>123</id> <forum> <title>Title1b</title> <id>123b</id> </forum> </forum> <forum> <title>Title2</title> <id>321</id> </forum> <forum> <title>Title3</title> <id>456</id> </forum> As you can see in the above structure, I have a nested "forum" tag in the first element but not in the second and third. I have tried running a if getElementsByTagName("forum").item(0).text on the parent nodes, but it throws an error for the second and third parent nodes because the child node for "forum" doesn't actually exist. How could I properly check to see if those child nodes exist and then act on them? Thanks!!! A: You didn't use the innerText method nor did you identify the parent element. Also, getElementsByTagName returns an array. My example works as expected. http://jsfiddle.net/M2F64/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7507433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: static ConfigurationManager Access Class Operation I'm considering creating a static class to handle all of my Web.config appSettings access. For example, it would look like this: public static class ConfigManager { public static string Timeout = ConfigurationManager.AppSettings["Timeout"]; public static string Version = ConfigurationManager.AppSettings["Version"]; } I believe that this would give me a central location to change keys in the app settings if I wanted to change one in the future and would give me intellisense for all the configuration settings in my application. My question is how this would operate as I'm not sure how static works under the hood. My hope is that the first time I accessed one of the properties, all the properties would be read from the config and placed in memory and that all subsequent hits would then just go to memory instead of looking at the config. Unfortunately, this would mean that runtime changes to the config wouldn't take effect. I also thought it may be possible that only the property I'm looking at would be loaded, or that they would all be loaded every time I access any property. Does anyone know how the combo of having a static property reading from the configs would behave under the hood? A: Static means that there will only be one instance of that class or variable in memory. Since you chose a static class the values will be set once by your assignment when the static constructor is called. This will happen the first time the class is used. Anytime you access the variable after that it will be pulling the value from memory. If you are concerned about being able to change values at runtime, you could use a property instead and then implement a caching strategy that would refresh that property at a given time interval.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: handling back button I have of menu list, on click of list item it goes to an activity containing list of category buttons and on button click it shows different list depending upon which category those group of listview item belong to. menu->buttons->list view The problem is from list view when I pressed the back button, it goes back to menu. Is there any way to handle so that in stead of menu, by back button it should go back to list of buttons. Thank you... A: You will need to override the onBackPressed() method like this.. @Override public void onBackPressed() { // do something on back like launch your list of buttons activity. return; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7507436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Index on first part of string I'm querying a very large table (over 3M records) in MySQL that has a category_id, subcategory_id and zipcode. The zip may or may not be 10 characters in the db. The purpose is to get all the cat/subcat items w/in a certain radius of the specified zip. I have a function that returns a list of 5-digit zips for one specified. This list is then fed to my query like so... SELECT whatever FROM tblName WHERE cat_id = 1 AND subcat_id = 5 AND LEFT(zip,5) IN (11111,22222,33333,44444,55555) I have a compound index on cat_id, subcat_id and zip, but the zip being 10 characters in some cases may be throwing it off. Can I index the LEFT(zip,5) somehow? A: You should have a column with the normal 5 digit zip and column with all of the extra digits and let SQL handle it normally. There are ways you could do what your talking about, but this is by far the most efficient solution. A: To answer your question directly: yes, you can index left(zip, 5). alter table tblName add index (zip(5)); And if you want the query to be able to use the index to search all columns: alter table tblName add index (cat_id, subcat_id, zip(5)); A: If you want to use an index, change the query to: SELECT whatever FROM tblName WHERE cat_id = 1 AND subcat_id = 5 AND ( zip LIKE '11111%' OR zip LIKE '22222%' OR zip LIKE '33333%' OR zip LIKE '44444%' OR zip LIKE '55555%') Another option is to denormalize your table (should really be the last option) and add an extra field with that contains the 5 leftmost chars in zip. Then you can do: SELECT whatever FROM tblName WHERE cat_id = 1 AND subcat_id = 5 AND LEFTzip5 IN (11111,22222,33333,44444,55555) Don't forget to put an index on field leftzip5.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JQuery AJAX returns OK 200 , but no response I have a website where I am using JQuery to make an AJAX call to a PHP page. The PHP page takes the parameters passed from the AJAX call and inserts the data into a MySQL database. When I call the API directly by inserting the URL string into my URL bar, everything works and I get a response. However, my firebug console doesn't show a response. I see changes reflected in the database, so I know that the parameters are being passed and the PHP/MySQL is ok. In firebug, the console shows '200 ok' for the query string, but the query string is red instead of the usual black. The file that contains the PHP code is on the same server as the page that is calling it. The site is hosted on a GoDaddy shared webhosting legacy grid. I'm at a loss for what's going on. It's important that I figure this out, as I have JQuery code that depends on getting a response from the API. Any suggestions? A: Are you sure the PHP file is actually writing data to the return stream? Check to make sure your are calling echo $response; where $response is the data you want to return.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Serialize List (where the objects are supported primitives) in Protobuf.NET? How to I serialize an object like this with protobuf-net: public class MyObject{ public string Key {get; set;} public List<Object> Values {get; set;} } When I try to serialize this with a TypeModel protobuf-net throws an error stating that it doesn't know how to serialize System.Object. Now I know that Values will only ever contain primitives (int, string, float, DateTime, etc.). So how do I let protobuf-net know about this? A: This isn't really doable in pure ProtoBuf, in any sense. ProtoBuf is strongly typed, yet does not contain type information in the message; type information is always specified externally. Thus there are two "good" solutions; Ie, solutions which would be easy to interpret by a protobuf implementation other than Protobuf-net (Which you may or may not care about, but marc sure seems to). 1: Replace List<object> with List<PrimitiveType> where PrimitiveType contains optional fields corresponding to all the 12-or-so primitive types (Depending on your definition of "Primitive Type".), and you ensure only one of those is filled in on each instance. 2: Replace List<object> with a combination of List<int>, List<double>, List<string> etc. A: See In Protobuf-net how can I pass an array of type object with objects of different types inside, knowing the set of potential types in advance. As per Marc post (the author of Protobuf.NET) object is problematic. Although I can't find it right now, I distinctly remember seeing a check for object in the source to throw an exception against attempts to serialise object properties directly. To work around this you should use a more specific class to be serialised and not use object directly. You can use IProtoSerializer to implement custom serialisation/deserialisation. Protobuf will also support ISerializable and IXmlSerializable interfaces if that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: overriding SWIG casting It seems that SWIG pointer-casting is broken: *(int **)&jresult = result; // shenanigans return jresult; It really should just be jresult= (jlong)result; How can I hook into SWIG to tell it how to cast? A: You could use a typemap. See doc here for more info. Probably look something like the code below. %typemap(out) TYPE * %{ *($&1_ltype)&$result = (jlong)$1; %} A: While Frohnzie's answer is technically correct (it's what I asked for, after all), the best solution is not to hack how SWIG does casting, but to pass -fno-strict-aliasing to gcc. Buried in the SWIG docs it specifically says what to do: Important If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing. The GCC optimisations have become more aggressive from gcc-4.0 onwards and will result in code that fails with strict aliasing optimisations turned on. See the C/C++ to Java typemaps section for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sort Array of Dictionaries by NSDate I have an array of dictionaries. Within each dictionary, there is a a key dateOfInfo (an NSDate) and several other things. I want to sort the array by each dictionaries dateOfInfo with the most recent being the first result. How can I do this? A: You can sort using NSSortDescription, e.g. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey: @"dateOfInfo" ascending: NO]; NSArray *sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; [sortDescriptor release]; You can also use the method - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context A: The basic bubble sorting algorithm would work. In this case you need to loop through your array, use valueForKey message on [array objectAtIndex:] to get the NSDate values. For comparing dates see this post . So if you are sorting in ascending order of date, just add the object with the lower date (remember bubble sort comparisons?) to an array which will hold your sorted result. A: try like this, NSDateFormatter *fmtDate = [[NSDateFormatter alloc] init]; [fmtDate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; NSComparator compareDates = ^(id string1, id string2) { NSDate *date1 = [fmtDate dateFromString:string1]; NSDate *date2 = [fmtDate dateFromString:string2]; return [date1 compare:date2]; }; NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"StartTime" ascending:YES comparator:compareDates]; [youArray sortUsingDescriptors:@[sortDesc1]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7507457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android NDK problem pthread_mutex_unlock issue I'm having an issue with pthread_mutex_unlock and my native activity NDK app. I've added logging messages to each mutex initialization, lock, lock success and unlock. My program is getting deadlocked because the mutex unlock is telling me that the thread trying to unlock the mutex did not lock it. My logging says otherwise. So I'm wondering if there is something I'm doing / not doing that could be causing this. The number in () is the mutex_t* followed by the code line number and thread id returned by pthread_self(). To me it looks as though thread 1584064 has acquired the lock and is doing its processing. Then thread 1597448 attempts to lock and correctly is paused waiting to acquire the lock. The problem is when 1584064 then completes its work and tries to release the lock pthread_mutex_unlock returns an error (1). 09-21 13:55:27.098: WARN/native-activity(1333): Try to lock mutex (2154220968) Line:3041 Thread:1584064 09-21 13:55:27.098: WARN/native-activity(1333): Success: Locked Mutex (2154220968) Line:3041 Thread:1584064 09-21 13:55:31.668: DEBUG/dalvikvm(352): GC_EXPLICIT freed 8K, 4% free 8606K/8963K, paused 3ms+423ms 09-21 13:55:31.898: WARN/native-activity(1333): Try to lock mutex (2154220968) Line:3041 Thread:1597448 09-21 13:55:32.198: WARN/native-activity(1333): Error:1 Unlocking Mutex(2154220968) Line:3045 Thread:1584064 Initialization is a macro that looks like this: #define InitializeCriticalSection(p, X) \ { \ LOGW("Initialize Mutex(%u)", p); \ *p = PTHREAD_MUTEX_INITIALIZER; \ pthread_mutexattr_t attr; \ pthread_mutexattr_init(&attr); \ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); \ int ii_p = pthread_mutex_init((pthread_mutex_t *)p, &attr); \ pthread_mutexattr_destroy(&attr); \ LOGW("Initialize Mutex(%u) Returned %d", (pthread_mutex_t *)p, ii_p); \ } One thread is the standard NDK thread, the other one is my own timer thread initialized like this: pthread_t thread; pthread_attr_t pattr; int state; state = pthread_attr_init(&pattr); pthread_attr_setdetachstate(&pattr, PTHREAD_CREATE_DETACHED); if (!state) { LOGW("Creating Timers Thread %d MS", dwMsecs); int iRetTest = pthread_create(&thread, &pattr, TimersThread, (void *)pTimer); pthread_attr_destroy(&pattr); } etc... error handling It doesn't seem to make any difference if I AttachCurrentThread to the vm or not in my timers thread. It seems like mutexes are not working across threads correctly. THanks in advance for any help you can provide. A: I figured it out. The problem was in the initialization. Although this works on several other platforms, I really wasn't doing it right. If you use custom init you should new the mutex). New init looks like this: #define InitializeCriticalSection(p) \ { \ p = new pthread_mutex_t; \ LOGW("Initialize Mutex(%u)", p); \ pthread_mutexattr_t attr; \ pthread_mutexattr_init(&attr); \ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); \ int ii_p = pthread_mutex_init(p, &attr); \ pthread_mutexattr_destroy(&attr); \ LOGW("Initialize Mutex(%u) Returned %d", p, ii_p); \ } Whew!
{ "language": "en", "url": "https://stackoverflow.com/questions/7507462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One to many rel in GAE using G data Store Entity I want to create one to many relation using Google DataStore entities Something like: Entity proj=new Entity("Project"); proj.setProperty("name","Project 1"); Now I want to associated multiple user entities with this project Entity user1= new Entity("User"); user1.setProperty("name", "User1"); Entity user2= new Entity("User"); user2.setProperty("name","user2"); How do I associate multiple users 1&2 to same Project proj? A: Set the project reference on the user entity
{ "language": "en", "url": "https://stackoverflow.com/questions/7507463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: searching for a word in all triggers in a schema - oracle I'm having problems running my application - Oracle is raising an ORA-04092: cannot COMMIT in a trigger issue. Now I am trying to find the trigger which contains commit statement. Is it possible to find the trigger which has the commit statement in all `dba_triggers'? select * from dba_triggers statement gives me all dba triggers. Now I have to search these triggers with the word commit. A: If you get the full error stack, you should be able to see what line of what trigger is throwing the error. That's the most efficient approach. For example, if you create a trigger that commits and run an INSERT, the stack trace will show you what line of what trigger caused the error. SQL> create table t ( 2 col1 number 3 ); Table created. SQL> ed Wrote file afiedt.buf 1 create trigger trg_t 2 before insert on t 3 for each row 4 begin 5 commit; 6* end; SQL> / Trigger created. SQL> begin 2 insert into t values( 1 ); 3 end; 4 / begin * ERROR at line 1: ORA-04092: cannot COMMIT in a trigger ORA-06512: at "SCOTT.TRG_T", line 2 ORA-04088: error during execution of trigger 'SCOTT.TRG_T' ORA-06512: at line 2 You can search the source for all triggers looking for a particular string. Something like this will look for the literal "COMMIT" in any trigger in whatever schemas you specify. SELECT name, text, line FROM dba_source WHERE owner IN (<<schemas you want to search>>) AND upper(text) like '%COMMIT%'; On the other hand, there is a strong probability that the trigger that is failing is calling a stored procedure and it is the stored procedure that is committing. So searching the source of your triggers may not be beneficial. You could potentially mitigate that by doing a recursive query on DBA_DEPENDENCIES (or ALL_DEPENDENCIES or USER_DEPENDENCIES depending on your privilege level and the scope of what you want to search for) to find all of the procedures that are potentially called from any trigger and to search the source of all of those procedures from DBA_SOURCE. But that's going to be much more complex than simply examining the full error stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook like button on Wordpress I added a like button to my index.php and single.php on yssencial.com (using wordpress) but on the main page (index.php) it is not sharing the article but the site url (www.yssencial.com) instead. A: You need to set the data-href property of the individual posts to your posts url. Otherwise it will use the page that it is actually on, eg your home page. <div class="fb-like" data-href="http://www.yssencial.com/2011/09/20/terra-nova-quando-o-parque-jurassico-encontra-a-maquina-do-tempo/" data-send="false" data-layout="button_count" data-width="140" data-show-faces="true"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7507480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine if the last_seen_at Time field is great than 1 minute ago In my Room model I have a field last_activity_at I want to do something like if last_activity_at is greater than 1 minute ago? What's the right way in rails to do that? Thanks A: How about this: record.last_activity_at > 1.minute.ago
{ "language": "en", "url": "https://stackoverflow.com/questions/7507486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Substituting classes that adopt a particular protocol (Objective-c) In Objective-c if two classes adopt a particular protocol can instances of the classes be used interchangeably? Say I have the following code: @protocol MyProtocol @required @property (nonatomic, retain) SomeObject *object; @end @interface ClassA <MyProtocol> @property (nonatomic, retain) SomeObject *object; // ... @end @interface ClassB <MyProtocol> @property (nonatomic, retain) SomeObject *object; // ... @end Can I substitute (id <MyProtocol>)instanceOfClassB when a method expects an instance of ClassA ? A: Nope. Instances of different classes that conform to the same protocol can be used interchangeably when the API is explicitly typed that way though, e.g.: - (void)someMethod:(id <MyProtocol>)someObj;
{ "language": "en", "url": "https://stackoverflow.com/questions/7507489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamically disabling form fields in MVC 3 with Razor I have a large form in a Razor view and want to make certain form elements disabled depending on the state of the model object I'm passing in. So some logic has to be defined to determine whether to show this element, make it read-only or make it editable. My current thinking is leading me to define some Razor @helper's with the logic there, although I'm not sure if that's the best way to do it. Kind of like ... @helper determineElementStatus(string modelProperty) { if (modelProperty == someState) { @Html.TextBoxFor....etc } } @determineElementStatus(model.someProperty) Indeed I'm not sure if the view is the right place. It is presentation logic in the fact that it changes the appearance of the form, but is it best place elsewhere and how??. Help would be appreciated. A: In the View you can control the logic of the change css. eg Depending the value of the Model values i create the displayMode and apply it to the Html. @{ string isInherited = Model.IsInheritedValue ? "editor-field inherColor" : "editor-field"; object displayMode = Model.IsDisabled ? new { @disabled = "disabled", @class = isInherited } : (object)new { @class = isInherited }; } So now whenever you show @Html.TextBoxFor(x => x.Value, displayMode) The displayMode will determine how to show it. hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is "backporting" Python 3's `range` to Python 2 a bad idea? One of my classes requires assignments to be completed in Python, and as an exercise, I've been making sure my programs work in both Python 2 and Python 3, using a script like this: #!/bin/bash # Run some PyUnit tests python2 test.py python3 test.py One thing I've been doing is making range work the same in both versions with this piece of code: import sys # Backport Python 3's range to Python 2 so that this program will run # identically in both versions. if sys.version_info < (3, 0): range = xrange Is this a bad idea? EDIT: The reason for this is that xrange and range work differently in Python 2 and Python 3, and I want my code to do the same thing in both. I could do it the other way around, but making Python 3 work like Python 2 seems stupid, since Python 3 is "the future". Here's an example of why just using range isn't good enough: for i in range(1000000000): do_something_with(i) I'm obviously not using the list, but in Python 2, this will use an insane amount of memory. A: You can use the six package which provides a Python 2 and 3 compatibility library and written by one of the Python core developers. Among its features is a set of standard definitions for renamed modules and functions, including xrange -> range. The use of six is one of many recommendations in the official Porting Python 2 Code to Python 3 HOWTO included in the Python Documentation set. A: What you probably should be doing is making sure it works cleanly under 2.x, and then passing it through 2to3 and verifying that the result works cleanly in 3.x. That way you won't have to go through hoops such as redefining range as you have already done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to enable multitouch cocos2d I want to be able to enable multitouch for cocos2d. How can I do this? I want to test each touch event like my code below. Please help. -(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *myTouch = [touches anyObject]; CGPoint location = [myTouch locationInView:[myTouch view]]; location = [[CCDirector sharedDirector] convertToGL:location]; b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO); CGSize screenSize = [CCDirector sharedDirector].winSize; if (locationWorld.x >= screenSize.width*2/5/PTM_RATIO && locationWorld.x <= screenSize.width*3.25/5/PTM_RATIO) { cannonballTouch1 = 1; float force = 6; b2Vec2 direction = cannonballBody->GetWorldCenter() - cannonBody->GetWorldCenter(); b2Vec2 iforce = b2Vec2(1.0f/direction.x * force, 1.0f/direction.y * force); NSLog(@"%.2f", direction.y); NSLog(@"%.2f", iforce.y); b2Vec2 force1 = b2Vec2(0, iforce.y); cannonballBody->ApplyLinearImpulse(force1, cannonballBody->GetPosition()); } if (locationWorld.x > screenSize.width*3.25/5/PTM_RATIO) { cannonballTouch2 = 1; float force = 6; b2Vec2 direction = cannonballBody2->GetWorldCenter() - cannonBody2->GetWorldCenter(); b2Vec2 iforce = b2Vec2(1.0f/direction.x * force, 1.0f/direction.y * force); NSLog(@"%.2f", direction.y); NSLog(@"%.2f", iforce.y); b2Vec2 force1 = b2Vec2(0, iforce.y); cannonballBody2->ApplyLinearImpulse(force1, cannonballBody2->GetPosition()); } } A: this page discribe it pretty well. http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/MultitouchEvents/MultitouchEvents.html To handle multitouch events, you must first create a subclass of a responder class. This subclass could be any one of the following: A custom view (subclass of UIView) A subclass of UIViewController or one of its UIKit subclasses A subclass of a UIKit view or control class, such as UIImageView or UISlider A subclass of UIApplication or UIWindow (although this would be rare) A view controller typically receives, via the responder chain, touch events initially sent to its view if that view does not override the touch-handling methods. For instances of your subclass to receive multitouch events, your subclass must implement one or more of the UIResponder methods for touch-event handling, described below. In addition, the view must be visible (neither transparent or hidden) and must have its userInteractionEnabled property set to YES, which is the default. The following sections describe the touch-event handling methods, describe approaches for handling common gestures, show an example of a responder object that handles a complex sequence of multitouch events, discuss event forwarding, and suggest some techniques for event handling.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Confusion about CFNetwork, CFReadStreamOpen, and CFRunLoopRun That sinking feeling when you realize you have no idea what's going on... I've been using this code in my network code for almost two years without problems. if (!CFReadStreamOpen(myReadStream)) { CFStreamError myErr = CFReadStreamGetError(myReadStream); if (myErr.error != 0) { // An error has occurred. if (myErr.domain == kCFStreamErrorDomainPOSIX) { // Interpret myErr.error as a UNIX errno. strerror(myErr.error); } else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) { OSStatus macError = (OSStatus)myErr.error; } // Check other domains. } } I believe it was originally based on the code samples given here: http://developer.apple.com/library/mac/#documentation/Networking/Conceptual/CFNetwork/CFStreamTasks/CFStreamTasks.html I recently noticed, however, that some connections are failing, because CFReadStreamOpen returns false but the error code is 0. After staring at the above link some more, I noticed the CFRunLoopRun() statement, and added it: if (!CFReadStreamOpen(myReadStream)) { CFStreamError myErr = CFReadStreamGetError(myReadStream); if (myErr.error != 0) { // An error has occurred. if (myErr.domain == kCFStreamErrorDomainPOSIX) { // Interpret myErr.error as a UNIX errno. strerror(myErr.error); } else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) { OSStatus macError = (OSStatus)myErr.error; } // Check other domains. } else // start the run loop CFRunLoopRun(); } This fixed the connection problem. However, my app started showing random problems - interface sometimes not responsive, or not drawing, text fields not editable, that kind of stuff. I've read up on CFReadStreamOpen and on run loops (specifically, that the main run loop runs by itself and I shouldn't run a run loop unless I'm setting it up myself in a secondary thread - which I'm not, as far as I know). But I'm still confused about what's actually happening above. Specifically: 1) Why does CFReadStreamOpen sometimes return FALSE and error code 0? What does that actually mean? 2) What does the CFRunLoopRun call actually do in the above code? Why does the sample code make that call - if this code is running in the main thread I shouldn't have to run the run loop? A: I guess I'll answer my own question, as much as I can. 1) In my code, at least, CFReadStreamOpen always seems to return false. The documentation is a bit confusing, but I read it to mean the stream wasn't opened yet, but will be open later in the run loop. 2) Most of the calls I was making were happening in the main thread, where the run loop was already running, so calling CFRunLoopRun was unnecessary. The call that was giving me problems was happening inside a block, which apparently spawned a new thread. This new thread didn't start a new run loop - so the stream would never open unless I explicitly ran the new thread's run loop. I'm still not 100% clear on what happens if I call CFRunLoopRun() on a thread with an already running run loop, but it's obviously not good. I ended up ditching my home-brewed networking code and switching to ASIHTTPRequest, which I was considering to do anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: the objects inside a NSMutableDictionary are lost during runtime. the pointers are lost somehow I have a NSMutableDictionary in a class @interface ClassName : UITableViewController { NSMutableArray *doctors_set; } @property (nonatomic, retain) NSMutableArray *doctors_set; @implementation ClassName @synthesize DocID,doctors_set; I'm adding 4 objects DoctorsSet *set = [[DoctorsSet alloc] init]; //DoctorsSet is an extended NSObject [doctors_set addObject:set]; what I want is to use the sets in the same class (I'm using a tableview) so when I tap on the cell I must recover the set on the index tapped DoctorsSet *set = (DoctorsSet *)[doctors_set objectAtIndex:indexPath.row]; when the didSelectRowAtIndexPath event occurs.. the sets at the indexes are lost, i can see it in the debugger. the indexes don't even have the DoctorsSet type..they're replace by some random types that tells me that somehow the objects are not retained... This happens if I tap 2,3 times on the table cells when I assign the array in the debugger i get self doctors_set = (_NSARRAYM *) pointerid 4 objects 0 = (DoctorsSet *) pointerid 1 = (DoctorsSet *) pointerid 2 = (DoctorsSet *) pointerid 3 = (DoctorsSet *) pointerid when I get the error , because it sais that the selector does not belong to the object (that's because the object itself is lost) self doctors_set = (_NSARRAYM *) pointerid 4 objects 0 = (NSObject *) pointerid 1 = (NSObject *) pointerid 2 = (NSCFString *) pointerid 3 = (UITouchData *) pointerid A: Where do you allocate the NSMutableArray and assign it to your doctors_set property? My guess is that you are assigning it without keeping it retained. You probably want to do something like: doctors_set = [[NSMutableArray alloc] init]; If you show how you allocate and store this property it should be easier to tell how to fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ideal way to pass filtered relationship of a model to a template? This is more of what feels like a lot of work / hackish code... Say I have some models like this: class Semester(models.Model): year = models.IntegerField() month = models.IntegerField() # ... some fields class Course(models.Model): semesters = models.ManyToManyField(Semester) # ... some fields class Section(models.Model): semesters = models.ManyToManyField(Semester) course = models.ForeignKey(Course, related_name='sections') # ... more fields So, for a view, I'm fetching a list of courses by semester. But I also want to list the sections for the courses in a given semester. This creates a dilemma: where do I put this? I can't do it in the templates (because the templates can't really process methods with arguments) and I always have been doing something like this: def view(request, year, month): # for simplicity, no error handling semester = Semester.objects.get(year=year, month=month) courses = [] for c in Course.objects.filter(semesters=semester): courses.append({ 'semesters': c.semesters.all(), # repeat for every course field 'sections': c.sections.filter(semesters=semester), }) # render template with courses variable I feel like this isn't the optimal way, since there is a lot of data translation going on just to the templates happy. I would normally write methods to the model for ones that don't require any arguments, but what about ones that do? A: You're going to have data translation either way... but if you want to make it a little easier on the template you could return a generator instead of a list of courses and/or semesters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django-registration not recognizing urls.py accounts page? I am trying to setup django-registration and it is not recognizing the URLs. I get Error 404 when I visit http://localhost:8000/accounts/ Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/ Using the URLconf defined in namekeepr.urls, Django tried these URL patterns, in this order: ^pk/$ ^pk/index/$ ^admin/ ^accounts/ ^activate/complete/$ [name='registration_activation_complete'] ^accounts/ ^activate/(?P<activation_key>\w+)/$ [name='registration_activate'] ^accounts/ ^register/$ [name='registration_register'] ^accounts/ ^register/complete/$ [name='registration_complete'] ^accounts/ ^register/closed/$ [name='registration_disallowed'] ^accounts/ ^login/$ [name='auth_login'] ^accounts/ ^logout/$ [name='auth_logout'] ^accounts/ ^password/change/$ [name='auth_password_change'] ^accounts/ ^password/change/done/$ [name='auth_password_change_done'] ^accounts/ ^password/reset/$ [name='auth_password_reset'] ^accounts/ ^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$ [name='auth_password_reset_confirm'] ^accounts/ ^password/reset/complete/$ [name='auth_password_reset_complete'] ^accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] ^admin/ ^accounts/profile/$ ^accounts/password_reset/$ ^accounts/password_reset_done/$ ^accounts/password_change/$ ^accounts/password_change_done/$ The current URL, accounts/, didn't match any of these. A: Try going to http://localhost:8000/accounts/ with a slash on the end. That is the 'regular' django url, usually it would redirect to this but it is not for some reason.... but before you try to solve that problem, should make sure it works this way. A: based on the server response, you have not defined a url for ^/accounts/$ (the root of accounts)
{ "language": "en", "url": "https://stackoverflow.com/questions/7507508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add manually Google API library to a project in Eclipse? I'm doing small GPS project. Before I work on 32-bit laptop and I had option Target device: 2 x per every API. one was from Google and second from device. my laptop went down. I've bought new one 64-bit. I've installed every thing from beginning and now I don't have Google API option when I'm beginning new project. And when I try to add any libraries to an existing project I have also not even a single one to pick. I've had reinstall everything 3 times and nothing, so now I have only one option - add it manually to my project. Where I can download Google Maps API for Android, and how to add them to my existing project manually A: You can install the Google API targets by opening the SDK and AVD manager. Either go to Window -> SDK and AVD Manager inside eclipse or start the android application from the ANDROID_SDK\tools folder. When open, select Available packages on the left, then open the Android Repository tree. There should be various google APIs listed. Check the ones with the API levels you need and click Install selected. After everything went through, you can start a new project with the desired google APIs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to efficiently execute JavaScript functions when elements are inserted? Initially, when the page loads, I search with jQuery for stuff like this: <label for="first_name">name</label> <input type="text" name="first_name" /> And change html to be fancier. The problem becomes when I try to dynamically insert elements like these into DOM. Since nothing is binded to the newly created elements, I am not sure what's a proper way to run my "adjustement" functions. I wouldn't simply want to hack it and call adjust_html1(), adjust_html2(), etc manually right after inserting. What is the most organized and efficient way to run code after html is inserted? (sidenote: would be even cooler if there's a way to run it only on new html) Edit: added a "for" Edit 2: Here's my sample jQuery code that runs on document ready: $('label').each(function() { /* do stuff */ }); A: You could checkout the livequery plugin: $('[name="first_name"]').livequery(function() { alert('A node with name=first_name was injected into the DOM'); adjust(this); }); A: Use the live() binding method. Attach a handler to the event for all elements which match the current selector, now and in the future. A: Create your html like this: var elem = $('<p></p>').text('hello').appendTo(document.body); adjust_html(elem); A: Okay, perhaps I didn't explain what I wanted correctly. The purpose is to basically be able to run a set of functions on newly inserted html - efficiently, without having to manually call them. For now I am going to go with the code I wrote below. Initially, you have templates on your page, and you bind functions for certain selectors (that exist inside of your template) to all your templates. So that when you insert the template into the page, those selectors try to match inside of your template, and run binded functions. The code below is neither efficient, nor optimized or thoroughly tested. So, I am not going to accept it as the final answer. It is just a sample solution, and kind of hacky anyway. But it works. I am sure backbone.js or some plugin do it much better, so I'll wait for a JS guru to show the right way. As a sidenote: I realize there's 2 disadvantages: a) the way of setting html has to be done through template object, rather than natural jQuery way, and b) template is inserted into DOM, and only then functions start running on it. My first version did work on the template before it was inserted, but some functions like .replaceWith() don't work exactly the same on strings as on DOM nodes. On the plus side, the code is tiny, and does just what I wanted. <html> <body> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> window.template = { queue: {}, set: function(container, content) { /* first insert content */ container.html(content); /* now run a list of functions in the queue */ $.each(this.queue, function(s, fs) { var el = $(s, container); for (var i = 0, len = fs.length; i < len; ++i) el.each(fs[i]); }); }, bind: function(selector, func) { if (typeof this.queue[selector] === 'undefined') this.queue[selector] = []; /* push function to queue for that specific selector */ this.queue[selector].push(func); } }; $(function() { var templateContents = $('#my-template').html(); /* for each <label>, replace it with another <input> */ template.bind('label[for="first_name"]', function() { $(this).replaceWith('<input type="text" name="last_name" value="last name" />'); }); $('a').click(function(e) { e.preventDefault(); $('body').append('<div class="container"></div>'); /* get the div that we just appended to body */ var newDiv = $('.container').last(); /* set that newDiv's html to templateContents, and run binded functions */ template.set(newDiv, templateContents); }); }); </script> </head> <body> <script id="my-template" type="text/template"> <label for="first_name">name</label> <input type="text" name="first_name" /> </script> <a href="#">add dynamically</a> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7507517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Iterator.each: why is this working I was refactoring a bit of code in a project for work when I came across an odd bit of syntax. I confirmed it has been in the file since it was first created and the bit of code is being called. worksheet.each 1 do |row| Dashboard::LocalizedMessagingField.create({blah blah blah}) end When I run something like the following in irb it complains about 1 for 0 parameters on each. [1,2,3].each 1 do |i| puts i end Why does it work in the RoR application? Anyone ever see something like this before? A: I found the answer after a bit of digging. We have the Spreadsheet gem installed and it provides an each method that takes a parameter to skip the first n rows of a spreadsheet. def each skip=dimensions[0], &block skip.upto(dimensions[1] - 1) do |idx| block.call row(idx) end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7507520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python and Regex - extracting a number from a string I'm new to regex, and I'm starting to sort of get the hang of things. I have a string that looks like this: This is a generated number #123 which is an integer. The text that I've shown here around the 123 will always stay exactly the same, but it may have further text on either side. But the number may be 123, 597392, really one or more digits. I believe I can match the number and the folowing text using using \d+(?= which is an integer.), but how do I write the look-behind part? When I try (?<=This is a generated number #)\d+(?= which is an integer.), it does not match using regexpal.com as a tester. Also, how would I use python to get this into a variable (stored as an int)? NOTE: I only want to find the numbers that are sandwiched in between the text I've shown. The string might be much longer with many more numbers. A: You don't really need a fancy regex. Just use a group on what you want. re.search(r'#(\d+)', 'This is a generated number #123 which is an integer.').group(1) if you want to match a number in the middle of some known text, follow the same rule: r'some text you know (\d+) other text you also know' A: res = re.search('#(\d+)', 'This is a generated number #123 which is an integer.') if res is not None: integer = int(res.group(1)) A: if you want to get the numbers only if the numbers are following text "This is a generated number #" AND followed by " which is an integer.", you don't have to do look-behind and lookahead. You can simply match the whole string, like: "This is a generated number #(\d+) which is an integer." I am not sure if I understood what you really want though. :) updated In [16]: a='This is a generated number #123 which is an integer.' In [17]: b='This should be a generated number #123 which could be an integer.' In [18]: exp="This is a generated number #(\d+) which is an integer." In [19]: result =re.search(exp, a) In [20]: int(result.group(1)) Out[20]: 123 In [21]: result = re.search(exp,b) In [22]: result == None Out[22]: True A: You can just use the findall() in the re module. string="This is a string that contains #134534 and other things" match=re.findall(r'#\d+ .+',string); print match Output would be '#1234534 and other things' This will match any length number #123 or #123235345 then a space then the rest of the line till it hits a newline char.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initializing a member class of an object using a non-default constructor in C++ I have a specific situation where I've got an object that I want to use the boost random number generators on, and it has lead to a greater question which I cannot seem to answer. Here is the example code of what I'm trying to produce. First, my header: Class MyObject { protected: double some variable; boost::random::mt19937 rgenerator; boost::uniform_real<double> dist_0_1; boost::variate_generator< boost::mt19937&, boost::uniform_real<double> > rand01 } Now what I want to do is: Class MyObject { protected: double some variable; boost::random::mt19937 rgenerator(std::time(0)); //initialize to a "random" seed boost::uniform_real<double> dist_0_1(0,1); //set the distribution to 0-1 boost::variate_generator< boost::mt19937&, boost::uniform_real<double> > rand01(rgenerator, dist_0_1);//tell it to use the above two objects } But this doesn't work because it is in a header. I thought I could use the constructor of MyObject to somehow call the constructors on the various sub-objects (distribution, generator, but I can't figure out how. By the time the constructor of MyObject is called, the sub-objects' default constructors have already been called, and I haven't found that they have member methods to reset these properties... besides which, that isn't the point where I am confused. Now maybe there are too many things going on and I'm confusing issues, but as far as I can tell, my problem reduces to this following, childish example: Class Tree { Tree(); Tree(int); protected: fruit apples(int); } Tree::Tree() { apples(0); //won't work because we can't call the constructor again? } Tree::Tree(int fruit_num) { apples(fruit_num); //won't work because we can't call the constructor again? } Class Fruit { public: Fruit(); Fruit(int); protected: int number_of_fruit; } Fruit::Fruit() { number_of_fruit = 0; } Fruit::Fruit(int number) { number_of_fruit = number; } I'm sure this is second nature to everyone else out there, but I can't find an article that talks about the best practice for initializing member objects of an object to a non-default constructor value. A: What you want is an initializer list. For example: Tree::Tree(int fruit_num) : apples(fruit_num) // Initializes "apple" with "fruit_num" { } You simply add a colon (:) after the constructor parameters and before the opening brace {. You can separate different member constructors with commas (,). Example: Tree::Tree(int fruit1, int fruit2) : apples(fruit1), bananas(fruit2) { } A: The answer to this question is relatively straightforwards. You use initializer lists. Here's an example: class MyClass { private: SomeOtherType sot; public: MyClass() : sot(parametersForConstructorOfSOT) {} }; You can extend this to multiple member objects, of course; it can also be used to call the constructor of a parent class to initialize private entries in a parent class if you need to do something like that. A: You're so close! Just use the initialiser list syntax: Tree::Tree() : apples(0) { // ... } Tree::Tree(int fruit_num) : apples(fruit_num) { // ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7507526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing value from child window to parent window using WPF and MVVM pattern I have parent window which has textBox called "SchoolName", and a button called "Lookup school Name". That Button opens a child window with list of school names. Now when user selects school Name from child window, and clicks on "Use selected school" button. I need to populate selected school in parent view's textbox. Note: I have adopted Sam’s and other people’s suggestion to make this code work. I have updated my code so other people can simply use it. SelectSchoolView.xaml (Parent Window) <Window x:Class="MyProject.UI.SelectSchoolView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Parent" Height="202" Width="547"> <Grid> <TextBox Height="23" Width="192" Name="txtSchoolNames" Text="{Binding Path=SchoolNames, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> <Label Content="School Codes" Height="28" HorizontalAlignment="Left" Margin="30,38,0,0" Name="label1" VerticalAlignment="Top" /> <Button Content="Lookup School Code" Height="30" HorizontalAlignment="Left" Margin="321,36,0,0" Name="button1" VerticalAlignment="Top" Width="163" Command="{Binding Path=DisplayLookupDialogCommand}"/> </Grid> </Window> SchoolNameLookup.xaml (Child Window for Look up School Name) <Window x:Class="MyProject.UI.SchoolNameLookup" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" Title="SchoolCodeLookup" Height="335" Width="426"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="226*" /> <RowDefinition Height="70*" /> </Grid.RowDefinitions> <toolkit:DataGrid Grid.Row="0" Grid.Column="1" x:Name="dgSchoolList" ItemsSource="{Binding Path=SchoolList}" SelectedItem="{Binding Path=SelectedSchoolItem, Mode=TwoWay}" Width="294" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" CanUserSortColumns="True" SelectionMode="Single"> <Button Grid.Row="1" Grid.Column="1" Content="Use Selected School Name" Height="23" Name="btnSelect" Width="131" Command="{Binding Path=UseSelectedSchoolNameCommand}" /> </Grid> </Window> SchoolNameLookupViewModel private string _schoolNames; public string SchoolNames { get { return _schoolNames; } set { _schoolNames= value; OnPropertyChanged(SchoolNames); } } private ICommand _useSelectedSchoolNameCommand; public ICommand UseSelectedSchoolNameCommand{ get { if (_useSelectedSchoolNameCommand== null) _useSelectedSchoolNameCommand= new RelayCommand(a => DoUseSelectedSchollNameItem(), p => true); return _useSelectedSchoolNameCommand; } set { _useSelectedSchoolNameCommand= value; } } private void DoUseSelectedSchoolNameItem() { StringBuilder sfiString = new StringBuilder(); ObservableCollection<SchoolModel> oCol = new ObservableCollection<SchoolModel>(); foreach (SchoolModel itm in SchollNameList) { if (itm.isSelected) { sfiString.Append(itm.SchoolName + "; "); _schoolNames = sfiString.ToString(); } } OnPropertyChanged(SchoolNames); } private ICommand _displayLookupDialogCommand; public ICommand DisplayLookupDialogCommand { get { if (_displayLookupDialogCommand== null) _displayLookupDialogCommand= new RelayCommand(a => DoDisplayLookupDialog(), p => true); return _displayLookupDialogCommand; } set { _displayLookupDialogCommand= value; } } private void DoDisplayLookupDialog() { SchoolNameLookup snl = new SchoolNameLookup(); snl.DataContext = this; //==> This what I was missing. Now my code works as I was expecting snl.Show(); } A: My solution is to bind both the windows to the same ViewModel, then define a property to hold the resulting value for codes, lets call it CurrentSchoolCodes, Bind the label to this property. Make sure that CurrentSchoolCodes raises the INotifyPropertyChanged event. then in the DoUseSelectedSchoolNameItem set the value for CurrentSchoolCodes. For properties in your models I suggest you to load them as they are required(Lazy Load patttern). I this method your property's get accessor checks if the related field is still null, loads and assigns the value to it. The code would be like this code snippet: private ObservableCollection<SchoolModel> _schoolList; public ObservableCollection<SchoolModel> SchoolList{ get { if ( _schoolList == null ) _schoolList = LoadSchoolList(); return _schoolList; } } In this way the first time your WPF control which is binded to this SchoolList property tries to get the value for this property the value will be loaded and cached and then returned. Note: I have to say that this kind of properties should be used carefully, since loading data could be a time consuming process. And it is better to load data in a background thread to keep UI responsive. A: The Solution Sam suggested here is a correct one. What you didn't get is that you should have only one instance of you viewmodel and your main and child page should refer to the same one. Your viewmodel should be instanciated once: maybe you need a Locator and get the instance there... Doing like this the code in your ctor will fire once, have a look at the mvvmLight toolkit, I think it will be great for your usage, you can get rid of those Classes implementing ICommand too... You can find a great example of using that pattern here: http://blogs.msdn.com/b/kylemc/archive/2011/04/29/mvvm-pattern-for-ria-services.aspx basically what happens is this: you have a Locator public class ViewModelLocator { private readonly ServiceProviderBase _sp; public ViewModelLocator() { _sp = ServiceProviderBase.Instance; // 1 VM for all places that use it. Just an option Book = new BookViewModel(_sp.PageConductor, _sp.BookDataService); } public BookViewModel Book { get; set; } //get { return new BookViewModel(_sp.PageConductor, _sp.BookDataService); } // 1 new instance per View public CheckoutViewModel Checkout { get { return new CheckoutViewModel(_sp.PageConductor, _sp.BookDataService); } } } that Locator is a StaticResource, in App.xaml <Application.Resources> <ResourceDictionary> <app:ViewModelLocator x:Key="Locator" d:IsDataSource="True" /> </ResourceDictionary> </Application.Resources> in your views you refer you viewmodels trough the Locator: DataContext="{Binding Book, Source={StaticResource Locator}}" here Book is an instance of BookViewModel, you can see it in the Locator class BookViewModel has a SelectedBook: private Book _selectedBook; public Book SelectedBook { get { return _selectedBook; } set { _selectedBook = value; RaisePropertyChanged("SelectedBook"); } } and your child window should have the same DataContext as your MainView and work like this: <Grid Name="grid1" DataContext="{Binding SelectedBook}">
{ "language": "en", "url": "https://stackoverflow.com/questions/7507527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows installer: How to supress Installation Incomplete window when search condition is not met VS2010, Setup Project I add a Search64bitOffice property in Search Target Machine, Name Search64bitOffice Property: OFFICEIS64BIT RegKey: Software\Microsoft\Office\14.0\Outlook\Bitness Root vsdrrHKLM Value: x64 Then I add a launch condition Search64bitOffice Condition: OFFICEIS64BIT Message: This installer only works for 64 bit Office. When I try installer on Win 7 64 bit + Office 32 bit, a window pops up saying "This installer only works for 64 bit Office" which is expected. I click OK to dismiss the window, then another window comes up saying Installation Incomplete The installer was interrupted before * could be installed. You need to restart the installer to try again. Click close to exit. I do not want the second window to show up. How to remove it from installer? thanks another question: how to use the reverse condition, say when the condition is false, I want installer to continue? I tried ~OFFICEIS64BIT, do not work A: I do not want the second window to show up. How to remove it from installer? You can't remove it. It's the user exit dialog which is shown when the installation is cancelled by the user or a launch condition. The most you can do is modify it, but this is not supported by Visual Studio. how to use the reverse condition, say when the condition is false, I want installer to continue? Use NOT to negate the condition: NOT OFFICEIS64BIT A: Use this in Launch Condition !(OFFICEIS64BIT) I had similar problem & it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I show the values of deeply nested fields? I have a tables of Users, Carts, Orders and OrderTransactions. My schema looks like: * *User has one cart *Cart has one order *Order has many transactions I would like to display the user_id in the order transaction partial. I can display the cart_id with <%= order_transaction.order.cart_id %> So I thought that <%= order_transaction.order.cart.user_id %> would work but it's giving a "undefined method `user_id' for nil:NilClass" error. What am I missing here? Any help would be much appreciated! A: Just noticed, It does actually work. I needed to delete all transactions created before the changes I made.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting up svn repository I recently setup svn on a Windows 2003 server over ssh. I'm familiar with the developer end of svn, but I've never had to be the admin. The point of it is to allow remote development through visual studio. I have an existing directory with all files for my site that was not previously under version control. The site points to this directory, and so I do not want to move these files. How do I create a repository and add all the existing files to it without having to move them? Thanks A: 1st: create repository and its necessary branches/tags/trunk structure on server and make it available over network via apache or svnserve: svnadmin create /opt/svn/myrepo svn mkdir file:///opt/svn/myrepo/trunk -m "creating repo structure" svnserve -d -r /opt/svn/ 2nd: check out repositories target folder(eg trunk) into your topmost directory of your source code: svn co http://[YOUR_SERVER]/myrepo/trunk c:\development\myproject\src 3rd: commit source code into repository as initial import svn commit -m "initial import of myproject" You can also use the svn import command, however this one will allow you to continue your development without another check out of your source code. Also note that I did not create the full repository structure because of brevity, usually you would do this by creating the top level folder and using svn import A: As others have stated: svnadmin create /path/to/repository will create the repository for you. You'll then have to have some server mechanism. I'm not sure how you'll do svn+ssh on Windows since sshd is not part of the standard Windows utility. You can use svnserve directly or download CollabNet Subversion Edge which will integrate Apache with Subversion (and ViewVC) in one package. What I recommend though, is that you read the on line book about Subversion Administration. This is a fairly quick read, well written, and will get you up and running on the Subversion server end in no time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Forward and backward navigation buttons for Android I am porting an iPhone app to Android, and I can't find the Android equivalent of the UINavigationItem. These are buttons with a triangular side indicating movement between different screens. For an example of what I'm trying to accomplish, this is from the BeyondPod app: http://mobiputing.wpengine.netdna-cdn.com/wp-content/uploads/2011/05/beyondpod.jpg The buttons labeled "Categories" and Podcasts" are what I'd like to duplicate. A: Android has a hardware back button. Forward is typically accomplished by some widget, such as a button or link, somewhere in the Activity. A: I looked at the screenshot you posted again and noticed that your left and right buttons are to switch between categories and not to go to an earlier screen.(Im not sure if im right) If that's the case using the left and right buttons are okay as they are to switch between categories and not the previous screen. But keeping a left button just to go to the previous screen isn't really necessary. Here we need to think in terms of an android user. They are hardwired to press the hardware back button to go to a previous screen. There are many examples of apps that have a bit of changes in their android and iPhone version. Eg Evernote. It uses tabs on the iPhone but in android they sort of created a dashboard in combination with an action bar. So main thing to consider when porting an iphone app is to make enough changes so that an android user will feel like it has a navigation they are used to. Most apps that look exactly the same as iphone apps are created with these cross mobile development tools(titanium, sencha touch).
{ "language": "en", "url": "https://stackoverflow.com/questions/7507535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON ARRAY Return I have a Array that is pulling back X amount of Data from a JSON file, Lets say 40 I wanted some help where If i want X amount of data from that file, lets say just 20, What't the best approach to do so? Is there any example out there. I tried using jQuery.grep function but i was not getting it to work. Any help will be greatly appreciated Thanks in advance. A: If the JSON "file" is a server-side script, then you could add a query string parameter to the request and then change the server-side code to restrict the number of results. Otherwise, you can simply use the slice method of Array to get a subset of the array of data in your client-side code: var subset = origArray.slice(20);
{ "language": "en", "url": "https://stackoverflow.com/questions/7507538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why would OnShow not be called for a TForm? I'm working in a project in Delphi 7 and I'm not extremely intimate with the language or runtime. I'm attempting to debug an issue where a form is made visible and painted and such but for some reason the OnShow event is not called. In what case can this happen? Where exactly should I look? A: The only explanation that makes sense to me is that the OnShow event is not correctly connected to your handler. Check in the Object Inspector or the .dfm form. If you are connecting in code, make sure you connect early enough. A: There is one more possibility when OnShow event is not called, when form is displayed with ShowWindow(Form.Handle, SW_SHOW); I saw such thing in the past during looking into some project, that's really a bad idea for Delphi. A: you should check here Fist OnShow() must be decleared. type TForm2 = class(TForm) procedure FormShow(Sender: TObject); // <--- IM HERE! private { Private declarations } public { Public declarations } end; Secondly... implementation {$R *.dfm} procedure TForm2.FormShow(Sender: TObject); <--- IM HERE! begin //this time will trigger end; and the last thing, you should open the Dfm look for the FormShow Event object Form2: TForm2 Left = 0 Top = 0 Caption = 'Form2' ClientHeight = 284 ClientWidth = 418 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnShow = FormShow <--- IM HERE! without this it will not trigger the OnFormShow PixelsPerInch = 96 TextHeight = 13 end if still doesn't work it might be referred to other function name OnShow = FormStart or wat ever function name. A: If you would like to do some things when the form is loaded and you want to be sure that all components are initialized you might use loaded protected procedure Loaded; override; It is called during form creation. It has the additional benefit that the form pops up initialized without a slow building of the form as may happen with OnActivate. A: Having a similar problem when the OnShow handler set using the object inspector was not called I found that another handler was assigned during program execution overwriting my settings, so you may also look for a possible assignment to OnShow in the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to replace garbled characters in a string? I have this text... “I’m not trying to be credible,†David admits with a smile broadening" ...and I would like to delete those funny characters, I've tried str_replace() but it does not work. Any ideas? A: You probably have handled text in a different encoding then its source encoding. So if the text is UTF-8, you are not handling it currently as UTF-8. The easiest way is to send a header such as... header('Content-Type: text/html; charset=UTF-8'); You could also add the meta element, but ensure it is the first child of your head element. You need to fix that at the source instead of trying to patch it later (which will never work well). A: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> ... </head> Different sources often have different encodings, so you need to specify the encoding in which you are presenting the view. Utf-8 is the most popular, since it covers all of ASCII and many, many other languages. php's utf8_(de)encode converts iso-8859-1 to utf-8 and the opposite and regular string manipulating functions are not multibyte-(which utf-8 can be) character aware. Either you use functions specific to mb_strings or enable encoding with certain parameters. //comment if i'm mistaken A: Well, you are using a different character encoding that you should probably use(you should be using utf-8 encoding), so I would change that instead of trying to just fix it on the spot with a quick-fix(you will run into less problems overall that way). If you really want to fix it using PHP, you can use the ctype_alpha() function; you should be able to do something like this: $theString = "your text here"; // your input string $newString = ""; // your new string $i = 0; while($theString[$i]) // while there are still characters in the string { if(ctype_alpha($theString[$i]) // if it's a character in your current set { $newString .= $theString[$i]; // add it to the new string, increment pointer, and go to next loop iteration $i++; continue; } // if the specific character at the $i index is an alphabetical character, add it to the new string else { $i++; } // if it's a bad character, just move the pointer up by one for the next iteration } Then use $newString however you want to. Really though, just change your character encoding instead of doing it this way. You want the encoding to be the same across your entire project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Expanding Panel on click to view hidden controls I am currently working on a C# wpf project. What I was looking for is a GUI control that can have other GUI controls inside but are hidden and when the user clicks on the GUI control it then expands the panel to reveal the hidden GUI components. I have seen other programs but I can't find anything like that in C#. Thanks for any help you can provide. A: You're probably looking for the <Expander ... /> control. This tutorial has a few pictures.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: exe created using install4j eats up all CPU after 30-40 seconds from launching I have created an installer for my Java application using install4j. it is running on JDK1.6 and uses Jetty as a web server and struts2 as an MVC. The application installs just fine and an exe file is created correctly. When I launch the application by double clicking on the exe file, the application launch and starts just fine and all functionality behaves correctly. After about 30 to 40 seconds from launching the application, I notice that the exe process is eating almost all the CPU power (up to 99%). making it so hard to use any other application on my PC. This only happens on Windows XP and Vista. But when I try it on Windows 7 I do not get this problem. The windows XP and Vista machines spec are very good (3GHZ processor with 4 GB of RAM). I really have no idea why the exe eats up all the CPU after 30 to 40 seconds of starting the application. There are no threads, no back ground workers, no logic being processed at all. its a very simply MVC application. Matter of fact i just try open the application then wait for 30 to 40 seconds (without using it) and the CPU usage shots up high. In the task manager I noticed that 2 processors are created, one for the exe and one for the Java processor created by the exe during launching the app. only the exe process is using 99% of CPU while the Java process is idle. Any one face something similar? any help is appreciated. Thanks, A: Have you tried looking into the Java process using VisualVM? It's part of any JDK install. It can hook into any running Java program and sample/profile it very thoroughly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mathematica doesn't solve wave equation when given boundary conditions Still new to Mathematica syntax. When I do: DSolve[{ D[u[x, t], {x, 2}] == (1/(v*v))*D[u[x, t], {t, 2}], u[0, t] == 0, u[l, 0] == 0 }, u, {x, t}] it just returns what I entered DSolve[{(u^(2,0))[x,t]==(u^(0,2))[x,t]/v^2,u[0,t]==0,u[l,0]==0},u,{x,t}] However, when I remove the boundary conditions, I get {{u->Function[{x,t},C[1][t-(Sqrt[v^2] x)/v^2]+C[2][t+(Sqrt[v^2] x)/v^2]]}} with C[1] and C[2] representing the functions for the boundary conditions. Anyone know why this is happening? A: 2 things: * *Don't you need more boundary and initial conditions than just 2? You have second order derivatives on left and right side, each requires 2 conditions. Hence total is 4. see http://mathworld.wolfram.com/WaveEquation1-Dimensional.html *I do not think DSolve or NDSolve can solve initial and boundary value problems? I seem to have read this somewhere sometime ago. No time to check now. A: I think that Mathematica doesn't know how to deal with these boundary conditions for 2nd order PDEs. How would you want the answer returned? As a general Fourier series? This is mentioned in the Mathematica Cookbook (and probably other places)... Breaking down the problem for Mathematica (with the dimensional factor v->1), you find In[1]:= genSoln = DSolve[D[u[x, t], {x, 2}] == D[u[x, t], {t, 2}], u, {x, t}] // First Out[1]= {u -> Function[{x, t}, C[1][t - x] + C[2][t + x]]} In[2]:= Solve[u[0, t] == 0 /. genSoln] Out[2]= {{C[1][t] -> -C[2][t]}} In[3]:= u[l, 0] == 0 /. genSoln /. C[1][x_] :> -C[2][x] // Simplify Out[3]= C[2][-l] == C[2][l] that the solution is written as f(t-x)-f(t+x) where f is periodic over [-l,l]... You can't do any more with out making assumptions about the smoothness of the solution. You can check that the standard Fourier series approach would work, e.g. In[4]:= f[x_, t_] := Sin[n Pi (t + x)/l] - Sin[n Pi (t - x)/l] In[5]:= And[D[u[x, t], {x, 2}] == D[u[x, t], {t, 2}], u[0, t] == 0, u[l, 0] == 0] /. u -> f // Reduce[#, n] & // Simplify Out[5]= C[1] \[Element] Integers && (n == 2 C[1] || n == 1 + 2 C[1])
{ "language": "en", "url": "https://stackoverflow.com/questions/7507564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Problem with .htaccess file and exclude command I have a simple .htaccess which redirect non www to www domain RewriteEngine on RewriteCond %{HTTP_HOST} !^www.example.com$ RewriteRule (.*) http://www.example.com/$1 [R=301,L] What I need to do is to exclude the IP calling from this redirect. In other words I need that if someone call site by IP then it won't be redirected to www domain, it will call the IP itself and visitor can navigate all the site links without the 301 redirect. This means he will still navigate the site through the IP. A: Try RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com$ RewriteRule (.*) http://www.example.com/$1 [R=301,L] It looks to see if the host does not start with www and if so it redirects to the www URL. It won't match the IP address or any other subdomains (i.e. test.example.com)
{ "language": "en", "url": "https://stackoverflow.com/questions/7507566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on Rails build query in pieces There was a very similar question before but i still struggle. Is it possible to build a query up in stages? Let's say I have a search form with many text and select fields that may be chained with and/or or which could be blank. So the sql statement should consist of several parts that are connected individually for each search. I tried to create strings for every option and put them to a symbol? (i mean @options) and put that in the where clause (e.g. Product.where(@options) ). That works somehow but i have got troubles with this part: 'params[:query]' when it's in quotes. Either my sql statement says 'select products from products where (name like params[:query]') or if i try #{params[:query]} it says: select products from products (where 'name' like ''.) So how can i chain different parts of a query? I looking forward to your answers! A: Never, ever, ever embed raw strings in your SQL. This is extremely bad form. You should always use the escaping mechanism provided by Rails or something equivalent to avoid ending up in serious trouble. Inserting content from params is very dangerous and should never be done as it only takes this to nuke your app: { :query => '\"-- DROP TABLE users;' } Generally you use the helper methods provided by ActiveRecord to build up your query in stages: scope = Product if (params[:query].present?) scope = scope.where([ 'name LIKE ?', "%#{params[:query]}%" ]) end if (params[:example].present?) scope = scope.where(:example => true) end @products = scope.all You can build it up in stages like this, modifying the scope in-place each time, and then execute the final call to retrieve it. Generally that's when you use your paginator to split up the results. It's okay to put pretty much anything in your options because it should be escaped by the time it hits the SQL phase, much as anything on the HTML side is escaped for you as well. Don't confuse instance variables like @options with a symbol like :query. The two are very different things. Instance variables have the benefit of propagating to your view automatically, so they are often used extensively in controllers. Views should avoid modifying them whenever possible as a matter of style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there a way to simulate touch events in Windows 8 Is there a way to simulate touch events in Windows 8 (and preferably in windows 7). I know there is a project called Multi touch vista but I feel its a bit overkill and I never got it working correctly with multiple screens. What I want to do is very simple, I want to start an app that can send touch events to Windows no need for multiple mice or any thing like that. Can it be done or do I need a (MMV) driver to do that? Thanks /Jimmy A: I was looking for something similar and found this article Simulating Touch Input in Windows Developer preview using Touch Injection API and sample code (C++) may answer your question. However, this seems to work only on Windows 8 (not Windows 7). It simulates Tap, Hold, Drag, Pinch/Pan, Rotate and Cross-Slide. Here is the touch (Tap) code: POINTER_TOUCH_INFO contact; InitializeTouchInjection(1, TOUCH_FEEDBACK_DEFAULT); // Here number of contact point is declared as 1. memset(&contact, 0, sizeof(POINTER_TOUCH_INFO)); contact.pointerInfo.pointerType = PT_TOUCH; contact.pointerInfo.pointerId = 0; //contact 0 contact.pointerInfo.ptPixelLocation.y = 200; // Y co-ordinate of touch on screen contact.pointerInfo.ptPixelLocation.x = 300; // X co-ordinate of touch on screen contact.touchFlags = TOUCH_FLAG_NONE; contact.touchMask = TOUCH_MASK_CONTACTAREA | TOUCH_MASK_ORIENTATION | TOUCH_MASK_PRESSURE; contact.orientation = 90; // Orientation of 90 means touching perpendicular to screen. contact.pressure = 32000; // defining contact area (I have taken area of 4 x 4 pixel) contact.rcContact.top = contact.pointerInfo.ptPixelLocation.y - 2; contact.rcContact.bottom = contact.pointerInfo.ptPixelLocation.y + 2; contact.rcContact.left = contact.pointerInfo.ptPixelLocation.x - 2; contact.rcContact.right = contact.pointerInfo.ptPixelLocation.x + 2; contact.pointerInfo.pointerFlags = POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT; InjectTouchInput(1, &contact); // Injecting the touch down on screen contact.pointerInfo.pointerFlags = POINTER_FLAG_UP; InjectTouchInput(1, &contact); // Injecting the touch Up from screen Another article: Getting Started with Windows Touch Gestures A: I haven't had a chance to try it myself, but according to this article, the simulator included with the Windows 8 Dev Preview allows for simulating multi-touch zoom and rotation gestures using a mouse. You can see a demonstration of this at approximately 35:40 of this BUILD conference session: Tools for building Metro style apps A: Further to the solution which points to the C++ Sample code for InjectTouchInput which comes packaged in the User32.dll of Windows 8, the C# solution can be found here: InjectTouchInput Windows 8 C# not working (returns false) A: Creating a virtual Hid driver appears to be the only way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: ordering/sorting a pulldown box/dropdown list I am trying to order/sort a pulldown/dropdown list. What do I have to add to the following code? public void financeInit() { financeEntities db = new financeEntities(); ViewData["currencyList"] = db.exchrates.ToList(); } A: There are many things that you should do to this code but for starters try ordering: ViewData["currencyList"] = db.exchrates .OrderBy(x => x.SomePropertyYouWnatToOrderBy) .ToList(); and the other things that you should do with this code: * *use a repository instead of directly invoking a database call inside a controller in order to weaken the coupling between your controllers and data access layer. *define view models and get rid of ViewData. Then pass a strongly typed view model to the view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java get query expansion terms Does anyone know if its possible to easily get query expansion terms programmatically using Java? For example when you do a google search, at the bottom of the results page there is a "Searches Related to [term]" section, is there a way to harvest those terms? I feel like this would be easiest. I dont want to create my own query expansion algorithm because of time constraints and would like a quick and easy way to get the terms. for example "fashion design" -> ["fashion design courses", "fashion design careers", "fashion design sketches"] thank you in advance for any help -MC A: You could scrape the google answer to your query (making an HTTP request), capture the content near "Search relates.." section, and extract suggested terms. Pro: * *You use google (without implementing your query-expansion algorithm). Cons: * *You need internet connection A: The Wikipedia page for query expansion points to two Java implementations that might be helpful: * *LucQE *LuceneQE A: QueryParser.parse(string) ; This simple yet powerful call uses Lucene's Query Parser to parse the string and returns a Query object that contains all the Terms in a tree like structure. Use this to convert a natural language search query like content:(whatever) in:(inbox,sent) AND body:(something) NOT (nothing) into an appropriate tree structure retaining all the logical conditions such as AND OR NOT etc and it is really easy to traverse. Now your java app has the power of understanding simple google like syntax. Of course you also need a powerful back end to support such searches! Lucene can help you with that as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where should I start in making industry standard audio in my iPhone applications? I am trying to get started in advanced audio with the iPhone SDK. I really want to make professional level audio components. I know the basics (e.g. how to use NSAVAudioPlayers), but I don't know what to do for the more complicated sort of audio (e.g. osculation and audio cones). Does anyone know where to go for this? (I tried research online, and all that came up weer the sort of simplistic audio components). A: Core Audio. That's where you'll find an OpenAL implementation. You might also want to look at the Audio Processing Graph API (also part of core audio).
{ "language": "en", "url": "https://stackoverflow.com/questions/7507574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Galleria Fullscreen theme captions between image and thumbnails I'm using the Galleria jQuery slideshow framework. My question is, how can I bottom-align the caption in the Fullscreen theme, so it's between the thumbnails and the main image, without cropping the images, with white (i.e. blank) space behind it? In other words, is there a way to place the description so that it's not overlapping the main image? I posted this question on the Galleria support site a few months ago, but I can't get any help from the developer. Here's my page. A: The image dimensions are being calculated somewhere in the code, dig it out and minus 20-50 pixels from the height.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: org-timer module load error in emacs I want to use the pomodoro technique in org-mode as explained in http://orgmode.org/worg/org-gtd-etc.html I have added the following lines in .emacs file (add-to-list 'org-modules 'org-timer) (setq org-timer-default-timer 25) (add-hook 'org-clock-in-hook '(lambda () (if (not org-timer-current-timer) (org-timer-set-timer '(16))))) When starting the emacs the following warning is displayed in the Warnings buffer. Symbol's value as variable is void: org-modules I am using org-mode version - 7.7.291.g37db which is cloned from git://orgmode.org/org-mode.git How to get rid of the error. A: org-modules is defined in org.el. If you want to add an element to the list, you need to wait until the variable is defined (with a default list). One way to do that is delay the addition until immediately after org.el is loaded: (defun my-after-load-org () (add-to-list 'org-modules 'org-timer)) (eval-after-load "org" '(my-after-load-org)) Note that add-hook can cope with a variable that isn't defined yet, but add-to-list can't. You could write (setq org-modules '(org-timer)), but that would overwrite the default module list instead of adding to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: NSMutableArray works in ViewDidLoad, but not in DidSelectRowAtIndexPath Menu.h @interface Menu : UITableViewController { NSMutableArray *arrayCellCollectionOrder; NSMutableDictionary *dictCellCollection; NSMutableDictionary *dictCellIndividual; } @property (nonatomic, retain) NSMutableArray *arrayCellCollectionOrder; @end Menu.m ViewDidLoad works as normal. @synthesize arrayCellCollectionOrder; - (void)viewDidLoad { // Codes to read in data from PLIST // This part works NSString *errorDesc = nil; NSPropertyListFormat format; NSString *plistPath; NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; plistPath = [rootPath stringByAppendingPathComponent:@"InfoTableDict.plist"]; if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) { plistPath = [[NSBundle mainBundle] pathForResource:@"InfoTableDict" ofType:@"plist"]; } NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc]; if (!temp) { NSLog(@"Error reading plist: %@, format: %d", errorDesc, format); } arrayCellCollectionOrder = [[[NSMutableArray alloc] init] retain]; arrayCellCollectionOrder = [temp objectForKey:@"CellCollectionOrder"]; // I can access `arrayCellCollectionOrder` here, it's working. } cellForRowAtIndexPath works as normal. I can access arrayCellCollectionOrder. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"PhotoCell"; PhotoCell *cell = (PhotoCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PhotoCell" owner:self options:nil]; for (id currentObject in topLevelObjects) { if ([currentObject isKindOfClass:[PhotoCell class]]) { cell = (PhotoCell *) currentObject; break; } } } // Copy the specific dictionary from CellCollection to Cell Individual dictCellIndividual = [dictCellCollection objectForKey:[NSString stringWithFormat:@"%@", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]]; cell.photoCellTitle.text = [dictCellIndividual objectForKey:@"Title"]; // Load cell title cell.photoCellImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", [dictCellIndividual objectForKey:@"ThumbnailFilename"]]]; // Load cell image name return cell; } didSelectRowAtIndexPath NOT WORKING. I cannot access arrayCellCollectionOrder. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Browser NSMutableArray *arrayPhotos = [[NSMutableArray alloc] init]; NSLog(@"indexPath.row = %d", indexPath.row); // Returns the row number i touched, works. NSLog(@"arrayCellCollectionOrder = %@", [NSString stringWithFormat:@"%@", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]); // DOES NOT WORK. // Copy the specific dictionary from CellCollection to Cell Individual dictCellIndividual = [dictCellCollection objectForKey:[NSString stringWithFormat:@"%@", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]]; // This similar line gives error too. ... ... ... ... ... ... ... ... } Error is: * Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (1) beyond bounds (0)' i.e.: I clicked on row 1, but arrayCellCollectionOrder is NULL. There should have data in arrayCellCollectionOrder as it's declared in ViewDidLoad. Is there something that I missed out? Thanks a lot in advance. A: arrayCellCollectionOrder = [[[NSMutableArray alloc] init] retain]; arrayCellCollectionOrder = [temp objectForKey:@"CellCollectionOrder"]; Do you see what you are doing to arrayCellCollectionOrder? You first assign it to a new NSMutableArray (and retain it needlessly), and then you immediately orphan the array and assign arrayCellCollectionOrder to another object that you are getting from the temp dictionary. In other words, that first line isn't doing anything for you, other than create a leaked mutable array. If the second line is correct and you are getting a valid object and that is what you want, then the problem is that I don't see where that object is getting retained. As long as it is in the dictionary, it is probably retained, but if temp is discarded, then its members are released. If you did a self.arrayCellCollectionOrder = [temp objectForKey:@"CellCollectionOrder"]; then the setter would retain it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pygettext: Seen unexpected token "%" I am currently trying to implement internationalization in an application (Python 2.6) and have run into an error involving string formatting. A string marked translatable looks like this: foo = _("I would like to have %d pounds of cheese" % amount) Running pygettext on my source tree then complains when it hits this line: $ pygettext . *** ./foobar.py:45: Seen unexpected token "%" The resulting messages.pot file does not contain the string after pygettext has done its work. What is the way to go for string formatting with gettext? A: Translate the unreplaced string. Or replace on the translated string. foo = _("I would like to have %d pounds of cheese") % amount
{ "language": "en", "url": "https://stackoverflow.com/questions/7507588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Im trying to use backgroundworker i want to see the upload progress but it dosent work why? In the designer i put backgroundworker and i have two events: Do Work and Progress Changed. I used breakpoint and its getting inside the Do Work event but it never get into the Progress Changed event. Its never stop there like the event isnt working. Why the progrss changed event isnt working ? This is the code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.Extensions.MediaRss; using Google.GData.YouTube; using Google.YouTube; using System.Threading; namespace YoutubeTesting { public partial class Form1 : Form { YouTubeRequestSettings settings; YouTubeRequest request; string devkey = "AI39si6xhSQXx95FTYIACWPfq-lLIphblgaReuz9z6VEjR1Q6YjrV6FRN2U6FN6P6-lGF2OYaUZhCVOKJ_MCk4o6kPeUszvf5A"; string username = "chocolade13091972@gmail.com"; string password = "password"; public Form1() { InitializeComponent(); worker.RunWorkerAsync(); } private void Form1_Load(object sender, EventArgs e) { } private void upload() { try { settings = new YouTubeRequestSettings("You Manager", devkey, username, password); settings.Timeout = -1; request = new YouTubeRequest(settings); Video video = new Video(); video.Title = "test"; video.Tags.Add(new MediaCategory("Comedy", YouTubeNameTable.CategorySchema)); video.Keywords = "Comedy"; video.Private = false; video.MediaSource = new MediaFileSource("d:\\VIDEO0037.3gp", "video/3gp"); request.Upload(video); MessageBox.Show("Successfully Uploaded"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void worker_DoWork(object sender, DoWorkEventArgs e) { upload(); } private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { textBox1.Text = e.ProgressPercentage.ToString(); } } } A: You need to report the progress using worker.ReportProgress() From MSDN: If you need the background operation to report on its progress, you can call the ReportProgress method to raise the ProgressChanged event. The WorkerReportsProgress property value must be true, or ReportProgress will throw an InvalidOperationException. It is up to you to implement a meaningful way of measuring your background operation's progress as a percentage of the total task completed. The call to the ReportProgress method is asynchronous and returns immediately. The ProgressChanged event handler executes on the thread that created the BackgroundWorker. A: You have to set this. backgroundWorker.WorkerReportsProgress = true; Gets or sets a value indicating whether the BackgroundWorker can report progress updates. EDIT If still not working checks whether you have bind the event properly in the designer code. Or just add something like below in your class. backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.worker_ProgressChanged); In your Upload method you have to report progress. Otherwise above event won't fire. Keep in mind that, it's not easy to report actual progress always. Below is an example code for a DoWork method. Look at here if you want to see a complete example. static void bw_DoWork (object sender, DoWorkEventArgs e) { for (int i = 0; i <= 100; i += 20) { if (_bw.CancellationPending) { e.Cancel = true; return; } _bw.ReportProgress (i); Thread.Sleep (1000); // Just for the demo... don't go sleeping } // for real in pooled threads! e.Result = 123; // This gets passed to RunWorkerCompleted }
{ "language": "en", "url": "https://stackoverflow.com/questions/7507593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best practice for OnPaint, Invalidate, Clipping and Regions I have a User Control with completely custom drawn graphics of many objects which draw themselves (called from OnPaint), with the background being a large bitmap. I have zoom and pan functionality built in, and all the coordinates for the objects which are drawn on the canvas are in bitmap coordinates. Therefore if my user control is 1000 pixels wide, the bitmap is 1500 pixels wide, and I am zoomed at 200% zoom, then at any given time I would only be looking at 1/3 of the bitmap's width. And an object which has a rectangle starting at point 100,100 on the bitmap, would appear at point 200,200 on the screen provided you were scrolled to the far left. Basically what I need to do is create an efficient way of redrawing only what needs to be redrawn. For example, if I move an object, I can add the old clip rectangle of that object to a region, and union the new clip rectangle of that object to that same region, then call Invalidate(region) to redraw those two areas. However doing it this way means I have to constantly convert the objects bitmap coordinates into screen coordinates before supplying them to Invalidate. I have to always assume that the ClipRectangle in PaintEventArgs is in screen coordinates for when other windows invalidate mine. Is there a way that I can make use of the Region.Transform and Region.Translate capabilities so that I do not need to convert from bitmap to screen coordinates? In a way that it won't interfere with receiving PaintEventArgs in screen coordinates? Should I be using multiple regions or is there a better way to do all this? Sample code for what I'm doing now: invalidateRegion.Union(BitmapToScreenRect(SelectedItem.ClipRectangle)); SelectedItem.UpdateEndPoint(endPoint); invalidateRegion.Union(BitmapToScreenRect(SelectedItem.ClipRectangle)); this.Invalidate(invalidateRegion); And in the OnPaint()... protected override void OnPaint(PaintEventArgs e) { invalidateRegion.Union(e.ClipRectangle); e.Graphics.SetClip(invalidateRegion, CombineMode.Union); e.Graphics.Clear(SystemColors.AppWorkspace); e.Graphics.TranslateTransform(AutoScrollPosition.X + CanvasBounds.X, AutoScrollPosition.Y + CanvasBounds.Y); DrawCanvas(e.Graphics, _ratio); e.Graphics.ResetTransform(); e.Graphics.ResetClip(); invalidateRegion.MakeEmpty(); } A: Since a lot of people are viewing this question I will go ahead and answer it to the best of my current knowledge. The Graphics class supplied with PaintEventArgs is always hard-clipped by the invalidation request. This is usually done by the operating system, but it can be done by your code. You can't reset this clip or escape from these clip bounds, but you shouldn't need to. When painting, you generally shouldn't care about how it's being clipped unless you desperately need to maximize performance. The graphics class uses a stack of containers to apply clipping and transformations. You can extend this stack yourself by using Graphics.BeginContainer and Graphics.EndContainer. Each time you begin a container, any changes you make to the Transform or the Clip are temporary and they are applied after any previous Transform or Clip which was configured before the BeginContainer. So essentially, when you get an OnPaint event it has already been clipped and you are in a new container so you can't see the clip (your Clip region or ClipRect will show as being infinite) and you can't break out of those clip bounds. When the state of your visual objects change (for example, on mouse or keyboard events or reacting to data changes), it's normally fine to simply call Invalidate() which will repaint the entire control. Windows will call OnPaint during moments of low CPU usage. Each call to Invalidate() usually will not always correspond to an OnPaint event. Invalidate could be called multiple times before the next paint. So if 10 properties in your data model change all at once, you can safely call Invalidate 10 times on each property change and you'll likely only trigger a single OnPaint event. I've noticed you should be careful with using Update() and Refresh(). These force a synchronous OnPaint immediately. They're useful for drawing during a single threaded operation (updating a progress bar perhaps), but using them at the wrong times could lead to excessive and unnecessary painting. If you want to use clip rectangles to improve performance while repainting a scene, you need not keep track of an aggregated clip area yourself. Windows will do this for you. Just invalidate a rectangle or a region that requires invalidation and paint as normal. For example, if an object that you are painting is moved, each time you want to invalidate it's old bounds and it's new bounds, so that you repaint the background where it originally was in addition to painting it in its new location. You must also take into account pen stroke sizes, etc. And as Hans Passant mentioned, always use 32bppPArgb as the bitmap format for high resolution images. Here's a code snippet on how to load an image as "high performance": public static Bitmap GetHighPerformanceBitmap(Image original) { Bitmap bitmap; bitmap = new Bitmap(original.Width, original.Height, PixelFormat.Format32bppPArgb); bitmap.SetResolution(original.HorizontalResolution, original.VerticalResolution); using (Graphics g = Graphics.FromImage(bitmap)) { g.DrawImage(original, new Rectangle(new Point(0, 0), bitmap.Size), new Rectangle(new Point(0, 0), bitmap.Size), GraphicsUnit.Pixel); } return bitmap; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7507602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I search for a string of text in the native Google Maps app from PhoneGap on iOS AND Android? I'm developing a cross-platform PhoneGap app, and I'd like a string of text in a 'Location' field, when tapped, to open up the native Google Maps app in PhoneGap or Android. Everyone seems to be embedding their maps directly in PhoneGap these days with the Google Maps API v3. BUT, I'd rather not, so that... * *my user's get 'turn-by-turn-directions' of the native Maps app, and to, *prevent PhoneGap's performance issues with Geolocation enabled. So far I've found: * *this guide to open native Google Maps in iOS in Mobile Safari, and in the native browser on other platforms. *this guide to invoke Google Applications on Android Devices. (This is native, not HTML5 in PhoneGap.) But I don't think that works in PhoneGap, aka UIWebView, so... we need this guide on integrating PhoneGap with Google Maps on the iPhone. And another for Android. To open native Google Maps on iPhone in PhoneGap, the command is: <a href="/javascript:Device.exec("openmap:q=QUERY');">QUERY</a> I have yet to test this, and I need to find the same code for Android. The final execution of this would need to open the Native Google Apps on either platform, and also on an HTML5 web version. Any tips? A: Do Something like this for Android: <a href="http://maps.google.com/maps?q=TD Bank Garden Boston, MA"> Android OS will ask if you want to open this with Browser or the Maps App.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: set text in textview with text from an edittext in another class Im completely new to Android so apologies if this is a silly question. But my problem is this: I have created a number of classes for each of the pages in my app and I would like to update the text in a textview of a particular class from the text in an edittext field from another class. To be more specific, I have a login page and I want the username (input by the user in an edittext box) to be transferred to a textfield in the logged in page. Currently I am trying to achieve this by using a click listener for the log in button in the log in page: public void sign_in_click(View view) { EditText tv1 = (EditText) findViewById(R.id.txt_input_uname); String username=tv1.getText().toString(); LoginDetails unamede=new LoginDetails(); unamede.setuname(username); Intent myIntent = new Intent(view.getContext(), customer.class); startActivityForResult(myIntent, 0); } So the click listener initialises a new class variable I have defined in another class like so: public class LoginDetails { public String uname; public void setuname(String username){ uname=username; } public String getuname(){ return uname; } } and it gives uname the username from the edittext box in the login page. Then I have in the logged in page under oncreate: LoginDetails unamed= LoginDetails(); String username=unamed.getuname(); tv1.setText(username); but the text in the textview box doesnt get anything written to it. Now I wont be surprised if I'm doing this completely wrong but any advice would be much appreciated. thanks A: What i would suggest is put the user's log in information into a SharedPreference. To transfer the date to another activity. For example... SharedPreferences myPrefs = getSharedPreferences("USER_INFO", 0); myPrefsEdit.putString("USER_ID", username=tv1.getText().toString();); //This is the username you get from edittext myPrefsEdit.putString("PASSWORD", password); //this is the user password you get from edittext myPrefsEdit.commit(); In your next activity. Get reference to your SharePreference like... SharedPreferences info = getSharedPreferences("USER_INFO, 0); String username = info.getString("USER_ID", "DOESNT EXIST"); String userpassword = info.getString("PASSWORD", "DOESNT EXIST"); This should do it A: You could try putting the username to activity intent extra (when you don't want to persist it in the shared preferenced right now): Intent myIntent = new Intent(view.getContext(), customer.class); myIntent.putExtra("uname", username); startActivityForResult(myIntent, 0); And then in onCreate: tv1.setText(getIntent().getStringExtra("uname"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7507605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert string to wstring, encoding issues I've read Stroustrup's Appendix D (particular attention to Locales and Codecvt). Stroustrup does not give a good codecvt and widen example (IMHO). I've been trying to knob turn stuff from the internet with no joy. I've also tried imbue'ing stringstreams without success. Would anyone be able to show (and explain) the code to go from a UTF-8 to a UTF-16 (or UTF-32) encoding? NOTE: I do not know the size of the input/output string in advance, so I expect the solution should use reserve and a back_inserter. Please don't use out.resize(in.length()*2). When finished, it would be great if the code actually worked (its amazing how much broken code is out there). Please make sure the following 'round trips'. The bytes below are the Han character for 'bone' in UTF-8 and UTF-{16|32}. const std::string n("\xe9\xaa\xa8"); const std::wstring w = L"\u9aa8"; My apologies for a basic question. On Windows, I use the Win32 API and don't have these problems moving between encodings. A: Just use UTF8-CPP : std::wstring conversion; utf8::utf8to16(utf8_str.begin(), utf8_str.end() , back_inserter(conversion)); Caveat: this will only work where wchar_t is 2-bytes long (windows). For a portable solution you could do : std::vector<unsigned short> utf16line; // uint16_t if you can utf8::utf8to16(utf8_line.begin(), utf8_line.end(), back_inserter(utf16line)); But then you're losing the string support. Hopefully, we'll get char16_t soon enough. A: It seems pretty obvious that he was smoking weed. As for the codepage conversions, look no further than iconv!
{ "language": "en", "url": "https://stackoverflow.com/questions/7507606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to tell if an object has implemented ToString explicitly in c# I am trying to log information about the state of some objects and classes in my code. Not all the classes or libraries were implemented with Serialization. So I am using Reflection on the Properties to write out an XML document of the state. However, I have a challenge in that some objects like builtin Classes (ie Strings, DateTime, Numbers etc...) have a ToString function that prints out the value of the class in a meaningful way. But for other classes, calling ToString just uses the inherited base ToString to spit out the name of the object type (For example a Dictionary). In that case I want to recursively examine to properties inside that class. So if anyone can help me with reflection to either figure out if there is a ToString implemented on the property I'm looking at that isn't the base method OR to point out the proper way of using GetValue to retrieve collection properties I would appreciate it. J A: To determine whether a method has overridden the default .ToString() check MethodInfo.DeclaringType like so: void Main() { Console.WriteLine(typeof(MyClass).GetMethod("ToString").DeclaringType != typeof(object)); Console.WriteLine(typeof(MyOtherClass).GetMethod("ToString").DeclaringType != typeof(object)); } class MyClass { public override string ToString() { return ""; } } class MyOtherClass { } Prints out: True False
{ "language": "en", "url": "https://stackoverflow.com/questions/7507609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ASP.NET Equivalent to this cURL command I'm working with the Twilio API and it provides examples in PHP and Ruby. I'm working on a site to send text messages through the API that's coded in ASP.NET MVC 3, and using my limited knowledge of the WebRequest object, I was able to translate this: curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/AC4840da0d7************f98b20b084/SMS/Messages.xml' \ -d 'From=%2B14155992671' \ -u AC4840da0d7************f98b20b084:f7fc2**************75342 Into this: var request = WebRequest.Create(MessageApiString + "?From=+14*********1&To=" + Phone + "&Body=" + smsCampaign.Message); var user = "AC4840da0d7************f98b20b084"; var pass = "f7fc2**************75342"; string credentials = String.Format("{0}:{1}", user, pass); request.Headers.Add("Authorization", credentials); var result = request.GetResponse(); But it's not authenticating, I'm getting a 401 from their API. What is the equivalent C# to the cURL -u command? Update var request = WebRequest.Create(MessageApiString + "?From=+14155992671&To=" + Phone + "&Body=" + smsCampaign.Message); var cc = new CredentialCache(); cc.Add(new Uri(MessageApiString), "NTLM", new NetworkCredential("AC4840da0d7************f98b20b084", "f7fc2**************75342")); request.Credentials = cc; request.Method = "POST"; var result = request.GetResponse(); Still getting 401. Any ideas? Update 2 Alright, thanks to the answers below I was able to get through to the api, but now I'm getting a 400 Bad Request. Is there a cleaner way to build a query string to pass this data along? The three fields are From, To, and Body. A: Try including request.Method = "POST"; and request.Credentials = new NetworkCredential("username", "password"); A: The -u option in Curl is to specify a username and password for Server Authentication. For C# this is set using the WebRequest.Credentials property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How To Get A Server Control Property Name With A Dash In It I'm creating a custom server control in ASP.NET WebForms and want to have a hyphen in my property name the same way the ASP.NET server controls do in the markup. For example, a Label control has a "Font-Size" property in the markup like so: <asp:Label ID="Label1" Font-Size="small" Text="hi" runat="server" /> How do I accomplish this? A: Just use complex properties on your control: public class MyControl: WebControl { public Test() { // Make sure to initialize the complex property or you will get a NRE // when you try to set the Complex-Bar property in the webpage Complex = new Complex(); } public Complex Complex { get; set; } } public class Complex { public string Bar { get; set; } } and then: <asp:MyControl runat="server" ID="myControl" Complex-Bar="foo bar" /> A: I added the following to get intellisense working with the complex property: [Category("Appearance")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [PersistenceMode(PersistenceMode.InnerProperty)]
{ "language": "en", "url": "https://stackoverflow.com/questions/7507615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Post message referencing users As a facebook app I want to post a message that references a set of users (e.g. @John Doe, @Tom Cruise) so that the message will show up on their wall (and their friends can see). How can I do this programmatically? Through what API calls? A: As stated by aFacebook employee, tagging users in statuses is not available through the API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Socket closing not throwing IOException I'm writing a basic Server-client program in Java and I'm trying to handle the case where the client terminates unexpectedly. public void run() { while(alive) { try { // socketIn is a BufferedReader wrapped around the socket's InputStream. String input = socketIn.readLine(); if(input == null) continue; String response = processInput(input); // socketOut is a PrintWriter wrapped around the socket's OutputStream. if(response != null) { socketOut.println(response); socketOut.flush(); } } catch(IOException e) { System.out.println("TRACE 1"); alive = false; } } System.out.println("TRACE 2"); } But when I kill the client, the loop keeps going and neither TRACE is printed out. I'm assuming that when a socket is closed from the other end and I am trying to read from it, it will throw an IOException. Was this a bad assumption? What can I do to fix this? A: readLine() will return null at end of stream, which is what happens when the remote end closes the connection normally. You are attempting to continue on this condition, which will loop forever. IOException will be thrown if the connection is broken abnormally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Updating Facebook from Android I have the below script running and it works perfectly. What I am wondering is. Why does facebook give me a secret key if I dont have to implement it as I have not below. Facebook facebook = new Facebook("APP_ID"); // Application ID of your app at facebook boolean isLoggedIn = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Implementing SSO facebook.authorize(this, new String[]{"publish_stream"}, new DialogListener(){ @Override public void onComplete(Bundle values) { //control comes here if the login was successful // Facebook.TOKEN is the key by which the value of access token is stored in the Bundle called 'values' Log.d("COMPLETE","AUTH COMPLETE. VALUES: "+values.size()); Log.d("AUTH TOKEN","== "+values.getString(Facebook.TOKEN)); updateStatus(values.getString(Facebook.TOKEN)); } @Override public void onFacebookError(FacebookError e) { Log.d("FACEBOOK ERROR","FB ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause()); } @Override public void onError(DialogError e) { Log.e("ERROR","AUTH ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause()); } @Override public void onCancel() { Log.d("CANCELLED","AUTH CANCELLED"); } }); } //updating Status public void updateStatus(String accessToken){ try { Bundle bundle = new Bundle(); bundle.putString("message", "test update"); //'message' tells facebook that you're updating your status bundle.putString(Facebook.TOKEN,accessToken); //tells facebook that you're performing this action on the authenticated users wall, thus // it becomes an update. POST tells that the method being used is POST String response = facebook.request("me/feed",bundle,"POST"); Log.d("UPDATE RESPONSE",""+response); } catch (MalformedURLException e) { Log.e("MALFORMED URL",""+e.getMessage()); } catch (IOException e) { Log.e("IOEX",""+e.getMessage()); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d("onActivityResult","onActivityResult"); facebook.authorizeCallback(requestCode, resultCode, data); } A: The most likely reason is that you had already logged on for this app, or had previously logged on with the Facebook app, as a result of which Facebook had allocated you an access token - which is then valid until the app explicitly signs off, or the user disables app access (in the Facebook server-side user profile). So when you do the authorize, the underlying Facebook SDK simply retrieves the access token, and you do not need to login. You can disable the access token by going to Facebook for your user and doing Account settings (drop down at top right), then Apps (at left) and disabling your app's access. At which point, when you next run your app, the user will have to log in to Facebook and authorize your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to define action with simple form for? I am trying to define the action "savenew" in admin/photographers controller. I have tried this: <%= simple_form_for(:photographer_savenew, :action => 'savenew', :id => params[:id], :multipart => true ) do |f| %> But the action in the form is still: /admin/photographers When it should be: /admin/photographers/savenew A: Is there a reason you're not using REST for this? It would make your life a lot easier and requires much less code. If you're set on using this custom action, you will need to specify the url and probably the method: <%= simple_form_for @photographer, :url => savenew_photographers_path, :method => :post ... # etc
{ "language": "en", "url": "https://stackoverflow.com/questions/7507633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: javax.naming.NameNotFoundException: Name 'Manager1Factory' not found in context '' I get the error javax.naming.NameNotFoundException: Name 'Manager1Factory' not found in context '' when I try to deploy my hibernate app in JBoss 7. The line of code that is throwing this exception looks like entityManagerFactory = (EntityManagerFactory)ctx.lookup("java:/Manager1Factory"); EntityManager entityManager = entityManagerFactory.createEntityManager(); I have the JNDI name defined in persistence.xml like <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="primary2"> <!-- If you are running in a production environment, add a managed data source, the example data source is just for proofs of concept! --> <!-- We may want to make this a jta-data-source and let the container create entityManagers/look up EntityManagers via JNDI in our business objs --> <non-jta-data-source>java:jboss/datasources/MySqlDS2</non-jta-data-source> <class>com.mycompany.myapp.anywhere.common.businessobjects.CurrentTransaction</class> <class>com.mycompany.myapp.anywhere.common.businessobjects.ServerSettings</class> <class>com.mycompany.myapp.anywhere.common.persistence.HibernateUtil</class> <properties> <!-- Properties for Hibernate --> <!-- <sproperty name="hibernate.hbm2ddl.auto" value="create-drop" /> --> <!-- <property name="hibernate.show_sql" value="false" /> --> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.ejb.interceptor.session_scoped" value="com.mycompany.myapp.anywhere.common.persistence.BusinessObjectInterceptor"/> <property name="jboss.entity.manager.jndi.name" value="java:/Manager1"/> <property name="jboss.entity.manager.factory.jndi.name" value="java:/Manager1Factory"/> </properties> </persistence-unit> </persistence> I'm not sure why I'm receiving this error - when I check the JBoss console I see the name Manager1Factory shows up under JNDI bindings, so it seems like the EntityManagerFactory is being created but it is not being injected into my class? Any ideas why this is happening? Thanks! A: Try with <property name="jboss.entity.manager.factory.jndi.name" value="java:jboss/Manager1Factory"/> and java:jboss/Manager1Factory
{ "language": "en", "url": "https://stackoverflow.com/questions/7507634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Oracle - Problem creating trigger that updates another table I've read the Oracle docs on creating triggers and am doing things exactly how it shows, however this just isn't working. My goal is to update the TPM_PROJECT table with the minimum STARTDATE appearing in the TPM_TRAININGPLAN table. Thus, every time someone updates the STARTDATE column in TPM_TRAININGPLAN, I want to update teh TPM_PROJECT table. Here's what I'm trying: CREATE TRIGGER Trigger_UpdateTrainingDelivery AFTER DELETE OR INSERT OR UPDATE OF STARTDATE ON TPM_TRAININGPLAN FOR EACH ROW WHEN (new.TRAININGPLANTYPE='prescribed') BEGIN UPDATE TPM_PROJECT SET TRAININGDELIVERYSTART = (SELECT MIN(TP.STARTDATE) FROM TPM_TRAININGPLAN TP WHERE TP.PROJECTID = new.PROJECTID AND TP.TRAININGPLANTYPE='prescribed') WHERE PROJECTID = new.PROJECTID END; The trigger is created with no errors, but I do get a warning: Warnings: ---> W (1): Warning: execution completed with warning <--- Of course Oracle isn't nice enough to actually tell me what the warning is, I simply am shown that there is one. Next, if I update the training plan table with: UPDATE TPM_TRAININGPLAN set STARTDATE = to_date('03/12/2009','mm/dd/yyyy') where TRAININGPLANID=15916; I get the error message: >[Error] Script lines: 20-22 ------------------------ ORA-04098: trigger 'TPMDBO.TRIGGER_UPDATETRAININGDELIVERY' is invalid and failed re-validation Script line 20, statement line 1, column 7 Any ideas what I'm doing wrong? Thanks! A: A few issues in no particular order. First, in the body of a row-level trigger, you need to use :new and :old to reference the new and old records. The leading colon is necessary. So your WHERE clause would need to be WHERE PROJECTID = :new.PROJECTID Second, if you are running your CREATE TRIGGER in SQL*Plus, you can get a list of the errors and warnings using the SHOW ERRORS command, i.e. SQL> show errors You could also query the DBA_ERRORS table (or ALL_ERRORS or USER_ERRORS depending on your privilege level) but that's not something you normally need to resort to. Third, assuming the syntax errors get corrected, you're going to get a mutating table error if you use this logic. A row level trigger on table A (TPM_TRAININGPLAN in this case) cannot query table A because the table may be in an inconsistent state. You can work around that, as Tim shows in his article, by creating a package with a collection, initializing that collection in a before statement trigger, populating the data in the collection in a row-level trigger, and then processing the modified rows in an after statement trigger. That's a decent amount of complexity to add to the system, however, since you'll have to manage multiple different objects. Generally, you'd be better off implementing this logic as part of whatever API you use to manipulate the TPM_TRAININGPLAN table. If that is a stored procedure, it makes much more sense to put the logic to update TPM_PROJECT in that stored procedure rather than putting it in a trigger. It is notoriously painful to try to debug an application that has a lot of logic embedded in triggers because that makes it very difficult for developers to follow exactly what operations are being performed. Alternately, you could remove the TRAININGDELIVERYSTART column from TPM_PROJECT table and just compute the minimum start date at runtime. Fourth, if your trigger fires on inserts, updates, and deletes, you can't simply reference :new values. :new is valid for inserts and updates but it is going to be NULL if you're doing a delete. :old is valid for deletes and updates but is going to be NULL if you're doing an insert. That means that you probably need to have logic along the lines of (referencing Tim's package solution) BEGIN IF inserting THEN trigger_api.tab1_row_change(p_id => :new.projectid, p_action => 'INSERT'); ELSIF updating THEN trigger_api.tab1_row_change(p_id => :new.projectid, p_action => 'UPDATE'); ELSIF deleting THEN trigger_api.tab1_row_change(p_id => :old.projectid, p_action => 'DELETE'); END IF; END; A: As Justin Cave have suggested, you can calculate the minimum start date when you need it. It might help if you create an index on (projectid, startdate); If you really have a lot of projects and training plans, another solution could be to create a MATERIALIZED VIEW that has all the data that you need: CREATE MATERIALIZED VIEW my_view ... add refresh options here ... AS SELECT t.projectid, MIN(t.start_date) AS min_start_date FROM TPM_TRAININGPLAN t GROUP BY t.projectid; (sorry, don't have Oracle running, the above code is just for the reference)
{ "language": "en", "url": "https://stackoverflow.com/questions/7507636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Any standard mechanism for detecting if a JavaScript is executing as a WebWorker? A WebWorker executes with a scope completely separate from the 'window' context of traditional JavaScript. Is there a standard way for a script to determine if it is, itself, being executed as a WebWorker? The first 'hack' I can think of would be to detect if there is a 'window' property in the scope of the worker. If absent, this might mean we are executing as a WebWorker. Additional options would be to detect properties not present in a standard 'window' context. For Chrome 14, this list currently includes: FileReaderSync FileException WorkerLocation importScripts openDatabaseSync webkitRequestFileSystemSync webkitResolveLocalFileSystemSyncURL Detecting WorkerLocation seems like a viable candidate, but this still feels a bit hackish. Is there a better way? EDIT: Here is the JSFiddle I used to determine properties present in the executing WebWorker that are now in 'window'. A: Although post a bit old, adding a couple of generic alternatives What is used in Asynchronous.js library (a library for generic handling of asynchronous/parallel processes, author) is the following: // other declarations here ,isNode = ("undefined" !== typeof global) && ('[object global]' === Object.prototype.toString.call(global)) // http://nodejs.org/docs/latest/api/all.html#all_cluster ,isNodeProcess = isNode && !!process.env.NODE_UNIQUE_ID ,isWebWorker = !isNode && ('undefined' !== typeof WorkerGlobalScope) && ("function" === typeof importScripts) && (navigator instanceof WorkerNavigator) ,isBrowser = !isNode && !isWebWorker && ("undefined" !== typeof navigator) && ("undefined" !== typeof document) ,isBrowserWindow = isBrowser && !!window.opener ,isAMD = "function" === typeof( define ) && define.amd ,supportsMultiThread = isNode || "function" === typeof Worker ,isThread = isNodeProcess || isWebWorker // rest declarations here.. A: This worked for me if (self.document) { console.log('We are calculating Primes in Main Thread'); } else { console.log('We are calculating Primes in Worker Thread'); } A: The spec says: The DOM APIs (Node objects, Document objects, etc) are not available to workers in this version of this specification. This suggests checking for the absence of document is a good way to check you're in a worker. Alternatively you could try checking for the presence of WorkerGlobalScope? A: this works for me: if (self instanceof Window) { // not in worker } A: There's even more: WorkerNavigator etc. Unless there's a keyword to detect webworkers, you got to use a variable. (Nothing can stop a rogue script running before your script from setting or replacing variables. ) So, assuming you do not have any rogue scripts running before your script, any of these lines will work: this.DedicatedWorkerGlobalScope?this.__proto__ === this.DedicatedWorkerGlobalScope.prototype:false this.WorkerGlobalScope?this.__proto__.__proto__ === this.WorkerGlobalScope.prototype:false // works for shared workers too this.constructor === this.DedicatedWorkerGlobalScope //or SharedWorkerGlobalScope !(this.DedicatedWorkerGlobalScope === undefined) !(this.DedicatedWorkerGlobalScope === undefined) You can also use self § instead of this, but since this can't be set, its neater. I prefer: this.DedicatedWorkerGlobalScope !== undefined Of course, if you only have worker context and window context, you can do the inverse tests for window context. Eg this.Window === undefined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Translate website into different language How can I convert my website into different language, for ex I want to translate it into Russian. It is a commercial website, i cant use google translate. How can I do it please guide me. Thanks A: I Don't think for such a scenario you can use any automatic translator tools available as none of them can render a perfect translation. Your best bet is to get a translator and create a separate version of the website. I was wondering by the way, is that a c# question? :) A: Hire a translator. If you want a quality product, it really is that simple. A: There are many articles in codeproject that can help you achieve this, refer to this, this, this, this and several others. Try searching ASP.NET Globalization or ASP.NET Culture in google and stackoverflow, you'll find several articles and posts. Of course, nothing beats the old fashion way of translating ;) I agree with MSI and Christopher, hiring a translator is the best solution to your problem (that's what we did for our website). Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Place a custom template in VS 2010 New File dialog I'm trying to create a Visual Studio template that should appear in the New File dialog of Visual Studio 2010. No solution or project needs to be opened in order for my template to appear. So far I know how to place my template in the Add New Item dialog, but can't find info on how to place it in New File dialog. How can this be achieved? A: Solved this by making my WiX installer put my template (a .mysql file) in a subfolder of my vsix extension folder (which goes a couple of levels below C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions) and then modifyied my .pkgdef file to add an entry to the Windows Registry that will specify that same dir as the TemplatesDir for this template: [$RootKey$\Projects\{A2FE77E1-B743-11D0-AE1A-00A0C90FFFC3}\AddItemTemplates\TemplateDirs\{79a115c1-b133-4891-9e7b-242509dad272}\/1] @="#105" "Package"="{79a115c1-b133-4891-9e7b-242509dad272}" "TemplatesDir"="$PackageFolder$\\Templates" "SortPriority"=dword:00000020
{ "language": "en", "url": "https://stackoverflow.com/questions/7507641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AdMob AdView does not show up in TableLayout I have successfully gotten AdMob test ads to show up in a LinearLayout, but if I change to a TableLayout, they do not show up. No errors show in logcat. This is what works: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AdRequest request = new AdRequest(); request.setTesting(true); request.addTestDevice(AdRequest.TEST_EMULATOR); AdView adview = new AdView(this, AdSize.BANNER, [admob id deleted for posting on stackoverflow]); // all code before this point is the same in both examples LinearLayout layout = new LinearLayout(this); layout.addView(adview); // all code after this point is the same in both examples this.setContentView(layout); adview.loadAd(request); } I get a nice little banner ad at the top of the emulator screen that says "Success! Now you are ready to travel through the App Galaxy [Google logo]". So far so good. But it does not appear if I change it to a TableLayout, as follows: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AdRequest request = new AdRequest(); request.setTesting(true); request.addTestDevice(AdRequest.TEST_EMULATOR); AdView adview = new AdView(this, AdSize.BANNER, [admob id deleted for posting on stackoverflow]); // all code before this point is the same in both examples TableLayout layout = new TableLayout(this); TableRow row = new TableRow(this); row.addView(adview); layout.addView(row); // all code after this point is the same in both examples this.setContentView(layout); adview.loadAd(request); } I get no errors in LogCat. In both instances (LinearLayout or TableLayout) all I get in LogCat from Admob is two informational messages: Ads Received ad url: <"url": "[URL to the 'App Galaxy' test ad]"> Ads onRecievedAd() That's it. No complaints about not having enough space, which seems common from other posts. All I get is a black screen. If I add in another TableRow afterward, containing a TextView, that TextView shows up 50px below the top of the screen, as if the ad were there. Any ideas on stuff to try to get it to show up? I've already written an app based on a TableLayout and if possible I'd rather not have to redo it in LinearLayout(s) . . . A: I guess the parent of the AdView should have the property: xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
{ "language": "en", "url": "https://stackoverflow.com/questions/7507645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Will every line in a program(except variable declarations) ultimately use atleast one system call? I was thinking about system calls and code that we write! Lets say I have a program like below #include<stdio.h> int main() { int a=0,b=2,c; c=a+b; printf("The value of c is %d", c); return 0; } Lets take the case of c = a+b; if it was c++ compiler, then i beleive there would be a call to operator+() function. The compiler ofcourse might optimize it by replacing it with the actual code that performs addition rather than a function call within an assembly code. And printf will have to use system call in order to write it to different hardware buffers. So i beleive most of the api's provided by the language would use system call to accomplish the function.. I am not sure if my understanding is correct. Please do correct me if I am wrong. A: Adding to Ethereal's answer, even if you mean "call" (as in to a function) rather than "system call" the answer is still no. For example, c=a+b is likely to generate inline assembly similar to the following pseudo-assembly: mov reg1, [a] mov reg2, [b] add reg1, reg2 mov [c], reg1 No calls needed! A: No, not at all. I'm unsure if you have your definition of a system call correct. Stealing a definition from Wikipedia: In computing, a system call is how a program requests a service from an operating system's kernel. This means that the kinds of operations that result in system calls are I/O, timing, etc -- not math, assignments, (most) memory assignments, ... Even malloc() is usually implemented so you don't always need a system call. In general: only actions that affect or interact with the program's surrounding enviroment require a system call. Registers, program variables, etc. do not count as part of the surrounding environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WifiManager.startScan() - doesn't wake wifi if off, right? The following will not turn wifi on, if the user has it turned off, right?: WifiManager manager = (WifiManager)context.getSystemService( Context.WIFI_SERVICE); manager.startScan(); <-- ! I want to make sure the wifi isn't being turned on (if off) when the above is called, Thanks A: Yes, you are correct. The above code will not turn on wifi. You can however use setWifiEnabled(true) to enable wi-fi access. You will need to add android.permission.CHANGE_WIFI_STATE to your manifest file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL: Indexes on GROUP BY I have a reasonably big table (>10.000 rows) which is going to grow much bigger fast. On this table I run the following query: SELECT *, MAX(a) FROM table GROUP BY b, c, d Currently EXPLAIN tells me that there are no keys, no possible keys and it's "Using temporary; Using filesort". What would the best key be for such a table? A: What about composite key b+c+d+a? Btw, SELECT * makes no sense in case when you have GROUP BY A: A primary index on field b,c,d would be nice if applicable. In that case you just do a SELECT * FROM table1 group by <insert PRIMARY KEY here> If not put an index on b,c,d. And maybe on a, depends on the performance. If b,c,d are always used in unison, use a composite index on all three. Very important! Always declare a primary key. Without it performance on InnoDB will suck. To elaborate on @zerkms, you only need to put those columns in the group by clause that completely define the rows that you are selecting. If you select * that may be OK, but than the max(a) is not needed and neither is the group by. Also note that the max(a) may come from a different row than the rest of the fields. The only use case that does make sense is: select t1.*, count(*) as occurrence from t1 inner join t2 on (t1.id = t2.manytoone_id) group by t1.id Where t1.id is the PK. I think you need to rethink that query. Ask a new question explaining what you want with the real code. And make sure to ask how to make the outcomedeterminate, so that all values shown are functionally dependent on the group by clause. A: In the end what worked was a modification to the query as follows: SELECT b, c, d, e, f, MAX(a) FROM table GROUP BY b, c, d And creating an index on (b, c, d, e, f). Thanks a lot for your help: the tips here were very useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7507655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Deserialize an anonymous type into a dynamic I have an application that contains a business entity called a 'Task'. This entity has a fixed set of properties, but also the ability to behave as an expando. So, its schema looks like this: namespace RavenResearch { public class Task { public Guid TaskId { get; set; } public DateTime CreatedDate { get; set; } public dynamic DynamicProperties { get; set; } } } When this is stored in RavenDB, it look liks this { "TaskId": "9cac592f-98ec-4fda-a823-e5402736078e", "CreatedDate": "2011-09-22T10:25:35.2701544+12:00", "DynamicProperties": { "$type": "<>f__AnonymousType0`2[[System.Int32, mscorlib],[System.String, mscorlib]], RavenResearch", "MatterNumber": 0, "CustomerNumber": "37" } } Of course, when I attempt to query this datastore from ANOTHER program, it attempts to look for an anonymous type containing an int and string. That other program is the EXE which saved the document originally - I dont want to have to reference this. What would be the best way to pull out the dynamic properties? My goal is to be able to query a list of Task objects from Raven, and pass them to Xaml for rendering in the UI - which is why databinding to an Expando is so attractive to me, the properties need not be known at compile time. I create instances (to store in Raven) with statements like this new RavenResearch.Task() { TaskId = Guid.NewGuid(), CreatedDate = DateTime.Now, DynamicProperties = new { MatterNumber = 0, CustomerNumber = "37" } } @Jacob: I would lose all type information about the dynamic properties if I used a dictionary - however, I could do something like this: public class Task { public Guid TaskId { get; set; } public DateTime CreatedDate { get; set; } public Dictionary<string, SimpleValue> DynamicProperties { get; set; } } public abstract class SimpleValue { } public class SimpleValue<T> : SimpleValue { public T Value { get; set; } public SimpleValue(T value) { this.Value = value; } } A: Remember that at runtime, dynamic is simply object, we have no way of knowing what you actually meant there. You might be better of by using RavenJObject there instead. It would be a more natural way of working with dynamic data, and it will preserve type information A: Maybe avoiding using dynamic is best in this case. If you use a Dictionary<string, object> instead, creating a Task wouldn't be too horrible: new RavenResearch.Task { TaskId = Guid.NewGuid(), CreatedDate = DateTime.Now, DynamicProperties = new Dictionary<string, object> { { "MatterNumber", 0 }, { "CustomerNumber", "37" } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7507660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }