text
stringlengths
8
267k
meta
dict
Q: Counter to Close JFrame, bring up Confirm Dialog This post relates to my last one regarding a timer. I decided the easiest thing to do for immediate results was to just write a Counter thread that counts down from a certain time (in this case 5 seconds) and if the counter reaches 0, the JFrame closes and let's the user know that time has expired. I'm running into some trouble, however. I cannot seem to make the JFrame close when the counter reaches 0. I'm not sure if I'm missing something stupid or if I am misunderstanding the way threads work and the way JFrames work. Here is the code, let me know what you think. On a side note, I understand it would probably be most efficient to use a swing.Timer, but I just don't quite grasp the nature of them yet. I'm under self-imposed time constraints (I'm not a student or anything, I just like to stay motivated) and so I'm "jerry-rigging" this thing for now. Anyway, on to the code! import javax.swing.*; import javax.swing.event.*; import java.awt.*; public class RacerDoom extends JFrame { boolean timesUp=false; public RacerDoom() { //create JFrame super("Racer Doom Squared"); setSize(WIDTH,HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); if(timesUp==true) { dispose(); JOptionPane.showConfirmDialog(null, "Time's Up! Click Okay to try again!"); } Counter c1 = new Counter(); c1.start(); //Counter private class Counter extends Thread { public Counter() {} public void run() { for(int i=5;i>=0;i--) { if(i==0) { timesUp=true; } System.out.println(i); try{ Thread.sleep(1000); } catch(InterruptedException e){} } } } ... EDIT: I have the timer implemented and working. It does exactly what I need it to, but I can't get the timer.stop(); command to work. I get the error "The local variable timer may not have been initialized. Like I said, the timer works, it just never stops working until the program is terminated. Here is the constructor code for the JFrame, where the timer is located. int counter = 0; public RacerDoom() { //create JFrame super("Racer Doom Squared"); setSize(WIDTH,HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); final Timer timer=new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(counter>=10) { timer.stop(); //the error occurs here dispose(); JOptionPane.showConfirmDialog(null, "Time's Up!"); } else{ counter++; } System.out.println(counter); } }); //inner thread Move1 m1 = new Move1(); m1.start(); timer.start(); } A: Thats easy to do with the help of a swing timer.. See this code sample: final java.swing.Timer timer=new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(counter>5) { timer.stop(); <dispose the fram here> }else{ counter++; } } }); timer.start(); I put this code in the constructor of my JFrame which will run in the Event despatch thread. If you dont want hang up your GUI, make sure that you run this timer on another thread and when you are disposing the JFrame wrap the call with SwingUtilities.invokeLater() - This ensures that the call gets queued on the event despatch thread. I think your code is not working for the same reason, that you trying to something that does not get queued up in the event despatch thread. Here's an article that will get you going http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7558017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Make a select like Google Translate I'm trying to make a select like the snapshoot but I can't make it, and then receve a value with php, I need the select only appears a image, but on click appears image and little description on image's right side, and when click an option close menu and change image to selected, but allow to change it again (Google not allow to change, see an expample that I need on picture added or here: Google Translate (snapshoot make on Chrome). I need it to receive data by php script. I'm try it but I can't do it, please help me, thank in advanced (sorry for my bad english). A: That is not really a <select> it is an image and when you click on it, it shows a <div> that was previously hidden. When you click on one of the rating icons it changes the picture and the tooltip text and sends an AJAX request to store your rating. Instead of sending an AJAX request you could also change the value in a hidden field, that would somehow resemble a <select>. Some pseudo HTML/JS code <input type="hidden" name="myField" id="myField" /> <img src="unselected.png" onClick="document.getElementById('selectDiv').style.visibility = 'visible'" id="image" /> <div style="visibility: hidden" id="selectDiv"> <ul> <li><a href="#" onclick="document.getElementById('image').src = 'option1.png'; document.getElementById('myField').value = 'option1'">Option 1</li> <li><a href="#" onclick="document.getElementById('image').src = 'option2.png'; document.getElementById('myField').value = 'option2'">Option 2</li> <li><a href="#" onclick="document.getElementById('image').src = 'option2.png'; document.getElementById('myField').value = 'option3'">Option 3</li> </ul> </div> Just quick & dirty. You would need to move the div so that it displays underneath the image and some styling, etc... But that's the general idea behind this A: I know it's late, but for those of you, who just happen to still see this. For "click away" that was asked for please see "outside" event in jQuery. There is a really beautiful example here: http://benalman.com/code/projects/jquery-outside-events/examples/clickoutside/ Have fun As requested I'm putting the example here to be viewed: <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Testpage</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" language="javascript"> /*! * jQuery outside events - v1.1 - 3/16/2010 * http://benalman.com/projects/jquery-outside-events-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery outside events // // *Version: 1.1, Last updated: 3/16/2010* // // Project Home - http://benalman.com/projects/jquery-outside-events-plugin/ // GitHub - http://github.com/cowboy/jquery-outside-events/ // Source - http://github.com/cowboy/jquery-outside-events/raw/master/jquery.ba-outside-events.js // (Minified) - http://github.com/cowboy/jquery-outside-events/raw/master/jquery.ba-outside-events.min.js (0.9kb) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // clickoutside - http://benalman.com/code/projects/jquery-outside-events/examples/clickoutside/ // dblclickoutside - http://benalman.com/code/projects/jquery-outside-events/examples/dblclickoutside/ // mouseoveroutside - http://benalman.com/code/projects/jquery-outside-events/examples/mouseoveroutside/ // focusoutside - http://benalman.com/code/projects/jquery-outside-events/examples/focusoutside/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome, Opera 9.6-10.1. // Unit Tests - http://benalman.com/code/projects/jquery-outside-events/unit/ // // About: Release History // // 1.1 - (3/16/2010) Made "clickoutside" plugin more general, resulting in a // whole new plugin with more than a dozen default "outside" events and // a method that can be used to add new ones. // 1.0 - (2/27/2010) Initial release // // Topic: Default "outside" events // // Note that each "outside" event is powered by an "originating" event. Only // when the originating event is triggered on an element outside the element // to which that outside event is bound will the bound event be triggered. // // Because each outside event is powered by a separate originating event, // stopping propagation of that originating event will prevent its related // outside event from triggering. // // OUTSIDE EVENT - ORIGINATING EVENT // clickoutside - click // dblclickoutside - dblclick // focusoutside - focusin // bluroutside - focusout // mousemoveoutside - mousemove // mousedownoutside - mousedown // mouseupoutside - mouseup // mouseoveroutside - mouseover // mouseoutoutside - mouseout // keydownoutside - keydown // keypressoutside - keypress // keyupoutside - keyup // changeoutside - change // selectoutside - select // submitoutside - submit (function($,doc,outside){ '$:nomunge'; // Used by YUI compressor. $.map( // All these events will get an "outside" event counterpart by default. 'click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup'.split(' '), function( event_name ) { jq_addOutsideEvent( event_name ); } ); // The focus and blur events are really focusin and focusout when it comes // to delegation, so they are a special case. jq_addOutsideEvent( 'focusin', 'focus' + outside ); jq_addOutsideEvent( 'focusout', 'blur' + outside ); // Method: jQuery.addOutsideEvent // // Register a new "outside" event to be with this method. Adding an outside // event that already exists will probably blow things up, so check the // <Default "outside" events> list before trying to add a new one. // // Usage: // // > jQuery.addOutsideEvent( event_name [, outside_event_name ] ); // // Arguments: // // event_name - (String) The name of the originating event that the new // "outside" event will be powered by. This event can be a native or // custom event, as long as it bubbles up the DOM tree. // outside_event_name - (String) An optional name for the new "outside" // event. If omitted, the outside event will be named whatever the // value of `event_name` is plus the "outside" suffix. // // Returns: // // Nothing. $.addOutsideEvent = jq_addOutsideEvent; function jq_addOutsideEvent( event_name, outside_event_name ) { // The "outside" event name. outside_event_name = outside_event_name || event_name + outside; // A jQuery object containing all elements to which the "outside" event is // bound. var elems = $(), // The "originating" event, namespaced for easy unbinding. event_namespaced = event_name + '.' + outside_event_name + '-special-event'; // Event: outside events // // An "outside" event is triggered on an element when its corresponding // "originating" event is triggered on an element outside the element in // question. See the <Default "outside" events> list for more information. // // Usage: // // > jQuery('selector').bind( 'clickoutside', function(event) { // > var clicked_elem = $(event.target); // > ... // > }); // // > jQuery('selector').bind( 'dblclickoutside', function(event) { // > var double_clicked_elem = $(event.target); // > ... // > }); // // > jQuery('selector').bind( 'mouseoveroutside', function(event) { // > var moused_over_elem = $(event.target); // > ... // > }); // // > jQuery('selector').bind( 'focusoutside', function(event) { // > var focused_elem = $(event.target); // > ... // > }); // // You get the idea, right? $.event.special[ outside_event_name ] = { // Called only when the first "outside" event callback is bound per // element. setup: function(){ // Add this element to the list of elements to which this "outside" // event is bound. elems = elems.add( this ); // If this is the first element getting the event bound, bind a handler // to document to catch all corresponding "originating" events. if ( elems.length === 1 ) { $(doc).bind( event_namespaced, handle_event ); } }, // Called only when the last "outside" event callback is unbound per // element. teardown: function(){ // Remove this element from the list of elements to which this // "outside" event is bound. elems = elems.not( this ); // If this is the last element removed, remove the "originating" event // handler on document that powers this "outside" event. if ( elems.length === 0 ) { $(doc).unbind( event_namespaced ); } }, // Called every time a "outside" event callback is bound to an element. add: function( handleObj ) { var old_handler = handleObj.handler; // This function is executed every time the event is triggered. This is // used to override the default event.target reference with one that is // more useful. handleObj.handler = function( event, elem ) { // Set the event object's .target property to the element that the // user interacted with, not the element that the "outside" event was // was triggered on. event.target = elem; // Execute the actual bound handler. old_handler.apply( this, arguments ); }; } }; // When the "originating" event is triggered.. function handle_event( event ) { // Iterate over all elements to which this "outside" event is bound. $(elems).each(function(){ var elem = $(this); // If this element isn't the element on which the event was triggered, // and this element doesn't contain said element, then said element is // considered to be outside, and the "outside" event will be triggered! if ( this !== event.target && !elem.has(event.target).length ) { // Use triggerHandler instead of trigger so that the "outside" event // doesn't bubble. Pass in the "originating" event's .target so that // the "outside" event.target can be overridden with something more // meaningful. elem.triggerHandler( outside_event_name, [ event.target ] ); } }); }; }; })(jQuery,document,"outside"); $(function(){ // Elements on which to bind the event. var elems = $('#test, #test div, #test .bind-me'); // Clear any previous highlights and text. $(document) .bind( 'click', function(event){ elems .removeClass( 'event-outside' ) .children( '.event-target' ) .text( ' ' ); }) .trigger( 'click' ); // Bind the 'clickoutside' event to each test element. elems.bind( 'clickoutside', function(event){ var elem = $(this), target = $(event.target), // Update the text to reference the event.target element. text = 'Clicked: ' + target[0].tagName.toLowerCase() + ( target.attr('id') ? '#' + target.attr('id') : target.attr('class') ? '.' + target.attr('class').replace( / /g, '.' ) : ' ' ); // Highlight this element and set its text. elem .addClass( 'event-outside' ) .children( '.event-target' ) .text( text ); }); }); </script> <style type="text/css"> #test, #test div { padding: 1em; margin-top: 1em; } #test .bind-me { padding: 0 0.5em; margin-left: 0.5em; white-space: nowrap; line-height: 1.6em; } #test, #test div, #test .bind-me { color: #ccc; border: 2px solid #ccc; } .event-outside { color: #0a0 !important; border-color: #0a0 !important; background-color: #cfc !important; } #test .bind-me, .event-target { display: inline-block; width: 180px; overflow: hidden; white-space: pre; vertical-align: middle; } </style> </head> <body> <div id="test" class="event-outside"> test <span class="event-target">Clicked: body </span> <div id="a" class="event-outside"> a <span class="event-target">Clicked: body </span> <div id="b" class="event-outside"> b <span class="event-target">Clicked: body </span> </div> </div> <div id="c" class="event-outside"> c <span class="event-target">Clicked: body </span> <span id="d" class="bind-me event-outside">d <span class="event-target">Clicked: body </span> </span> <span id="e" class="bind-me event-outside">e <span class="event-target">Clicked: body </span> </span> </div> <div id="f" class="event-outside"> f <span class="event-target">Clicked: body </span> <div id="g" class="event-outside"> g <span class="event-target">Clicked: body </span> <span id="h" class="bind-me event-outside">h <span class="event-target">Clicked: body </span> </span> <span id="i" class="bind-me event-outside">i <span class="event-target">Clicked: body </span> </span> </div> </div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7558018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Groovy XmlSlurper vs XmlParser I searched for a while on this topic and found some results too, which I am mentioning at the end of post. Can someone help me precisely answer these three questions for the cases listed below them? * *For which use-cases using XmlSluper makes more sense than XmlParser and vice-versa (from point of view ease of use of API/Syntax)? *Which one is more memory efficient? (looks like Slurper) *which one processes the xml faster? Case a. when I have to read almost all nodes in the xml? Case b. when I have to read just few nodes (like using gpath expression)? Case c. when I have to update/transform the xml? provided the xml document is not trivial one (with level of depths and size of the xml). Resources : http://www.tutkiun.com/2009/10/xmlparser-and-xmlslurper.html states : Difference between XMLParser and XMLSlurper: There are similarities between XMLParser and XMLSlurper when used for simple reading but when we use them for advanced reading and when processing XML documents in other formats there are differences between two. XMLParser stores intermediate results after parsing documents. But on the other hand, XMLSlurper does not stores internal results after processing XML documents. The real, fundamental differences become apparent when processing the parsed information. That is when processing with direct in-place data manipulation and processing in a streaming scenario. http://groovy.dzone.com/news/john-wilson-groovy-and-xml The groovy doc (XmlParser, XmlSlurper) and the groovy's site explains them well (here and here)but does not do a great job in explaining the aforementioned question. A: I will give you crisp answers: * *XML Parser is faster than XML Slurper. *XML Slurper consumes less memory than XML Parser. *XML Parser can parse and update the XML simultaneously. *For XML Slurper you need to MarkupBuild the XMLs after each update you make. *When you want to use path expressions XML Slurper would be better than parser. *For reading almost all nodes XML Parser would be fine. Hope it helps A: The big difference between XmlSlurper and XmlParser is that the Parser will create something similar to a DOM, while Slurper tries to create structures only if really needed and thus uses paths, that are lazily evaluated. For the user both can look extremely equal. The difference is more that the parser structure is evaluated only once, the slurper paths may be evaluated on demand. On demand can be read as "more memory efficient but slower" here. Ultimately it depends how many paths/requests you do. If you for example want only to know the value of an attribute in a certain part of the XML and then be done with it, XmlParser would still process all and execute your query on the quasi DOM. In that a lot of objects will be created, memory and CPU spend. XmlSlurper will not create the objects, thus save memory and CPU. If you need all parts of the document anyway, the slurper loses the advantage, since it will create at least as many objects as the parser would. Both can do transforms on the document, but the slurper assumes it being a constant and thus you would have to first write the changes out and create a new slurper to read the new xml in. The parser supports seeing the changes right away. So the answer to question (1), the use case, would be, that you use the parser if you have to process the whole XML, the slurper if only parts of it. API and syntax don't really play much a role in that. The Groovy people try to make those two very similar in user experience. Also you would prefer the parser over the slurper if you want to make incremental changes to the XML. That intro above also explains then what is more memory efficient, question (2). The slurper is, unless you read in all anyway, then the parser may, but I don't have actual numbers about how big the difference is then. Also question (3) can be answered by the intro. If you have multiple lazy evaluated paths, you have to eval again, then this can be slower than if you just navigate an existing graph like in the parser. So the parser can be faster, depending on your usage. So I would say (3a) reading almost all nodes itself makes not much of a difference, since then the requests are the more determining factor. But in case (3b) I would say that the slurper is faster if you just have to read a few nodes, since it will not have to create a complete structure in memory, which in itself already costs time and memory. As for (3c)...these days both can update/transform the XML. Which is faster is actually more linked to how many parts of the xml you have to change. If many parts I would say the parser, if not, then maybe the slurper. But if you want to for example change an attribute value from "Fred" to "John" with the slurper, just to later query for this "John" using the same slurper, it won't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: MVC3 and WCF Cross site .NET newbie here. I have an MVC3 web application EF 4.1 Code First and Data Entity Framework, works great. I am trying to create another WCF Service/Application that will run on a different IIS server than the MVC3 application. The objective is "Cross site communication": * *MVC3 app saves data to local host database. "works" *MVC3 app Sends data to another IIS that hosts the WCF. *WCF service saves data to database that is identical to the one on the MVC3. *WCF sends confirmation back to MVC if data has been saved or not. *WCF does not have to be complex, simple will do, WCF REST / WCF Web etc. I went through dozens of articles and video tutorials but its all about exposing the service within same project/site. i am trying to find an actual CODE SAMPLES to at least send the data from one server to another. your help is greatly appreciated. A: Once you have exposed your WCF service on some server all you have to do in your ASP.NET MVC 3 application is to add a Service Reference ... and point to the WSDL of the remote WCF service which will generate a strongly typed proxy class and add a bunch of config sections in your web.conig. Then simply call the service: using (var client = new MyServiceClient()) { var result = client.SomeMethod(); } Here's an article on MSDN which illustrates how WCF services could be hosted and consumed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP reindex array? I have array that i had to unset some indexes so now it looks like $myarray [0] a->1 [1] a-7 b->3 [3] a-8 b->6 [4] a-3 b->2 as you can see [2] is missing all i need to do is reset indexes so they show [0]-[3]. A: Use array_values. $myarray = array_values($myarray); A: array_values does the job : $myArray = array_values($myArray); Also some other php function do not preserve the keys, i.e. reset the index. A: $myarray = array_values($myarray); array_values A: This might not be the simplest answer as compared to using array_values(). Try this $array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4'); $arrays =$array; print_r($array); $array=array(); $i=0; foreach($arrays as $k => $item) { $array[$i]=$item; unset($arrays[$k]); $i++; } print_r($array); Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7558022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "169" }
Q: Using MSBuild to buld a solution (.sln) with many projects in how can I make each project build into its own folder? I am trying to create a simple build process for a quite complex (many projects) vs2010 solution. I wish for a folder structure such as this -Build -Proj1 -proj1.exe -proj1.dll -Proj2 -proj2.exe -proj2.dll ...... -Projn -projn.exe -projn.dll What I am getting from my attempts below is -Build -proj1.exe -proj1.dll -proj2.exe -proj2.dll -projn.exe -projn.dll I currently have this as a .proj file. (see below) This builds things fine, however it puts everything in the "build" folder that I specify. I want each project to be in its own seperate folder within that 'build' folder. How can I achive this? <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <BuildOutputDir>C:\Projects\BuildScripts\Build</BuildOutputDir> <SolutionToCompile>PathToSolution.sln</SolutionToCompile> </PropertyGroup> <Target Name="Clean"> <RemoveDir Directories="$(BuildOutputDir)" /> </Target> <Target Name="Compile"> <MakeDir Directories="$(BuildOutputDir)" /> <MSBuild Projects="$(SolutionToCompile)" properties = "OutputPath=$(BuildOutputDir)" Targets="Rebuild" /> </Target> <Target Name="Build" DependsOnTargets="Clean;Compile"> <Message Text="Clean, Compile"/> </Target> </Project> I call the .proj with a simple bat "%windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" /nologo externalBuild.proj /m:2 %* pause I have also tried a more complex version (copy and paste!) that looks more like it should work, but still puts things in a single folder. <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="BuildAll" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <ProjectsToBuild Include="path to solution folder\**\*proj" Exclude="$(MSBuildProjectFile)"/> </ItemGroup> <PropertyGroup> <Configuration>CI</Configuration> </PropertyGroup> <Target Name="CoreBuild"> <MSBuild Projects ="@(ProjectsToBuild)" ContinueOnError ="false" Properties="Configuration=$(Configuration)"> <Output ItemName="OutputFiles" TaskParameter="TargetOutputs"/> </MSBuild> </Target> <PropertyGroup> <DestFolder>Build\</DestFolder> </PropertyGroup> <Target Name="CopyFiles"> <Copy SourceFiles="@(OutputFiles)" DestinationFiles="@(OutputFiles->'$(DestFolder)%(RecursiveDir)%(Filename)%(Extension)')" /> </Target> <Target Name="CleanAll"> <!-- Delete any files this process may have created from a previous execution --> <CreateItem Include="$(DestFolder)\**\*exe;$(DestFolder)\**\*dll"> <Output ItemName="GeneratedFiles" TaskParameter="Include"/> </CreateItem> <Delete Files="@(GeneratedFiles)"/> <MSBuild Projects="@(ProjectsToBuild)" Targets="Clean" Properties="Configuration=$(Configuration);"/> </Target> <PropertyGroup> <BuildAllDependsOn>CleanAll;CoreBuild;CopyFiles</BuildAllDependsOn> </PropertyGroup> <Target Name="BuildAll" DependsOnTargets="$(BuildAllDependsOn)"/> </Project> A: Using devenv.com to build from the command line will do what you want. It will use the output directories specified in the project files. This is what we're using, because at the moment we don't need more control over the build mechanism.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to tell hadoop how much memory to allocate to a single mapper job? I've created a Elastic MapReduce job, and I'm trying to optimize its performance. At this moment I'm trying to increase the number of mappers per instance. I am doing this via mapred.tasktracker.map.tasks.maximum=X elastic-mapreduce --create --alive --num-instance 3 \ --bootstrap-action s3://elasticmapreduce/bootstrap-actions/configure-hadoop \ --args -s,mapred.tasktracker.map.tasks.maximum=5 Each time I try to set X over 2 per small instance, the initialization fails, from which I conclude, that hadoop allocated 800m of memory per map task. To me that seems too excessive. I'd like it to be 400m tops. How do I tell hadoop to use less memory for each map task? A: Check the mapred.child.java.opts property. It's defaulted to -Xmx200m, which means 200MB of heap for each of the map/reduce task. Looks like EC2 small has 1.7 GB memory. Here is the memory with the default settings by the Hadoop processes on the TaskTracker node. Thanks to "Hadoop : The Definitive Guide" Datanode 1,000 MB Tasktracker 1,000 MB Tasktracker child map task 400 MB (2 * 200 MB) Tasktracker child map task 400 MB (2 * 200 MB) Total's to 2,800MB. On top of this, there is the OS memory. Either pickup a nicer configuration or change the default settings. FYI, here is the recommendation on the H/W configuration for the different nodes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Button for continous scrolling of a div with Javascript code Found this code on the net. Want to modify it to make it scroll a div continously when the mouse button is down and stop scrolling when the mouse button is up. I tried this: * *Change from the click event to the mousedown event. That did not do it. *Added a call to the same function within the function. That did not do it either. What should I modify in this function to have the continous scrolling on mouse down? (function ($) { var vscrollid = 0; $.fn.vScroll = function (options) { var options = $.extend({}, { speed: 500, height: 300, upID: "#up-arrow", downID: "#bottom-arrow", cycle: true }, options); return this.each(function () { vscrollid++; obj = $(this); var newid = vscrollid; obj.css("overflow", "hidden"); obj.css("position", "relative"); obj.css("height", options.height + "px"); obj.children().each( function (intIndex) { $(this).addClass("vscroll-" + vscrollid + "-" + intIndex); }); var itemCount = 0; $(options.downID).click(function () { var nextCount = itemCount + 1; if ($('.vscroll-' + newid + '-' + nextCount).length) { var divH = $('.vscroll-' + newid + '-' + itemCount).outerHeight(); itemCount++; $("#vscroller-" + newid).animate({ top: "-=" + divH + "px" }, options.speed); } else { if (options.cycle) { itemCount = 0; $("#vscroller-" + newid).animate({ top: "0" + "px" }, options.speed); } } }); $(options.upID).click(function () { var prevCount = itemCount - 1; if ($('.vscroll-' + newid + '-' + prevCount).length) { itemCount--; var divH = $('.vscroll-' + newid + '-' + itemCount).outerHeight(); $("#vscroller-" + newid).animate({ top: "+=" + divH + "px" }, options.speed); } }); obj.children().wrapAll("<div style='position: relative; top: 0' id='vscroller-" + vscrollid + "'></div>"); }); }; })(jQuery); /* * jQuery vScroll * Copyright (c) 2011 Simon Hibbard * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /* * Version: V1.2.0 * Release: 10-02-2011 * Based on jQuery 1.4.2 */ A: Was able to get the continuous scrolling with simpler code. <script type="text/javascript"> $(document).ready(function($) { $(".scrolling_prev", $("#'.$node['ID'].'")).mousedown(function() { startScrolling($(".link_drop_box", $("#'.$node['ID'].'")), "-=50px"); }).mouseup(function() { $(".link_drop_box", $("#'.$node['ID'].'")).stop() }); $(".scrolling_next", $("#'.$node['ID'].'")).mousedown(function() { startScrolling($(".link_drop_box", $("#'.$node['ID'].'")), "+=50px"); }).mouseup(function() { $(".link_drop_box", $("#'.$node['ID'].'")).stop(); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7558032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework Data Reader Production Error Only on production, I'm getting this error: "Execution of the command requires an open and available connection. The connection's current state is closed." What's weird is where its saying its happening. It's happening in a place that's never happened in all of our development, testing, or UAT sessions.... here is the underlying process. We use the MVP pattern. This isn't as important, but here's essentially the flow: * *Presenter instantiates an associated repository and call a method to query the appropriate data, and pass it to the model. The query is still live against the database at this point (not iterated through or had ToList called). *View binds this data to a drop down control. Here, when it iterates through to create the list of items, the error occurs. We are binding around 8 drop downs at this point. Again, I've not experienced this at any other point - this isn't consistent enough either. Any ideas? Thanks. A: I suspect your connection pool is being maxed out due to the context not being disposed properly (as @Adam has stated). Increase your pool settings (or decrease timeout) to test but you need to dispose of the context properly (credit goes to @Adam). You can test this using performance counters http://msdn.microsoft.com/en-US/library/ms254503(v=VS.80).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7558033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there some way to create a class that have an object of a class that have an object of this class in C++? In C++, is there some way to create a class that have, as attribute, an object of a class that have, as attribute, an object of the first class? e.g.: class A { B attribute; public: A(){} }; class B { A attribute; public: B(){} }; The code above does not compile. Is there some way to do something alike? Thanks! A: First, you need to forward declare your class B. If not, the compiler wouldn't know what the B is. Also, change the attributes to be pointers, or else you will still have a compiler error, even though you forward declared B, it still doesn't know the implementation yet! The following code may help, good luck... class B; class A { B *attribute; public: A(){} }; class B { A *attribute; public: B(){} }; A: These definitions, even if you could use forward declaration to make them work (which you can't), are inherently recursive. An A contains a B, which contains an A, which contains a B, and on and on. It is nonsensical. A: You need to rethink your structure. You're trying to define a structure that contains another structure, which contains the first structure which contains the second structure, etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7558036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSP Reference Books There seems to be a dearth of fresh JSP reference books to purchase. Most are from between 1999 and 2003, with almost nothing after that. There are still lots of Java books, and while most of the syntax is easily swapped, I'd rather have a reference book specifically for the dynamic browser aspect. Does anyone have recommendations? A: Head First Servlets and JSP covers the topic very comprehensively and gently. The 2nd edition was published in 2008 and AFAIK there have been little or no changes to the JSP spec since then. Although this book covers both Servlets and JSPs, in most environments where JSPs are being used, Servlets (or something similar like Struts actions) are also used. Because JSPs are Servlets at runtime, it could be argued that understanding Servlets is a pre-requisite for understanding JSPs. A: * *Head First Servlets and JSP by kathy Sierra & Bert Bates *Java for the Web with Servlets, JSP, and EJB: A Developer's Guide to J2EE Solutions by Budi Kurniawan, this is a very old book most probably not available in market but I found it very interesting. Though these are not particularly for JSP but I am sure you will get everything you're looking for. The first one is undisputedly the best book available.I have the pdf of second one,in case you want to have a look. Enjoy :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7558039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PATH variable in Python How can I change the Environmental PATH variable through code in python ? I am trying to return the path of an executable file. The code does not work because the shell is pointing to another directory. Any help is appreciated. A: You can use os.environ. Example: path = os.environ["PATH"] # a ':'-separated string path += ":/var/custom/bin" os.environ["PATH"] = path Or in a single line: os.environ["PATH"] = ':'.join(os.environ["PATH"].split(":") + ["/var/bin"]) A: You aren't looking for the PATH variable. You want to either set the current working directory with os.chdir or pass the absolute path with os.path.abspath. A: os.environ["PATH"] += ":/usr/local/bin" See http://docs.python.org/library/os.html#os.environ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Grails Spring Security Authentication - GSP error not shown I am new to Grails Spring Security and am struggling to show the login error message. The plugin is installed and correctly configured against my DB. When a wrong username/password is provided, LoginController takes over and actions auth > authfail are invoked. That's the correct default behaviour. THOUGH, when I configure Config.groovy, LoginController takes over calling only auth (without invoking authfail), therefore the error message is not added to flash so to be shown in auth.gsp. Bellow is my Config.groovy configuration related to Spring Security: grails.plugins.springsecurity.successHandler.defaultTargetUrl = '/organisation/summaryLandingPage' grails.plugins.springsecurity.logout.afterLogoutUrl = '/login/authfail' grails.plugins.springsecurity.securityConfigType = "InterceptUrlMap" grails.plugins.springsecurity.interceptUrlMap = [ '/login/auth': ['IS_AUTHENTICATED_ANONYMOUSLY'], '/**': ['IS_AUTHENTICATED_FULLY'] ] grails.plugins.springsecurity.userLookup.userDomainClassName = 'User' grails.plugins.springsecurity.userLookup.authorityJoinClassName = UserRole' grails.plugins.springsecurity.authority.className = 'lookups.Role' grails.plugins.springsecurity.authority.nameField = 'value' grails.plugins.springsecurity.password.algorithm = 'MD5' grails.plugins.springsecurity.useSessionFixationPrevention = true Any help would be much appreciated! A: grails.plugins.springsecurity.interceptUrlMap = [ '/login/auth': ['IS_AUTHENTICATED_ANONYMOUSLY'], '/**': ['IS_AUTHENTICATED_FULLY'] ] It looks like that line is allowing only /login/auth (i.e. LoginController.auth) to be served up to anonymous users. Try adding '/login/authFail': ['IS_AUTHENTICATED_ANONYMOUSLY'] or '/login/**': ['IS_AUTHENTICATED_ANONYMOUSLY'] to your interceptUrlMap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem loading CSS styles with a PHP static files loader I have exactly the same problem treated in this topic. That's: I have some static files in some folders and I want only some users to see that content. That users are coming from a previous login. To get that, I'm trying to implement the first solution given in this topic, that's: Create the following .htaccess file under "static-files": Options +FollowSymLinks RewriteEngine on RewriteRule ^(.*)$ ../authorize.php?file=$1 [NC] And then in authorize.php... if (isLoggedInUser()) readfile('static-files/'.$_REQUEST['file']); else echo 'denied'; This authorize.php file is grossly over simplified, but you get the idea.kquote So, redirect any request to the authorize.php file, who check if the user is logged in and, if so, serve the content. That's working perfectly with html, js and images... but I don't know why css styles are not showed. It's strange, because I can access that css files directly with my browser, but when they are called from the html it's not working. Of course, if I try to work without the authorize.php styles are showed as usual. What am I missing out? Thank you, A: You are probably not sending the right content-type header. That makes style sheets fail in Firefox. Do a header("Content-type: text/css"); whenever a CSS style sheet has been requested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing a variable in a union which is inside a class Sorry for naive question in C++. For below code, there is a class, inside which there is a union declaration having two variables. How to access the variables in the union using the class object in code below: class my { public: //class member functions, and oeprator overloaded functions public: union uif { unsigned int i; float f; }; private: //some class specific variables. }; if there is an object of type my defined like my v1; in a function later Using v1 how do i access float f; inside union above in code? also I want to watch the value of this float f in the watch window of a debugger(VS-2010), how to do that? I tried v1.uif.f , this gave error in the watch window as : Error oeprator needs class struct or union. v1. A: You are only defining the union within the scope of the class, not actually creating a member variable of its type. So, change your code to: class my { public: //class member functions, and oeprator (sic) overloaded functions public: union uif { unsigned int i; float f; } value; private: //some class specific variables. }; Now you can set the member variables in your union member, as follows: my m; m.value.i=57; // ... m.value.f=123.45f; A: You never actually defined any member of that union. You only ever defined the union itself. There is no spoon float. A: You've only defined the type of the uniion, you've not yet declared an object of this union type. Try this: class my { public: union uif { unsigned int i; float f; }; uif obj; //declare an object of type uif }; my v; v.obj.f = 10.0; //access the union member A: One option I don't see already here is that of an Anonymous Union, which is where you have no type or instantiation. Like so: class my { public: //class member functions, and oeprator (sic) overloaded functions function(int new_i) { i = new_i;} function(float new_f) { f = new_f;} public: union /* uif */ { unsigned int i; float f; }; private: //some class specific variables. }; my m; m.i=57; m.f=123.45f; Remember that with unions, it is only defined to read from the last member variable written to. A: You have defined your union in your class, but you haven't created an instance of it! Try: union uif { unsigned int i; float f; } myUif; And then use v1.myUif.f (or i).
{ "language": "en", "url": "https://stackoverflow.com/questions/7558058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Add multiple drop down lists to ASP.NET form on-the-fly I have an ASP.NET form with one drop-down list. I want to have a "+" sign next to the list to allow the user to add another drop-down to the form, and so on, up to a maximum of 15 drop-downs. Ideally, this will be handled client-side, but I would also be open to a solution that involved a form post back. What is the best approach?
{ "language": "en", "url": "https://stackoverflow.com/questions/7558065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: customize sfApplyApply or create separate module? I'm not sure if I am approaching this the right way; looking for some input from the community. I'm using the following pluggins: * *sfDoctrineGuardPluggin //for user management *sfForkedDoctrineGuardApplyPluggin //for registration of new users What I'm trying to achieve: I'd like to allow my registered users to register child-users. To do this, the child-user's that they create must inherit a couple of the parents attributes (their corporate_id, employer_type, etc... in child-user's profile at bind time). Setting these attributes has been challenging, as from what I can surmise from my reasearch, the sfApplyApply form does not have setters that can be overridden. As an alternative, I attempted to create a whole new "user" module which uses the sf_guard_user table schema. This worked somewhat, but it lost the features found in the registration pluggin (email confirmation) and it was not salting the password or something because I was never able to login a user created this way - which always produced an error saying the username or password were incorrect. So the question is, what's the best approach to achieve my desired result? A: In your action: public function executeNew(sfWebRequest $request) { $this->form = new sfApplyChildApplyForm(); } In the plugin forms, create a form called sfApplyChildApplyForm modeled after sfApplyApplyForm. That's it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set Rounded Border for Blackberry BitmapField I trying to set rounded border for Blackberry Bitmap field.But it is not working for me. I overriding paint method of Bitmap field. g.drawRoundRect(0,0,HomeScreenIcons.barcode.getWidth(),HomeScreenIcons.barcode.getHeight(), 10, 10); How can i set Border for Bitmap field in Blackberry. A: You can give a try this way: BitmapField bitf = new BitmapField(); bitf.setBorder(BorderFactory.createRoundedBorder(new XYEdges(6,6,6,6))); Hope this helps...
{ "language": "en", "url": "https://stackoverflow.com/questions/7558073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby: convert day as decimal to day as name Is it possible to convert quickly a strftime("%u") value to a strftime("%A") or do i need to build an equivalence hash like {"Monday" => 1, ......... "Sunday" => 6} I have an Array with some day as decimal values class_index=[2,6,7] and I would like to loop through this array to build and array of days name like this [nil, "Tuesday", nil, nil, nil, "Saturday", "Sunday"] so I could do class_list=[] class_index.each do |x| class_list[x-1] = convert x value to day name end Is that even possible? A: How about: require "date" DateTime.parse("Wednesday").wday # => 3 Oh, I now see you've expanded your question. How about: [2,6,7].inject(Array.new(7)) { |memo,obj| memo[obj-1] = Date::DAYNAMES[obj%7]; memo } Let me explain that one: input = [2,6,7] empty_array = Array.new(7) # => [nil, nil, nil, nil, nil, nil, nil] input.inject(empty_array) do |memo, obj| # loop through the input, and # use the empty array as a 'memo' day_name = Date::DAYNAMES[obj%7] # get the day's name, modulo 7 (Sunday = 0) memo[obj-1] = day_name # save the day name in the empty array memo # return the memo for the next iteration end The beauty of Ruby. A: To go from decimal to weekday: require 'date' Date::DAYNAMES[1] # => "Monday" So, in your example, you could simply do: class_list=[] class_index.each do |x| class_list[x-1] = Date::DAYNAMES[x-1] end A: Here’s one way that comes to mind: require "date" def weekday_index_to_name(index) date = Date.parse("2011-09-26") # Canonical Monday. (index - 1).times { date = date.succ } date.strftime("%A") end A: class_index=[2,6,7] class_index.map{|day_num| Date::DAYNAMES[day_num%7]} #=> ["Tuesday", "Saturday", "Sunday"] note that day names are from 0 to 6, so you can either work from 0 to 6 or have it modulo 7
{ "language": "en", "url": "https://stackoverflow.com/questions/7558074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Office Interop Issue on Windows Server I am trying to access the Word Office Interop on a server from my aplication using the following line: Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); This however causes an exception to be throw: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)). Does anyone know what I can do to allow my program to access this? A: You need to grant permission to 'Launch and Activate' for the user running IIS. Start-->Run-->dcomcnfg Under Component Services\Computers Right-Click 'My Computer' Permissions are under COM Security
{ "language": "en", "url": "https://stackoverflow.com/questions/7558076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Emacs: python-shell doesn't respond to RET When I start python-shell (or even just start python from M-x shell), Emacs gives the expected prompt: bash-3.2$ python Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> But when I type something at the prompt and press RET, the cursor moves down a line but the command is not executed. The only commands I can get the subprocess to respond to are interrupts like C-C C-c. After an interrupt, another prompt (>>>) appears and I can use M-n and M-p to navigate the lines I "entered" earlier. >>> test hmmm, definitely pressed enter there C-c C-c KeyboardInterrupt >>> Curiously, this occurs both in Aquaemacs and in emacs -nw. I've tried moving my .emacs and .emacs.d files and the behavior is the same. Any ideas on what might be causing this? A: After you do "M-x shell" and then "python RET", do "C-h k RET" and then what is displayed? the Help buffer should say that "comint-send-input" is the command that is executed for RET. If it isn't showing "comint-send-input" as the command executed by "RET" then there is probably something in one of your init files (the .emacs file isn't the only init file) that is overriding this binding. So, then try running emacs with "emacs -nw -q -no-site-file" and repeat the above. If it wasn't displaying "comint-send-input" previously and is displaying "comint-send-input" now, then it's definitely something in one of your init files. Look at both your local (http://www.gnu.org/software/emacs/emacs-lisp-intro/elisp/Init-File.html#Init-File) and site-wide (http://www.gnu.org/software/emacs/emacs-lisp-intro/html_node/Site_002dwide-Init.html#Site_002dwide-Init) init files to try to find the culprit. If it's not obvious after examining the files, your best bet is to rename any init files you find and gradually re-introduce the code until you find what is causing the "breakage".
{ "language": "en", "url": "https://stackoverflow.com/questions/7558095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iPhone: Customizing group table cell border style I have customized group table cell background where I am using following code to draw table cell border. The border appears correct but it always appear solid line. Is there anyway to make it etched/dotted line? What do I need to modify in following code? -(void)drawRect:(CGRect)rect { CGContextRef c = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(c, [borderColor CGColor]); CGContextSetLineWidth(c, 2); ..... Thanks. A: See CGContextSetLineDash here. This allows you to set a variety of dash patterns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you search for a string in a webpage with javascript? I am making a javascript greasemonkey script that redirects you when it finds a certain string in a webpage. Here is my code: // ==UserScript==<br> // @name No 009 Sound System!<br> // @version 1.0<br> // @namespace http://www.cakeman.biz/<br> // @description Warn user when about to view a youtube video with 009 Sound System audio<br> // @include http://*/*<br> // @copyright 2011+, Zack Marotta // ==/UserScript== var result, search_term = 'somerandomsearchterm'; var str = document.URL; var url_check = str.search(search_term); if (url_check !== -1) { var result = search_term; alert(str); window.location = "http://www.web.site"; } Nothing happens when the script runs. What did I do wrong? A: For some specific functions, you have to use unsafeWindow instead of window in a Greasemonkey UserScript. If you want to get your script work at GreaseMonkey and other locations, use this: var win = typeof unsafeWindow != "undefined" ? unsafeWindow : window; I've shrinkened by original answer, because that seems not to be your issue. Most likely, you've forgot to add // @include to your meta block. If your script has to redirect a certain, fixed page using GreaseMonkey, you can also shorten your scrip to: // ==UserScript== // @name Redirect // @include *i-am-afraid-of-this-word* // ==/UserScript== location.href = "http://www.google.com/search?q=need-help-getting-courage"; For more information about the meta block, see: http://wiki.greasespot.net/Metadata_block A: You notice that you're performing a Case-Sensitive search? it would not trigger if just one letter is capital when looking for a lower-case, or vice versa, if you want a case-Insensitive you need a RegExp as your "search-term". Other thing is, you don't need <br> in the metadata block, because then the include is the one not working, otherwise the page would need to have <br> in the address to match and execute. Extra: The !== should work just fine, but it's not needed, in this case a != would do, and it is strongly recommended that you don't use unsafeWindow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to compile single fortran objects using translator f2c? I have the following problem: I want to simulate some control engineering system. As it is quite complicated I used the computer to derive some (complicated) equations which can only be exported to fortran77 code. On my development pc this is no problem (linux machine). No I want to do it in hardware and here I have to use a windows OS. Unfortunately matlab does not support gfortran on windows. Therefore I can not compile the fortran files on that box. My idea was now to translate to C as a C compiler is available at matlab on win. Any other (better) options? I have several SUBROUTINES in the manner of the following. SUBROUTINE sys_rhs (x, v, dx, param) REAL*8 x(6) C code is coming here RETURN END SUBROUTINE Is it good practice and does it work to use the function sys_rhs__ in the interface function written in C? The problem is, that I can not test it as I do not have massive access to the windows machine. So it should work if I try it and I should not need to experiment a lot. Also what lib's do I need on windows? Where can I get them? Thanks Christian A: Intel sells a pretty good fortran compiler (http://software.intel.com/en-us/articles/fortran-compilers/) which they used to give away for free for testing ... ;-) PS No, Im not linked to this company in any way! A: You might wanna check the gnumex project, which allows to compile MEX-files using the GNU GCC compiler suite (using either MinGW or Cygwin), with the ability to use g77 to compile Fortran programs. A: The answer was quite simple: I had some syntax errors in my fortran code. gfortran does no such strict syntax checking and therefor interpreted the fortran code correctly. After removing the typos I succceded transcoding with f2c. Thanks A: there is a better solution to all this use your linux machine or your windows machine to implement the function in c/c++ and then generate a dll file. In matlab you can load the DLL and make a call to the functions inside it. here is a simple tutorial that show how to call the dll with matlab. http://www.mathworks.com/matlabcentral/fileexchange/15065-example-of-loading-c-dll-and-performance-comparison
{ "language": "en", "url": "https://stackoverflow.com/questions/7558103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Calling Accept() second time gives new socket for the same client request I like to write a server program with two threads, one thread for accepting requests and queuing them. Second one, worker thread, for processing them (I have not written this yet). Here is the pseudo code. while (1) { newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); read_from_newsockfd() put_in_queue // I am not closing the newsockfd here. If I close it here how to I communicate with the client from my second worker thread. } Now when I send the request from browser, accept() gets called second time giving another socket for the same request without blocking. I tried sending second request from different browser, I got segmentation fault. Could any one please tell me how to approach this problem? A: Is it possible that the browser is making multiple requests, in particular for /favicon.ico as well as the HTML? I suggest you use Wireshark to see what's going on at the network level. A: Most likely, your client is sending multiple requests for multiple resources?
{ "language": "en", "url": "https://stackoverflow.com/questions/7558104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strange problem with Google Maps and jQuery animation on Safari 5.1 I have a page with a Google map and a slider made by me that uses a simple horizontal animation. Everything works fine except on Safari 5.1 (mac) where the animation is screwed up (it doesn't go all the way across). I found out that removing the map (loaded with API v3) fixes the issue. I've setup a jsfiddle so you can test it out: http://jsfiddle.net/tGRf6/29/ (simply click on "Next" to run the slider) EDIT It may have something to do with "repaint" and stuff like that, since I noticed that resizing the window brings the slide in place. A: This update to your example seems to work in Safari 5.1: http://jsfiddle.net/tGRf6/33/ Removing overflow:hidden from div#slider fixed the issue. In order to hide the other slide elements again, I then wrapped another <div id="innerslider"> around the <ul> and moved the overflow:hidden property from <div id="slider"> to that new <div> (plus some more CSS). I would still (first search for and then) issue a bug report with your jsfiddle example, pointing out that overflow:hidden seems somehow involved. Hope this helps. Before coming to this potential solution (did not test in other browsers than Safari 5.1 and Firefox 7) I had written down some observations: * *Replacing the .animate() method by some plain JavaScript using setTimeout did not change the effect. *Non-animated changing of the left property works as expected, however, with the map included it is always "1 click behind" (first click changes the property to -800 but nothing changes, second click sets it to -1600 but the middle sliderelement is shown etc.). *Lowering the animation duration to 20 worsens the error as the "pixel steps" get bigger per iteration. Again, it does look like the last change does not "get through". Accordingly, when setting the duration to 800 (1ms/px) the element is one pixel off afterwards. *In-/decrementing the value for left in the developer tools shows also some strange effects when the map is included, e.g. when decrementing by 2 the sliderelement moved 1px right, then back 1px to the left. Everything ok when the map is thrown out. *Removing the "overflow:hidden" property of the slider div fixes the error, but you would have to hide the sliderelements some other way (see the revised jsfiddle). *It does a lot look like the last change of the left property is not reflected in the rendered page, when the map is included.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RTT calculation using tcptrace For the below attached tcptrace output (this is taken from the site http://tcptrace.org/manual/index.html under RTT stats) 1 arg remaining, starting with 'indica.dmp.gz' Ostermann's tcptrace -- version 6.4.5 -- Fri Jun 13, 2003 153 packets seen, 153 TCP packets traced elapsed wallclock time: 0:00:00.128422, 1191 pkts/sec analyzed trace file elapsed time: 0:00:19.092645 TCP connection info: 1 TCP connection traced: TCP connection 1: host a: 192.168.0.70:32791 host b: webco.ent.ohiou.edu:23 complete conn: yes first packet: Thu Aug 29 18:54:54.782937 2002 last packet: Thu Aug 29 18:55:13.875583 2002 elapsed time: 0:00:19.092645 total packets: 153 filename: indica.dmp.gz a->b: b->a: total packets: 91 total packets: 62 . . . . . . . . . . . . throughput: 10 Bps throughput: 94 Bps RTT samples: 48 RTT samples: 47 RTT min: 74.1 ms RTT min: 0.1 ms RTT max: 204.0 ms RTT max: 38.8 ms RTT avg: 108.6 ms RTT avg: 8.1 ms RTT stdev: 44.2 ms RTT stdev: 14.7 ms RTT from 3WHS: 75.0 ms RTT from 3WHS: 0.1 ms RTT full_sz smpls: 1 RTT full_sz smpls: 1 RTT full_sz min: 79.5 ms RTT full_sz min: 0.1 ms RTT full_sz max: 79.5 ms RTT full_sz max: 0.1 ms RTT full_sz avg: 79.5 ms RTT full_sz avg: 0.1 ms RTT full_sz stdev: 0.0 ms RTT full_sz stdev: 0.0 ms post-loss acks: 0 post-loss acks: 0 So the question I have is that if you see RTT average for a->b and for b->a there is a major difference in the values. I dont expect them to be exaclty the same but the difference is quite big. I think there is something happening behind the scene in the way RTT is being calculated which I am not sure of. A: Summary: Make sure you look at the RTT for the correct half of the conversation, depending on where you made the capture This answer explains that tcptrace uses the difference between timestamps of the data segment and that of the ACK that acknowledges it to calculate RTT. This means that the RTT calculation will depend on where you are capturing the trace For example, if you are capturing packets on node A, you will see A's ACK almost immediately after you see the corresponding segment arriving from node B and thus see a very low value for RTT in the B->A segments. For A->B segments you will be measuring the real RTT as a 'real' round-trip will have occurred between seeing the segment from A and the corresponding ACK from b. If you made the capture on node b the situation would be reversed, and if you made the capture somewhere in the middle the 'true' RTT would be approximately the sum of A->B + B->A. A: The RTT calculations are not made at the sender node. They could have been made at a point along the path. The a->b and b->a is not necessarily between the sender and receiver nodes. It can be something like this S--A--------->R where S is Sender and R is receiver and A is some point between S and R. a->b can represent the RTT from A to R while b->a can represent RTT from A to S.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to add tooltip for a item or cell of a vaadin table I noticed that vaadin 6.7.0 beta1 supports to add tooltip for row/cell of a table. However, I did not find any example how to add it. Is there anybody who can provide some sample? A: Use code as below: table.setItemDescriptionGenerator(new ItemDescriptionGenerator() { public String generateDescription(Component source, Object itemId, Object propertyId) { if(propertyId == null){ return "Row description "+ itemId; } else if(propertyId == COLUMN1_PROPERTY_ID) { return "Cell description " + itemId +","+propertyId; } return null; }} A: You could accomplish this by setting a formfieldfactory. Here you could return a button that only loooks like text with styling CSS. This will let you set a caption on the button. This is obviously a ugly hack. More info about buttons and links in vaadin. table.setTableFieldFactory(new TableFieldFactory() { // container is the datasource // item is the row // property is the column // @Override public Field createField(Container container, Object itemId, Object propertyId, Component uiContext) { }) A: You can't add tooltpis (setDescription) to a row/cell nativly - not yet! It is already in there issue tracker but don't know when they will implement this feature
{ "language": "en", "url": "https://stackoverflow.com/questions/7558119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Azure web role receiving results from a long process My Azure web role uses Ajax to call a function (in default.aspx.cs) that delegates work to worker roles. Worker roles may take up to 30-40 minutes depending on input file selected by user. If the worker roles return the result quickly it is received by the webrole and displays correctly on the web page. If it takes long the results are still received by the webrole (tried printing to trace) but nothing gets displayed on the web page. I feel there is some kind of time out that kills the connection between the ajax code on the page and the webrole. The code looks like: <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnSubmit").click(function () { var params = '{ map1 : "' + document.getElementById('<%=ddlMap1.ClientID %>').value + '",' + 'map2 : "' + document.getElementById('<%=ddlMap2.ClientID %>').value + '",' + 'op : "' + document.getElementById('<%=ddlOperator.ClientID %>').value + '"}'; $('#spinner').show(); $('#results').text(''); $.ajax({ type: "POST", url: "Default.aspx/Overlay", data: params, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { var dmsg = ''; if (msg == null) { dmsg = 'null'; } else { dmsg = msg.d; } $('#spinner').hide(); $('#results').text(dmsg); }, error: function (error) { $('#results').text(''); } }); }); }); </script> A: The azure load balancer kills any inactive connections after 1 minute. See my answer to this question about how to work around this problem. A: I would try to override the default timeout value of jquery to see if it helps: $.ajaxSetup({ timeout: 3600000 // one hour }); This issue could be caused by jquery but also be dependent on browser and network settings as stated in this SO question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: methods using yield not allowed to call themselves This could well be a user error (I'm kinda hoping so). I'm running into a strange case in C# were if I try to make recursive call in a method that uses yield it doesn't seem to be respected (i.e. the call is ignored). The following program illustrates this: // node in an n-ary tree class Node { public string Name { get; set; } public List<Node> ChildNodes { get; set; } } class Program { // walk tree returning all names static IEnumerable<string> GetAllNames(IEnumerable<Node> nodes) { foreach (var node in nodes) { if (node.ChildNodes != null) { Console.WriteLine("[Debug] entering recursive case"); // recursive case, yield all child node names GetAllNames(node.ChildNodes); } // yield current name yield return node.Name; } } static void Main(string[] args) { // initalize tree structure var tree = new List<Node> { new Node() { Name = "One", ChildNodes = new List<Node>() { new Node() {Name = "Two"}, new Node() {Name = "Three"}, new Node() {Name = "Four"}, } }, new Node() {Name = "Five"} }; // try and get all names var names = GetAllNames(tree); Console.WriteLine(names.Count()); // prints 2, I would expect it to print 5 } } A: You are making the call but doing nothing with it. You need to actually use the result here static IEnumerable<string> GetAllNames(IEnumerable<Node> nodes) { foreach (var node in nodes) { if (node.ChildNodes != null) { foreach (var childNode in GetAllNames(node.ChildNodes)) { yield return childNode; } } yield return node.Name; } } A: You aren't returning the results of the recursive call. You need to yield return each item returned from the call: foreach(var x in GetAllNames(node.ChildNodes)) yield return x; A: This is a very interesting problem that can result in A LOT of resource utilization for arbitrarily-deep structures. I think Mr. Skeet proposed a 'flattening' technique but I don't recall the link. Here's the code we use based on his idea (it's an extension method on IEnumerable): public static class IEnumerableExtensions { /// <summary> /// Visit each node, then visit any child-list(s) the node maintains /// </summary> /// <typeparam name="T"></typeparam> /// <param name="subjects">IEnumerable to traverse/></param> /// <param name="getChildren">Delegate to get T's direct children</param> public static IEnumerable<T> PreOrder<T>(this IEnumerable<T> subjects, Func<T, IEnumerable<T>> getChildren) { if (subjects == null) yield break; // Would a DQueue work better here? // A stack could work but we'd have to REVERSE the order of the subjects and children var stillToProcess = subjects.ToList(); while (stillToProcess.Any()) { // First, visit the node T item = stillToProcess[0]; stillToProcess.RemoveAt(0); yield return item; // Queue up any children if (null != getChildren) { var children = getChildren(item); if (null != children) stillToProcess.InsertRange(0, children); } } } } This avoids recursion and a lot of nested iterators. You would then call it: // try and get all names var names = tree.PreOrder<Node>(n => n.ChildNodes); Now this IS a 'pre-order' where the node name comes first, but you could easily write a post-order if that's what you prefer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting current category with FPC enabled Is it possible to get current category when Full Page Cache is enabled? Catalog controller is not executed in this case, so the registry (current_category key) is empty. All I can get is the root category Thanks A: As one of the possible solution is to get category ID by given url. You have table of url rewrites and you have request string. // Try to get category id directly from request if (Mage::app()->getRequest()->getParam('id')) { return Mage::app()->getRequest()->getParam('id'); } // Try to get category id from request by rewrite request path $aliases = Mage::app()->getRequest()->getAliases(); if ($aliases && is_array($aliases) && !empty($aliases) && $aliases['rewrite_request_path']) { $urlRewrite = Mage::getModel('core/url_rewrite')->loadByRequestPath($aliases['rewrite_request_path']); if ($urlRewrite && $urlRewrite->getId()) { return $urlRewrite->getCategoryId(); } } May be it's not beautiful solution but it worked well for me. A: You need to get it via the layer: $layer = Mage::getSingleton('catalog/layer'); $_category = $layer->getCurrentCategory(); $currentCategoryId= $_category->getId(); Regards, Kenny A: You are hole punching your block as indicated here: I'm writing a module with random products list block, it's not affected by FPC by implementing hole punching This means that your block is a stripped down version of Magento (see applyWithoutApp() method), so to access the current_category out of the registry, you'll need to register it in your Container in your hole punch module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Search API Solr integration with fivestar (or similar) rating system (fascet and sort) I'm attempting to sort nodes by ratings using the Search API faceted search with Solr integration. I've already set up fivestar ratings (about 9 per node, its a large multi-axis rating system.) but i'm unable to index these ratings! Can someone help me understand how to change this so I can use a facet search for ratings? Otherwise, are there any recommendations on other modules (aside from fivestar) which would allow the votes to be indexed? Thank you! Justin A: first you need install facetapi module -that's for facets. second, on hook_update_index, you need to add rating to apachesolr index <?php function module_apachesolr_update_index(&$document, $node) { //add additional offers; if (count($node->field_add_offers)) { $field = $node->field_add_offers; foreach ($field as $lang => $values) { foreach ($values as $value) { if (isset($value['value'])) { $document->setMultiValue('sm_offers', $value['value']); } } } } } ?> Please note, it's just an example. I run 2 loops because of multilingual site and problem with this "und" key in field array. Here also you can not add all ratings, but calculate, for instance,one modifier per node, which will be used for sorting (if you don't have that one in ratings) Third, add facets with using hook_facetapi_facet_info <?php function module_facetapi_facet_info(array $searcher_info) { return array( 'sm_games_facet' => array( 'name' => 'sm_games_facet', 'label' => t('games'), 'description' => t('Filter games'), 'field' => 'sm_games', 'field alias' => 'game', 'query type' => 'term', 'default widget' => 'facetapi_links', 'allowed operators' => array(FACETAPI_OPERATOR_OR => TRUE, FACETAPI_OPERATOR_AND => TRUE), 'default sorts' => array( array('display', SORT_ASC), ), ) ); } ?> more about facets you can find at facetapi.api.php file; Forth - reindex content and enable facet in apachesolr settings. Regards, Slava
{ "language": "en", "url": "https://stackoverflow.com/questions/7558132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is Metro, is it going to replace .NET completely? Heard that Microsoft is planning to release Metro (http://connect.microsoft.com/metro), calling next generation technologies and some of them said its going to replace .NET, is it true? How Metro is important for a .NET developer? A: Metro style is a new type of ux. It will not be replaced and in fact the new windows 8 has two modes. It all depends on the goal of your application. Take a look at this blog it explains it pretty well. http://blogs.telerik.com/blogs/posts/11-09-15/i-know-what-you-re-thinking-and-you-re-wrong.aspx Let me know if you have any other questions. A: Metro is the new GUI, started with Windows Phone 7, prior to that similar interface used in MS Zune player.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Absolute positioned element displays in different position in safari compared to IE8 For www.zabb.co.uk/test2b.html the displayDiv displays higher up in IE8 than in Safari. How can I make it so they display in exactly the same vertical position? Thanks in advance. A: I haven't examined your page, so while there may be problems with the css, I suspect the two browsers are just different. I would suggest one of these: 1) Design your page so you don't require a certain element to be an exact absolute position (use more relative positioning) 2) Use conditional comments to add a wrapper class to your page and write a new css rule to adjust the div, e.g. .ie8 #myAbsoluteDiv { top: /* something different from safari */ } A: The element is positioned top: 50%, meaning that the top of the box is positioned half way down the visible area of the window (the 'viewport') when the page loads. This is a fairly standard bit of CSS, and should work fine in both browsers. However, because the position is based on the size of the visible browser window size, the exact position will vary in different browsers, even if you have them both maximized on the same screen, because the two browsers will use different amounts of space for their toolbars, etc, and thus their browser viewports will differ in size. This is most likely reason for what you're seeing: the browsers are both working fine; they're just following the same instruction differently because their viewports are different sizes. You'll also notice the same effect if you change the size of the browser window, and this also means that users with different screen resolutions to yours will see it differently, even in the same browser. There's nothing intrinsically wrong with this effect -- if you are trying to position something to 50%, then it will naturally be in a different position according to the size of the window it's in. This may actually be a good thing, as it means you can ensure it is visible and centered for all users, no matter what their screen size. However, if you do want to prevent this effect, I would suggest using a fixed pixel value for the top style, rather than a percentage. If you want to position it absolute, but positioned in relation to the whole page rather than the window size, then you need to make an element outside of it (possibly your body element) position:relative;. It will then measure the absolute position of your box against that rather than against the viewport. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use the same variable in two methods? I hope this question is not too basic for someone to help me out on. I have a variable who's value I define in one method that I would like to use and manipulate in another. Is this possible? I hope the simple expample code attached will help. I want the value for 'c' to be 3, but it is only 2. int a = 0; -(void)method1 { int a = 1; NSLog(@"method 1--> a = %d", a); } -(void)method2 { int b = 2; NSLog(@"method 2--> b = %d", b); int c = a + b; NSLog(@"method 2--> c = %d", c); } A: int a = 1 in method1 declares new local variable distinct from 'a' declared globally. If you want global 'a' to be used here - omit 'int' here.This will turn declaration of local variable 'a' with initialization into assignment to the globally declared 'a'. A: Okay, how it will work for you. You have redeclared global variable inside your local function. This is not problem, but you should know, that global value will not be used, and after finishing function, global value will become the same. So, if you want to manipulate variable in both methods, it should be global, for both of them. Like this: int a = 0; -(void)method1 { // int a = 1; Now it is local and will not be changed, after function finishing. a = 1; // Now it is local, so will stay 1 after the end of method. NSLog(@"method 1--> a = %d", a); } -(void)method2 { int b = 2; NSLog(@"method 2--> b = %d", b); int c = a + b; NSLog(@"method 2--> c = %d", c); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ExtJs Combobox problem Hi i have a formpanel with remote combobox, the store is jsonstore and is get from webservices with paging results, everything is well, but when you pick an option form the combo always pick the first one, you can pick the third but the combo choose the first option i don't know the reason for this the configuration for the combo is this: { xtype: 'combo', fieldLabel: 'Sitio Interés', anchor: '100%', triggerAction: 'all', store: dsPuntos, mode: 'remote', displayField: "Nombre", valueField: "Id", typeAhead: false, width: 222, hideLabel: true, allowBlank: false, id: 'cboDato', editable: true, pageSize: 20, minChars: 0, hideTrigger: true, //enableKeyEvents: true, emptyText: 'Escriba un sitio de interés', tpl: '<tpl for="."><div class="x-combo-list-item">{Nombre} - {Municipio}</div></tpl>', listeners: { scope: this, specialkey: function (f, e) { if (e.getKey() == e.ENTER) { Ext.getCmp('btnConsultar').handler.call(Ext.getCmp('btnConsultar').scope); } } } }, and the store is here: var dsPuntos = new Ext.data.JsonStore({ proxy: new Ext.data.HttpProxy({ url: 'Services/MapService.svc/GetSitiosInteres', method: 'GET' }), root: 'd.rows', totalProperty: 'd.total', id: 'Id', fields: ['Nombre', 'Municipio', 'Id'] }); Thanks A: Your store config is a little off. It should be idProperty instead of id. Also check the json coming from the server. Make sure that the id are unique.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: undefined local variable or method `acts_as_taggable' in gem I'm working on converting a plugin to a gem. In one of the models I'm using acts_as_taggable_on, and it looks like this class BlogPost < ActiveRecord::Base acts_as_taggable .... end However, I get this error when I run it: undefined local variable or method `acts_as_taggable' for #<Class:0x000000060799b8> and the stack trace looks like this: activerecord (3.1.0) lib/active_record/base.rb:1082:in `method_missing' test_gem (0.1.0) app/models/blog_post.rb:28:in `<class:BlogPost>' test_gem (0.1.0) app/models/blog_post.rb:2:in `<top (required)>' The acts_as_taggable gem is included in my gemspec file and is installed on the system. gem install acts-as-taggable-on Successfully installed acts-as-taggable-on-2.1.1 1 gem installed Installing ri documentation for acts-as-taggable-on-2.1.1... Installing RDoc documentation for acts-as-taggable-on-2.1.1... I have no idea what could be wrong - please help me out A: none of above answers works for me, what I did was put : require 'acts-as-taggable-on' in the beginning the model where I'm using the gem :) A: Have you put the following in you Gemfile: gem 'acts-as-taggable-on', '~>2.1.0' then bundle install A: I had the same issue. I restarted my server and it worked fine after
{ "language": "en", "url": "https://stackoverflow.com/questions/7558141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Better solution for this 2x fast-enumeration? I'm looping through an array and comparing the objects tag property in this array with the objects in another array. Here's my code: NSArray *objectsArray = ...; NSArray *anotherObjectArray = ...; NSMutableArray *mutableArray = ...; for (ObjectA *objectA in objectsArray) { for (ObjectZ *objectZ in anotherObjectArray) { if ([objectA.tag isEqualToString:objectZ.tag]) { [mutableArray addObject:objectA]; } } } Is there a better way to do this? Please note the tag property is not an integer, so have to compare strings. A: You can do this by iterating over each array once, rather than nesting: NSMutableSet *tagSet = [NSMutableSet setWithCapacity:[anotherObjectArray count]]; for(ObjectZ *objectZ in antherObjectArray) { [tagSet addObject:objectZ.tag]; } NSMutableArray *output = [NSMutableArray mutableArray]; for(ObjectA *objectA in objectsArray) { if([tagSet containsObject:objectA.tag]) { [output addObject:objectA]; } } A: Well, the simplest change (as there can only be one match per objectA) then you could do a break after your [mutableArray addObject:objectA]. When a match occurs, that would reduce the inner loop by 50%. More dramatically, if you're doing this a lot and the order of anotherObjectArray doesn't matter, would be to invert your anotherObjectArray data structure and use a dictionary, storing the objects by tag. Then you just iterate over objectA asking if its tag is in the dictionary of ObjectZs. A: May be you can use [NSArray filteredArrayUsingPredicate:]; - http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html But you may have to tweak for property tag yourself. NSArray *objectsArray = [NSArray arrayWithObjects:@"Miguel", @"Ben", @"Adam", @"Melissa", nil]; NSArray *tagsArray = [NSArray arrayWithObjects:@"Miguel", @"Adam", nil]; NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF IN %@", tagsArray]; NSArray *results = [objectsArray filteredArrayUsingPredicate:sPredicate]; NSLog(@"Matched %d", [results count]); for (id a in results) { NSLog(@"Object is %@", a); } Hope this helps A: Thanks for all the answers. While I have accepted the NSMutableSet solution, I actually ended up going with the following, as it turned out it was a tiny bit faster: NSMutableDictionary *tagDictionary = [NSMutableDictionary dictionaryWithCapacity:[anotherObjectArray count]]; for (ObjectZ *objectZ in anotherObjectArray) { [tagDictionary setObject:objectZ.tag forKey:objectZ.tag]; } for (ObjectA *objectA in objectsArray) { if ([tagDictionary objectForKey:objectA.tag]) { [direction addObject:objectA]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unexpected Thread Abort Exception using Tasks. Why? I have a console application running in an app domain. The app domain is started by a custom windows service. The application uses parent tasks to start several child tasks that do work. There can be many parent tasks with children running at any given time as the timer looks for new work. The handle to all parent tasks is in a List of tasks: static List<Task> _Tasks = new List<Task>(); The windows service is able to send a stop signal to the running application by putting a string token in an app domain slot when an admin changes an xml config file (or when the calling service is shut down). The application is running on a timer and checks for a signal to shut down in the slot, then attempts to gracefully conclude what it is doing by waiting for all tasks to end. Tasks are started like so: Task parent = Task.Factory.StartNew(() => { foreach (var invoiceList in exportBucket) { KeyValuePair<string, List<InvoiceInfo>> invoices = new KeyValuePair<string, List<InvoiceInfo>>(); invoices = invoiceList; string taskName = invoices.Key; //file name of input file Task<bool> task = Task.Factory.StartNew<bool>(state => ExportDriver(invoices), taskName, TaskCreationOptions.AttachedToParent); } }); _Tasks.Add(parent); A custom GAC dll holds a class that does the work. There are no shared objects in the GAC function. The GAC class is instantiated in each child task: Export export = new Export(); Each child task calls a method at some point during execution: foreach (var searchResultList in SearchResults) { foreach (var item in searchResultList) { if (item.Documents.Count > 0) { //TODO: this is where we get thread issue if telling service to stop var exported = export.Execute(searchResultList); totalDocuments += exported.ExportedDocuments.Count(); } } } searchResultList is not shared between tasks. While the application runs, export.Execute performs as expected for all child tasks. When the stop signal is detected in the application, it attempts to wait for all child tasks to end. I've tried a couple ways to wait for the child tasks under each parent to end: foreach (var task in _Tasks){task.Wait();} and while (_Tasks.Count(t => t.IsCompleted) != _Tasks.Count){} While the wait code executes a threading exception occurs: Error in Export.Execute() method: System.Threading.ThreadAbortException: Thead was being aborted at WFT.CommonExport.Export.Execute(ICollection '1 searchResults) I do not wish to use a cancellation token as I want the tasks to complete, not cancel. I am unclear why the GAC class method is unhappy since each task should have a unique handle to the method object. UPDATE: Thanks for the comments. Just to add further clarification to what was going on here... In theory, there shouldn't be any reason the approach of waiting on child tasks: while (_Tasks.Count(t => t.IsCompleted) != _Tasks.Count){} shouldn't work, though Task.WaitAll() is certainly a better approach, and helped flesh out the problem. After further testing it turns out that one of the issues was that when the app domain application told the calling service no work was being done by populating a slot read by the service: AppDomain.CurrentDomain.SetData("Status", "Not Exporting"); the timing and placement of that statement in code was wrong in the application. Being new to multithreading, it took me a while to figure out tasks were still running when I issued SetData to "Not Exporting". And so, when the service thought it was OK to shut down and tore down the app domain, I believe that caused the ThreadAbortException. I've since moved the SetData statement to a more reliable location. A: To answer your question: you are receiving a thread-abort because tasks are executed on a "background" thread. Background threads are not waited-on before application terminating. See this MSDN link for further explanation. Now to try to help solve your actual problem, I would suggest the Task.WaitAll() method Jim mentions, however you should handle application termination more robustly. I suspect that while you wait for tasks to complete before shutting down, you don't prevent new tasks from being enqueued. I would recommend an exit-blocking semaphore and the system that enques tasks increment this on initialization, and decrement on dispose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: oracle rollback and commit In the following sql statements: BEGIN update table1 set col1 = 'Y'; commit; update table2 set col2 = 'Y'; rollback; end; / Will it rollback both the updates or only update #2? A: Just #2 You might be interested in save points A: Your statement will rollback only the current transaction. i.e. the update of table2. You ended the update of table1 transaction when you issued a commit. As vc74 says, save points are a useful tool for controlling where you can rollback to without having to issue commits etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can i save my n3 file formate like it's origin file i programing with c# and dotnetrdflibrery'I have an n3 file that i open it in a notpad and show it below @prefix my: <http://www.codeproject.com/KB/recipes/n3_notation#>. my:Peter a my:person, my:boy;     my:suffers my:acrophobia, my:insomnia, my:xenophobia;     my:name "Peter";     my:likes my:Kate. my:Mark a my:person, my:boy;     my:suffers my:insomnia;     my:name "Mark". my:Kate a my:person, my:girl; my:name "Kate". when i save this file with g.savetofile() it save it like this format that i dont like it i think this have not good view: @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>. @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>. @prefix xsd: <http://www.w3.org/2001/XMLSchema#>. @prefix my: <http://www.codeproject.com/KB/recipes/n3_notation#>. <http://www.codeproject.com/KB/recipes/n3_notation#Kate> <http://www.codeproject.com/KB/recipes/n3_notation#name> "Kate". <http://www.codeproject.com/KB/recipes/n3_notation#Kate> a <http://www.codeproject.com/KB/recipes/n3_notation#girl>. <http://www.codeproject.com/KB/recipes/n3_notation#Kate> a <http://www.codeproject.com/KB/recipes/n3_notation#person>. <http://www.codeproject.com/KB/recipes/n3_notation#Mark> <http://www.codeproject.com/KB/recipes/n3_notation#name> "Mark". <http://www.codeproject.com/KB/recipes/n3_notation#Mark> <http://www.codeproject.com/KB/recipes/n3_notation#suffers> <http://www.codeproject.com/KB/recipes/n3_notation#insomnia>. <http://www.codeproject.com/KB/recipes/n3_notation#Mark> a <http://www.codeproject.com/KB/recipes/n3_notation#boy>. <http://www.codeproject.com/KB/recipes/n3_notation#Mark> a <http://www.codeproject.com/KB/recipes/n3_notation#person>. <http://www.codeproject.com/KB/recipes/n3_notation#Peter> <http://www.codeproject.com/KB/recipes/n3_notation#likes> <http://www.codeproject.com/KB/recipes/n3_notation#Kate>. <http://www.codeproject.com/KB/recipes/n3_notation#Peter> <http://www.codeproject.com/KB/recipes/n3_notation#name> "Peter". <http://www.codeproject.com/KB/recipes/n3_notation#Peter> <http://www.codeproject.com/KB/recipes/n3_notation#suffers> <http://www.codeproject.com/KB/recipes/n3_notation#acrophobia>. <http://www.codeproject.com/KB/recipes/n3_notation#Peter> <http://www.codeproject.com/KB/recipes/n3_notation#suffers> <http://www.codeproject.com/KB/recipes/n3_notation#insomnia>. <http://www.codeproject.com/KB/recipes/n3_notation#Peter> <http://www.codeproject.com/KB/recipes/n3_notation#suffers> <http://www.codeproject.com/KB/recipes/n3_notation#xenophobia>. <http://www.codeproject.com/KB/recipes/n3_notation#Peter> a <http://www.codeproject.com/KB/recipes/n3_notation#boy>. <http://www.codeproject.com/KB/recipes/n3_notation#Peter> a <http://www.codeproject.com/KB/recipes/n3_notation#person>. <http://www.dotnetrdf.org/> <http://example.org/createdBy> "Rob Vesse". this format show all uri compeletly, how can i save it like the first format? please help me A: Graph graph1 = new Graph(); TripleStore store = new TripleStore(); Notation3Parser n3parser = new Notation3Parser(); n3parser.Load(graph1, AppPath + "\\n3\\ontology.n3"); //Create some Nodes graph1.NamespaceMap.AddNamespace("my", UriFactory.Create("http://0.0.0.1/#")); IUriNode Person = graph1.CreateUriNode("my:firas"); IUriNode rdfType = graph1.CreateUriNode("my:name"); IBlankNode dse = graph1.CreateBlankNode("a"); ILiteralNode robVesse = graph1.CreateLiteralNode("firas"); Triple t = new Triple(Person, dse, robVesse); graph1.Assert(t); IUriNode Person1 = graph1.CreateUriNode("my:firas"); //ILiteralNode LtrNode = graph1.CreateLiteralNode("a", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString)); IUriNode rdfType1 = graph1.CreateUriNode("my:a"); IUriNode robVesse1 = graph1.CreateUriNode("my:person"); IGraphLiteralNode dfa = graph1.CreateGraphLiteralNode(graph1); Triple t1 = new Triple(Person1, rdfType1, robVesse1); graph1.Assert(t1); IUriNode Person2 = graph1.CreateUriNode("my:firas"); IUriNode rdfType2 = graph1.CreateUriNode("my:suffers"); IUriNode robVesse2 = graph1.CreateUriNode("my:insomnia"); Triple t2 = new Triple(Person2, rdfType2, robVesse2); graph1.Assert(t2); //SparqlResultSet resultSet = graph.ExecuteQuery(str2) as SparqlResultSet; store.Add(graph1); Notation3Writer n3w = new Notation3Writer(); n3w.Save(graph1, AppPath + "\\n3\\ontology.n3"); A: //correction String AppPath = HttpContext.Current.Request.PhysicalApplicationPath.ToString(); Graph graph1 = new Graph(); TripleStore store = new TripleStore(); Notation3Parser n3parser = new Notation3Parser(); n3parser.Load(graph1, AppPath + "\\n3\\ontology.n3"); //Create some Nodes graph1.NamespaceMap.AddNamespace("my", UriFactory.Create("http://0.0.0.1/#")); IUriNode Person = graph1.CreateUriNode("my:firas"); IUriNode rdfType = graph1.CreateUriNode("my:name"); //IBlankNode dse = graph1.CreateBlankNode("a"); ILiteralNode robVesse = graph1.CreateLiteralNode("firas"); Triple t = new Triple(Person, rdfType, robVesse); graph1.Assert(t); IUriNode Person1 = graph1.CreateUriNode("my:firas"); //ILiteralNode LtrNode = graph1.CreateLiteralNode("a", UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString)); IUriNode rdfType1 = graph1.CreateUriNode("my:a"); IUriNode robVesse1 = graph1.CreateUriNode("my:person"); IGraphLiteralNode dfa = graph1.CreateGraphLiteralNode(graph1); Triple t1 = new Triple(Person1, rdfType1, robVesse1); graph1.Assert(t1); IUriNode Person2 = graph1.CreateUriNode("my:firas"); IUriNode rdfType2 = graph1.CreateUriNode("my:suffers"); IUriNode robVesse2 = graph1.CreateUriNode("my:insomnia"); Triple t2 = new Triple(Person2, rdfType2, robVesse2); graph1.Assert(t2); //SparqlResultSet resultSet = graph.ExecuteQuery(str2) as SparqlResultSet; store.Add(graph1); Notation3Writer n3w = new Notation3Writer(); n3w.Save(graph1, AppPath + "\\n3\\ontology.n3");
{ "language": "en", "url": "https://stackoverflow.com/questions/7558148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: When should we host WCF service in IIS and when should we host in a windows service? I need to host my WCF service but I am unable to decide whether I should host it in IIS or a windows service? What are the advantages, drawbacks, benefits of one over the other please? Thank you A: IIS under version 7 is out of the question for any serious hosting anyway.... As for IIS7+/WAS vs. self-hosting in a NT service: * *the IIS7/WAS setup will "load on demand", e.g. when your first request comes in, a ServiceHost will be created, then that service host creates the service class to handle the request. This is beneficial from a memory point of view (uses no memory for the ServiceHost if no requests come in), but it's a bit of an additional overhead on the first call when IIS first needs to spin up the service host *NT Service allows you to pre-create the ServiceHost and open it so it's ready to handle requests right away; a bit more memory usage, but a bit more responsive, at least on "first calls" Another benefit of self-hosting: you're 100% in charge of when the service host starts, pauses, stops, and so on. With IIS/WAS, you're at times at the mercy of IIS with its potential to recycle app pools at the worst possible moment...... A: The main advantages of IIS is that it handles the lifetime of your service for you: activation, recycling... Its main drawback if you don't have v7 is that without WAS it can only host http based web services The services need more care in case of fatal error... and then need to be installed whereas a web site can be copied to its web folder once it has been created If your version of iis is >= 7, then I don't see a lot of interest in not using WAS as it supports all the wcf transports, others might have a different view though...
{ "language": "en", "url": "https://stackoverflow.com/questions/7558152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: rake db:create - rake aborted - no rakefile found So, the title is quite self explanatory, but here's the following .. rake db:create rake aborted! No rakefile found (looking for: rakefile, Rakefile, rakefile.rb, Rakefile.rb) Any help would be appreciated. A: You have to be in the root of the Rails app that you are creating. Currently you must be one step up. A: What is your current working directory when calling the rake db:create command? Are you in the root of the Rails app? A: Case I: Check out your directory. If you are in same directory where your application is available then you wont' get is this message. You are getting this message because you are out of your application directory. To check you present directory you can use this command pwd Case II You might missing your Rakefile. Check it out in your directory. For example, $ ls app/ bin/ config/ db/ ... If you don't find Rakefile then create new one. Puts this code # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) Blog::Application.load_tasks
{ "language": "en", "url": "https://stackoverflow.com/questions/7558157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to deserialize JSON string is correct in c#? Help to deal with JSON deserialization correct answer. For example, we have JSON response to the following: {"variant":"otvet1", "source":"otvet2", "items":[ {"list":"512"}, {"vist":"315"}, {"zist":"561"}]} To deserialize using the following code: [DataContract] public partial class ItemsList { [DataMember(Name = "list")] public string lisType { get; set; } [DataMember(Name = "vist")] public string vistType { get; set; } [DataMember(Name = "zist")] public string zistType { get; set; } } [DataContract] public partial class SourceList { [DataMember(Name = "variant")] public string variantType { get; set; } [DataMember(Name = "source")] public string vistType { get; set; } [DataMember(Name = "items")] public List <ItemsList> TestItemsList { get; set; } } public class JsonStringSerializer { public static T Deserialize<T>(string strData) where T : class { MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strData)); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); T tRet = (T)ser.ReadObject(ms); ms.Close(); return (tRet); } } private static SourceList SourceTempList; SourceTempList = JsonStringSerializer.Deserialize<SourceList>(e.Result); //in e.Result JSON response In the previous code, it works, but if you change the JSON response, it does not work ... New JSON response: {"variant":"otvet1", "source":"otvet2", "items":[3, {"list":"512"}, {"vist":"315"}, {"zist":"561"}]} In this case, c # code for deserialization does not work ... Items in the number 3 appeared, tell me how to deserialize the JSON response to this? Were available to list vist and zist ...Help me...please A: Historically the DataContractJsonSerializer has been seen as broken. The reccomendation is to use JSON.Net http://james.newtonking.com/projects/json-net.aspx Check out Deserialization problem with DataContractJsonSerializer
{ "language": "en", "url": "https://stackoverflow.com/questions/7558162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Numbers occasionally not adding correctly in JQuery This code is inside a jquery mobile form. It adds up the numbers and displays the total in a disabled text box. When the the total is 100, the continue (submit) button is enabled. The session var code properly puts in zeroes when there isn't a value. Problem: Sometimes people will type a number after the zero (eg: 0100). It seems like this, combined with erasing a number will cause the numbers not to add up properly. I could use your assistance with: Getting rid of the random bugginess in calculating the total, especially when the value is cleared. Should I be using parseInt instead? Thanks in advance. <script> $(document).ready(function() { <?php if (!isset($_SESSION['num1'])) { echo "$('#num1').val(0);"; } if (!isset($_SESSION['num2'])) { echo "$('#num2').val(0);"; } if (!isset($_SESSION['num3'])) { echo "$('#num3').val(0);"; } if (!isset($_SESSION['num4'])) { echo "$('#num4').val(0);"; } ?> //to handle previously entered values if back button used: <br/> var tot = ($('#num1').val() - 0) + ($('#num2').val() - 0) + ($('#num3').val() -0) + ($('#num4').val() - 0); $('#total').val(tot); if (tot==100) { $('#continue').removeAttr('disabled'); } else { $('#continue').attr("disabled","disabled"); } //to handle numbers on update. $('input[name^="int"]').keypress(function() { var tot = ($('#num1').val() - 0) + ($('#num2').val() - 0) + ($('#num3').val() -0) + ($('#num4').val() - 0); $('#total').val(tot); if (tot==100) { $('#continue').removeAttr("disabled"); } else { $('#continue').attr("disabled","disabled"); } }); A: try with parseInt($('#num').val(),10) instead of $('#num').val() - 0 to transform the strings to numbers A: You should be using parseInt instead. However, make sure you use it properly: parseInt("09",10); // equals 9 parseInt("09); // equals zero, because it thinks it's an octal number A: To get an int out of an input using only one line of code: var n=parseInt($('#num').val(),10)||0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7558166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: StringIO with binary files? I seem to get different outputs: from StringIO import * file = open('1.bmp', 'r') print file.read(), '\n' print StringIO(file.read()).getvalue() Why? Is it because StringIO only supports text strings or something? A: When you call file.read(), it will read the entire file into memory. Then, if you call file.read() again on the same file object, it will already have reached the end of the file, so it will only return an empty string. Instead, try e.g. reopening the file: from StringIO import * file = open('1.bmp', 'r') print file.read(), '\n' file.close() file2 = open('1.bmp', 'r') print StringIO(file2.read()).getvalue() file2.close() You can also use the with statement to make that code cleaner: from StringIO import * with open('1.bmp', 'r') as file: print file.read(), '\n' with open('1.bmp', 'r') as file2: print StringIO(file2.read()).getvalue() As an aside, I would recommend opening binary files in binary mode: open('1.bmp', 'rb') A: The second file.read() actually returns just an empty string. You should do file.seek(0) to rewind the internal file offset. A: Shouldn't you be using "rb" to open, instead of just "r", since this mode assumes that you'll be processing only ASCII characters and EOFs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7558168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: On pressed button block the other buttons How could I make my button to do the on click action even if the button is pressed and the finger is still on the screen (the button is not released). Or I would accept the solution that when a button is pressed and is not release, the other buttons on the layout to not be blocked. A: Instead of using an OnClickListener consider using an OnTouchListener. You can then detect when the user's finger touches:ACTION_DOWN and releases ACTION_UP the button. A method like this would probably work fine: public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_DOWN: //DISABLE THE OTHER BUTTONS break; case MotionEvent.ACTION_UP: // RE-ENABLE THE OTHER BUTTONS break; } return true; } A: One option would be to use the onmousedown event rather than the onclick event in your javascript: myButton.onmousedown = myOnClickFunction;
{ "language": "en", "url": "https://stackoverflow.com/questions/7558170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WPI - Visual Studio 2010 SP1 I am at a total loss when it comes to WPI and the continous reinstallation of Visual Studio 2010 SP1. I have even went as far as creating a virgin machine and installed VS2010 and then immediatly installed the tools from WPI. After completion (which shows success) I reboot the machine and then load the WPI again to add on secondary tools. At which point, the WPI triggers an installation of the SP1 -- 90 minutes later, the list shows up as successful, and other tools are listed for installation. Every time you run WPI, it wants to go through the VS2010 setup over and over. Is there any way to fix this behaviour? Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Image.SelectActiveFrame memory problem I'm writing a control to show images. My problem comes out using Image class on multipage TIFFs. I use this (I post only relevant code) at the beginning: Image img; int pages; img = Bitmap.FromFile(filename); pages = img.GetFrameCount(FrameDimension.Page); then, when the user wants to show a different page: public override Image GetPage(int page) { if (page < 1 || page > pages) return null; try { #if !TEST img.SelectActiveFrame(FrameDimension.Page, page - 1); return new Bitmap(img); #else MemoryStream ms = new MemoryStream(); img.SelectActiveFrame(FrameDimension.Page, page - 1); img.Save(ms, ImageFormat.Jpeg); Image ret = Image.FromStream(ms); ms.Flush(); ms.Dispose(); return ret; #endif } catch (Exception ex) { "Tiff GetPage error: {0}".ToDebug(ex.Message); return null; } } Using img.SelectActiveFrame(FrameDimension.Page, page - 1); (in both versions) about 7MB are allocated in memory and those are never freed (even exiting the method)!!! If I goes to next page 7MB are allocated and not freed everytime, while going back (on an already visited pages) previously allocated memory is used. To give you an example: think Task Manager reports my app is using x MB; going one page forward memory increases to x + y (after SelectActiveFrame()) + z (Image ret = ...). Well, I should have x + z (y part should be zero or GC collected exiting the method), but obviously that's not what happens, even calling GC.Collect manually. Going back to a previously visited page, memory increases effectively only with z, as expected. I find it terrible (think about a file with 80 pages...), but how can I force img object to free allocated memory? Am I doing something wrong? I've already thought closing and reopening img, but speed is not good. Thanks to everybody A: Don't use new Bitmap(img) because it will force the system to create new memory for a new Bitmap object using 32-bit color by default. You can just use var bitmap = (Bitmap)img; to retrieve a Bitmap object for that page. A: If I'm not mistaken you're not destroying the used controls at every possible point. I think you might need to test this - but make sure that you're disposing all the used controls. ie. ImageControlUsed.Dispose(); A: I answer my question after trying different solutions and accept soluzion given by user965487 because at the end he was right (thanks to Hans Passant too). If you have a class (call it QV) similar to this public class QV { Image img; int pages; public QV(filename) { img = Bitmap.FromFile(filename); pages = img.GetFrameCount(FrameDimension.Page); } ~QV() { img.Dispose(); img = null; } public Image GetPage(int page) { if (page < 1 || page > pages) return null; img.SelectActiveFrame(FrameDimension.Page, page - 1); return new Bitmap(img); } } then every time you call GetPage(...) your memory will grow not only for the size of returned image, but also for img.SelectActiveFrame(...) statement. I don't know why and how, but it happens. Releasing returned image and calling frees memory for image size, not for the amount taken from SelectActiveFrame() (anyway this memory is not duplicated if you return on a previously seend page). So you'd better open and close the image everytime, like this: public class QV { Image img; int pages; public QV(filename) { img = Bitmap.FromFile(filename); pages = img.GetFrameCount(FrameDimension.Page); img.Dispose(); } public Image GetPage(int page) { if (page < 1 || page > pages) return null; img = Bitmap.FromFile(filename); img.SelectActiveFrame(FrameDimension.Page, page - 1); Image ret = Bitmap(img); img.Dispose(); return ret; } } Payload for opening and disposing image everytime user requests a new page is really nothing compared to dangerous memory allcation done with first solution. I hope someone needs this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any java memory structures that will automatically page data to disk? Basically, I am caching a bunch of files in memory. The problem is, if I get too many files cached into memory I can run out of memory. Is there any sort of java memory structure that will automatically page part of itself to disk? For example, I would like to set a 2 mb limit the size of the files in memory. After that limit I would like some of the files to be written to disk. Is there any library that does this sort of thing? Grae A: ‎"files in memory". Conventionally, in memory data is stored in some data structure like a HashMap or whatever, and referred to as a 'file' when its written to disc. You could code a data storage class which did this programmatically. I don't know of any library which did this. It would be pretty useful. In effect you would be implementing virtual memory. This link will might help you : http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html A: EhCache is general purpose caching library for Java. One of the option is to have disk-backed cache, which overflows to file system. Seems to be exactly what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql drop permission for Wordpress We are running a Wordpress site and one of the plug-ins requires drop permission on the database. (We currently do not grant drop permission and have not needed to for any other plug-ins.) Is there a security concern if I grant the public connection/user drop privileges? The plug-in in question is simplepress and we receive an error asking for drop permissions: [DROP command denied to user xxxxxxx for table 'wp_sfwaiting'] TRUNCATE wp-sfwaiting A: Mysql changed in that it requires DROP permission since 5.1.16: Check it here. Truncate is often used as a fast table clear option (as recommended by MySQL themselves). It should be changed to delete from <table> by that plugin programmer to get away only with the DELETE permission. Until that you may grant drop only for that specific table..
{ "language": "en", "url": "https://stackoverflow.com/questions/7558177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting No Linked You Tube account while implementing the API I have been trying to upload video to you tube using AuthSub.I cant use Zend here so the client library is out of the question.I am following following steps: 1.Redirecting the user to the authorization page. 2.Getting the token from the redirection. 3.Getting the AuthSubSession token from https://www.google.com/accounts/AuthSubSessionToken which i successfully extracted. 4.Using the token from the step 3 to upload metadata of videos to the site through url ttp://gdata.youtube.com/action/GetUploadToken after which i will get the URL to upload the video. The problem is on calling http://gdata.youtube.com/action/GetUploadToken i get a NoLinkedYoutube account error. I tried creating a fresh account as well,But to no avail.Can any one figure out what i am doing wrong here?Please help me i only have this week to solve this. Regards Himanshu Sharma
{ "language": "en", "url": "https://stackoverflow.com/questions/7558179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compute range over list of `xts` objects In R, I've got a list of xts objects and I want to compute the range of the time index over all the items in the list. I can't find a smooth way to do it though, it keeps losing the classes of the objects & becoming raw numeric vectors. For example (my list is called states, it's indexed by a GMT POSIXct): > c(min(sapply(states, start)), max(sapply(states, end))) [1] 1252714110 1315785360 > range(sapply(states, function(x) range(index(x)))) [1] 1252714110 1315785360 It's a hassle to convert those back to POSIXct, I'm doing it like so: minmax <- range(sapply(states, function(x) range(index(x)))) epoch <- as.POSIXct(0, origin="1970-01-01", tz="GMT") rg <- as.POSIXct(minmax, origin="1970-01-01", tz="GMT") Advice appreciated! A: Use lapply to find the index range of each list element. Then use do.call to find the range of the list: do.call(range, lapply(states, function(x) range(index(x)))) or, if you prefer a functional paradigm: Reduce(range, Map(function(x) range(index(x)), states)) sapply doesn't work because the simplification process converts the output to an atomic vector or matrix with a single type of either: NULL < raw < logical < integer < real < complex < character < list < expression, in that order of precedence.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sort a table fast by its first column with Javascript or jQuery I have a table which is dynamically populated from FullCalendar. The problem is that FullCalendar does not care about its original order. The table looks like this: <table id="caltbl"> <thead> <tr> <th> </th> <th> Date </th> <th> hours </th> ... </tr> </thead> <tbody> <tr> <td class="sortnr">1</td> <td></td> ... </tr> <tr> <td class="sortnr">3</td> <td></td> ... </tr> <tr> <td class="sortnr">2</td> <td></td> ... </tr> <tr> <td class="sortnr">4</td> <td></td> ... </tr> </tbody> </table> The first of each row contains the number on which the table should be sorted. I had this code to sort it: var rows = $('#caltbl > tbody').children('tr').detach(); for (var counter = 1; counter<=rows.length; counter++) { $(rows).each(function(index) { if ($(this).find(".sortnr").text()==counter){ $('#caltbl > tbody:last').append($(this)); } }); } This works fine in Firefox but causes me a major headache in Internet Explorer because there are more than 500 items and it hangs. I could add a setTimeout but that would not fix the real problem. The sorting is slow. What is a faster way to sort this? Instead of having to start from the <table> html, as I said it gets populated dynamically so I have an Array which contains the html. 1 item per <tr> (unsorted) A: Try an approach like this: http://jsfiddle.net/qh6JE/ var rows = $('#caltbl > tbody').children('tr').get(); // creates a JS array of DOM elements rows.sort(function(a, b) { // use a custom sort function var anum = parseInt($(a).find(".sortnr").text(), 10); var bnum = parseInt($(b).find(".sortnr").text(), 10); return anum-bnum; }); for (var i = 0; i < rows.length; i++) { // .append() will move them for you $('#caltbl > tbody').append(rows[i]); } A: Fiddle: http://jsfiddle.net/qNwDe/ I've written an efficient, cross-browser method to sort the rows in your table. Multiple JQuery selectors in double loops are causing serious performance issues (as you've noticed), hence I've get rid of JQuery. An additional advantage of my function is that it doesn't mind missing index numbers. I'm currently referring to the first cell of each row, rather than getting the element by class name. If you want to refer by classname, I will alter my function: function sortTable(){ var tbl = document.getElementById("caltbl").tBodies[0]; var store = []; for(var i=0, len=tbl.rows.length; i<len; i++){ var row = tbl.rows[i]; var sortnr = parseFloat(row.cells[0].textContent || row.cells[0].innerText); if(!isNaN(sortnr)) store.push([sortnr, row]); } store.sort(function(x,y){ return x[0] - y[0]; }); for(var i=0, len=store.length; i<len; i++){ tbl.appendChild(store[i][1]); } store = null; } Call sortTable() whenever you want to sort the table. A: I think there are way too many loops in your case. With 500 items, you would loop 500*500 = 250000 times . Not so many browsers would know how to do that. I suggest using the native array.sort() method of javascript to do the sorting based on a custom "comparison function". Here is how it could be done (and most probably it can be optimized) : http://jsfiddle.net/tsimbalar/Dw6QE/. The idea is to sort a list of rows comparing the sortNumber value ... A: We can use jquery insead of javascript for the same thing answered by Rob W. It will not affect any performance issue like Multiple JQuery selectors in double loops. var $tbody = $('table tbody'); $tbody.find('tr').sort(function (a, b) { var tda = $(a).find('td:eq(' + ColumnIndex + ')').text(); // Use your wished column index var tdb = $(b).find('td:eq(' + ColumnIndex + ')').text(); // Use your wished column index // if a < b return 1 return tda > tdb ? 1 // else if a > b return -1 : tda < tdb ? -1 // else they are equal - return 0 : 0; }).appendTo($tbody); Use < instead of >for descending. FIDDLE A: Check out this http://square.github.com/crossfilter/ the team at Square has used a clever bitmap index technique to allow filtering 5.3MB data in <30ms ... I am not sure if this helps, but it is a very interesting technique
{ "language": "en", "url": "https://stackoverflow.com/questions/7558182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Is there a way to prevent SQL Server from Validating the SQL in a stored procedure during CREATE / ALTER One aspect of our system requires our SQL Server instance to talk to a MySQL Server via a linked Server Connection. MSSQL -> LinkedServer(MSDASQL ODBC Provider) -> MySQL ODBC Connector -> MySQL DB The Table on the linked server is called in a SPROC along the lines of CREATE PROCEDURE DoStuff AS SELECT a.ID, a.Name, b.OtherProperty FROM MyDatabase..MyTable a JOIN LINKSRVR...OtherTable b ON a.ID = b.ID GO The problem is that the MySQL database lives on another network, only accessible by VPN & that the CREATE or ALTER statement breaks with the following error unless the VPN is active. The OLE DB provider "MSDASQL" for linked server "LINKSRVR" reported an error. The provider did not give any information about the error. Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "LINKSRVR". Is there anyway to force SQL Server to just go ahead and create the SPROC with the SQL I tell it and not to try and validate if the LinkedServer is up/down. A: You'd have to "hide" the offending SQL from the compiler by placing it in a string and executing it as dynamic SQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Toggle several divs What I would like to do is show a couple of divs out of a selection so that the user get a almost tailor made page the idea is that there are several divs IE: <div id="vid1">some content</div> <div id="vid2">some content</div> <div id="vid3">some content</div> so if the user goes to a page with a name like index.html#vid1 it shows the corresponding div but if they go to the same page but through index.html#vid1&vid3 it shows more than one corresponding divs i don't know if the hash tag is the best way to go about this but i am open to any type of system as long as it works properly. A: You can get the hash with window.location.hash and then just split this by the & character. Then you have an array containing the div names over which you can iterate. With document.getElementById() you can access the according <div> and do whatever you want with it A: You need to change the display CSS of the DIV to none via JavaScript or similar method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective-C type not found I'm trying to compile my Objective-C application but it fails saying "Unknown type name 'OpenGLView'". Now I know what this means but the weird thing is I'm convinced I'm importing it just fine. #import <Foundation/Foundation.h> #import "OpenGLView.h" #import "Frame.h" #import "Mesh2.h" #import "Vector2.h" #import "StaticRigidBody.h" #import "DynamicRigidBody.h" @interface PhysicsApplicationController : NSObject { Frame* frame; OpenGLView* view; } It fails on line 11 of this sample. You can see I import it on line 2. The thing which I can't get my head around though is the same import works completely fine in this segment. #import <UIKit/UIKit.h> #import "OpenGLView.h" @interface PhysicsAppDelegate : UIResponder <UIApplicationDelegate> { OpenGLView* _glView; } Both source files for the two segments are in the same directory. I have no idea what is going on. [EDIT] Content of OpenGLView.h #import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> #include <OpenGLES/ES2/gl.h> #include <OpenGLES/ES2/glext.h> #import "PhysicsApplicationController.h" @interface OpenGLView : UIView { CAEAGLLayer* _eaglLayer; EAGLContext* _context; GLuint _colorRenderBuffer; GLuint _positionSlot; GLuint _colorSlot; PhysicsApplicationController* _physicsController; } typedef struct { float position[3]; float color[4]; } Vertex; - (void)renderFrame:(Frame*)frame; - (void)drawObjectsInFrame:(Frame*)frame; - (void)setupVBOsWithVertices:(Vertex*)vertices Indices:(GLubyte*)indices; - (void)setPhysicsController:(PhysicsApplicationController*)controller; @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7558189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to use jquery each loop in ajax I need output like below code, where each set of div is coming trough ajax as follows, i am getting div id dynamic as slide1, slide2 via jquery each function. assume that there is no anchor tag at start so how can i get href="#pix1", href="#pix2" ? every time href value is increasing by 1 thanks help is really appreciated <div id="slide1"> <ol> <li class="firstlist"><a href="#"><b>start</b></a></li> <li><a href="#pix1"><img src="images/thumbs/accesories/pic1.jpg"></a></li> <li><a href="#pix2"><img src="images/thumbs/accesories/pic2.jpg"></a></li> <li><a href="#pix3"><img src="images/thumbs/accesories/pic3.jpg"></a></li> <li><a href="#pix4"><img src="images/thumbs/accesories/pic4.jpg"></a></li> <li><a href="#pix5"><img src="images/thumbs/accesories/pic5.jpg"></a></li> <li><a href="#pix6"><img src="images/thumbs/accesories/pic6.jpg"></a></li> <li><a href="#pix7"><img src="images/thumbs/accesories/pic7.jpg"></a></li> <li class="lastlist"><a href="#"><b>last</b></a></li> </ol> </div> <div id="slide2"> <ol> <li class="firstlist"><a href="#"><b>start</b></a></li> <li><a href="#pix2"><img src="images/thumbs/accesories/pic2.jpg"></a></li> <li><a href="#pix3"><img src="images/thumbs/accesories/pic3.jpg"></a></li> <li><a href="#pix4"><img src="images/thumbs/accesories/pic4.jpg"></a></li> <li><a href="#pix5"><img src="images/thumbs/accesories/pic5.jpg"></a></li> <li><a href="#pix6"><img src="images/thumbs/accesories/pic6.jpg"></a></li> <li><a href="#pix7"><img src="images/thumbs/accesories/pic7.jpg"></a></li> <li><a href="#pix8"><img src="images/thumbs/accesories/pic8.jpg"></a></li> <li class="lastlist"><a href="#"><b>last</b></a></li> </ol> </div> and in jquery i am tring something like as follows $("div").each(function(si){ var slideindex = si+1 $(this).attr('id', 'slide'+slideindex); //I am successful here to get div id slide 0, slide1 }); $('div ol li a').each(function() { //how should i code here }); A: Like this: $(this).attr('href'); Inside the loop that is A: check this demo. http://www.balam.in/personal/stackoverflow/each_example.html You have already done that for div. For anchor, its the same. YOu just need to specify href attribute. Is that you are looking for? $('div ol li a').each(function(i) { var anchorindex = i+1 $(this).attr('href', '#pix'+anchorindex); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7558195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unbind or remove functions? I'm having some difficulty with the accordion UI. I want a set of divs to be an accordion when the window is a certain size (below 1024) and just divs (above 1024) The code that I have works if the window is greater than 1024 and then I resize to a smaller window. But if I expand the window it won't turn off the accordion. Here's the code, what am I not getting right? <script type="text/javascript"> var width = $(window).width(); $(document).ready(function() { if (width < 1024){ $('#accordion').accordion(); } }); $(window).resize(function() { var width = $(window).width(); if (width < 1024) { $('#accordion').accordion(); } if (width > 1024) { $('.accordion').remove(); }}); </script> A: Two things in the code you posted: * *The method to get rid of an accordion is not .remove() but .destroy(). *You changed from an id selector ("#accordion") to a class selector (".accordion"). It's possible for that to work--assuming the elements have both that id and that class--but not recommended; you should be consistent about the selectors within a given function/context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fetch request returns an array of objects - NSFetchedResultsController returns null req = [[NSFetchRequest alloc] init]; // entity ent = [NSEntityDescription entityForName:@"Medicine" inManagedObjectContext:context]; [req setEntity:ent]; // predicate pred = [NSPredicate predicateWithFormat:@"date > %@",referenceDate]; [req setPredicate:pred]; // sort descriptor sorter = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]; [req setSortDescriptors:[NSArray arrayWithObjects:sorter, nil]]; NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:req managedObjectContext:context sectionNameKeyPath:@"date" cacheName:@"asdsad"]; NSLog(@"%@",[frc fetchedObjects]); // returns (null) //NSArray *frc = [context executeFetchRequest:req error:nil]; //NSLog(@"%@",frc); // returns 4 objects As you can see by my code I've got two different bits at the end. The first code (uncommented) returns null in the NSLog. The second code (commented) returns an array of 4 objects from the context. Any reason why this is happening? Am I doing something wrong? A: Because you need to do one more thing: performFetch. Here's the details in the docs: performFetch: Executes the receiver’s fetch request. * *(BOOL)performFetch:(NSError **)error Parameters error If the fetch is not successful, upon return contains an error object that describes the problem. Return Value YES if the fetch executed successfully, otherwise NO. Discussion After executing this method, you can access the receiver’s the fetched objects with the property fetchedObjects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP.NET MVC. How to return json with html I have a controller method (Method1) that should return JsonResult with the following properties: return Json(new { someProperty1 = 'value1', someProperty2 = 'value2', html = "html_code_that_will_be_rendered" }); As you can see it has 'html' property. This html should be generated as a result (HTML) of another controller method (Method2). The question is how can I get a rendered HTML code of Method2 in Method1 of the controller? A: If you mean, how can you pass the html variable as say: <p>Some actual html</p> and then output it on method1, you would need to assign the result of the call to method2 to something you can access, eg. myHtml and then use the HTML.Raw() function like this: @Html.Raw(myHtml) This will avoid the Razor view engine encoding all your html
{ "language": "en", "url": "https://stackoverflow.com/questions/7558210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create an ajax call on jQuery slide change? How do I call this Jquery ajax call on jQuery slide change? function callpage() { $('#formcontent').empty().html('<p style="margin-top:20px;text-align:center;font-family:verdana;font-size:14px;">Vent venligst, henter webhosts.</p><p style="margin-top:20px;margin-bottom:20px;text-align:center;"><img src="../images/ajax.gif" /></p>'); var form = $(this).closest('form'); $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), success:function(msg){ $('#formcontent').html(msg); } } My jQuery slider code: $("#slider").slider({ value:'', min: 0, max: 5000, step: 250, slide: function(event, ui) { if (ui.value == $(this).slider('option', 'max')) { $(ui.handle).html('Ubegrænset'); $('#sliderValueplads').val('99999'); } else { $(ui.handle).html(ui.value + ' MB'); $('#sliderValueplads').val(ui.value); } } }).find('a').html($('#slider').slider('value')); $('#sliderValueplads').val($('#slider').slider('value')); My new slider code: $("#slider").slider({ value:'', min: 0, max: 5000, step: 250, stop: function(_, ui){ callpage(); }, slide: function(event, ui) { if (ui.value == $(this).slider('option', 'max')) { $(ui.handle).html('Ubegrænset'); $('#sliderValueplads').val('99999'); } else { $(ui.handle).html(ui.value + ' MB'); $('#sliderValueplads').val(ui.value); } } }).find('a').html($('#slider').slider('value')); The problem is that the ajax call is not made, but the HTML is replaced. Which is a little strange because I just have tested the callpage with this $('#left input:checkbox').change(callpage); and the callpage did work as expected A: If you mean when the user stops moving the slider then bind it to the stop event in your constructor. stop: function(_, ui){ callpage(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SWT TreeViewer, trim string text in columns I'm using a SWT TreeViewer to show some paths, is it possible to trim the path string to insert "..." (points) when the path is too long a is not fully visible in the tree column? Something like this: Thanks in advance A: Ok, reading the TreeColumn code I have noticed that the TreeViewer add ellipsis (...) to the columns automatically, but only if the column index is > 0. So column 0 strings are not truncated. Try all eclipse views that uses a TreeView. Really I don't understand this behavior. A: Yes, you can use DecoratingLabelProvider over the LabelProvider which shows full paths (which is presumably what you have at the moment).
{ "language": "en", "url": "https://stackoverflow.com/questions/7558213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Autoheight of vertical column header in C# using DevXpress I used this http://www.devexpress.com/Support/Center/p/Q233111.aspx (the code is in VB so I converted it to C#) to get vertical column headers. I get the vertical headers but my problem is some of them doesn't fit, so they are not fully visible. Is it possible to autoheight the column headers ? (all height set to max height) A: As shown in Devexpress support center i think this will be the solution to your problem First add an helper class to your solution public class AutoHeightHelper { GridView view; public AutoHeightHelper(GridView view) { this.view = view; EnableColumnPanelAutoHeight(); } public void EnableColumnPanelAutoHeight() { SetColumnPanelHeight(); SubscribeToEvents(); } private void SubscribeToEvents() { view.ColumnWidthChanged += OnColumnWidthChanged; view.GridControl.Resize += OnGridControlResize; view.EndSorting += OnGridColumnEndSorting; } void OnGridColumnEndSorting(object sender, EventArgs e) { view.GridControl.BeginInvoke(new MethodInvoker(SetColumnPanelHeight)); } void OnGridControlResize(object sender, EventArgs e) { SetColumnPanelHeight(); } void OnColumnWidthChanged(object sender, DevExpress.XtraGrid.Views.Base.ColumnEventArgs e) { SetColumnPanelHeight(); } private void SetColumnPanelHeight() { GridViewInfo viewInfo = view.GetViewInfo() as GridViewInfo; int height = 0; for (int i = 0; i < view.VisibleColumns.Count; i++) height = Math.Max(GetColumnBestHeight(viewInfo, view.VisibleColumns[i]), height); view.ColumnPanelRowHeight = height; } private int GetColumnBestHeight(GridViewInfo viewInfo, GridColumn column) { GridColumnInfoArgs ex = viewInfo.ColumnsInfo[column]; GraphicsInfo grInfo = new GraphicsInfo(); grInfo.AddGraphics(null); ex.Cache = grInfo.Cache; bool canDrawMore = true; Size captionSize = CalcCaptionTextSize(grInfo.Cache, ex as HeaderObjectInfoArgs, column.GetCaption()); Size res = ex.InnerElements.CalcMinSize(grInfo.Graphics, ref canDrawMore); res.Height = Math.Max(res.Height, captionSize.Height); res.Width += captionSize.Width; res = viewInfo.Painter.ElementsPainter.Column.CalcBoundsByClientRectangle(ex, new Rectangle(Point.Empty, res)).Size; grInfo.ReleaseGraphics(); return res.Height; } Size CalcCaptionTextSize(GraphicsCache cache, HeaderObjectInfoArgs ee, string caption) { Size captionSize = ee.Appearance.CalcTextSize(cache, caption, ee.CaptionRect.Width).ToSize(); captionSize.Height++; captionSize.Width++; return captionSize; } public void DisableColumnPanelAutoHeight() { UnsubscribeFromEvents(); } private void UnsubscribeFromEvents() { view.ColumnWidthChanged -= OnColumnWidthChanged; view.GridControl.Resize -= OnGridControlResize; view.EndSorting -= OnGridColumnEndSorting; } } Then on your form you should make the helper class to Handle GridView's columns resize events by adding the following lines of code AutoHeightHelper helper; private void OnFormLoad(object sender, EventArgs e) { helper = new AutoHeightHelper(gridView1); helper.EnableColumnPanelAutoHeight(); } private void OnFormClosing(object sender, FormClosingEventArgs e) { helper.DisableColumnPanelAutoHeight(); } Hope this helps...
{ "language": "en", "url": "https://stackoverflow.com/questions/7558215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Trying to make regex JSLint compliant I'm trying to make this regex: var url_pattern = /(\()((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\))|(\[)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\])|(\{)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\})|(<|&(?:lt|#60|#x3c);)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(>|&(?:gt|#62|#x3e);)|((?:^|[^=\s'"\]])\s*['"]?|[^=\s]\s+)(\b(?:ht|f)tps?:\/\/[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]+(?:(?!&(?:gt|#0*62|#x0*3e);|&(?:amp|apos|quot|#0*3[49]|#x0*2[27]);[.!&',:?;]?(?:[^a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]|$))&[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]*)*[a-z0-9\-_~$()*+=\/#[\]@%])/img; JSLint compliant. It's complaining about the use of . and not escaping [ and ]. (Source: http://jmrware.com/articles/2010/linkifyurl/linkify.html) edit: Not that big of a deal, I just did it in the backend anyway. I'd still like a version (since I'm building a rendering engine-y thing, but this isn't super urgent anymore). A: Replace: var url_pattern = /(\()((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\))|(\[)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\])|(\{)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(\})|(<|&(?:lt|#60|#x3c);)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]+)(>|&(?:gt|#62|#x3e);)|((?:^|[^=\s'"\]])\s*['"]?|[^=\s]\s+)(\b(?:ht|f)tps?:\/\/[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]+(?:(?!&(?:gt|#0*62|#x0*3e);|&(?:amp|apos|quot|#0*3[49]|#x0*2[27]);[.!&',:?;]?(?:[^a-z0-9\-._~!$&'()*+,;=:\/?#[\]@%]|$))&[a-z0-9\-._~!$'()*+,;=:\/?#[\]@%]*)*[a-z0-9\-_~$()*+=\/#[\]@%])/img; with var url_pattern = new RegExp("([\\.+])", "img"); // simplified for my sanity With the string properly escaped, \ to \\ EDIT: var a = new RegExp("(\\()((?:ht|f)tps?:\\/\\/[a-z0-9\\-._~!$&'()*+,;=:\\/?#[\\]@%]+)(\\))|(\\[)((?:ht|f)tps?:\\/\\/[a-z0-9\\-._~!$&'()*+,;=:\\/?#[\\]@%]+)(\\])|(\\{)((?:ht|f)tps?:\\/\\/[a-z0-9\\-._~!$&'()*+,;=:\\/?#[\\]@%]+)(\\})|(<|&(?:lt|#60|#x3c);)((?:ht|f)tps?:\\/\\/[a-z0-9\\-._~!$&'()*+,;=:\\/?#[\\]@%]+)(>|&(?:gt|#62|#x3e);)|((?:^|[^=\\s'\"\\]])\\s*['\"]?|[^=\\s]\\s+)(\\b(?:ht|f)tps?:\\/\\/[a-z0-9\\-._~!$'()*+,;=:\\/?#[\\]@%]+(?:(?!&(?:gt|#0*62|#x0*3e);|&(?:amp|apos|quot|#0*3[49]|#x0*2[27]);[.!&',:?;]?(?:[^a-z0-9\\-._~!$&'()*+,;=:\\/?#[\\]@%]|$))&[a-z0-9\\-._~!$'()*+,;=:\\/?#[\\]@%]*)*[a-z0-9\\-_~$()*+=\\/#[\\]@%])", "gim"); The above passes jslint A: Here is a version with escaped [ characters: var url_pattern = /(\()((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#\[\]@%]+)(\))|(\[)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#\[\]@%]+)(\])|(\{)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#\[\]@%]+)(\})|(<|&(?:lt|#60|#x3c);)((?:ht|f)tps?:\/\/[a-z0-9\-._~!$&'()*+,;=:\/?#\[\]@%]+)(>|&(?:gt|#62|#x3e);)|((?:^|[^=\s'"\]])\s*['"]?|[^=\s]\s+)(\b(?:ht|f)tps?:\/\/[a-z0-9\-._~!$'()*+,;=:\/?#\[\]@%]+(?:(?!&(?:gt|#0*62|#x0*3e);|&(?:amp|apos|quot|#0*3[49]|#x0*2[27]);[.!&',:?;]?(?:[^a-z0-9\-._~!$&'()*+,;=:\/?#\[\]@%]|$))&[a-z0-9\-._~!$'()*+,;=:\/?#\[\]@%]*)*[a-z0-9\-_~$()*+=\/#\[\]@%])/img; It still complains about "insecure ^", which is difficult to fix because it’s essentially implying that you should write out all the characters you want to match instead of listing the ones you don’t want to match. Which of course defeats the purpose of ^. So you can ignore this warning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I do this layout in HTML & CSS? How do I do the following layout: / header width:100%, height: 100px (this is overlayed) / ///////////////////////////////////////////////////////////////////////////// / / / / div width: all available, height: 100% / div width: 200px; height: 100% / Basically, the iFrame width should cover the blue background here: http://jsfiddle.net/VaDTZ/3/ A: You can use jQuery to achieve this easily, This will ensure that both your primary div, and your sidebar div are the same height. $(document).ready(function({ var x = $('#primary').height(); $('#sidebar').css('height', x); }); Hope this helps A: here is something working :) http://jsfiddle.net/simoncereska/XQJPA/3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7558219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lucene: Iterate all entries I have a Lucene Index which I would like to iterate (for one time evaluation at the current stage in development) I have 4 documents with each a few hundred thousand up to million entries, which I want to iterate to count the number of words for each entry (~2-10) and calculate the frequency distribution. What I am doing at the moment is this: for (int i = 0; i < reader.maxDoc(); i++) { if (reader.isDeleted(i)) continue; Document doc = reader.document(i); Field text = doc.getField("myDocName#1"); String content = text.stringValue(); int wordLen = countNumberOfWords(content); //store } So far, it is iterating something. The debug confirms that its at least operating on the terms stored in the document, but for some reason it only process a small part of the stored terms. I wonder what I am doing wrong? I simply want to iterate over all documents and everything that is stored in them? A: Firstly you need to ensure you index with TermVectors enabled doc.add(new Field(TITLE, page.getTitle(), Field.Store.YES, Field.Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS)); Then you can use IndexReader.getTermFreqVector to count terms TopDocs res = indexSearcher.search(YOUR_QUERY, null, 1000); // iterate over documents in res, ommited for brevity reader.getTermFreqVector(res.scoreDocs[i].doc, YOUR_FIELD, new TermVectorMapper() { public void map(String termval, int freq, TermVectorOffsetInfo[] offsets, int[] positions) { // increment frequency count of termval by freq freqs.increment(termval, freq); } public void setExpectations(String arg0, int arg1,boolean arg2, boolean arg3) {} });
{ "language": "en", "url": "https://stackoverflow.com/questions/7558220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP/MySQL relational database problem. Filter to match options I have a table of people who need help, and a table of people who give help. They each have a one to many relationship with further tables for work hours, hobbies and activities. My problem is that when I am creating a filter in order to match them up I cant figure out the correct collection of queries to match them fully. function buildfilter(){ if($_GET['filter']=="clear" || $_GET['filt_age']<>""){$_SESSION['filter']="";} if($_SESSION['filter']==""){$query="SELECT `personal_assistant`.*,`hobby`.* FROM `personal_assistant`,`hobby`,`citizen`,`citizenhobby` WHERE `personal_assistant`.`status`='active'";} if($_GET['filt_car']=="1"){$query.=" AND `personal_assistant`.`licence`='1' AND `personal_assistant`.`car`='1'";} if($_GET['filt_age']<>"any" AND $_GET['filt_age']<>""){ $today=date ( 'Y-m-j' , time()); $ages = explode("-", $_GET['filt_age']); $ages[0]=strtotime ('-'.$ages[0].' year', strtotime($today)); $ages[1]=strtotime ('-'.$ages[1].' year', strtotime($today)); $query.=" AND `personal_assistant`.`dob`>='".$ages[1]."' AND `personal_assistant`.`dob`<='".$ages[0]."'"; } if($query<>""){ $query.=" AND (`personal_assistant`.`id`=`hobby`.`pa_id` AND `hobby`.`hobby_option_id`=`citizenhobby`.`hobby_option_id` AND `citizen`.`id`=`citizenhobby`.`ci_id` AND `citizen`.`id`='".$_GET['edcit']."')"; $query.=" AND (`personal_assistant`.`id`=`activity`.`pa_id` AND `activity`.`activity_option_id`=`citizenactivity`.`activity_option_id` AND `citizen`.`id`=`citizenactivity`.`ci_id` AND `citizen`.`id`='".$_GET ['edcit']."')"; } if($query==""){$query=$_SESSION['filter'];} if($_SESSION['filter']==""){$_SESSION['filter']=$query;} return $query; } That function so far would correctly return any personal assistants that have atleast one hobby that matches and atleast one activity that matches. What I cannot do however is make it only return people who match all of the activities instead of just one as these are all required. The query string looks like this so far: SELECT `personal_assistant`.*, `hobby`.* FROM `personal_assistant`, `hobby`, `citizen`, `citizenhobby` WHERE `personal_assistant`.`status`='active' AND ( `personal_assistant`.`id`=`hobby`.`pa_id` AND `hobby`.`hobby_option_id`=`citizenhobby`.`hobby_option_id` AND `citizen`.`id`=`citizenhobby`.`ci_id` AND `citizen`.`id`='6' ) A: multiple queries would achieve it
{ "language": "en", "url": "https://stackoverflow.com/questions/7558224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple objects subscribing to an NSNotification (Objective-c) I have an Objective-c class MyClass that subscribes to MyNSNotification. There are multiple instances of MyClass in my application. Hence multiple objects receive the notification. Is there a way to "filter" notifications for a particular object? I imagine doing a check in the selector. I'm just not sure how to set it up. A: Use userInfo for that purpose issuing notification. Recieving one check userInfo to decide if this notification targeted here or not. Sometimes enough to know who sent notification. Use object property for that. Consult class reference http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7558225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp net mvc and javascript response I had a javascript that needs to do two things: 1. Send data to be updated in database 2. Update my html form place in show mode. 3. Update the row of my table to reflect updated data. My javascript do only 1 and 2: $(".form-commands .save").live("click", function () { var f = $(".form-edit"); var sf = f.serialize(); $.post(this.href, sf, function (response) { f.html(response); }); // I need to do something here to update the html table row... return false; }); I think that a solution is to call another action that will render only the table row elements. How can I do this? -- The table row was created something like this: <tr id="h62"> <td>Ford</td> <td>Focus</td> </tr> where 62 is the "id" of this record. Working code, but ugly: $(".form-commands .save").live("click", function () { var f = $(".form-edit"); var sf = f.serialize(); var handle = $(".form-edit #Handle")[0].value; var itemLink = this.attributes["edititem"].value; var row = $("#grid #h" + handle); $.post(this.href, sf, function (response) { $("#form-edit").html(response); $.get(itemLink, sf, function (response) { row.replaceWith(response); }); }); return false; }); A: You need to do something like this: $(".form-commands .save").live("click", function (evt) { //Capture the jQuery event object and call preventDefault() to stop the default click action evt.preventDefault(); var f = $(".form-edit"); var sf = f.serialize(); $.post(this.href, sf, function (response) { f.html(response); }); //UPDATE THE ROWS $('#h62 td:eq(0)').text(newVehicleMakeName); $('#h62 td:eq(1)').text(newVehicleModelName); }); I am not sure from your code where the vehicle data is coming from. If you are passing it back from your controller then you will need to move this line into your success callback. Also, you should generally never return false, you should capture the jQuery event as a param and call preventDefault(). If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior. This is what was causing your problem, not because you were using click vs submit. The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire. A: Well I would just reload the page or recall the ajax routine (whichever is applicable) to reload the data, there is no straightforward method to do this. In fact I was not aware of the method you used (f.html(response)), i am still skeptical about that solution :) Well, if you really just want to update that single row: 1) You need to know to know the updated row's id in your javascript code. This value is "h62" (without quotes) in this example. 2) Give class names to your TDs, e.g. <tr id="h62"> <td class="brand">Ford</td> <td class="model">Focus</td> </tr> 3) Update using jquery. Let's say you hold the id of the row in a variable named "rowId": $('#'+rowId).find('.brand').html(response.brand); $('#'+rowId).find('.model').html(response.model); This will conclude the process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Need to read in an unspecified number into an array ok so i need to fill an array with integers based on a number that i specify in another part of the program. This is what I have so far: public abstract class Polygon implements Shape { //numSides is the number of sides in a polygon int numSides; //Vertices[] is the array of vertices, listed in counter-clockwise sense Point[] Vertices; public Polygon(Point[] Vertices){ //THIS IS WHERE I NEED THE HELP, DONT KNOW WHAT TO PUT IN HERE } public Point getPosition(){ return this.Vertices[0]; } } Thank you in advanced. Sorry for the lack of information. Yes this is for a class. I can see how an ArrayList would probably be better. The program its self has an interface, Shape, which gets implemented by a class Point and a class Polygon, which them has a class that extends that, rectangle. The idea is to put the number of vertices into an array and return the value at Vertices[0] as the position of the polygon. The rest of this class looks like this: public abstract class Polygon implements Shape { //numSides is the number of sides in a polygon int numSides; Point[] Vertices; public Polygon(Point[] Vertices){ //your code } public Point getPosition(){ return this.Vertices[0]; } } Not sure if you need to see the rest of the program. thank you again. A: You are not being very clear in what you need, but I guess you want help on your constructor: public Polygon(Point[] Vertices){ this.Vertices = Vertices; this.numSides = Vertices.length; } A: Maybe this will guide you in the right direction: public static void main(String[] args) { System.out.print("how many? "); Scanner in = new Scanner(System.in); int size = in.nextInt(); int[] numbers = new int[size]; System.out.println("Enter the " + size + " numbers."); for (int i = 0; i < size; i++) { System.out.print(" " + (i + 1) + ": "); numbers[i] = in.nextInt(); } System.out.println("Numbers entered: "); for (int number : numbers) { System.out.print(number); System.out.print(' '); } } As the others have said, more detail in the question will bring better detail in answers. Also, this smells like homework. If so, you should tag it as such. A: As your question is not clear I am assuming that you that you just want to fill your array with random integers. Here first of all you need to specify size of the array, and the best place to do this is your constructor. public Polygon(Point[] Vertices){ Vertices = new Point[i]; //based on a number i specified in another part of the program // Now you can use the scanner class to fill your array, see Ryan Stewart's answer for details on using Scanner class. } I hope this helps :) cheers!!! A: I think, you need an elegant array copy: public Polygon(Point[] Vertices) { if (Vertices == null || Vertices.length == 0) { return; } int i = Vertices.length; this.Vertices = new Point[i]; System.arraycopy(Vertices, 0, this.Vertices, 0, i); } After, you can iterate over your array: ... for (Point point : this.Vertices) { // Use point } ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7558230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: sendBroadcast(intent) gives a null pointer exception This is my second post today as fixing the 1st post lead to another problem which I am really struggling on. I want to use Broadcasts and intent to send data packets back from a service to the UI. I managed to bind and start the service successfully see my other post if you want history and code The null pointer exception comes on the sendBroadcast() inside the service. The service class does have its constructor re-called after binding the UI to the service. This happens from another class so Context can not be easily used. So I guess the sendBroadcast has no-where to go :( I suspect this is my problem...the re-calling of the Service constructor after the initial binding. I have onDestroy, onPause and onResume covered with binding an unbinding. Any ideas or suggestion would be great or maybe I am just going about this wrong is there another way? EDIT The previous problem of binding is now solved and due to me being new to the forums a slight delay in accepting the answer...sorry. The class diagram is like this (it is ported C#code) Activity doBind (on Curve.class)---> Activity starts a worker class (not treated as a service) Comm.class with a Handler for some comms--> the Comm starts another worker class --> previous worker class finally calls new Curve.class. It is this last stage Curve.class where the sendBroadcastReceiver() then throws a nullpointer ref becasue the binder is lost. I tested the broadcastreceiver just with a simple timer cutting out the worker classes in between and it works fine. Problems start when the Curve.class is recalled later further down the hierarchy and the binder gets nulled or "lost". I removed all references of the binder from Curve except in onBind(). This might not be a good idea. Again the code below does work if used with a simple timer started directly from the UI (no other worker classes). Some more code here: The service public class Curve extends Service { private NewCurvePointEventArgs newpoint = null; private static final String TAG = "Curve"; Intent intent; int counter = 0; @Override public void onCreate() { super.onCreate(); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub IBinder mBinder = new LocalBinder<Curve>(this); return mBinder; } @Override public void onStart(Intent intent, int startId) { } @Override public void onDestroy() { } public Curve(){ } private void refreshintent(NewCurvePointEventArgs tmp) { ArrayList<String> thepoint = new ArrayList<String>(); thepoint.add()//various things added here Bundle bundle = new Bundle(); // add data to bundle bundle.putStringArrayList("New_Point", thepoint); intent = new Intent(); intent.setAction(NEWCURVE_POINT); intent.putExtra("NEW_POINT", bundle sendBroadcast(intent); } The activity has this code now. the doBind() is called after the onCreate of the activity. private BroadcastReceiver CurveReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Curve.NEWCURVE_POINT)) { displaynewpoint(intent); } } }; private ServiceConnection CurveServiceConncetion = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub CurveService = ((LocalBinder<Curve>) service).getService(); } @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub CurveService = null; } }; @Override public synchronized void onResume() { super.onResume(); if(D) Log.e(TAG, "+ ON RESUME +"); } @Override public synchronized void onPause() { super.onPause(); if(D) Log.e(TAG, "- ON PAUSE -"); } @Override public void onStop() { super.onStop(); if(D) Log.e(TAG, "-- ON STOP --"); } @Override public void onDestroy() { super.onDestroy(); if(D) Log.e(TAG, "--- ON DESTROY ---"); unregisterReceiver(CurveReceiver); unbindService(CurveServiceConncetion); } public void doBind(){ Boolean tmp; tmp = bindService(new Intent(this, Curve.class), CurveServiceConncetion, Context.BIND_AUTO_CREATE);//Context.BIND_AUTO_CREATE IntentFilter filter = new IntentFilter(Curve.NEWCURVE_POINT); registerReceiver(CurveReceiver, filter); } This problem to me is because the Curve.class has its constructor called again after the initial doBind(). Surely there must be a way around this otherwise I have to load my worker classes closer in hierarchy to the UI with the code from Curve.class??? EDIT Curve is an object that processes data, constants etc sent from an external machine and contains the processed data in arrays. The logCat did of course exist I just wasn't looking in the right place here it is ARN/System.err(10505): java.lang.NullPointerException WARN/System.err(10505): at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:271) WARN/System.err(10505): at pi.droid.Core.Curve.refreshintent(Curve.java:206) WARN/System.err(10505): at pi.droid.Core.Curve.AddPoint(Curve.java:400) WARN/System.err(10505): at pi.droid.Core.Comm.CommMeasure$CommMeasurement.AddPoint(CommMeasure.java:363) WARN/System.err(10505): at pi.droid.Core.Comm.CommMeasure$GenericCommMeasurement.TryProcessData(CommMeasure.java:168) WARN/System.err(10505): at pi.droid.Core.Comm.CommMeasure$CommMeasurement.ProcessData(CommMeasure.java:302) WARN/System.err(10505):at pi.droid.Core.Comm.ClientConnection$timer_tick.run(ClientConnection.java:164) WARN/System.err(10505): at java.util.Timer$TimerImpl.run(Timer.java:289) You can also see the chain of the 2 other worker classes I use. The constructor of Curve is called after the bind from CommMeasure. So this is my problem. Do I need to totally change how my program is set up or is there another way around this? FINAL EDIT This code is brought from c# and Curve used eventhandlers to pass data around. I got rid of all them(java listeners) and used android Handler and broadcastreceiver. It has been suggested that I should pass the CurveService around but this will be problematic as Curve has multiple constructors. The no parameter 1 for the service and then 1 like this public Curve(Unit XUnit, Unit YUnit) { this.Title = "Curve"; this.finished = false; this.XUnit = XUnit; this.YUnit = YUnit; this.YDirection = CurveDirection.Unspecified; } so surely instantiating that would be a problem with CurveService, which has to be like this: public Curve(){} ?? Anyway many thanks for all your help and advice. Final Edit +1..lol The UI creates a new instance of ClientConnection, that in turns creates a new instance of CommMeasure and finally CommMeasure creates a new instance of Curve to access Curve.addpoint. I think this thread and the other linked 1 goes beyond a simple android problem and highlights the difficulties of code porting. Any .Net developer for example reading this will learn some peculiarities of android a lot quicker than I did. There is also good working code in there. Thanks to all who helped especially Justin Breitfeller A: The best thing for you to do is follow the example from the Android APIDemos. A service to be used like you want to use it: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html Look at the Binding class inside of this file to see a class that does binding like you should: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html Finally, if your constructor is being called twice on your service, you aren't binding to your service properly, or perhaps you are unbinding from it and binding to it again unexpectedly. EDIT From the stack trace, it appears that CommMeasure needs to have a reference to the instance of Curve that you receive in onServiceConnected. EDIT 2 If you really want to make your life simple, pass getApplicationContext() to your CommMeasure class and just appContext.sendBroadcast() from that class to send out your point. This will prevent you from requiring a reference to the service in your long-running task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nginx configuration for static sites in root directory, Flask apps in subdirectories I'd like to have a static site in my root public_html directory, then Flask apps in their own subdirectories (e.g. public_html/foo). The static root directory functions as expected. I have spent hours editing the nginx configuration to get the Flask apps working, but always end up back in the same place, namely that the following code always returns 'Bad Config' when I migrate to mysite/foo. I want it to return 'Hello World!' If I alter the nginx configuration so that the server root is in public_html/foo, the Flask applications work as expected (i.e. mysite.com returns 'Hello World!'). In the following configuration, the Flask index still points to mysite.com when I believe it should point to mysite.com/foo /etc/nginx/sites-enabled/mysite upstream frontends { # gunicorn server 127.0.0.1:18000; } server { listen 80; server_name www.mysite.com; rewrite ^/(.*) http://mysite.com$1 permanent; } server { listen 80; server_name mysite.com; server_name_in_redirect off; root /home/ubuntu/public_html/mysite; access_log /home/ubuntu/logs/mysite/access.log; error_log /home/ubuntu/logs/mysite/error.log; location / { index index.html; } location /foo { try_files $uri @foo; } location @foo { proxy_pass http://frontends; break; } } /home/ubuntu/public_html/mysite/foo/foo.py from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/') def index(): return 'Hello World!' @app.route('/foo') def test(): return 'Bad config' @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 if __name__ == '__main__': app.run() /home/ubuntu/public_html/mysite/foo/deploy.py workers = 2 bind = '127.0.0.1:18000' proc_name = 'foo_gunicorn' pidfile = 'foo.pid' Flask is launched with gunicorn -c deploy.py foo:app Update Adding rewrite /foo/(.*) /$1 break; to the nginx location /foo block makes mysite/foo return 'Hello World', however all its links (such as those to the stylesheet from a template) still point to the site root (e.g. mysite/static/style.css instead of mysite/foo/static/style.css) A: Got an answer from mitsuhiko (Flask lead dev): http://flask.pocoo.org/snippets/35/ You need to define a ReverseProxied class in your Flask app and add several proxy-set-header lines to the location /foo block in the nginx config.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Is it possible to ignore Float :: = HexFloat and only see numeric characters? I'm trying to parse the string value "87306E107" using hasNextDouble. This value is a string and should return false when using hasNextDouble but it returns true. I want know if it's possible to have this method return false? The reason I want to treat this value as a string is because I have to wrap it in single quotes for building a dynamic database insert statement. Here is my code below: String data = "87306E107,27.1,xyz,123,01449J204"; Scanner scanner = new Scanner(data); scanner.useDelimiter(","); if (!scanner.hasNextInt() && !scanner.hasNextDouble()){ if (DateUtils.isDate(data)){ //Format date to correct layout data = DateUtils.parseStringDate(data, "yyyy-MM-dd", 0); } //Escape any single quotes data = data.replaceAll("'", "''"); //Wrap in single quotes data = "'" + data + "'"; } A: You can try a string matcher instead of hasNextDouble(): scanner.hasNext("\\d+(\\.\\d+)?")
{ "language": "en", "url": "https://stackoverflow.com/questions/7558251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GWT CellTree Selection of Parent nodes I'm trying to use the GWT CellTree to display a heterogeneous, hierarchical data model. I need to be able to a single selection, but be able to select Parent nodes as well as child nodes. For example, if you look at GWT's own example, you'll see that they only provide one selection model for the leave nodes. I tried to extend their example by providing one selection model for all nodes. However, that seems impossible. So what I ended up with where 3 SelectionModels one for each node type (Composer, PlayList, Song). What am I missing? Thanks in advance. A: In the getNodeInfo function of your TreeViewModel you have to pass the selectionModel to each new DefaultNodeInfo instance at each level. return new DefaultNodeInfo<MyDTO>(dataProvider,new MyDTOCell(),selectionModel,null); and then in the SelectionChangeEventHandler you have do something like this: selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { Object object = selectionModel.getSelectedObject(); if (object instanceof MyRootDTO) { // DO SOMETHING with root level selected node } else if (object instanceof MySecondLevelDTO) { // DO SOMETHING WITH 2. level selected node } // additional levels }); Update: In order to get around the typing problem, you can define an abstract base class which is extended by all your DTO's. public abstract class BaseModel { public static final ProvidesKey<BaseModel> KEY_PROVIDER = new ProvidesKey<BaseModel>() { public Object getKey(BaseModel item) { return item == null ? null : item.getId(); } }; public abstract Object getId(); } In your DTO's you extend the BaseModel and implement the abstract getId() method: public class MyDTO extends BaseModel { @Override public Object getId() { //return unique ID (i.e. MyDTO_1) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert Razor text into string from Model Can anyone help me with some Razor syntax? I have a foreach loop ( shown at the end) and I would like to insert two items of text into a link to produce something like this: <a href="/PDFFiles/Dummy.pdf#page=123" target="_blank"> I hope my question is clear, Many thanks. @foreach (var item in Model) { <a href="/PDFFiles/**item.Filename**.pdf#page=**item.PageNum**" target="_blank"> } A: Just prefix your variable name with @ @foreach (var item in Model) { <a href="/PDFFiles/@(item.Filename).pdf#page=@(item.PageNum)" target="_blank"> } A: @foreach (var item in Model) { <a href="@Html.AttributeEncode(@Url.Content("~/PDFFiles/" + item.Filename + ".pdf#page=" + item.PageNum))" target="_blank">Download</a> }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Inverse" Limit? I'm using MySQL to store financial stuff, and using the data to build, among other things, registers of all the transactions for each account. For performance reasons - and to keep the user from being overwhelmed by a gargantuan table - I paginate the results. Now, as part of the register, I display a running balance for the account. So if I'm displaying 20 transactions per page, and I'm displaying the second page, I use the data as follows: * *Transactions 0 - 19: Ignore them - they're more recent than the page being looked at. *Transactions 20 - 39: Select everything from these - they'll be displayed. *Transactions 40 - ??: Sum the amounts from these so the running balance is accurate. It's that last one that's annoying me. It's easy to select the first 40 transactions using a LIMIT clause, but is there something comparable for everything but the first 40? Something like "LIMIT -40"? I know I can do this with a COUNT and a little math, but the actual query is a bit ugly (multiple JOINs and GROUP BYs), so I'd rather issue it as few times as possible. And this seems useful enough to be included in SQL - and I just don't know about it. Does anybody else? A: The documentation says: The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions: * *Within prepared statements, LIMIT parameters can be specified using ? placeholder markers. *Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables as of MySQL 5.5.6. With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1): SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15 To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last: SELECT * FROM tbl LIMIT 95,18446744073709551615; Next time, please use the documentation as your first port of call. A: You can hack it this way: select sel.* from ( SELECT @rownum:=@rownum+1 rownum, t.* FROM (SELECT @rownum:=0) r, YourTableOrYourSubSelect t ) sel where rownum > 40 It's kinda like having Oracle's rownum in MySQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: OpenLayers zoomToExtent does not zoom correctly I have an openlayers map with a couple of POI, and I want to zoom so these all fit the map, which I'm doing with the following code: var bbox = new OpenLayers.Bounds( <?php echo $this->box->getSmallestLongitude() ?>, <?php echo $this->box->getSmallestLatitude() ?>, <?php echo $this->box->getLargestLongitude() ?>, <?php echo $this->box->getLargestLatitude() ?> ).transform(map.displayProjection, map.projection); map.zoomToExtent(bbox); //normally zoom is auto, but for some reason it zooms to 0... //manual zoom looks like a correct workaround map.zoomTo(map.getZoomForExtent(bbox)); Now as you may already have noticed: I have to map.zoomTo manually; since the map.zoomToExtent does set the center correct; but zooms to 0.... Any ideas as to why it won't calculate the zoom correct the first time?
{ "language": "en", "url": "https://stackoverflow.com/questions/7558257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Default AsyncCallback in GWT Doing my app, I got bored from always implement the same default error treatment (show a message, caught.printstacktrace and etc..) in the asynccallback onfailure. I wonder if you can make a generic treatment or standard treatment, something like that. Thanks. A: I assume you are using standard GWT-RPC. Something like this might help public abstract class AbstractCallBack<T> implements AsyncCallback<T>{ @Override public void onFailure(Throwable caught) { //Default error Handling code goes here } } And whenever you use your service instead of instantiating an AsyncCallback you can instantiate this class and have generalized error handling. SomeServiceAsync service = GWT.create(SomeService.class); service.someMethod("Hello!", new AbstractCallBack<String>() { @Override public void onSuccess(String result) { // TODO Auto-generated method stub } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7558263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to add title and Done button on toolbar in a modal view I try to present a modal view (InfoViewController) from a navigation view controller(DateViewController). I add a toolbar on top of InfoViewContoller's view. Now I want to add a title "Info" and a "Done" button on the toolbar.(The Done button will perform the infoDismissAction method) Can anyone give me som tips? Thanks a lot! Here's code of DateViewController.h #import <UIKit/UIKit.h> #import "InfoViewController.h" @interface DateViewController : UIViewController { InfoViewController *infoViewController; } @property (nonatomic, retain) InfoViewController *infoViewController; @end DateViewController.m - (IBAction)modalViewAction:(id)sender{ if (self.infoViewController == nil) self.infoViewController = [[[InfoViewController alloc] initWithNibName: NSStringFromClass([InfoViewController class]) bundle:nil] autorelease]; [self presentModalViewController:self.infoViewController animated:YES]; } - (void)dealloc{ if (self.infoViewController != nil) { [infoViewController release]; } [super dealloc]; } - (void)viewDidLoad{ self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Info" style:UIBarButtonSystemItemPlay target:self action:@selector(modalViewAction:)] autorelease]; [modalBarButtonItem release]; [super viewDidLoad]; } Here's InfoViewController.m - (IBAction)infoDismissAction:(id)sender{ [self.parentViewController dismissModalViewControllerAnimated:YES]; } - (void)viewDidLoad { UIToolbar *toolBar; toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)]; toolBar.frame = CGRectMake(0, 0, 320, 50); toolBar.barStyle = UIBarStyleDefault; [toolBar sizeToFit]; [self.view addSubview:toolBar]; [toolBar release]; [backButton release]; [super viewDidLoad]; } A: Try this code. - (void)viewDidLoad { UIToolbar *toolBar; toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)]; toolBar.frame = CGRectMake(0, 0, 320, 50); toolBar.barStyle = UIBarStyleDefault; [toolBar sizeToFit]; UIBarButtonItem *flexibleSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease]; UIBarButtonItem *infoButton = [[[UIBarButtonItem alloc] initWithTitle:@"INFO" style:UIBarButtonItemStyleBordered target:self action:@selector(InfoAction:)] autorelease]; UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"DONE" style:UIBarButtonItemStyleBordered target:self action:@selector(doneAction:)]; NSArray *barButton = [[NSArray alloc] initWithObjects:flexibleSpace,infoButton,flexibleSpace,doneButton,nil]; [toolBar setItems:barButton]; [self.view addSubview:toolBar]; [toolBar release]; [barButton release]; barButton = nil; [super viewDidLoad]; } A: I'd recommend setting up another UINavigationController with your InfoViewController and present the navigation controller as your modal view. To answer your question you'd want to fill in your UIToolbar like this: - (void)viewDidLoad { [super viewDidLoad]; UIToolbar *toolBar; toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)]; toolBar.frame = CGRectMake(0, 0, 320, 50); toolBar.barStyle = UIBarStyleDefault; [toolBar sizeToFit]; [self.view addSubview:toolBar]; [toolBar release]; UIBarButtonItem* bbiInfo = [[UIBarButtonItem alloc] initWithTitle:@"Info" style:UIBarButtonItemStyleBordered target:self action:@selector(tappedInfoButton)]; UIBarButtonItem* flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; UIBarButtonItem* bbiDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(tappedDoneButton)]; NSArray* items = [[NSArray alloc] initWithObjects:bbiInfo, flexibleSpace, bbiDone, nil]; [toolBar setItems:items]; [items release]; [bbiInfo release]; [flexibleSpace release]; [bbiDone release]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Friend operator behavior (const vs non-const) I have the following C++ code: #include <iostream> template <class T> void assign(T& t1, T& t2) { std::cout << "First method" << std::endl; t1 = t2; } template <class T> void assign(T& t1, const T& t2) { std::cout << "Second method" << std::endl; t1 = t2; } class A { public: A(int a) : _a(a) {}; private: int _a; friend A operator+(const A& l, const A& r); }; A operator+(const A& l, const A& r) { return A(l._a + r._a); } int main() { A a = 1; const A b = 2; assign(a, a); assign(a, b); assign(a, a+b); } The output is: First method Second method Second method The output stays the same even if I comment out the the first 2 assigns in the main function. Can someone please explain to me why the operator+ returns a const A? The output is the same in both Linux Debian 64bit and Windows 7 64 bit. A: It doesn't return a const A at all. It returns a temporary A, which may only bind to a const reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java NIO Pipe vs BlockingQueue I just discovered that just has an NIO facility, Java NIO Pipe that's designed for passing data between threads. Is there any advantage of using this mechanism over the more conventional message passing over a queue, such as an ArrayBlockingQueue? A: Usually the simplest way to pass data for another thread to process is to use an ExecutorService. This wraps up both a queue and a thread pool (can have one thread) You can use a Pipe when you have a library which supports NIO channels. It is also useful if you want to pass ByteBuffers of data between threads. Otherwise its usually simple/faster to use a ArrayBlockingQueue. If you want a faster way to exchange data between threads I suggest you look at the Exchanger however it is not as general purpose as an ArrayBlockingQueue. The Exchanger and GC-less Java A: I believe a NIO Pipe was designed so that you can send data to a channel inside the selector loop in a thread safe way, in other words, any thread can write to the pipe and the data will be handled in the other extreme of the pipe, inside the selector loop. When you write to a pipe you make the channel in the other side readable. A: So after having a lot of trouble with pipe (check here) I decided to favor non-blocking concurrent queues over NIO pipes. So I did some benchmarks on Java's ConcurrentLinkedQueue. See below: public static void main(String[] args) throws Exception { ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>(); // first test nothing: for (int j = 0; j < 20; j++) { Benchmarker bench = new Benchmarker(); String s = "asd"; for (int i = 0; i < 1000000; i++) { bench.mark(); // s = queue.poll(); bench.measure(); } System.out.println(bench.results()); Thread.sleep(100); } System.out.println(); // first test empty queue: for (int j = 0; j < 20; j++) { Benchmarker bench = new Benchmarker(); String s = "asd"; for (int i = 0; i < 1000000; i++) { bench.mark(); s = queue.poll(); bench.measure(); } System.out.println(bench.results()); Thread.sleep(100); } System.out.println(); // now test polling one element on a queue with size one for (int j = 0; j < 20; j++) { Benchmarker bench = new Benchmarker(); String s = "asd"; String x = "pela"; for (int i = 0; i < 1000000; i++) { queue.offer(x); bench.mark(); s = queue.poll(); bench.measure(); if (s != x) throw new Exception("bad!"); } System.out.println(bench.results()); Thread.sleep(100); } System.out.println(); // now test polling one element on a queue with size two for (int j = 0; j < 20; j++) { Benchmarker bench = new Benchmarker(); String s = "asd"; String x = "pela"; for (int i = 0; i < 1000000; i++) { queue.offer(x); queue.offer(x); bench.mark(); s = queue.poll(); bench.measure(); if (s != x) throw new Exception("bad!"); queue.poll(); } System.out.println(bench.results()); Thread.sleep(100); } } The results: totalLogs=1000000, minTime=0, maxTime=85000, avgTime=58.61 (times in nanos) totalLogs=1000000, minTime=0, maxTime=5281000, avgTime=63.35 (times in nanos) totalLogs=1000000, minTime=0, maxTime=725000, avgTime=59.71 (times in nanos) totalLogs=1000000, minTime=0, maxTime=25000, avgTime=58.13 (times in nanos) totalLogs=1000000, minTime=0, maxTime=378000, avgTime=58.45 (times in nanos) totalLogs=1000000, minTime=0, maxTime=15000, avgTime=57.71 (times in nanos) totalLogs=1000000, minTime=0, maxTime=170000, avgTime=58.11 (times in nanos) totalLogs=1000000, minTime=0, maxTime=1495000, avgTime=59.87 (times in nanos) totalLogs=1000000, minTime=0, maxTime=232000, avgTime=63.0 (times in nanos) totalLogs=1000000, minTime=0, maxTime=184000, avgTime=57.89 (times in nanos) totalLogs=1000000, minTime=0, maxTime=2600000, avgTime=65.22 (times in nanos) totalLogs=1000000, minTime=0, maxTime=850000, avgTime=60.5 (times in nanos) totalLogs=1000000, minTime=0, maxTime=150000, avgTime=63.83 (times in nanos) totalLogs=1000000, minTime=0, maxTime=43000, avgTime=59.75 (times in nanos) totalLogs=1000000, minTime=0, maxTime=276000, avgTime=60.02 (times in nanos) totalLogs=1000000, minTime=0, maxTime=457000, avgTime=61.69 (times in nanos) totalLogs=1000000, minTime=0, maxTime=204000, avgTime=60.44 (times in nanos) totalLogs=1000000, minTime=0, maxTime=154000, avgTime=63.67 (times in nanos) totalLogs=1000000, minTime=0, maxTime=355000, avgTime=60.75 (times in nanos) totalLogs=1000000, minTime=0, maxTime=338000, avgTime=60.44 (times in nanos) totalLogs=1000000, minTime=0, maxTime=345000, avgTime=110.93 (times in nanos) totalLogs=1000000, minTime=0, maxTime=396000, avgTime=100.32 (times in nanos) totalLogs=1000000, minTime=0, maxTime=298000, avgTime=98.93 (times in nanos) totalLogs=1000000, minTime=0, maxTime=1891000, avgTime=101.9 (times in nanos) totalLogs=1000000, minTime=0, maxTime=254000, avgTime=103.06 (times in nanos) totalLogs=1000000, minTime=0, maxTime=1894000, avgTime=100.97 (times in nanos) totalLogs=1000000, minTime=0, maxTime=230000, avgTime=99.21 (times in nanos) totalLogs=1000000, minTime=0, maxTime=348000, avgTime=99.63 (times in nanos) totalLogs=1000000, minTime=0, maxTime=922000, avgTime=99.53 (times in nanos) totalLogs=1000000, minTime=0, maxTime=168000, avgTime=99.12 (times in nanos) totalLogs=1000000, minTime=0, maxTime=686000, avgTime=107.41 (times in nanos) totalLogs=1000000, minTime=0, maxTime=320000, avgTime=95.58 (times in nanos) totalLogs=1000000, minTime=0, maxTime=248000, avgTime=94.94 (times in nanos) totalLogs=1000000, minTime=0, maxTime=217000, avgTime=95.01 (times in nanos) totalLogs=1000000, minTime=0, maxTime=159000, avgTime=93.62 (times in nanos) totalLogs=1000000, minTime=0, maxTime=155000, avgTime=95.28 (times in nanos) totalLogs=1000000, minTime=0, maxTime=106000, avgTime=98.57 (times in nanos) totalLogs=1000000, minTime=0, maxTime=370000, avgTime=95.01 (times in nanos) totalLogs=1000000, minTime=0, maxTime=1836000, avgTime=96.21 (times in nanos) totalLogs=1000000, minTime=0, maxTime=212000, avgTime=98.62 (times in nanos) Conclusion: The maxTime can be scary but I think it is safe to conclude we are in the 50 nanos range for polling a concurrent queue. A: I suppose the pipe will have better latency as it could very likely be implemented with coroutines behind the scenes. Thus, the producer immediately yields to the consumer when data is available, not when the thread scheduler decides. Pipes in general represent a consumer-producer problem and are very likely to be implemented this way so that both threads cooperate and are not preempted externally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: CRUD module does not support Calendar type? CRUD module is so cool but small problem. I am using 'Calendar' types in model classes, and they do not appear in CRUD pages. Once their types changed to 'Date' from 'Calendar', they appear. It seems that CRUD does not support Calendar type. Question. How can I use Calendar type in model classes for CRUD module? You may simply suggest that I should use Date instead of Calendar. But it does not fit to my project because Date types do not work in some cases in my project. Thank you. FYI, one of the model classes @Entity @Table(name = "brands") public class Brand extends Model { @Column public String name; @Column public Calendar modified_at; @Column public Calendar created_at; ... } Only name field is showed at CRUD pages. But modified_at and created_at also appear once the types changed to 'Date'. A: CRUD is a basic module, it lacks support for several things (for example, dates only display the dd/mm/yyyy part, not the hour or minute). You may need to customize it. The code is available here as well as in the Play! distribution you have, in the "modules" folder. Just modify the content to suit you needs and deploy it as a local module in your dependencies file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JavaScript string replace IE problem This simple code works fine in FF and Chrome... but not in IE8: var pathtop = $('#autoplay').find('embed').attr('src'); pathtop = pathtop.replace('http://www.youtube.com/v/', ''); Gives: 'undefined' is null or not an object error on line 2 I also tried something like this: pathtop = pathtop.replace('', ''); and the same error! I am using jQuery in this project. A: pathtop on IE is most likely null, because the jquery find/attr chain failed. Split it up into parts and find out which layer ($('#autoplay'), .find() or .attr() is returning a null. Offhand guess - IE's ignoring embed tags in favor of <object>, so there's no embed in the DOM tree. and you're trying to get the src of a non-existence dom object, making pathtop null, which means there's no replace method available for it. A: try var pathtop = $('#autoplay').find('object').attr('src'); pathtop = pathtop.replace('http://www.youtube.com/v/', '');
{ "language": "en", "url": "https://stackoverflow.com/questions/7558279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initializing an array of objects I'm currently working on a card game, and I'm having trouble with some initialization code: // in my class... Card cards[20]; // in method... for(int i = 0; i <= 20;i++) cards++ = new Card(i, /*i as char +*/ "_Card.bmp"); The trouble is that my compiler's telling me that cards++ is not an l-value. I've read up on the whole pointer-array equivalence thing, and I thought I understood it, but alas, I can't get it to work. My understanding is that since cards degrades to a pointer, and the new operator gives me a pointer to the location of my new instance of Card, then the above code should compile. Right? I've tried using a subscript as well, but isn't cards+i, cards++, and cards[i] just 3 ways of saying the same thing? I thought that each of those were l-values and are treated as pointers. A: The code Card cards[20]; already creates an array of 20 Card objects and creates them with the default constructor. This may not be what you want given your code. I would suggest using vector instead. std::vector<Card> cards; for(int i = 0; i < 20;i++) { cards.push_back(Card(i, /*i as char +*/ "_Card.bmp")); } Note that your for loop goes from 0 to 20 and thus one past the end of the array. A: If you want to avoid unnecessary constructor calls and unnecessary resizing, then it's more complicated, because C++ normally initialises each objects one-by-one as it's allocated. One workaround is to do it the Java way -- use a loop and an array of pointers, like so: Card *cards[20]; for (int i=0; i<20; i++) { cards[i] = new Card(i); } Another option is to use malloc to get explicitly uninitialized memory: Card *cards = malloc(20 * sizeof(Card)); for (int i=0; i<20; i++) { new (&(cards[i])) Card(i); } A: Well, there is another possibility, when you are ok with your constructors being called automatically at initialization: // in my class... Card cards[20] = { Card(0, "0_Card.bmp"), Card(1, "1_Card.bmp"), /* ... */ }; The huge downside is that you cannot use a loop in this case. A: Card cards[20]; cards is already an array of objects. They are constructed with the default constructor(constructor with no arguments). There is no need to new again. Probably you need a member function equivalent to constructor arguments and assign through it. for ( int i=0; i<20; ++i ) // array index shouldn't include 20 cards[i].memberFunction(/*....*/); Even simpler is to use std::vector std::vector<Card> cards; for( int i=0; i<20; ++i ) cards.push_back(Card(i, /*i as char +*/ "_Card.bmp"); ) A: An array name, cards in your code, contains the address of the first element of the array. Such addresses are allocated at run time and you cannot change them. Hence the compiler complaining about cards being not an l-value. But you can definitely specify what those addresses can hold by using a pointer like below: // in my class... Card cards[20]; Card *cardsPointer = cards;// Pointer contains the address of the //1st element of 'cards' array. // in method... for(int i = 0; i < 20; i++) *(cardsPointer++) = Card(i, /*i as char +*/ "_Card.bmp");// Note that // there is no 'new' operator as 'cardsPointer' has type 'Card *' and // not 'Card **'. And 'cardsPointer' has type 'Card *' as the array is // of type 'Card'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: UIDocumentInteractionController on the detailView I'm previewing a file using UIDocumentInteractionController, but it is occupying all the area of the iPad. I would like it to appear on the detail view of the split view controller. I've checked that the UIView of my view controller doesn't occupy all the screen. Any ideas? I checked that the documentInteractionControllerRectForPreview: is called. -(void)requestExecutedWithSuccess:(Model *)model { UIDocumentInteractionController *docInteractionCont = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:model.filePath]]; self.docInteractionController = docInteractionCont; self.docInteractionController.delegate = self; BOOL attachmentShown = [self.docInteractionController presentPreviewAnimated:YES]; ... } - (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller { return [self navigationController]; } - (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller { return self.view; } - (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller { return self.view.frame; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get a string after another string in ObjectiveC? For example, the text is: my name is angie merkel and Im stupid! I'd like to get the angie merkel from the string. How can i do this? My head is going to explode... i can't trim this string because it's a variable (text from the user for a ChatBot) A: If the string always has the format `my name is and Im stupid!', you can do the following: NSString *name = [[startingString stringByReplacingOccurrencesOfString:@"my name is " withString:@""] stringByReplacingOccurrencesOfString:@" and Im stupid!" withString:@""];
{ "language": "en", "url": "https://stackoverflow.com/questions/7558284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: scroll bars showing up in iframe, width is only 500px, height set to fluid I cannot for the life of me figure out why there are scroll bars appearing on my iframe Page tab. The width is set at 500px, after knocking it down 5px at a time from 515px. There are no margins, and the height setting is on "fluid." When I view the html page that the iframe is showing directly, there is no extra white space, so it looks like Facebook is adding white space (a margin or pad?) on the left side of the iframe. The odd thing is that the scroll distance has remained the same as I've narrowed the page down from 515px to 500px. Further, the "fluid" option for the height does not seem to be applying to the iframe, so I can't use the hidden tag in my CSS or half of my content is chopped off. Is this an issue for anyone else, or am I just doing something wrong? I'll post the code for the page below. <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>index_loc3</title> <link rel="stylesheet" type="text/css" href="loc_styles.css" /> <script language="javascript" src="facebox/jquery.js"></script> <link rel="stylesheet" type="text/css" href="facebox/facebox.css" /> <script language="javascript" src="facebox/facebox.js"></script> <script type="text/javascript"> jQuery(document).ready(function($) { $('a[rel*=facebox]').facebox() }) </script> </head> <body> <div id="container" style="width:500px"> <div id="header"> <a href="http://www.fwymca.org"><img src="images/logo_slice.jpg" alt="" width="199" height="152" hspace="8" vspace="40" align="left" /></a> <img src="head_images/ymca1.jpg" align="right"> </div> <div id="name"><img src="images/text_slice.jpg" alt="YMCA of Greater Fort Wayne" width="485" height="37" hspace="12" /> </div> <br /> <div id="content1"><a href="cent_popup.html" rel="facebox"><img src="images/cent_loc3.jpg" vspace="5"></a> <a href="park_popup.html" rel="facebox"><img src="images/park_loc3.jpg" alt="Parkview Family Y" vspace="10"></a> <a href="wells_popup.html" rel="facebox"><img src="images/wells_loc2.jpg" alt="Wells County Y" vspace="6"></a> </div> <div id="content2"><a href="jorg_popup.html" rel="facebox"><img src="images/jorg_loc3.jpg" vspace="5"></a> <a href="renpt_popup.html" rel="facebox"><img src="images/ren_loc3.jpg" width="240" height="216" vspace="10"></a> <a href="whit_popup.html" rel="facebox"><img src="images/whit_loc3.jpg" vspace="5"></a> <a href="camp_popup.html" rel="facebox"><img src="images/camp_loc3.jpg" vspace="5"></a> </div> </div> </body> </html> UPDATE: I found a bit of code that got the iframe to resize properly and get rid of the scroll bars. However, this seems to have caused my Facebox implementation to get messed up. It doesn't appear Facebox recognizes the change in screen position to change the center for Facebox, so it is popping up at the top of the page instead of the current center of the screen. A: I had a similar problem where I had vertical and horizontal scrollbars being shown even when they were inactive (in Opera and Firefox, while in IE and Chrome the page was shown without the scrollbars). I had "fluid" height and width selected in the application settings. The problem finally disappeared when I reverted the height setting to "settable" and used the FB.Canvas.setSize function again. To me it seems that Facebook's "fluid" setting for the height isn't working correctly for all browsers at the moment, maybe try setting it back to settable and going from there. A: go to https://developers.facebook.com/apps/YOUR_APP_ID/advanced then scroll to Canvas Settings then set Canvas Width and Canvas Height as you wish
{ "language": "en", "url": "https://stackoverflow.com/questions/7558285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: using gestureoverlayview with scrollview problem I have scrollview in that i have tableview and in that I have gestureoverlayview ....my problem is when I do any gesture horizontally it works fine but when I do any gesture vertically the scrollview start moving ...the event get captured by scrollview ... I tried following code but it dint work out public boolean dispatchTouchEvent(MotionEvent ev) { System.out.println("m touched"); if(ev.equals(sEvent)){ System.out.println("in touched2"); return overlay.dispatchTouchEvent(ev); }else{ return scl.dispatchTouchEvent(ev); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jQuery variable substitution I have a simple jQuery function below.. I'm interested in dynamically changing the 'query:FOOTBALL' attribute with a dynamic page variable. So something like 'query:PAGE_TITLE' or PAGE_VAR I haven't had any luck get .replace() to work.. I must be overlooking something very simple; What approach do you all take here? jQuery(function($){ $("#query").tweet({ avatar_size: 32, count: 4, query: "FOOTBALL", loading_text: "searching twitter..." }); }); A: I'm not exactly clear on what you're asking, but I think you want to use a variable instead of a string literal... As query is expecting a String, you can use any String value there. So if you have a variable called myVar containing a string, you can use myVar in place of the string literal: var myVar = "Some String"; jQuery(function($){ $("#query").tweet({ avatar_size: 32, count: 4, query: myVar, loading_text: "searching twitter..." }); }); Or, you could do something like this to use the value entered into an input by the user: jQuery(function($){ $("#query").tweet({ avatar_size: 32, count: 4, query: $("#someInput").val(), //val() returns a string so it will work here loading_text: "searching twitter..." }); }); A: Just stuff it in a variable, then pass along. The page will have already loaded so you can grab the text from any element you'd like with jQuery. jQuery(function($){ // maybe you want the <title> tag value var query = location.title; // or maybe the text from the first <h1> //query = $('h1:first').text(); $("#query").tweet({ avatar_size: 32, count: 4, query: query, loading_text: "searching twitter..." }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7558292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating Anchor Link Within Masonry Set I have a unique problem with Masonry that I would love some help with. Because I am loading fonts externally through Typekit, I have to include the Masonry code within window.load instead of document.ready (It is necessary to load the fonts before Masonry loads because otherwise the line lengths are different so the absolute positioning gets messed up source). I also need to link directly to sections within the Masonry group (as anchors within the page). The problem with combining these two things is that if you use window.load then the anchor does not exist when the page loads, so the link leads to the top of the Masonry section instead of the specific section within the Masonry section with the link. Any ideas of how to correct this? The easiest solution would be to get the code to work without having to resort to window.load. Unfortunately I have not been able to find an alternative. Any help would be awesome. A: * *Use Typekit font event to trigger masonry have fonts have/haven't loaded *Catch any hashes and force scroll to them with $(window).load() var $container; function triggerMasonry() { // don't proceed if doc not ready if ( !$container ) { return } $container.masonry({ // options... }); } $(function(){ $container = $('#container'); triggerMasonry(); }); // trigger masonry after fonts have loaded Typekit.load({ active: triggerMasonry, inactive: triggerMasonry // triggered in Chrome }); // catch any hashes and force scroll to them // resolves Masonry bug var $window = $(window); $window.load(function(){ if ( window.location.hash ) { var destination = $( window.location.hash ).offset().top; $window.scrollTop( destination ); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7558297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Column header repeat don´t work in ssrs 2008 I have a report with a tablix that has row headers. I want to repeat the headers on each page, so I activated the flag "Repeat header columns on each page". But nothing happens... this worked with earlier versions of ssrs... A: Answer can be found here. A: You may also need to set KeepWithGroup to "After" in that Report Group properties. Need to switch to Advanced mode to see this option. How to switch to Advanced mode: click littel downward triangle on the right from "Column Groups" heading
{ "language": "en", "url": "https://stackoverflow.com/questions/7558299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgraded Coldfusion from 9.0 to 9.0.1 - new cfgrid problems in Firefox After running into problems with auto-suggest stripping off leading zeroes, I took the plunge and updated my dev copy of CF to 9.0.1, including the cumulative hot-fix. Now I see a new problem. Every one of my existing cfgrids is now displaying incorrectly in Firefox 6.0.2. The .x-panel, .x-panel-bwrap, .x-panel-body classes have a computed width of 12px, and are basically unviewable. I find that if I insert a css rule on those classes like so: .x-panel, .x-panel-bwrap, .x-panel-body { width: 100% !important; } the grids are again viewable. I did clear the browser cache to make sure it was importing the correct files. IE8 and Chrome both seem to be unaffected. A: OK, Peter, why not? My workaround, as posted in my question, is to add the following css rule: .x-panel, .x-panel-bwrap, .x-panel-body { width: 100% !important; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7558301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Receiving a SIGABRT when accessing NSDictionary When using a NSDictionary that navigates to a PLIST I keep on getting an SIGABRT error, **2011-09-26 18:31:01.740 AlarmAppiPhone[3126:10d03] -[__NSCFArray _isNaturallyRTL]: unrecognized selector sent to instance 0x5cb5090 2011-09-26 18:31:01.742 AlarmAppiPhone[3126:10d03] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray _isNaturallyRTL]: unrecognized selector sent to instance 0x5cb5090'** at this line, editLabelTextField.text = [alarm objectForKey:ROOT_KEY]; I don't know why I am getting this. The alarm is a NSDictionary and it uses object for key to navigate to a key which I have declared like this, #define ROOT_KEY @"Root". I defined it in another file. The plist looks somewhat like this, <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Root</key> <array> <dict> <key>label</key> <string>alarm1</string> <key>time</key> <date>2011-09-03T07:24:20Z</date> </dict> <dict> <key>label</key> <string>alarm2</string> <key>time</key> <string>2011-09-03T07:24:14Z</string> </dict> </array> </dict> </plist> A: [alarm objectForKey:@"Root"] returns an NSArray, which you're trying to assign to a property which expects an NSString. (_isNaturallyRTL is an iOS-specific, private function of NSString.) I assume you're trying to get to the label. Structurally, such an access would look like this (your variable alarm should probably be called alarmPlist): NSArray *alarms = [alarmPlist objectForKey:@"Root"]; NSDictionary *alarm = [alarms objectAtIndex:0]; editLabelTextField.text = [alarm objectForKey:@"label"]; Replace the 0 with a different index to access a different alarm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ColdFusion Builder 2 Client Error - Memory Leak/Loop on Edit I've not found any other resources on this issue, so I figured I would ask the SO community. :) I currently have an issue with my CFB2 client going into a memory leak about three seconds after I edit a particular file on one of our company webservers. This also occurs when I try and edit a local copy of the file. The leak is slow and would take many many hours to hold up all of my free RAM (~6.5GB/8GB physical). There is also a high CPU usage on the leak (anywhere from 25-45% | 1.8 GHz four-core). The only visual feedback I receive is in the Outline pane, where it extends infinitely into a loop of cfelseif tags. The pane also holds the loop before editing, but does not attempt to extend it. This error first occurred whilst I was creating a cffile tag and because I could not close it, the conditional statements were mis-highlighted. I believe this is the root cause of the issue, however, I do not know why this occurred. As I complete typing of this, I will move the file to a simple editor, remove the line that caused the error, and attempt to add it again, however I fear that the addition of the line will end in the same manner. EDIT: I moved the page source into Notepad and removed the pesky cffile line. Then, I proceeded to delete the file from the webserver, create a new file of the same name, and add the code back. I closed the tag before adding any attributes just to ensure the same issue would not occur, and it did not experience the same loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Search and display on same page in mvc2 asp net have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it. Right now I'm doing the following but it's not working out exactly the way I want: A: sathishkumar, You don't tag the question as being an ajax related solution or not. I'm going to present a simple ajax approach which may or may not be suitable. in the controller: public ActionResult Search(string searchTerm) { // you don't add code re your stored proc, so here is a repo based approach var searchItems = _repository.Find(x => x.searchfield.Contains(searchTerm)); return PartialView("SearchPartial", searchItems); } main view (index.aspx or whatever) (below where your main content is defined, add): <div id="searchResults"></div> in another part of the page (semi psuedo-code): <script type="text/javascript"> function getSearchResults() { // #yoursearchbox is a textbox on the index.aspx aview var tdata = { searchTerm: $('#yoursearchbox').val()}; // or your data in the format that will be used ?? $.ajax({ type: "GET", data: tdata, url : '<%= Url.Action("Search", "Home") %>', success: function (result) { success(result); } }); }); function success(result){ $("#searchResults").html(result); } </script> You'd then add a partial view SearchPartial.ascx that contained your model for the search results. Hope this helps. A: You can use Ajax to solve the problem. <div> `@using (Ajax.BeginForm("action", "controller", new AjaxOptions { UpdateTargetId = "results", HttpMethod = "GET", })) { @Html.TextBox() <input type="submit" value="Search" /> }` <div id="results"></div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7558308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java escaping chars that already exist in the string I need to escape chars that exist within a string but the escape chars are part of the escape code ie. Map<String, String> escapeChars = new HashMap<String, String>(); escapeChars.put("^", "^94;"); escapeChars.put("%", "^37;"); escapeChars.put("'", "^39;"); public String findEscapeChars(String x) { for(Map.Entry<String, String> entry : escapeChars.entrySet()) { if(x.contains(entry.getKey()) ) { x = x.replaceAll(entry.getKey(), entry.getValue()); } } return x; } //result should match assertEquals("^37;", findEscapeChars("%")); //example of the caret symbol escaping assertEquals("^37; 1 2 ^39; ^94; 4 ^37;", findEscapeChars("% 1 2 ' ^ 4 %")); It really needs to done in one loop and only one if condition. The problem is that the hash map doesn't traverse in a certain order therfore the caret symbol could try escape itself in the string. It seems to be tricky without numerous loops and if conditions, a simple solution would be ideal. Thanks D A: I'm going to assume you only need to escape a single character at a time. Then you can do: public String findEscapeChars(String original) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < original.length(); i++) { char c = original.charAt(i); String escaped = escapeMap.get(c); if (escaped != null) { builder.append(escaped); } else { builder.append(c); } } return builder.toString(); } Note that unless you really need to have the dynamic nature of a map, a simple switch would probably be simpler and more efficient. A: First, if you need order in map use LinkedHashMap instead. Second, you even can solve everything without maps at all but using regular experession with lookahead. See http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7558310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: preg_replace doubt What I'm doing wrong ? echo preg_replace('#\d{3}\d{3}\d{3}\d{2}#', '$1.$2.$3-$4', '12345678901'); Output would be this: 123.456.789-01. Isn't formating the string!! A: <?php echo preg_replace('#(\d{3})(\d{3})(\d{3})(\d{2})#', '$1.$2.$3-$4', '12345678901'); is correct, because dollar sign + integer refers to content in () brackets (grouping) demo A: You have not grouped correctly (missing brackets): echo preg_replace('#(\d{3})(\d{3})(\d{3})(\d{2})#', '$1.$2.$3-$4', '12345678901');
{ "language": "en", "url": "https://stackoverflow.com/questions/7558314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a ruby gem that enables cross-platform mouse manipulation? I need the ability to programmatically trigger a mouse click at specific coordinates. I've found AutoIt and the auto_click gem which both supposedly provide this ability, but only on Windows. I've also found the rautomation gem which aims to provide cross-platform capabilities, but which doesn't seem to support anything other than Windows at the moment. Are there any other gems out there that allow automating mouse clicks at specific x/y coordinates directly from Ruby? A: I think it is a heavily system-dependent task. You should provide your code a way to load system-dependent gems (AutoIt on Win, Automations on Linux). If you are targeting Mac OS, you could build your own lib by calling CGPostMouseEvent from the CGRemoteOperation.h via the FFI library. For example: require 'ffi' module Mouse extend FFI::Library ffi_lib '/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics' class CGPoint < FFI::Struct layout :x, :double, :y, :double end attach_function :CGPostMouseEvent, [ CGPoint, :bool, :int, :bool ], :void end point = Mouse::CGPoint.new point[:x] = 100 point[:y] = 100 Mouse::CGPostMouseEvent(point, true, 1, true) A: Take a look at rumouse gem. It provides simple API and supports linux, osx and windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Implement Timeout in HTTP Post What is the best way to implement a connection timeout (let's say, 20 seconds) within an HTTP post connection? My current code is as follows: -(NSData*) postData: (NSString*) strData { //postString is the STRING TO BE POSTED NSString *postString; //this is the string to send postString = @"data="; postString = [postString stringByAppendingString:strData]; NSURL *url = [NSURL URLWithString:@"MYSERVERHERE"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]]; //setting prarameters of the POST connection [request setHTTPMethod:@"POST"]; [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request addValue:msgLength forHTTPHeaderField:@"Content-Length"]; [request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"]; [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; [request setTimeoutInterval:10.0]; NSLog(@"%@",postString); NSURLResponse *response; NSError *error; NSLog(@"Starting the send!"); //this sends the information away. everybody wave! NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"Just finished receiving!"); if (&error) //OR TIMEOUT { NSLog(@"ERROR!"); NSString *errorString = [NSString stringWithFormat:@"ERROR"]; urlData = [errorString dataUsingEncoding:NSUTF8StringEncoding]; } return urlData; } Obviously the timeout interval is set to 10.0, but nothing seems to happen when those ten seconds hit. A: See: NSMutableURLRequest timeout interval not taken into consideration for POST requests Apparently timeouts under 240 seconds are ignored. The highest voted answer in that question links to a solution. However, I would simply recommend using the ASIHTTPRequest library instead. http://allseeing-i.com/ASIHTTPRequest/
{ "language": "en", "url": "https://stackoverflow.com/questions/7558318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }