Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working? ``` public static void main(String...aArguments) throws IOException { String usuario = "Jorman"; String password = "14988611"; String strDatos = "Jorman 14988611"; StringTokenizer tokens = new StringTokenizer(strDatos, " "); int nDatos = tokens.countTokens(); String[] datos = new String[nDatos]; int i = 0; while (tokens.hasMoreTokens()) { String str = tokens.nextToken(); datos[i] = str; i++; } //System.out.println (usuario); if ((datos[0] == usuario)) { System.out.println("WORKING"); } } ```
Use the [`string.equals(Object other)`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equals-java.lang.Object-) function to compare strings, not the `==` operator. The function checks the actual contents of the string, the `==` operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with `==`, but it's better not to rely on that. ``` if (usuario.equals(datos[0])) { ... } ``` NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the `datos` array otherwise you'll get an array-out-of-bounds exception.
## Meet Jorman Jorman is a successful businessman and has 2 houses. ![enter image description here](https://i.stack.imgur.com/xLcfG.png) But others don't know that. ## Is it the same Jorman? When you ask neighbours from either Madison or Burke streets, this is the only thing they can say: ![enter image description here](https://i.stack.imgur.com/ZjMlG.png) Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons. **That's how the operator `==` behaves.** So it will say that `datos[0]==usuario` is false, because it only *compares the addresses*. ## An Investigator to the Rescue What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms. Here's the source code of String's `equals()` method: ![enter image description here](https://i.stack.imgur.com/6MYZy.png) It compares the Strings character by character, in order to come to a conclusion that they are indeed equal. **That's how the String `equals` method behaves.** So `datos[0].equals(usuario)` will return true, because it performs a *logical comparison*.
String.equals versus ==
[ "", "java", "string", "" ]
Is there a way to shorten the markup for this repeater? I am binding a DataTable to this repeater. It bothers me because ((System.Data.DataRowView)Container.DataItem) is repetitive and makes the markup less readable especially when you have more fields. I am using .Net 3.5 C# WebForms. MVC is not an option. Thanks. ``` <asp:Repeater ID="rDefinitions" runat="server"> <ItemTemplate> <h3><%#((System.Data.DataRowView)Container.DataItem)["Name"]%></h3> <p>Definition: <%#((System.Data.DataRowView)Container.DataItem)["Definition"]%> </p> </ItemTemplate> </asp:Repeater> ```
Why not use the simplified data binding statements introduced with ASP.NET 2.0?
You can import the System.Data namespace to leave off the System.Data part. But as for the rest, I believe its necessary.
Any way to shorten or simplify the item template markup for a repeater control?
[ "", "c#", ".net", "webforms", "datatable", "repeater", "" ]
I have an unsorted Array holding the following IDs: ``` @un_array = ['bar', 'para-3', 'para-2', 'para-7'] ``` Is there a smart way of using [Nokogiri](http://github.com/tenderlove/nokogiri/tree/master) (or plain Javascript) to sort the array according to the order of the IDs in the example HTML document below? ``` require 'rubygems' require 'nokogiri' value = Nokogiri::HTML.parse(<<-HTML_END) "<html> <head> </head> <body> <p id='para-1'>A</p> <div id='foo'> <p id='para-2'>B</p> <p id='para-3'>C</p> <div id='bar'> <p id='para-4'>D</p> <p id='para-5'>E</p> <p id='para-6'>F</p> </div> <p id='para-7'>G</p> </div> <p id='para-8'>H</p> </body> </html>" HTML_END ``` In this case the resulting, sorted array should be: ``` ['para-2', 'para-3', 'bar', 'para-7'] ```
This is the solution a coworker and I came up with: ``` parent = value.css('body').first indexes = [] parent.children.each do |child| indexes << child['id'] end puts @un_array.sort! { |x,y| indexes.index(x) <=> indexes.index(y) } ``` First I fetch all IDs of the HTML document into an Array, than I sort `@un_array` according to the IDs-Array I created before.
I don't know what Nokogiri is, but if you have the HTML code as a String, than it would be possible to get the order with regexp matching, for example: ``` var str = '<html>...</html>'; // the HTML code to check var ids = ['bar', 'para-3', 'para-2', 'para-7']; // the array with all IDs to check var reg = new RegExp('(?:id=[\'"])('+ids.join('|')+')(?:[\'"])','g') // the regexp var result = [], tmp; // array holding the result and a temporary variable while((tmp = reg.exec(str))!==null)result.push(tmp[1]); // matching the IDs console.log(result); // ['para-2', 'para-3', 'bar', 'para-7'] ``` using this code you have to be careful with IDs containing regexp meta-characters. They should be escaped first.
Nokogiri: Sort Array of IDs according to order in HTML document
[ "", "javascript", "ruby-on-rails", "ruby", "dom", "nokogiri", "" ]
On a page with Ajax event, I want to disable all actions until the Ajax call returns (to prevent issues with double-submit etc.) I tried this by prepending `return false;` to the current onclick events when "locking" the page, and removing this later on when "unlocking" the page. However, the actions are not active any more after they are "unlocked" -- you just can't trigger them. Why is this not working? See example page below. Any other idea to achieve my goal? **Example code:** both the link and the button are showing a JS alert; when pressing lock, then unlock the event handler is the same as it was before, but doesn't work...?!? The code is meant to work with Trinidad in the end, but should work outside as well. ``` <html><head><title>Test</title> <script type="text/javascript"> function lockPage() { document.body.style.cursor = 'wait'; lockElements(document.getElementsByTagName("a")); lockElements(document.getElementsByTagName("input")); if (typeof TrPage != "undefined") { TrPage.getInstance().getRequestQueue().addStateChangeListener(unlockPage); } } function lockElements(el) { for (var i=0; i<el.length; i++) { el[i].style.cursor = 'wait'; if (el[i].onclick) { var newEvent = 'return false;' + el[i].onclick; alert(el[i].onclick + "\n\nlock -->\n\n" + newEvent); el[i].onclick = newEvent; } } } function unlockPage(state) { if (typeof TrRequestQueue == "undefined" || state == TrRequestQueue.STATE_READY) { //alert("unlocking for state: " + state); document.body.style.cursor = 'auto'; unlockElements(document.getElementsByTagName("a")); unlockElements(document.getElementsByTagName("input")); } } function unlockElements(el) { for (var i=0; i<el.length; i++) { el[i].style.cursor = 'auto'; if (el[i].onclick && el[i].onclick.search(/^return false;/)==0) { var newEvent = el[i].onclick.substring(13); alert(el[i].onclick + "\n\nunlock -->\n\n" + newEvent); el[i].onclick = newEvent; } } } </script> <style type="text/css"> </style> </head> <body> <h1>Page lock/unlock test</h1> <p>Use these actions to lock or unlock active elements on the page: <a href="javascript:lockPage()">lock</a>, <a href="javascript:unlockPage()">unlock</a>.</p> <p>And now some elements:</p> <a onclick="alert('This is the action!');return false;" href="#">link action</a> &nbsp; <input type="button" value="button action" onclick="alert('This is another action!')"/> </body> </html> ``` --- Thanks guys for your ideas and answers. Now I see that I have mixed up Strings and functions, which obviously can't work ;( I should have made clear that we use some Web FW and tag libraries (Trinidad) which create the event handling (and Ajax) code, hence I can't edit that directly or use synchronous Ajax etc. Moreover, Ajax is only one scenario where this code should be executed. It's purpose is to prevent the user to double-submit a page/action, which is also relevant for non-Ajax pages where you could kind of doulbe-click on a button. I know that this is not really safe, and it's only meant to be a "convenience" thingy to avoid getting the navigation error page too often (we have server-side protection, of course). So, will try the div overlay, probably. Thanks again, Christoph.
How about setting up a global var ``` actions_disabled = 0 ``` increment when the AJAX call starts then decrement when it finishes. All your "action" handlers can then start with ``` if (actions_disabled) return false; ``` Much simpler than debugging self-modifying code! Alternatively, to lock your controls you could set: ``` control.disabled="disabled" ``` which will have the bonus of greying them out, making it obvious to the user that they can't submit. To unlock, simply set: ``` control.disabled="" ``` NEW IDEA BASED ON COMMENTS (can't quote code in comments, it appears ...): You can always just hang extra attributes off Javascript objects: To lock, you could: ``` control.onclick_old = control.onclick control.onclick = "return false;" ``` To unlock, you could: ``` control.onclick = control.onclick_old ```
I once achieved this goal by creating a DIV that covered the area I wanted disabled, setting its `z-index` higher than any of the other elements on the page, and then setting its `opacity` to `0`. By default, this DIV was hidden by `display: none`, so that it wouldn't interfere with anything. However, when I wanted the area disabled, I just set its `display` to `block`. Steve
Javascript: How to temporarily disable all actions on the page?
[ "", "javascript", "events", "" ]
I am running my c++ application on an intel Xscale device. The problem is, when I run my application offtarget (Ubuntu) with [Valgrind](http://valgrind.org/), it does not show any memory leaks. But when I run it on the target system, it starts with 50K free memory, and reduces to 2K overnight. How to catch this kind of leakage, which is not being shown by Valgrind?
It might not be an actual memory leak, but maybe a situation of increasing memory usage. For example it could be allocating a continually increasing string: ``` string s; for (i=0; i<n; i++) s += "a"; ``` 50k isn't that much, maybe you should go over your source by hand and see what might be causing the issue.
A common culprit with these small embedded deviecs is memory fragmentation. You might have free memory in your application between 2 objects. A common solution to this is the use of a dedicated allocator (operator new in C++) for the most common classes. Memory pools used purely for objects of size N don't fragment - the space between two objects will always be a multiple of N.
Memory leak in c++
[ "", "c++", "memory-management", "memory-leaks", "" ]
I find it difficult to determine the responsiblity of classes: do i have to put this method in this class or should I put this method in another class? For example, imagine a simple User class with an id, forname, lastname and password. Now you have an userId and you want the forname and lastname, so you create a method like: public User GetUserById(int id){}. Next you want to show list of all the users, so you create another method: public List GetAllUsers(){}. And offcourse you want to update, delete and save a user. This gives us 5 methods: ``` public bool SaveUser(User user); public bool UpdateUser(User user); public bool DeleteUser(User user); public User GetUserById(int id); public List<User> GetAllUsers(); ``` So my question is: do you put all these methods in the User class? Or do you create another data class (UserData class) which may connect to the database and contain all these methods?
What you are describing here is basically a choice between the [Active Record Pattern](http://www.martinfowler.com/eaaCatalog/activeRecord.html) or the [Repository Pattern](http://www.martinfowler.com/eaaCatalog/repository.html). I'd advise you to read up on those patterns and choose whichever one fits your application / experience / toolset.
I would not put those specific methods into the 'User' class. There are 2 common approaches for this 'problem': * You put those method in the User class, and then this means you 're using the [Active Record](http://en.wikipedia.org/wiki/Active_record_pattern) pattern * You put those methods in a separate class (UserRepository) for instance, and then you're using the [Repository](http://www.martinfowler.com/eaaCatalog/repository.html) pattern. I prefer the repository-approach, since that keeps my 'User' class clean, and doesn't clutter it with data access code.
C# classes and methods
[ "", "c#", "oop", "" ]
I'm working with arrays of image filepaths. A typical array might have 5 image filepaths stored in it. For each array, I want to pull out just the "best" photo to display as a thumbnail for the collection. I find looping and arrays very confusing and after 4 hours of trying to figure out how to structure this, I'm at a loss. Here are the rules I'm working with: 1. The very best photos have "-large" in their filepaths. Not all arrays will have images like this in them, but if they do, that's always the photo I want to pluck out. 2. The next best photos are 260px wide. I can look this up with getimagesize. If I find one of these, I want to stop looking and use it. 3. The next best photos are 265 wide. If I find one I want to use it and stop looking. 4. The next best photos are 600px wide. Same deal. 5. Then 220px wide. Do I need 5 separate for loops? 5 nested for-loops Here's what I'm trying: ``` if $image_array{ loop through $image_array looking for "-large" if you find it, print it and break; if you didn't find it, loop through $image_array looking for 260px wide. if you find it, print it and break; } ``` and so on.... But this doesn't appear to be working. I want to "search" my array for the best single image based on these criteria. If it can't find the first type, then it looks for the second on so on. How's that done?
``` // predefined list of image qualities (higher number = best quality) // you can add more levels as you see fit $quality_levels = array( 260 => 4, 265 => 3, 600 => 2, 220 => 1 ); if ($image_arry) { $best_image = null; // first search for "-large" in filename // because looping through array of strings is faster then getimagesize foreach ($image_arry as $filename) { if (strpos('-large', $filename) !== false) { $best_image = $filename; break; } } // only do this loop if -large image doesn't exist if ($best_image == null) { $best_quality_so_far = 0; foreach ($image_arry as $filename) { $size = getimagesize($filename); $width = $size[0]; // translate width into quality level $quality = $quality_levels[$width]; if ($quality > $best_quality_so_far) { $best_quality_so_far = $quality; $best_image = $filename; } } } // we should have best image now if ($best == null) { echo "no image found"; } else { echo "best image is $best"; } } ```
``` <?php // decide if 1 or 2 is better function selectBestImage($image1, $image2) { // fix for strange array_filter behaviour if ($image1 === 0) return $image2; list($path1, $info1) = $image1; list($path2, $info2) = $image2; $width1 = $info1[0]; $width2 = $info2[0]; // ugly if-block :( if ($width1 == 260) { return $image1; } elseif ($width2 == 260) { return $image2; } elseif ($width1 == 265) { return $image1; } elseif ($width2 == 265) { return $image2; } elseif ($width1 == 600) { return $image1; } elseif ($width2 == 600) { return $image2; } elseif ($width1 == 220) { return $image1; } elseif ($width2 == 220) { return $image2; } else { // nothing applied, so both are suboptimal // just return one of them return $image1; } } function getBestImage($images) { // step 1: is the absolutley best solution present? foreach ($images as $key => $image) { if (strpos($image, '-large') !== false) { // yes! take it and ignore the rest. return $image; } } // step 2: no best solution // prepare image widths so we don't have to get them more than once foreach ($images as $key => $image) { $images[$key] = array($image, getImageInfo($image)); } // step 3: filter based on width $bestImage = array_reduce($images, 'selectBestImage'); // the [0] index is because we have an array of 2-index arrays - ($path, $info) return $bestImage[0]; } $images = array('image1.png', 'image-large.png', 'image-foo.png', ...); $bestImage = getBestImage($images); ?> ``` this should work (i didn't test it), but it is suboptimal. how does it work? first, we look for the absolutely best result, in this case, `-large`, because looking for a substrings is inexpensive (in comparsion). if we don't find a `-large` image we have to analyze the image widths (more expensive! - so we pre-calculate them). array\_reduce calls a filtering function that takes 2 array values and replaces those two by the one return by the function (the better one). this is repeated until there is only one value left in the array. this solution is still suboptimal, because comparisons (even if they're cheap) are done more than once. my big-O() notation skills are a bit (ha!) rusty, but i think it's O(n\*logn). soulmerges solution is the better one - O(n) :) you could still improve soulmerges solution, because the second loop is not necessary: first, pack it into a function so you have return as a break-replacement. if the first strstr matches, return the value and ignore the rest. afterwards, you don't have to store the score for every array key. just compare to the highestKey variable and if the new value is higher, store it. ``` <?php function getBestImage($images) { $highestScore = 0; $highestPath = ''; foreach ($images as $image) { if (strpos($image, '-large') !== false) { return $image; } else { list($width) = getImageInfo($image); if ($width == 260 && $highestScore < 5) { $highestScore = 5; $highestPath = $image; } elseif ($width == 265 && $highestScore < 4) { $highestScore = 4; $highestPath = $image; } elseif ($width == 600 && $highestScore < 3) { $highestScore = 3; $highestPath = $image; } elseif ($width == 220 && $highestScore < 2) { $highestScore = 2; $highestPath = $image; } elseif ($highestScore < 1) { // the loser case $highestScore = 1; $highestPath = $image; } } } return $highestPath; } $bestImage = getBestImage($images); ?> ``` didn't test, should work in O(n). can't imagine a faster, more efficient way atm.
Help pulling out data from a PHP array based on 5 rules
[ "", "php", "arrays", "loops", "" ]
I'm writing a .NET adaptor for a C/C++ library where a method "bar" takes a regular stdio FILE\*. Is it possible to build an interface so that managed code user can pass a managed (File)Stream? That is without creating an intermediary buffer and code to pipe the data between. Also does the assumption that bar() reads only make things any better? ``` // native code void bar(FILE*); // interface for managed code void foo(System::IO::FileStream^ file) { FILE* stdio_handle = ???; bar(stdio_handle); } ```
[`System.IO.FileStream.Handle`](http://msdn.microsoft.com/en-us/library/system.io.filestream.handle.aspx) It's not necessarily `stdio` handle. It's a Windows handle. I don't think `FileStream` is built upon `stdio` to have a `stdio` handle. As Marc pointed out and mentioned in the MSDN link, you might want to consider using `SafeFileHandle` property (if you are on .NET 2.0+) instead of `Handle` (which is now considered obsolete). Only `Handle` is available in older versions, though.
> Is it possible to build an interface > so that managed code user can pass a > managed (File)Stream? No, it's not possible to convert a stream to a file descriptor (`FILE`\*).
How to get the underlying stdio FILE* of a managed System.IO.FileStream?
[ "", ".net", "c++", "filestream", "stdio", "" ]
My webservice constructor is getting called each time that I call a webmethod. This is causing some problems with some new functionality that I am adding and I cannot figure out what I am doing wrong to cause this. The only place that I am newing the webservice is in global.asax.cs's Application\_Start, but if I remove the code to `new` the webservice, it still calls the constructor each time that I call a webmethod. I have tested this by browsing to the .asmx file and calling the webmethod's that way and I have also created a test console application that has a reference to the webservice and will call the methods that way. Both of these give the same results. I am using c# in ASP.NET 1.1. Any ideas? **Edit:** I am trying to create a heartbeat thread that polls a windows service. I am attempting to save the result in a hash table (multiple threads polling multiple services). I have changed the webmethod (as it used to poll the windows service) to get the results from the hashtable. We are trying to increase the speed of this webmethod call.
Whenever you call a web method, a new instance of the web service is created - this is the intended behaviour. Web services are stateless, which means that an instance of the service is not kept alive between web method calls, and therefore you cannot store any state in members (fields, properties) of the web service. If you want to save some values/state between web method calls, you have to use the ASP.NET session or a database for that purpose. See this question for details: [Is this supposed to work this way?](https://stackoverflow.com/questions/808168/is-this-supposed-to-work-this-way)
Err... this is kind of by design I'm afraid. Can you describe the problems you are getting and what you are trying to acheive, I think you need to refactor your design a little here.
Why is my WebService constructor getting called each time I call a webmethod?
[ "", "c#", "asp.net", "web-services", "constructor", ".net-1.1", "" ]
I use jQuery to get values of presaved elements from some websites, using paths like this: > HTML BODY #bodyContainer #mainContentContainer #mainContent #productContentRight #swatchContent #colorSwatchContent SPAN The problem i faced when the websites page contains tables and there are same element in another similar path such as: > /html/body/div/center/div/div[3]/div/table/tbody/tr[5]/td/div/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[3]/td In the last path as you can see that there are 5 `tr` which means that its possible to find the same element in another path. I use the path as a selector for jQuery and jQuery will return array of elements, i don't know which one is the right element. So my question is: How to save the path for better later use? and how to parse this new path to be ready as a jQuery selector. If the question is not clear please ask me and i will do my best to explain more.
I don't know why there are so many answers that you are using XPath because XPath was deprecated a long time ago and jQuery no longer supports it without the XPath compatibility plugin. See Release Notes of 1.2 : <http://www.learningjquery.com/2007/09/upgrading-to-jquery-12> XPath compatibility plugin : <http://docs.jquery.com/Release:jQuery_1.2#XPath_Compatibility_Plugin> Just use `$("#colorSwatchContent span")` as your selector. Which is a css style seclector meaning find me all descendent span elements of an element with id colorSwatchContent. Since id's in html are unique identitfiers, this is about as specific as you can get. `$("#colorSwatchContent > span")` will only select DIRECT descendents (immedieate children) `$("#colorSwatchContent > span:first")` will select the first span direct descendent
In order to grab one specific element when there are many that match you should give the elements classes, for example give each `table` a class describing what is in it, then give each `tr` a class describing what the row is about. Then each `td` with a class describing the specific part of the row that it describes, for example: ``` <table class="person"> <tr class="john-doe"> <td class="name">John Doe</td> <td class="phone-numbers"> <table class="phone-numbers"> <tr class="cell-phone"> <th class="label">Cell Phone:</th> <td class="number">555-1234</td> </tr> <tr class="home-phone"> <th class="label">Home Phone:</th> <td class="number">555-1234</td> </tr> </table> </td> </tr> </table> ``` Once you have your elements properly described then you can use CSS style selectors in jQuery. for example getting just the `td` that has the home phone would be as simple as doing: ``` $('table.person tr.home-phone td.number'); ``` Hope this gets you heading the right way. One thing to note tho, If you have incredibly complex table structures you might want to rethink whether it needs to be in a table or not.
How to get this element using jQuery selectors?
[ "", "javascript", "jquery", "html", "dom", "" ]
Does anyone know how to retrieve the option chosen from a drop-down select box? I'm using document.getElementById("mySelect").value and it doesn't seem to be working...
``` document.getElementById("mySelect").options[document.getElementById("mySelect").selectedIndex].value ```
Are you sure your drop-down has a value in it? Did you provide values for it? ``` <select id="dropdownBox"> <option value="val1">value 1</option> <option value="val2">value 2</option> <option value="val3">value 3</option> <option value="val4">value 4</option> </select> ``` The values are val1, val2...
How to figure out which option is chosen from a select field
[ "", "javascript", "html", "" ]
I have a small (200 rows / 400kb) table with 4 columns - nvarchar(MAX), nvarchar(50), and two ints. I'm having a problem with one particular row in which I can select and update the int fields, but when I attempt to select or update the nvarchar fields, the query runs indefinitely (at least 45 minutes before I cancel). I'm also unable to delete this row, or even truncate the table (again, the query runs indefinitely). Any ideas? One of the int fields has a primary key, but there are no foreign keys.
Looks like you have an uncommitted transaction locking things down. You can free them up through the Activity Monitor. It is located in the Management folder of the database you are looking at. Expand that, right click on Activity Monitor, and select View Processes. You can right click on processes and kill them there. This isn't always the best solution, especially with a production database. You generally want to figure out why the transaction is not committed, and either manually roll it back or commit it.
Are you sure that row isn't locked? Open a new connection, run your select query, note the SPID from either the top of the window 2000 / 2005 and the bottom 2008 management studio. In another window run `sp_who2`. Find the spid from the query running the record. If you don't care about uncommitted data, or just want to test the row, do: ``` select * from table with (nolock) where key = 'mykey' ```
Can't access single row in SQL Server 2005 table
[ "", "sql", "sql-server-2005", "" ]
I currently have a WCF Service with a CallBack Contract (duplex), and when I use the application that makes use of it on my computer everything works fine, but when I try it from a different computer, it doesn't connect. These problems started occurring once I switched to using this `wsDualHttpBinding` (for callbacks) because when I used `wsHttpBinding` everything worked fine. Why is the web service not accepting requests from other computers? Is it some hosting settings that need to be modified? --- As regards the logs, I am getting these: [alt text http://img17.imageshack.us/img17/4628/wcfissue.jpg](http://img17.imageshack.us/img17/4628/wcfissue.jpg) > The open operation did not complete > within the allotted timeout of > 00:01:00. The time allotted to this > operation may have been a portion of a > longer timeout > > Failed to open System.ServiceModel.Channels.ClientReliableDuplexSessionChannel > > Faulted > System.ServiceModel.Channels.ClientReliableDuplexSessionChannel > > Faulted > System.ServiceModel.Channels.ServiceChannel > > Failed to open > System.ServiceModel.Channels.ServiceChannel --- The port is open on my router (both TCP and UDP) so that is not the issue. As regards the Service Attributes, this is what I'm using: *Interface:* ``` [ServiceContract(Name = "MusicRepo_DBAccess_Service", CallbackContract = typeof(IOnlineUsersCallback), SessionMode=SessionMode.Required)] ``` *Service:* ``` [ServiceBehavior( ConcurrencyMode=ConcurrencyMode.Reentrant, InstanceContextMode=InstanceContextMode.Single)] ``` --- **[Update]** As regards [Orion Edwards](https://stackoverflow.com/questions/819871/wcf-failed-to-open-system-servicemodel-channels-clientreliableduplexsessionchann/837106#837106)' post: * No Firewall * See point 1 * Yes I can, because I have the port forwarded on my router * I'm using IIS to host the server. The thing is, this problem started happening when I switched from `wsHttpBinding` (which was working fine) to `wsDualHttpBinding` (because I needed callbacks) --- **[Update]** I have now switched from `wsDualHttpBinding` to `NetTcpBinding` and for some reason, everything is working fine. I have used [this article](http://www.singingeels.com/Articles/Duplex_WCF_Services_Hosted_in_IIS_Using_NetTcp.aspx) to help me set up hosting on IIS, and thankully everything is working as expected, with callbacks.
I have now switched from `wsDualHttpBinding` to `NetTcpBinding` and for some reason, everything is working fine. I have used [this article](http://www.singingeels.com/Articles/Duplex_WCF_Services_Hosted_in_IIS_Using_NetTcp.aspx) to help me set up hosting on IIS, and thankully everything is working as expected, with callbacks.
It would help if you posted the server and client configuration settings. Here's a summary of how the wsDualHttpBinding works from [MSDN](http://msdn.microsoft.com/en-us/library/ms731821.aspx) (emphasise mine): > The WSDualHttpBinding provides the > same support for Web Service protocols > as the WSHttpBinding, but for use with > duplex contracts. WSDualHttpBinding > only supports SOAP security and > requires reliable messaging. **This > binding requires that the client has a > public URI that provides a callback > endpoint for the service. This is > provided by the clientBaseAddress > attribute.** A dual binding exposes the > IP address of the client to the > service. The client should use > security to ensure that it only > connects to services it trusts. > > This binding can be used to > communicate reliably through one or > more SOAP intermediaries. > > By default, this binding generates a > runtime stack with > WS-ReliableMessaging for reliability, > WS-Security for message security and > authentication, HTTP for message > delivery, and a Text/XML message > encoding.
WCF: "Failed to open System.ServiceModel.Channels.ClientReliableDuplexSessionChannel"
[ "", "c#", "wcf", "web-services", "timeout", "wcf-binding", "" ]
I have a PHP page(registration.php) from where i would submit a file to another form(preocess.php) .So that in the next page that page will send that file as an attachment to an email id. Can i Call a function in another file and pass this file to that function ? It is some think like passing a stream to a function. (I am not sure .) Can anyone guide me on this ?
Absolutely, just include the file that originally calls the function. ``` <?php include ('file_with_function.php'); ?> ```
Should not pass a file around, better to handle it in the background. * store the file * put some id (in worst case the path) into session * forward the user to the next step (process.php) Better yet to review and refactor the code if necessary to make the processing in one step. This way you can avoid half-processed things, entry to the processing pipeline in the middle and similar common multi-page form handling problems.
PHP : Passing a file to a USer defined function
[ "", "php", "email", "" ]
OK here is what I would like to do. I have an array. What i want to do is make another array of the index values from the first one. Take the below I want to create and array from this : ``` Array ( [identifier] => ID [label] => HouseNum [items] => Array ( [0] => Array ( [ID] => 1 [HouseNum] => 17 [AptNum] => [Street] => birch glen dr [City] => Clifton Park [State] => NY [Zip5] => [EID] => E083223 [RequestDate] => 02/05/09 [Status] => In-Qeue [DateCompleted] => [CompletedBy] => [ContactName] => Suzy Q [ContactNumber] => 555-867-5309 [ContactTime] => 9-9 ) ) ); ``` That will end up looking like this : ``` Array( [0] => [ID] [1] => [HouseNum] [2] => [AptNum] [3] => [Street] [4] => [City] [5] => [State] [6] => [Zip5] [7] => [EID] [8] => [RequestDate] [9] => [Status] [10] => [DateCompleted] [11] => [CompletedBy] [12] => [ContactName] [13] => [ContactNumber] [14] => [ContactTime] ); ``` Any thoughts on how to achieve this ? I mostly need to know how to get just the index values.
``` $indexes = array_keys($whatever['items'][0]); ``` <http://us.php.net/manual/en/function.array-keys.php>
``` foreach($items[0] as $idx => $val) { $indexes[] = $idx; } ``` Or: ``` $indexes = array_keys($items[0]); ```
Create an array using the index values from another array
[ "", "php", "arrays", "" ]
I have a probably very basic problem with PIL's crop function: The cropped image's colors are totally screwed. Here's the code: ``` >>> from PIL import Image >>> img = Image.open('football.jpg') >>> img <PIL.JpegImagePlugin.JpegImageFile instance at 0x00 >>> img.format 'JPEG' >>> img.mode 'RGB' >>> box = (120,190,400,415) >>> area = img.crop(box) >>> area <PIL.Image._ImageCrop instance at 0x00D56328> >>> area.format >>> area.mode 'RGB' >>> output = open('cropped_football.jpg', 'w') >>> area.save(output) >>> output.close() ``` The original image: ![enter image description here](https://i.stack.imgur.com/xJCt3.jpg) [and the output](http://lh6.ggpht.com/_6sm8225Z3w8/SgG0AWKPUaI/AAAAAAAAAjw/SWP360wFo1M/cropped_football.jpg). As you can see, the output's colors are totally messed up... Thanks in advance for any help! -Hoff
`output` should be a file name, not a handler.
instead of ``` output = open('cropped_football.jpg', 'w') area.save(output) output.close() ``` just do ``` area.save('cropped_football.jpg') ```
Python's PIL crop problem: color of cropped image screwed
[ "", "python", "image-processing", "colors", "python-imaging-library", "crop", "" ]
I've been experiencing a high degree of flicker and UI lag in a small application I've developed to test a component that I've written for one of our applications. Because the flicker and lag was taking place during idle time (when there should--seriously--be nothing going on), I decided to do some investigating. I noticed a few threads in the Threads window that I wasn't aware of (not entirely unexpected), but what caught my eye was one of the threads was set to `Highest` priority. This thread exists at the time `Main()` is called, even before any of my code executes. I've discovered that this thread appears to be present in every .NET application I write, even console applications. Being the daring soul that I am, I decided to freeze the thread and see what happened. The flickering did indeed stop, but I experienced some oddness when it came to doing database interaction (I'm using SQL CE 3.5 SP1). My thought was that this might be the thread that the database is actually running on, but considering it's started at the time the application loads (before any references to the DB) and is present in other, non-database applications, I'm inclined to believe this isn't the case. Because this thread (like a few others) shows up with no data in the Location column and no Call Stack listed if I switch to it in the debugger while paused, I tried matching the StartAddress property through GetCurrentProcess().Threads for the corresponding thread, but it falls outside all of the currently loaded modules address ranges. Does anyone have any idea what this thread is, or how I might find out? **Edit** After doing some digging, it looks like the StartAddress is in kernel32.dll (based upon nearby memory contents). This leads me to think that this is just the standard system function used to start the thread, according to [this page](http://msdn.microsoft.com/en-us/library/system.diagnostics.processthread.startaddress.aspx), which basically puts me back at square one as far as determining where this thread actually comes from. This is further confirmed by the fact that ALL of the threads in this list have the same value for StartAddress, leading me to ask exactly what the purpose is...? **Edit 2** Process Explorer let me to an actually meaningful start address. It looks like it's `mscorwks.dll!CreateApplicationContext+0xbbef`. This dll is in %WINDOWS%\Microsoft.NET\Framework\v2.0.50, so it looks like it's clearly a runtime assembly. I'm still not sure why * it's Highest priority * it appears to be causing hiccups in my application
You could try using [Sysinternals](http://technet.microsoft.com/en-us/sysinternals/default.aspx). [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) let's you dig in pretty deep. Right click on the Process to access Properties. Then "Threads" tab. In there, you can see the thread's stack and module. EDIT: After [asking](https://stackoverflow.com/questions/830822) around some, it seems that your "Highest" priority thread is the `Finalizer` thread that runs due to a garbage collection. I still don't have a good reason as to why it would constantly keep running. Maybe you have some funky object lifetime behavior going on in your process?
I'm not sure what this is, but if you turn on unmanaged debugging, and set up Visual Studio with the [Windows symbol server](http://www.hanselman.com/blog/SetUpYourSystemToUseMicrosoftsPublicSymbolServer.aspx), you might get some more clues.
Determining the source of a thread
[ "", "c#", ".net", "multithreading", "debugging", "" ]
sqlite3\_column\_text returns a const unsigned char\*, how do I convert this to a std::string? I've tried std::string(), but I get an error. Code: ``` temp_doc.uuid = std::string(sqlite3_column_text(this->stmts.read_documents, 0)); ``` Error: ``` 1>.\storage_manager.cpp(109) : error C2440: '<function-style-cast>' : cannot convert from 'const unsigned char *' to 'std::string' 1> No constructor could take the source type, or constructor overload resolution was ambiguous ```
You could try: ``` temp_doc.uuid = std::string(reinterpret_cast<const char*>( sqlite3_column_text(this->stmts.read_documents, 0) )); ``` While `std::string` could have a constructor that takes `const unsigned char*`, apparently it does not. Why not, then? You could have a look at this somewhat related question: [Why do C++ streams use char instead of unsigned char?](https://stackoverflow.com/questions/277655/why-do-c-streams-use-char-instead-of-unsigned-char)
On the off-chance you actually want a string of unsigned characters, you could create your own type: ``` typedef std::basic_string <unsigned char> ustring; ``` You should then be able to say things like: ``` ustring s = sqlite3_column_text(this->stmts.read_documents, 0); ```
const unsigned char * to std::string
[ "", "c++", "std", "" ]
They seem to be equal. Can both have multiple keys separated by a comma.
Both are diffrent datakeysname are storing the name of the primay key column while datakeys will have the values for the that column. See the following examples. <http://www.highoncoding.com/Articles/87_Accessing_Invisible_Columns_of_GridView_Control.aspx>
DataKeyNames is where you specify the field names that comprise the key. It's compound to support compound keys. DataKeys stores the actual key values.
What is the difference between a Gridview's DataKeys property and DataKeyNames?
[ "", "c#", "asp.net", "gridview", "" ]
In my application I use the **WebClient** class to download files from a Webserver by simply calling the **DownloadFile** method. Now I need to check whether a certain file exists prior to downloading it (or in case I just want to make sure that it exists). I've got two questions with that: 1. What is the best way to check whether a file exists on a server without transfering to much data across the wire? (It's quite a huge number of files I need to check) 2. Is there a way to get the size of a given remote file without downloading it? Thanks in advance!
`WebClient` is fairly limited; if you switch to using `WebRequest`, then you gain the ability to send an HTTP HEAD request. When you issue the request, you should either get an error (if the file is missing), or a `WebResponse` with a valid `ContentLength` property. **Edit:** Example code: ``` WebRequest request = WebRequest.Create(new Uri("http://www.example.com/")); request.Method = "HEAD"; using(WebResponse response = request.GetResponse()) { Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType); } ```
When you request file using the **WebClient** Class, the 404 Error (File Not Found) will lead to an exception. Best way is to handle that exception and use a flag which can be set to see if the file exists or not. The example code goes as follows: ``` System.Net.HttpWebRequest request = null; System.Net.HttpWebResponse response = null; request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("www.example.com/somepath"); request.Timeout = 30000; try { response = (System.Net.HttpWebResponse)request.GetResponse(); flag = 1; } catch { flag = -1; } if (flag==1) { Console.WriteLine("File Found!!!"); } else { Console.WriteLine("File Not Found!!!"); } ``` You can put your code in respective if blocks. Hope it helps!
How to check if a file exists on a server using c# and the WebClient class
[ "", "c#", "http", "file", "webclient", "exists", "" ]
``` MyClass GlobalVar; int main() { MyClass VarInMain; } ```
A couple of things: 1. Typically, they're allocated in different places. Local variables are allocated on the stack, global variables are allocated elsewhere. 2. Local variables in main are only visible within main. On the other hand, a global variable may be accessed anywhere.
More differences: 1. If constructor/destructor of global object throws an exception, then function terminate is called and there is no chance to proceed. For local object, you can catch exception and do something (but it is still tricky to throw from destructor). 2. Order of construction/destruction of global objects is not well specified. This means, that generally for two global objects you cannot say, which one is constructed first. From the other hand, local objects are created at point of defintion and destructed at end of block in order reverse to order of creation. 3. Scope... (already mentioned) In general, it is not a good practice to use global objects without very strong reasons to do so. Using of globals often leads to code which is hard to maintain.
What's the difference between global variables and variables in main?
[ "", "c++", "" ]
I'm using the Linq to Entities. I've got my main table, Employee setup with a field named vendorID. Vendor ID is a foreign key into the Vendors table. As it is right now, the Employee object does not directly expose the vendorID. Instead, I can only access it this way: ``` var employee = (from e in context.Employees.Include("tbl_vendors") where e.employeeID = 1 select e).FirstOrDefault(); //this gets the vendor ID int vendorID = employee.tbl_vendors.vendorID; ``` That is just fine and dandy, but it is extra work on the database because it is forcing a join where none is needed. Is there a way to get that key value without being forced to do a join to the tbl\_vendors table?
You can access the foreign key via the entity reference. ``` Employee employee = context.Employees.Single(e => e.employeeID == 1); Int32 vendorID = (Int32)employee.tbl_vendorsReference.EntityKey. EntityKeyValues[0].Value; ``` See MSDN for reference on the [EntityReference](http://msdn.microsoft.com/de-de/library/bb154700(loband).aspx) and [EntityKey](http://msdn.microsoft.com/de-de/library/system.data.entitykey.aspx) classes.
Actually this is very simple you basically do this: ``` var tblVendorID = (from e in context.Employees select e.tbl_vendors.ID).FirstOrDefault(); ``` Even though this looks like you are doing a join L2E will optimize out the join. Which you can confirm with code like this: ``` var results = from e in ctx.Employees select e.tbl_vendors.ID; var query = results as ObjectQuery<int>; string sql = query.ToTraceString(); ``` Hope this helps Alex (Microsoft).
Linq to Entities (EF): How to get the value of a FK without doing the join
[ "", "c#", "asp.net", "entity-framework", "" ]
I have several vehicles that send a data to server each minute. The server should be listening and decode the data to store in the database. There will be thousands of entries per minute. What is the best approach to solve that problem?
My personal favorite, WCF or WebService farm pumps the data to a Microsoft Message Queue (MSMQ) and have a application server (1 or more) convert the data and put it into the DB. As you get deeper (if you ever need to), you can use the features of MSMQ to handle timeouts, load buffering, 'dead-letters', server failures, whatever. [Consider this article](http://www.csharphelp.com/archives3/archive581.html). On the web facing side of this, because it is stateless and thin you can easily scale out this layer without thinking about complex load balancing. You can use DNS load balancing to start and then move to a better solution when you need it. As a further note, by using MSMQ, you can also see how far 'behind' the system is by looking at how many messages are in the queue. If that number is near 0, then you good. If that number keeps rising non-stop, you need more performance (add another application server).
We're doing exactly what Jason says, except using a direct TCP/UDP socket listener with a custom payload for higher performance.
How the best solution to solve Vehicle Tracking GPS collecting data in C#?
[ "", "c#", "multithreading", "gps", "" ]
I have Javascript code that does this: `var oObjchbox = document.getElementById("CheckBox_" + countyId);` The countyId comes from an image map that is pre-made. The checkboxes on the other hand are created by ASP.NET. My first try was to use an asp.repeater with asp:checkBox, but that did not do the trick since ASP.NET insists on creating own IDs. The other try was to use HTML INPUT without runat=server, but then the checkboxes did not survive a roundtrip. Does anyone have a solution to this problem? I found a similar problem over here <http://www.velocityreviews.com/forums/t301617-hijack-databoundliteralcontrol.html> but no one answered his question.
If the problem is getting the ID from the Checkbox within a Repeater then this article might help, [Select All Checkboxes in a GridView](https://web.archive.org/web/20210316002334/http://aspnet.4guysfromrolla.com/articles/053106-1.aspx). It shows how to generate a Client Side select all feature on an ASP.Net Gridview. The issue you are dealing with is not an uncommon one. You want to access a control that is in a control that repeats layout (GridView, Repeater, DataList and the like) using JavaScript. The thing to remember is that you can access the generated ClientId during the DataBound events (**RowDataBound**, **ItemDataBound**) which can then be used on the client side. Then on the return trip as this is a standard control you should be able to find it. However if you are using a Repeater then Updating data might require a bit more work as the control itself is more designed for read-only type displays. If the problem is mapping each control to a predefined StateCode then in the ItemDataBound or RowDataBound(if you change from Repeater to Something else) events you could wire a call to a JavaScript method with 1 or 2 parameters depending on the need. Either the currentCheckBoxId and the appropriate StateCode separately or already concatenated and use that as a lookup type feature. Sorry for the two answers, but the question seemed a little vague as to what you were actually trying to do, maybe I just need another cup of coffee. Hope one of these ideas help.
You can use jquery for solve this problem, it provide functionality to select elements by custom query, for example $("[id\*=CheckBox1") - return all elements where end of id is CheckBox1. $("[id^=CheckBox1") - return all elements where start of id is CheckBox1. and you can find by contains word and many other selectors. For more information jquery.com, you will like it =)
Using checkboxes with ASP.NET and Javascript
[ "", "asp.net", "javascript", "input", "checkbox", "repeater", "" ]
Is there a built-in function in PHP or MySQL that will provide the total number of MySQL queries used on a page? I've seen on a lot of sites (mainly forums) they have a message at the bottom saying something like "Page generated in 0.6 seconds with 20 queries". If there's nothing built in then I'll add something to my database class to count them, but it seems like the kind of functionality that would already be available.
Option one would be to pass all of your queries through a wrapper: ``` function custom_mysql_query($sql) { $GLOBAL['query_count'] ++; return mysql_query($sql); } ``` Please note that's for illustration only and without error handling, etc. You could query MySQL for the number of queries run: ``` mysql> SHOW STATUS LIKE 'Com_select'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | Com_select | 2 | +---------------+-------+ 1 row in set (0.00 sec) ``` You might want to do something like: ``` SHOW STATUS LIKE 'Com_%'; ``` and then add together Com\_select, Com\_update, Com\_insert and Com\_delete
What I do is make an sql query class that counts, it adds 1 to a variable called querycount every time the query methods in the class are run, That way I have a running total.
How can I count the total number of MySQL queries used per page?
[ "", "php", "mysql", "count", "" ]
I was doing some testing with some sites (that I will not mention), and they are returning 200 code when they are page not found pages. Is this against any web development standard? This is the code that I am using to see the return code of a URL: ``` System.out.println(new String("getRespCode=" + urlConnection.getResponseCode() + ", HttpURLConnection=" + HttpURLConnection.HTTP_OK + "\n")); ``` Any ideas?
This is called a `Soft 404` or `False 404`. Wikipedia has a [detailled discussion](http://en.wikipedia.org/wiki/Soft_404#Soft_404_errors). It is not allowed by any web standard (and I don't know of any argument *in favor*), but so is invalid HTML.
Sounds like an error on their side. It may be possible too, that the 404 error was redirected to another page to display a better response, and that page is sending the 200.
Is it normal for a website to return HTTP Code 200 for a Page not Found(404) Page?
[ "", "java", "standards", "" ]
For the past few years, I've been working on a team that does .NET and SQL Server. I'll soon be joining a team that is Java and Oracle. What can I read/do to get up-to-speed.
This, similar, [SO Thread](https://stackoverflow.com/questions/471448/tips-for-moving-from-c-to-java/471739) might be helpful.
Start here: <http://java.sun.com/javase/6/docs/> Sun's documentation is pretty good. See also: * [Hidden Features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java) * [Best Java Book you have Read So Far](https://stackoverflow.com/questions/75102/best-java-book-you-have-read-so-far) * [Overriding Equals and Hashcode in Java](https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java) * [What is the Most Freequent Concurrency Problem You've Encountered in Java](https://stackoverflow.com/questions/461896/what-is-the-most-frequent-concurrency-problem-youve-encountered-in-java)
Switching from .NET to Java?
[ "", "java", ".net", "" ]
[It's recommended](http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html) that one should not put a PHP closing tag at the end of the file to avoid all sorts of untoward error. But is there any circumstances when PHP tag closing is needed?
A closing tag is needed if you want to switch from the PHP code block to the plain text output. Here’s an example: ``` <?php // PHP code block ?> <!-- plain text output and not processed by PHP --> </body> ```
BTW if you want to know what error you are preventing by skipping the closing tag. Since Zend's explanation doesn't go into detail. > It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response. This means that if you want to use header() to redirect some person to some other location or change the HTTP header in any way... then you can't and will get an error if some file ends like this. ``` } ?> //space here ``` Because then this space will be outputted to the site as content and then you can't modify the headers.
PHP tag closing-- when is needed?
[ "", "php", "" ]
Both should run in O(n log n), but in general sort is faster than stable\_sort. How big is the performance gap in practice? Do you have some experience about that? I want to sort a very large number of structs that have a size of about 20 bytes. The stability of the result would be nice in my case, but it is not a must. At the moment the underlying container is a plain array, perhaps it could be changed to a std::deque later on.
There are good answers that compared the algorithms theoretically. I benchmarked `std::sort` and `std::stable_sort` with [google/benchmark](http://github.com/google/benchmark) for curiosity's sake. It is useful to point out ahead of time that; * Benchmark machine has `1 X 2500 MHz CPU` and `1 GB RAM` * Benchmark OS `Arch Linux 2015.08 x86-64` * Benchmark compiled with `g++ 5.3.0` and `clang++ 3.7.0` (`-std=c++11`, `-O3` and `-pthread`) * `BM_Base*` benchmark tries to measure the time populating `std::vector<>`. That time should be subtracted from the sorting results for better comparison. First benchmark sorts `std::vector<int>` with `512k` size. ``` [ g++ ]# benchmark_sorts --benchmark_repetitions=10 Run on (1 X 2500 MHz CPU ) 2016-01-08 01:37:43 Benchmark Time(ns) CPU(ns) Iterations ---------------------------------------------------------------- ... BM_BaseInt/512k_mean 24730499 24726189 28 BM_BaseInt/512k_stddev 293107 310668 0 ... BM_SortInt/512k_mean 70967679 70799990 10 BM_SortInt/512k_stddev 1300811 1301295 0 ... BM_StableSortInt/512k_mean 73487904 73481467 9 BM_StableSortInt/512k_stddev 979966 925172 0 ``` ``` [ clang++ ]# benchmark_sorts --benchmark_repetitions=10 Run on (1 X 2500 MHz CPU ) 2016-01-08 01:39:07 Benchmark Time(ns) CPU(ns) Iterations ---------------------------------------------------------------- ... BM_BaseInt/512k_mean 26198558 26197526 27 BM_BaseInt/512k_stddev 320971 348314 0 ... BM_SortInt/512k_mean 70648019 70666660 10 BM_SortInt/512k_stddev 2030727 2033062 0 ... BM_StableSortInt/512k_mean 82004375 81999989 9 BM_StableSortInt/512k_stddev 197309 181453 0 ``` Second benchmark sorts `std::vector<S>` with `512k` size (`sizeof(Struct S) = 20`). ``` [ g++ ]# benchmark_sorts --benchmark_repetitions=10 Run on (1 X 2500 MHz CPU ) 2016-01-08 01:49:32 Benchmark Time(ns) CPU(ns) Iterations ---------------------------------------------------------------- ... BM_BaseStruct/512k_mean 26485063 26410254 26 BM_BaseStruct/512k_stddev 270355 128200 0 ... BM_SortStruct/512k_mean 81844178 81833325 8 BM_SortStruct/512k_stddev 240868 204088 0 ... BM_StableSortStruct/512k_mean 106945879 106857114 7 BM_StableSortStruct/512k_stddev 10446119 10341548 0 ``` ``` [ clang++ ]# benchmark_sorts --benchmark_repetitions=10 Run on (1 X 2500 MHz CPU ) 2016-01-08 01:53:01 Benchmark Time(ns) CPU(ns) Iterations ---------------------------------------------------------------- ... BM_BaseStruct/512k_mean 27327329 27280000 25 BM_BaseStruct/512k_stddev 488318 333059 0 ... BM_SortStruct/512k_mean 78611207 78407400 9 BM_SortStruct/512k_stddev 690207 372230 0 ... BM_StableSortStruct/512k_mean 109477231 109333325 8 BM_StableSortStruct/512k_stddev 11697084 11506626 0 ``` Anyone who likes to run the benchmark, here is the code, ``` #include <vector> #include <random> #include <algorithm> #include "benchmark/benchmark_api.h" #define SIZE 1024 << 9 static void BM_BaseInt(benchmark::State &state) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist; while (state.KeepRunning()) { std::vector<int> v; v.reserve(state.range_x()); for (int i = 0; i < state.range_x(); i++) { v.push_back(dist(mt)); } } } BENCHMARK(BM_BaseInt)->Arg(SIZE); static void BM_SortInt(benchmark::State &state) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist; while (state.KeepRunning()) { std::vector<int> v; v.reserve(state.range_x()); for (int i = 0; i < state.range_x(); i++) { v.push_back(dist(mt)); } std::sort(v.begin(), v.end()); } } BENCHMARK(BM_SortInt)->Arg(SIZE); static void BM_StableSortInt(benchmark::State &state) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist; while (state.KeepRunning()) { std::vector<int> v; v.reserve(state.range_x()); for (int i = 0; i < state.range_x(); i++) { v.push_back(dist(mt)); } std::stable_sort(v.begin(), v.end()); } } BENCHMARK(BM_StableSortInt)->Arg(SIZE); struct S { int key; int arr[4]; }; static void BM_BaseStruct(benchmark::State &state) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist; while (state.KeepRunning()) { std::vector<S> v; v.reserve(state.range_x()); for (int i = 0; i < state.range_x(); i++) { v.push_back({dist(mt)}); } } } BENCHMARK(BM_BaseStruct)->Arg(SIZE); static void BM_SortStruct(benchmark::State &state) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist; while (state.KeepRunning()) { std::vector<S> v; v.reserve(state.range_x()); for (int i = 0; i < state.range_x(); i++) { v.push_back({dist(mt)}); } std::sort(v.begin(), v.end(), [](const S &a, const S &b) { return a.key < b.key; }); } } BENCHMARK(BM_SortStruct)->Arg(SIZE); static void BM_StableSortStruct(benchmark::State &state) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist; while (state.KeepRunning()) { std::vector<S> v; v.reserve(state.range_x()); for (int i = 0; i < state.range_x(); i++) { v.push_back({dist(mt)}); } std::stable_sort(v.begin(), v.end(), [](const S &a, const S &b) { return a.key < b.key; }); } } BENCHMARK(BM_StableSortStruct)->Arg(SIZE); BENCHMARK_MAIN(); ```
[`std::stable_sort`](http://en.cppreference.com/w/cpp/algorithm/stable_sort) performs NlogN comparisons when sufficient memory is available. When insufficient memory is available, it degrades to N((logN)^2) comparisons. Therefore it is roughly of the same efficiency as [`std::sort`](http://en.cppreference.com/w/cpp/algorithm/sort) (which performs O(NlogN) comparisons in both average and worst case) when memory is available. For those interested, sort() uses an [introsort](http://en.wikipedia.org/wiki/Introsort) (quicksort which switches to heapsort when the recursion reaches a certain depth) and stable\_sort() uses a [merge sort](http://en.wikipedia.org/wiki/Merge_sort).
How big is the performance gap between std::sort and std::stable_sort in practice?
[ "", "c++", "sorting", "stl", "" ]
Is there an Ant API for reading and ant build.xml and retrieving elements from it? Specifically I want to be able to retrieve the values in a path element and be able to walk all of the elements in the path. My purpose is to retrieve a given path and ensure that it is referenced correctly in a manifest, so that the build and the manifest match when the product goes out to production. EDIT: Regarding the responses (and thank you for them) to use an XML API, the problem is that the build file as currently constructed is more complex than that. Namely the classpath references a different classpath and includes it and the elements referenced in the classpath are themselves defined in a properties file, so there is too much of the Ant API to reasonably recreate.
You can use the `ProjectHelper` class to configure your project with a buildfile. If the path you want to check is contained in a reference, then you can just get the reference from the project by its ID. For example, if you have something like this in your `build.xml`: ``` <path id="classpath"> <fileset dir="${basedir}/lib" includes="*.jar"/> </path> ``` Then you can get the `Path` reference with the following code: ``` import java.io.File; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; import org.apache.tools.ant.types.Path; public class Test { public static void main(String[] args) throws Exception { Project project = new Project(); File buildFile = new File("build.xml"); project.init(); ProjectHelper.configureProject(project, buildFile); Path path = (Path) project.getReference("classpath"); } } ``` Note that `ProjectHelper.configureProject` is deprecated in ant 1.6.2, but not in 1.7.
Some time we need to parse xml file in Ant script to run the java file or read some property value and more like this. It is very easy, we can do this with tag called `<xmlproperty>`. This tag loads the xml file and it convert all the values of xml file in ant property value internally and we can use those value as ant property. For example ``` <root> <properties> <foo>bar</foo> </properties> </root> ``` is roughly equivalent to this into ant script file as: `<property name="root.properties.foo" value="bar"/>` and you can print this value with ${root.properties.foo}. Complete Example: 1. Create one xml file say Info.xml 2. Create one ant script say Check.xml Info.xml ``` <?xml version="1.0" encoding="UTF-8"?> <Students> <Student> <name>Binod Kumar Suman</name> <roll>110</roll> <city> Bangalore </city> </Student> </Students> ``` Check.xml ``` <?xml version="1.0" encoding="UTF-8"?> <project name="Check" default="init"> <xmlproperty file="Info.xml" collapseAttributes="true"/> <target name = "init"> <echo> Student Name :: ${Students.Student.name} </echo> <echo> Roll :: ${Students.Student.roll} </echo> <echo> City :: ${Students.Student.city} </echo> </target> </project> ``` Now after run this (Check.xml) ant script, you will get output Buildfile: C:\XML\_ANT\_Workspace\XML\_ANT\src\Check.xml init: [echo] Student Name :: Binod Kumar Suman [echo] Roll :: 110 [echo] City :: Bangalore BUILD SUCCESSFUL Total time: 125 milliseconds It was very simple upto here, but if you have multiple records in xml (StudentsInfo.xml) then it will show all record with comma seperated like this Buildfile: C:\XML\_ANT\_Workspace\XML\_ANT\src\Check.xml init: [echo] Student Name :: Binod Kumar Suman,Pramod Modi,Manish Kumar [echo] Roll :: 110,120,130 [echo] City :: Bangalore,Japan,Patna BUILD SUCCESSFUL Total time: 109 milliseconds [Link](http://binodsuman.blogspot.com/2009/06/how-to-parse-xml-file-in-ant-script.html)
How to parse and interpret ant's build.xml
[ "", "java", "ant", "build", "classpath", "" ]
Is there a way to add item to a WinForms ListBox, to the beginning of the list without rewriting entire list in a loop? Other way to solve my problem would be to display ListBox in reverse order (last item on the top) but I don't know how to do it. My ListBox control is used as a log viewer where the most recent entry should be on the top.
Use the [`Insert`](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection.insert.aspx) method on the items of your `ListBox`.
If I understand correctly, can't you use the `Insert(int index, object item)` method? For example: ``` myListBox.Items.Insert(0, "First"); ``` This inserts "First" as the first item of the listbox.
How to add item to the beginning of the list in ListBox?
[ "", "c#", "winforms", "listbox", "" ]
I inherited a project that makes extensive use of JMS. It compiles, runs and passes all of its unit tests using Java 6 SE. I created a netbeans (v 6.5) free form project to go along with it. I added all the libraries and everything correctly (checked this several times). Now, here is the problem: it produces tons of Netbeans error messages saying things like "package javax.jms does not exist" and so forth. Since the project compiles under JDK 1.6 SE, I assume that javax.jms and friends exists in the JDK. However, Netbeans is obviously not finding it. My only clue as to what might be going wrong here is that under 'Project Properties' I can only select 1.3,1.4 and 1.5 - 1.6 source level is not an option. How can I make Netbeans see javax.jms?
`javax.jms` is not a standard part of the JDK. When you were compiling at the command line, you probably had some extra JARs on your classpath which NetBeans doesn't know about; jms-1.1.jar was apparently one of these. So all you need to do is add it as a library in NetBeans. I believe that since this is a free-form project, you'll have to modify your Ant script to do this. Off to try it myself now... **Edit:** [Here's a reference](http://www.netbeans.org/kb/articles/freeform-import.html#Chapter2.2) for setting up the code-completion classpath. I don't have any free-form projects lying around to test with.
JMS is not part of Java SE, it is part of Java EE. You will have to find a javaee.jar or some JMS specific jar that is provided with your JMS implementation.
How do I make Netbeans believe I have JMS?
[ "", "java", "netbeans", "jms", "" ]
I want to add some functionality track certain calls to ActiveX object methods in javascript. I usually create my activeX object like this: var tconn = new ActiveXObject("Tconnector"); I need to log every time the **open** method is called on tconn and all other instances of that activeX control. I cant modify tconn's prototype because it does not have one! I think that i can create a dummy ActiveXObject function that creates a proxy object to proxy calls to the real one. Can you help me do that? Note: writing a direct wrapper is out of question, because there are already 1000s of calls to this activeX within the application.
You can in fact override `ActiveXObject()`. This means you can try to build a transparent proxy object around the actual object and hook on method calls. This would mean you'd have to build a proxy around every method and property your ActiveX object has, unless you are absolutely sure there is no code whatsoever calling a particular method or property. I've built a small wrapper for the `"MSXML2.XMLHTTP"` object. There are probably all kinds of problems you can run into, so take that with a grain of salt: ``` var ActualActiveXObject = ActiveXObject; var ActiveXObject = function(progid) { var ax = new ActualActiveXObject(progid); if (progid.toLowerCase() == "msxml2.xmlhttp") { var o = { _ax: ax, _status: "fake", responseText: "", responseXml: null, readyState: 0, status: 0, statusText: 0, onReadyStateChange: null // add the other properties... }; o._onReadyStateChange = function() { var self = o; return function() { self.readyState = self._ax.readyState; self.responseText = self._ax.responseText; self.responseXml = self._ax.responseXml; self.status = self._ax.status; self.statusText = self._ax.statusText; if (self.onReadyStateChange) self.onReadyStateChange(); } }(); o.open = function(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword) { varAsync = (varAsync !== false); this._ax.onReadyStateChange = this._onReadyStateChange return this._ax.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword); }; o.send = function(varBody) { return this._ax.send(varBody); }; // add the other methods... } else { var o = ax; } return o; } function Test() { var r = new ActiveXObject('Msxml2.XMLHTTP'); alert(r._status); // "fake" r.onReadyStateChange = function() { alert(this.readyState); }; r.open("GET", "z.xml"); r.send(); alert(r.responseText); } ``` Disclaimer: Especially the async/onReadyStateChange handling probably isn't right, and the code may have other issues as well. As I said, it's just an idea. Handle with care. P.S.: A COM object is case-insensitive when it comes to method- and property names. This wrapper is (as all JavaScript) case-sensitive. For example, if your code happens to call both `"Send()"` and `"send()"`, you will need a skeleton "Send()" method in the wrapper as well: ``` o.Send = function() { return this.send.apply(this, arguments); }; ```
Thank you very much for your wrapper. With your help I was able to create a xmlrequest detector for IE and FF and the rest. I have added a version (combined from another example) that works for FF , IE and the rest of the gang, ``` if(window.XMLHttpRequest) { var XMLHttpRequest = window.XMLHttpRequest; // mystery: for some reason, doing "var oldSend = XMLHttpRequest.prototype.send;" and // calling it at the end of "newSend" doesn't work... var startTracing = function () { XMLHttpRequest.prototype.uniqueID = function() { // each XMLHttpRequest gets assigned a unique ID and memorizes it // in the "uniqueIDMemo" property if (!this.uniqueIDMemo) { this.uniqueIDMemo = Math.floor(Math.random() * 1000); } return this.uniqueIDMemo; } // backup original "open" function reference XMLHttpRequest.prototype.oldOpen = XMLHttpRequest.prototype.open; var newOpen = function(method, url, async, user, password) { console.log("[" + this.uniqueID() + "] intercepted open (" + method + " , " + url + " , " + async + " , " + user + " , " + password + ")"); this.oldOpen(method, url, async, user, password); } XMLHttpRequest.prototype.open = newOpen; // backup original "send" function reference XMLHttpRequest.prototype.oldSend = XMLHttpRequest.prototype.send; var newSend = function(a) { console.log("[" + this.uniqueID() + "] intercepted send (" + a + ")"); var xhr = this; var onload = function() { console.log("[" + xhr.uniqueID() + "] intercepted load: " + xhr.status + " " + xhr.responseText); }; var onerror = function() { console.log("[" + xhr.uniqueID() + "] intercepted error: " + xhr.status); }; xhr.addEventListener("load", onload, false); xhr.addEventListener("error", onerror, false); this.oldSend(a); } XMLHttpRequest.prototype.send = newSend; } startTracing(); } else if (window.ActiveXObject) { var ActualActiveXObject = ActiveXObject; var ActiveXObject = function(progid) { var ax = new ActualActiveXObject(progid); if (progid.toLowerCase() == "msxml2.xmlhttp") { var o = { _ax: ax, _status: "fake", responseText: "", responseXml: null, readyState: 0, status: 0, statusText: 0, onReadyStateChange: null }; o._onReadyStateChange = function() { var self = o; return function() { self.readyState = self._ax.readyState; if (self.readyState == 4) { self.responseText = self._ax.responseText; self.responseXml = self._ax.responseXml; self.status = self._ax.status; self.statusText = self._ax.statusText; } if (self.onReadyStateChange) self.onReadyStateChange(); } }(); o.open = function(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword) { console.log("intercepted open (" + bstrMethod + " , " + bstrUrl + " , " + varAsync + " , " + bstrUser + " , " + bstrPassword + ")"); varAsync = (varAsync !== false); this._ax.onReadyStateChange = this._onReadyStateChange return this._ax.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword); }; o.send = function(varBody) { return this._ax.send(varBody); }; } else var o = ax; return o; } } ```
Extending an ActiveXObject in javascript
[ "", "javascript", "proxy", "activex", "" ]
I would like to share an object between various instances of objects of the same class. Conceptually, while my program is running, all the objects of class A access the same object of class B. I've seen that `static` is system-wide and that its usage is discouraged. Does that mean that if I've got another program running on the same JVM that instantiates objects of class A, these objects could potentially access the same B object as the one accessed in the previous program? What are generally the flaws behind using static fields? Are there any alternatives (that do not require a huge effort of implementation)?
Static doesn't quite mean "shared by all instances" - it means "not related to a particular instance at all". In other words, you could get at the static field in class A without ever creating *any* instances. As for running two programs within the same JVM - it really depends on exactly what you mean by "running two programs". The static field is *effectively* associated with the class object, which is in turn associated with a classloader. So if these two programs use separate classloader instances, you'll have two independent static variables. If they both use the same classloader, then there'll only be one so they'll see each other's changes. As for an alternative - there are various options. One is to pass the reference to the "shared" object to the constructor of each object you create which needs it. It will then need to store that reference for later. This can be a bit of a pain and suck up a bit more memory than a static approach, but it does make for easy testability.
Static methods and members are discouraged because they're so frequently misused, but this sounds like a situation where static is the correct way to go. As to static shared across multiple programs, this is not the case. Each program runs in a completely separate environment.
What is the exact meaning of static fields in Java?
[ "", "java", "static", "jvm", "" ]
Although the actual schema is a bit more complex, the following should be a bit easier for me to get across. In one table I have a list of jobs: ``` Job Status Open date Close date 1 Closed 04/29/2009 04/30/2009 2 Open 04/30/2009 3 Open 04/30/2009 ``` ..and in another I have a list of notes associated with the jobs: ``` ID Job Type Date Text 1 1 Open 04/29/2009 Please fix my printer 2 1 Close 04/30/2009 Printer fixed 3 2 Open 04/30/2009 Please fix my monitor 4 2 Update 04/30/2009 Part required 5 3 Open 05/01/2009 Please fix my mouse ``` Each job will have an "Open" note, optionally one or more "Update" notes, and optionally a "Close" note. There is obviously a one-many relationship on the Job field. What I'd like to have is a single query that returns a list of jobs, open date, opening note and, if present, closing note, like this: ``` Job Status Open date Open note Close note 1 Closed 04/29/2009 Please fix my printer Printer fixed 2 Open 04/30/2009 Please fix my monitor 3 Open 04/30/2009 Please fix my mouse ``` My attempts at doing this always fail because I end up with the following: ``` Job Status Open date Open note Close note 1 Closed 04/29/2009 Please fix my printer 1 Closed 04/29/2009 Printer fixed 2 Open 04/30/2009 Please fix my monitor 2 Open 04/30/2009 3 Open 05/01/2009 Please fix my mouse 3 Open 05/01/2009 ``` ..or: ``` Job Status Open date Open note Close note 1 Closed 04/29/2009 Please fix my printer 1 Closed 04/29/2009 Printer fixed 2 Open 04/30/2009 Please fix my monitor 3 Open 05/01/2009 Please fix my mouse ``` I'm using SQL in Access 2003 and although the eventual query will be from an Excel front-end via ADO, I'm only trying to get this working from within Access at the moment.
What 1800 Information said, but that won't work correctly without a predicate to limit the join to open and closed notes, respectively: ``` select a.job, a.status, a.opendate, b.note as opennote, c.note as closenote from job a join note b on (a.job = b.job and b.type = 'Open') left outer join note c on (a.job = c.job and c.type = 'Closed'); ```
The solution suggested by tpdi worked when I created the command in Access, but then threw a "join expression not supported" wobbler when I tried to edit it, or run the query via ADODB from Excel. Closing the MDB and reopening was enough to let me run it again, but as soon as I tried to view/edit it in the SQL or QBE views it would start throwing exceptions. Eventually I could not open or edit the query, even after a "compact & repair" - presumably some sort of internal corruption within Access. Strangely though, I was able to get it working by referencing the query (`SELECT * FROM noteReport;`) - weird. It appears that my initial success was a fluke, as I was not able to recreate the exact query and have it work again. However, I was eventually able to replicate the desired report with the following: ``` SELECT a.callReference, b.callPriority, datevalue(INT(a.openedDT)), b.callerFirstName & ' ' & b.callerSurname AS Caller, c.noteText, d.noteText FROM ((tblMain AS a INNER JOIN tblCalldetails AS b ON a.callreference=b.callReference) LEFT JOIN tblNotes AS c ON a.callReference=c.callReference) LEFT JOIN tblNotes AS d ON a. callReference =d.callReference WHERE a.status = 'Closed' AND c.noteType='Open' AND d.noteType='Closing' AND INT(a.closedDT) = #5/1/2009#; ``` Posting this here as much as for my benefit as for anyone else that may find this via Google.
Return parts of two different records from same table in one query
[ "", "sql", "ms-access", "" ]
I'm inserting a bunch of new rows into a table which is defined as follows: ``` CREATE TABLE [sometable]( [id] [int] IDENTITY(1,1) NOT NULL, [someval] sometype NOT NULL ) ``` using the following insert: ``` insert into sometable select somefield as someval from othertable ``` when I've finished, I'd like to know the IDs of all the newly inserted rows. `SCOPE_IDENTITY()` only returns the ID last row inserted. How can I get all the new IDs? One method that springs to mind would be to grab the current largest identity from sometable and the scope\_identity() post-insert, and use these two values to select from sometable. For example: ``` declare @currentMaxId int; select @currentMaxId=MAX(id) from sometable insert into sometable select somefield as someval from othertable select * from sometable where id>@currentMaxId and id<=SCOPE_IDENTITY() ``` Is there a better pattern?
Use the OUTPUT functionality to grab all the INSERTED Id back into a table. ``` CREATE TABLE MyTable ( MyPK INT IDENTITY(1,1) NOT NULL, MyColumn NVARCHAR(1000) ) DECLARE @myNewPKTable TABLE (myNewPK INT) INSERT INTO MyTable ( MyColumn ) OUTPUT INSERTED.MyPK INTO @myNewPKTable SELECT sysobjects.name FROM sysobjects SELECT * FROM @myNewPKTable ```
Expanding on @Robin Day's answer -- you can map your temp Id's to the new Id's using a `MERGE` trick. ``` DECLARE @Keys TABLE (TempId INT, RealId INT) MERGE MyTable USING @NewStuff t ON 1 = 0 WHEN NOT MATCHED THEN INSERT (col1, col2, col3) VALUES (t.col1, t.col2, t.col3) OUTPUT t.TempId, Inserted.RealId INTO @Keys ``` From @Ivan Starostin's clever answer here: [List of inserted ID in SQL Server](https://stackoverflow.com/questions/37612195/list-of-inserted-id-in-sql-server?rq=1)
Getting new IDs after insert
[ "", "sql", "sql-server", "insert", "identity", "" ]
I'm doing something in Java SE that would require me to use SSL in an unusual way. The required steps would be something like: * Establish an SSL session; * Exchange some private information; * Renegotiate connection parameters to stop using cryptographic operations. I haven't found in the Java API a way to to this. I believe that the problem solution would somehow be addressed by using the session renegotiation but with a cipher suite with no cryptographic operations, but there isn't such an option; or to access the underling socket and bypass cryptographic operations. Are any of these options possible? Do you believe that such functionality would be available in other languages and frameworks (C, PHP, Ruby, .NET, Perl, Python, etc.)? Thanks for the help, Luís M. Costa
You could do something like this in Java, but it's definitely not standard. I can't vouch for other platforms having the necessary support for this. The JSSE provides support for transport-independent SSL with the [`SSLEngine`](http://java.sun.com/javase/6/docs/api/javax/net/ssl/SSLEngine.html). You could use this to temporarily "decorate" a socket with SSL, then turn it off when you are done and use the raw socket IO directly. I can't guess why you'd want to turn off SSL once you had gone to the expense of negotiating the SSL session. If it is for the sake of performance, you can renegotiate the cipher suite to use "NULL" confidentiality and integrity protocols, as long as both parties allow it. You'd still have a little overhead in the SSL record layer. However, the overhead of SSL after the session parameters have been negotiated is extremely low. If your application is that sensitive to this overhead, you might want to consider dedicated SSL hardware.
One reason to turn off SSL on the existing socket is for implementing the FTP clear control channel (CCC) command (FTP over TLS). This switches the control channel back to cleartext so that firewalls can see the dynamic port request.
Java SSL renegotiation (from SSL to clear channel)
[ "", "java", "ssl", "interop", "" ]
I'm trying to update my current project from 1.7 to 1.8. What do I have to change so that it does not break?
most features will still work with legacy code. try it out on your test environment and read the ZF change log. one important thing is that the loader works differently now. especially if you're using autoload. Until 1.7 ``` require_once 'Zend/Loader.php'; Zend_Loader::registerAutoload(); ``` Since 1.8 ``` require_once 'Zend/Loader/Autoloader.php'; $loader = Zend_Loader_Autoloader::getInstance(); $loader->registerNamespace('Namespace_'); ```
**Short answer:** Run your test suite and check the results ;) **Long answer:** I remember two points where backward compatibility was broken: 1. If your bootstrapping does not set the Zend\_Locale correctly, ZF >= 1.7.2 will throw an exception that it cannot detect the browsers Locale if you run a script via *console*. 2. [Zend\_View changes in 1.7.5](http://weierophinney.net/matthew/archives/206-Zend-Framework-1.7.5-Released-Important-Note-Regarding-Zend_View.html)
Updating web app from Zend Framework 1.7 to 1.8
[ "", "php", "zend-framework", "" ]
I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?
[Unidecode](http://pypi.python.org/pypi/Unidecode) looks like a complete solution. It converts fancy quotes to ascii quotes, accented latin characters to unaccented and even attempts transliteration to deal with characters that don't have ASCII equivalents. That way your users don't have to see a bunch of ? when you had to pass their text through a legacy 7-bit ascii system. ``` >>> from unidecode import unidecode >>> print unidecode(u"\u5317\u4EB0") Bei Jing ``` <http://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/>
In my original answer, I also suggested `unicodedata.normalize`. However, I decided to test it out and it turns out it doesn't work with Unicode quotation marks. It does a good job translating accented Unicode characters, so I'm guessing `unicodedata.normalize` is implemented using the `unicode.decomposition` function, which leads me to believe it probably can only handle Unicode characters that are combinations of a letter and a diacritical mark, but I'm not really an expert on the Unicode specification, so I could just be full of hot air... In any event, you can use `unicode.translate` to deal with punctuation characters instead. The `translate` method takes a dictionary of Unicode ordinals to Unicode ordinals, thus you can create a mapping that translates Unicode-only punctuation to ASCII-compatible punctuation: ``` 'Maps left and right single and double quotation marks' 'into ASCII single and double quotation marks' >>> punctuation = { 0x2018:0x27, 0x2019:0x27, 0x201C:0x22, 0x201D:0x22 } >>> teststring = u'\u201Chello, world!\u201D' >>> teststring.translate(punctuation).encode('ascii', 'ignore') '"hello, world!"' ``` You can add more punctuation mappings if needed, but I don't think you necessarily need to worry about handling every single Unicode punctuation character. If you *do* need to handle accents and other diacritical marks, you can still use `unicodedata.normalize` to deal with those characters.
Where is Python's "best ASCII for this Unicode" database?
[ "", "python", "unicode", "ascii", "" ]
I have written a class that extends JPanel. Is it possible to use this in the NetBeans GUI Builder and have it survive all of the automatic code generation? I have used the customised code option in the GUI builder to instantiate the object as the new class, but it seems like the declaration can't be changed from JPanel, so only methods that I have overridden get called, I can't call new ones that are not present in JPanel.
Simply drag the class from the projects tree on to the form in the GUI designer. Just like it says in [stackoverflow question 691890](https://stackoverflow.com/questions/691890/reusing-a-jpanel-in-netbeans-gui-designer).
You can use the Palette Manager to add your component to the palette, then you can use it in the GUI builder as you would any other class. At one point this was covered on the NetBeans Wiki, which is now defunct. Now the only official documentation I can find on it is [in the new Apache NetBeans knowledge base](https://netbeans.apache.org/kb/docs/java/quickstart-gui.html#_getting_familiar_with_the_gui_builder): > For advanced developers, the Palette Manager is available that enables you to add custom components from JARs, libraries, or other projects to the Palette. To add custom components through the Palette Manager, choose Tools > Palette > Swing/AWT Components.
How to include custom panel with NetBeans GUI Builder?
[ "", "java", "swing", "netbeans", "jpanel", "" ]
I understand the purpose of events, especially within the context of creating user interfaces. I think this is the prototype for creating an event: ``` public void EventName(object sender, EventArgs e); ``` What do event handlers do, why are they needed, and how do I to create one?
To understand event handlers, you need to understand [delegates](https://msdn.microsoft.com/en-us/library/ms173171.aspx). In [C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29), you can think of a delegate as a pointer (or a reference) to a method. This is useful because the pointer can be passed around as a value. The central concept of a delegate is its signature, or shape. That is (1) the return type and (2) the input arguments. For example, if we create a delegate `void MyDelegate(object sender, EventArgs e)`, it can only point to methods which return `void`, and take an `object` and `EventArgs`. Kind of like a square hole and a square peg. So we say these methods have the same signature, or shape, as the delegate. So knowing how to create a reference to a method, let's think about the purpose of events: we want to cause some code to be executed when something happens elsewhere in the system - or "handle the event". To do this, we create specific methods for the code we want to be executed. The glue between the event and the methods to be executed are the delegates. The event must internally store a "list" of pointers to the methods to call when the event is raised.\* Of course, to be able to call a method, we need to know what arguments to pass to it! We use the delegate as the "contract" between the event and all the specific methods that will be called. So the default `EventHandler` (and many like it) represents a *specific shape of method* (again, void/object-EventArgs). When you declare an event, you are saying *which shape of method* (EventHandler) that event will invoke, by specifying a delegate: ``` //This delegate can be used to point to methods //which return void and take a string. public delegate void MyEventHandler(string foo); //This event can cause any method which conforms //to MyEventHandler to be called. public event MyEventHandler SomethingHappened; //Here is some code I want to be executed //when SomethingHappened fires. void HandleSomethingHappened(string foo) { //Do some stuff } //I am creating a delegate (pointer) to HandleSomethingHappened //and adding it to SomethingHappened's list of "Event Handlers". myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened); //To raise the event within a method. SomethingHappened("bar"); ``` (\*This is the key to events in .NET and peels away the "magic" - an event is really, under the covers, just a list of methods of the same "shape". The list is stored where the event lives. When the event is "raised", it's really just "go through this list of methods and call each one, using these values as the parameters". Assigning an event handler is just a prettier, easier way of adding your method to this list of methods to be called).
C# knows two terms, `delegate` and `event`. Let's start with the first one. ## Delegate A `delegate` is a reference to a method. Just like you can create a reference to an instance: ``` MyClass instance = myFactory.GetInstance(); ``` You can use a delegate to create an reference to a method: ``` Action myMethod = myFactory.GetInstance; ``` Now that you have this reference to a method, you can call the method via the reference: ``` MyClass instance = myMethod(); ``` But why would you? You can also just call `myFactory.GetInstance()` directly. In this case you can. However, there are many cases to think about where you don't want the rest of the application to have knowledge of `myFactory` or to call `myFactory.GetInstance()` directly. An obvious one is if you want to be able to replace `myFactory.GetInstance()` into `myOfflineFakeFactory.GetInstance()` from one central place (aka **factory method pattern**). ### Factory method pattern So, if you have a `TheOtherClass` class and it needs to use the `myFactory.GetInstance()`, this is how the code will look like without delegates (you'll need to let `TheOtherClass` know about the type of your `myFactory`): ``` TheOtherClass toc; //... toc.SetFactory(myFactory); class TheOtherClass { public void SetFactory(MyFactory factory) { // set here } } ``` If you'd use delegates, you don't have to expose the type of my factory: ``` TheOtherClass toc; //... Action factoryMethod = myFactory.GetInstance; toc.SetFactoryMethod(factoryMethod); class TheOtherClass { public void SetFactoryMethod(Action factoryMethod) { // set here } } ``` Thus, you can give a delegate to some other class to use, without exposing your type to them. The only thing you're exposing is the signature of your method (how many parameters you have and such). "Signature of my method", where did I hear that before? O yes, interfaces!!! interfaces describe the signature of a whole class. Think of delegates as describing the signature of only one method! Another large difference between an interface and a delegate is that when you're writing your class, you don't have to say to C# "this method implements that type of delegate". With interfaces, you do need to say "this class implements that type of an interface". Further, a delegate reference can (with some restrictions, see below) reference multiple methods (called `MulticastDelegate`). This means that when you call the delegate, multiple explicitly-attached methods will be executed. An object reference can always only reference to one object. The restrictions for a `MulticastDelegate` are that the (method/delegate) signature should not have any return value (`void`) and the keywords `out` and `ref` is not used in the signature. Obviously, you can't call two methods that return a number and expect them to return the same number. Once the signature complies, the delegate is automatically a `MulticastDelegate`. ## Event Events are just properties (like the get;set; properties to instance fields) which expose subscription to the delegate from other objects. These properties, however, don't support get;set;. Instead, they support add; remove; So you can have: ``` Action myField; public event Action MyProperty { add { myField += value; } remove { myField -= value; } } ``` ## Usage in UI (WinForms,WPF,UWP So on) So, now we know that a delegate is a reference to a method and that we can have an event to let the world know that they can give us their methods to be referenced from our delegate, and we are a UI button, then: we can ask anyone who is interested in whether I was clicked, to register their method with us (via the event we exposed). We can use all those methods that were given to us and reference them by our delegate. And then, we'll wait and wait.... until a user comes and clicks on that button, then we'll have enough reason to invoke the delegate. And because the delegate references all those methods given to us, all those methods will be invoked. We don't know what those methods do, nor we know which class implements those methods. All we do care about is that someone was interested in us being clicked, and gave us a reference to a method that complied with our desired signature. ## Java Languages like Java don't have delegates. They use interfaces instead. The way they do that is to ask anyone who is interested in 'us being clicked', to implement a certain interface (with a certain method we can call), then give us the whole instance that implements the interface. We keep a list of all objects implementing this interface and can call their 'certain method we can call' whenever we get clicked.
Understanding events and event handlers in C#
[ "", "c#", ".net", "events", "event-handling", "" ]
It seems like I can serialize classes that don't have that interface, so I am unclear on its purpose.
`ISerializable` is used to provide custom binary serialization, usually for `BinaryFormatter` (and perhaps for remoting purposes). Without it, it uses the fields, which can be: * inefficient; if there are fields that are only used for efficiency at runtime, but can be removed for serialization (for example, a dictionary may look different when serialized) * inefficient; as even for fields that are needed it needs to include a lot of additional metadata * invalid; if there are fields that **cannot** be serialized (such as event delegates, although they can be marked `[NonSerialized]`) * brittle; your serialization is now bound to the *field* names - but fields are meant to be an implementation detail; see also [Obfuscation, serialization and automatically implemented properties](http://marcgravell.blogspot.com/2009/03/obfuscation-serialization-and.html) By implementing `ISerializable` you can provide your own binary serialization mechanism. Note that the xml equivalent of this is `IXmlSerializable`, as used by `XmlSerializer` etc. For DTO purposes, `BinaryFormatter` should be avoided - things like xml (via `XmlSerializer` or `DataContractSerializer`) or json are good, as are cross-platform formats like protocol buffers. For completeness, protobuf-net does include hooks for `ISerializable` (allowing you to use a portable binary format without writing lots of code), but `BinaryFormatter` wouldn't be your first choice here anyway.
Classes can be serialized in .NET in one of two ways: 1. Marking the class with `SerializableAttribute` and decorating all the fields that you *don't* want to be serialized with the `NonSerialized` attribute. (As Marc Gravell points out, `BinaryFormatter`, which is the class typically used to format `ISerializable` objects, automatically serializes all fields unless they are specifically marked otherwise.) 2. Implementing the `ISerializable` interface for fully custom serialization. The former is simpler to use as it simply involves marking declarations with attributes, but is limited in its power. The latter allows more flexibility but takes significantly more effort to implement. Which one you should use depends completely on the context. Regarding the latter (`ISerializable`) and it usage, I've quoted from the [MSDN page](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx) for the interface: > Any class that might be serialized > must be marked with the > SerializableAttribute. If a class > needs to control its serialization > process, it can implement the > ISerializable interface. The Formatter > calls the GetObjectData at > serialization time and populates the > supplied SerializationInfo with all > the data required to represent the > object. The Formatter creates a > SerializationInfo with the type of the > object in the graph. Objects that need > to send proxies for themselves can use > the FullTypeName and AssemblyName > methods on SerializationInfo to change > the transmitted information. > > In the case of class inheritance, it > is possible to serialize a class that > derives from a base class that > implements ISerializable. In this > case, the derived class should call > the base class implementation of > GetObjectData inside its > implementation of GetObjectData. > Otherwise, the data from the base > class will not be serialized.
What is the point of the ISerializable interface?
[ "", "c#", "serializable", "iserializable", "" ]
I'm fleshing out a WPF business application in my head and one thing that sparked my interest was how I should handle making it incredibly modular. For example, my main application would simply contain the basics to start the interface, load the modules, connect to the server, etc. These modules, in the form of class libraries, would contains their own logic and WPF windows. Modules could define their own resource dictionaries and all pull from the main application's resource dictionary for common brushes and such. What's the best way to implement a system of this nature? How should the main interface be built so that the modules it loads can alter virtually any aspect of its user interface and logic? I realize it's a fairly vague question, but I'm simply looking for general input and brainstorming. Thanks!
Check out [Composite Client Application Guidance](http://msdn.microsoft.com/en-us/library/cc707819.aspx) The Composite Application Library is designed to help architects and developers achieve the following objectives: Create a complex application from modules that can be built, assembled, and, optionally, deployed by independent teams using WPF or Silverlight. Minimize cross-team dependencies and allow teams to specialize in different areas, such as user interface (UI) design, business logic implementation, and infrastructure code development. Use an architecture that promotes reusability across independent teams. Increase the quality of applications by abstracting common services that are available to all the teams. Incrementally integrate new capabilities.
First of all you might be interested in [SharpDevelop](http://www.icsharpcode.net/OpenSource/SD/) implementation. It is based on it's own addin system known as AddInTree. It is a separate project and can be used within your own solutions for free. Everything is split across different addins where addins are easily added/removed/configured by means of xml files. SharpDevelop is an open source project so you'll have a chance examining how the infrastructure is introduced, as well as service bus and cross-addin integrations. The core addin tree can be easily moved to WPF project without implications. Next option is taking "[Composite Client Application Guidance](http://msdn.microsoft.com/en-us/library/cc707819.aspx)" (aka [Prism](http://www.codeplex.com/prism), aka [CompositeWPF](http://www.codeplex.com/CompositeWPF)) already mentioned earlier. You will get the Unity (Object builder) support out-of-box, Event Aggregation as well as the set of valuable design patterns implemented. If you want to perform some low level design and architecture yourself the [MEF](http://www.codeplex.com/mef) will be the best choise (though working with all three I personally like this one). This is what VS 2010 will be based on so you might be sure the project won't lose support in future. My advice is elaborating on these approaches and selecting the best and efficient one that perfectly suits your needs and the needs of your project.
Building a highly modular business application with WPF?
[ "", "c#", "wpf", "module", "add-in", "" ]
**Duplicate:** [What is the best way to create rounded corners](https://stackoverflow.com/questions/7089/what-is-the-best-way-to-create-rounded-corners-using-css) [How to make a cross browser, W3C valid, semantic, non-javascript ROUND corner?](https://stackoverflow.com/questions/746627/) What techniques (That are standards compliant) are there for putting rounded corners on display elements in an HTML page? I put HTML CSS and javascript on the tag list below because I believe they are fairly ubiquitous, but if you have a technique that uses other techniques that may be used and are (relatively) reliable across standard browsers that works as well, but please put a note on what browsers fail.
CSS3 has a border-radius tag and box-shadow tag, but they are only implemented in Mozilla and Safari I think. You can round corners and create shadow very easily using that. <http://www.css3.info/preview/rounded-border/> Other then that, what I do is create images and load those using CSS and DIV tags. This link is what I used to get started. <http://www.cssjuice.com/25-rounded-corners-techniques-with-css/> Good luck!
At a company I have previously worked at, there were extensive quantities of graphics resources that were just rounded edges to enable this. Clunky to manage, but it worked well and looked really nice.
Rounded Corners
[ "", "javascript", "html", "css", "" ]
I would like to parse out any HTML data that is returned wrapped in CDATA. As an example `<![CDATA[<table><tr><td>Approved</td></tr></table>]]>` Thanks!
The expression to handle your example would be ``` \<\!\[CDATA\[(?<text>[^\]]*)\]\]\> ``` Where the group "text" will contain your HTML. The C# code you need is: ``` using System.Text.RegularExpressions; RegexOptions options = RegexOptions.None; Regex regex = new Regex(@"\<\!\[CDATA\[(?<text>[^\]]*)\]\]\>", options); string input = @"<![CDATA[<table><tr><td>Approved</td></tr></table>]]>"; // Check for match bool isMatch = regex.IsMatch(input); if( isMatch ) Match match = regex.Match(input); string HTMLtext = match.Groups["text"].Value; end if ``` The "input" variable is in there just to use the sample input you provided
I know this might seem incredibly simple, but have you tried string.Replace()? ``` string x = "<![CDATA[<table><tr><td>Approved</td></tr></table>]]>"; string y = x.Replace("<![CDATA[", string.Empty).Replace("]]>", string.Empty); ``` There are probably more efficient ways to handle this, but it might be that you want something that easy...
Regex to parse out html from CDATA with C#
[ "", "c#", "regex", "cdata", "" ]
I've been searching for some good guidance on this since the concept was introduced in .net 2.0. Why would I ever want to use non-nullable data types in c#? (A better question is why wouldn't I choose nullable types by default, and only use non-nullable types when that explicitly makes sense.) Is there a 'significant' performance hit to choosing a nullable data type over its non-nullable peer? I much prefer to check my values against null instead of Guid.empty, string.empty, DateTime.MinValue,<= 0, etc, and to work with nullable types in general. And the only reason I don't choose nullable types more often is the itchy feeling in the back of my head that makes me feel like it's more than backwards compatibility that forces that extra '?' character to explicitly allow a null value. Is there anybody out there that always (most always) chooses nullable types rather than non-nullable types? Thanks for your time,
The reason why you shouldn't always use nullable types is that sometimes you're able to guarantee that a value *will* be initialized. And you should try to design your code so that this is the case as often as possible. If there is no way a value can possibly be uninitialized, then there is no reason why null should be a legal value for it. As a very simple example, consider this: ``` List<int> list = new List<int>() int c = list.Count; ``` This is *always* valid. There is no possible way in which `c` could be uninitialized. If it was turned into an `int?`, you would effectively be telling readers of the code "this value might be null. Make sure to check before you use it". But we know that this can never happen, so why not expose this guarantee in the code? You are absolutely right in cases where a value is optional. If we have a function that may or may not return a string, then return null. Don't return string.Empty(). Don't return "magic values". But not all values are optional. And making everything optional makes the rest of your code far more complicated (it adds another code path that has to be handled). If you can specifically guarantee that this value will always be valid, then why throw away this information? That's what you do by making it a nullable type. Now the value may or may not exist, and anyone using the value will have to handle both cases. But you know that only one of these cases is possible in the first place. So do users of your code a favor, and reflect this fact in your code. Any users of your code can then rely on the value being valid, and they only have to handle a single case rather than two.
Because it's inconvenient to always have to check whether the nullable type is `null`. Obviously there are situations where a value is genuinely optional, and in those cases it makes sense to use a nullable type rather than magic numbers etc, but where possible I would try to avoid them. ``` // nice and simple, this will always work int a = myInt; // compiler won't let you do this int b = myNullableInt; // compiler allows these, but causes runtime error if myNullableInt is null int c = (int)myNullableInt; int d = myNullableInt.Value; // instead you need to do something like these, cumbersome and less readable int e = myNullableInt ?? defaultValue; int f = myNullableInt.HasValue ? myNullableInt : GetValueFromSomewhere(); ```
Why shouldn't I always use nullable types in C#
[ "", "c#", "null", "c#-2.0", "nullable", "" ]
I have this script- ``` import lxml from lxml.cssselect import CSSSelector from lxml.etree import fromstring from lxml.html import parse website = parse('http://example.com').getroot() selector = website.cssselect('.name') for i in range(0,18): print selector[i].text_content() ``` As you can see the for loop stops after a number of times that I set beforehand. I want the for loop to stop only after it has printed everything.
The CSSSelector.cssselect() method returns an iterable, so you can just do: ``` for element in selector: print element.text_content() ```
What about ``` for e in selector: print e.text_content() ``` ?
Python Iterator Help + lxml
[ "", "python", "iterator", "for-loop", "lxml", "" ]
``` $('.Schedule .Full input').each(function(i) { var controls = $('.Morning input, .MorningPart input, .Afternoon input, .AfternoonPart input', $(this).parents('.Schedule')); alert(controls.length + " Conflicting Controls\n"+ $(this).parents('.Schedule').attr('id') + " Parent"); }); ``` When I run this code in Firefox the first execution of this function produces an alert box saying the following: > 17 Conflicting Controls > Monday Parent The exact same page run in IE 6 or 7 produces an alert box saying the following: > 45 Conflicting Controls > Monday Parent Firefox is right, there are only 17 conflicting controls. The 45 that IE is identifying are controls that are not a descendant of "Monday". If I've specified "Monday" as the context for the $() function, why is IE returning controls outside of it?
Give this a try ``` var controls = $(this).parents('.Schedule').children('.Morning input, .MorningPart input, .Afternoon input, .AfternoonPart input') ```
I modified your example a bit because my structure is a little different ``` $(this).parents('.RadioSchedule').children('.Morning, .MorningPart, .Afternoon, .AfternoonPart').find('input'); ``` this worked produced the same results across IE and Firefox
jquery $ function returning different results in IE
[ "", "javascript", "jquery", "" ]
``` Attacklab.wmd_env.buttons=Attacklab.wmd_env.buttons||_4; ``` what does the || do in this case? Adds \_4 to the array which is Attacklab.wmd\_env.buttons?
The `||` operator in JavaScript returns the value on the left if that value does not evaluate to `false`, otherwise it returns the value on the right. From [Mozilla's Core JavaScript 1.5 Reference](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Logical_Operators): > `expr1 || expr2` > Returns `expr1` if it can be converted to true; otherwise, returns `expr2`. Thus, when used with Boolean values, `||` returns true if either operand is true; if both are false, returns false. So, in this case, if `Attacklab.wmd_env.buttons` doesn't have a value, it sets the value to `_4`.
It's a fancy way of writing ``` if(!Attacklab.wmd_env.buttons) Attacklab.wmd_env.buttons = _4; ``` It's nice for providing default values. Keep in mind that not only `null` and `undefined` will trigger the conditional, but also `0`, `false` and `''`, ie everything which is considered `false` in boolean contexts.
What does the || operator do?
[ "", "javascript", "operators", "" ]
The code worked all along. Somehow I manage to get Visual C++ Express not hit the break point on the final return statement and it appeared to run for ever. In the example code bellow EnumWindows enumerates infinitely. How can one make it stop after all windows has been enumerated. ``` #include <Windows.h> BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam) { TCHAR buff[255]; if (IsWindowVisible(hWnd)) { GetWindowText(hWnd, (LPWSTR) buff, 254); printf("%S\n", buff); } return TRUE; } int _tmain(int argc, _TCHAR* argv[]) { EnumWindows(EnumWindowsProc, 0); return 0; } ```
Your code works for me, once I removed the wide-character stuff and added `#include <stdio.h>` to get the printf() declaration. What output does it produce on your system? The code that works for me is: ``` #include <windows.h> #include <stdio.h> BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) { char buff[255]; if (IsWindowVisible(hWnd)) { GetWindowText(hWnd, (LPSTR) buff, 254); printf("%s\n", buff); } return TRUE; } int main() { EnumWindows(EnumWindowsProc, 0); return 0; } ```
`EnumWindowsProc` should never run infinitely. It should run until: * Your callback returns FALSE * There are no more top level windows to enumerate So I suspect it appears to be running infinitely for you because of memory corruption or a memory access violation. Your printf should be using %s not %S. ``` BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam) { TCHAR buff[255]; if (IsWindowVisible(hWnd)) { GetWindowText(hWnd, (LPWSTR) buff, 254); printf("%s\n", buff);//<--- %s means use TCHAR* which is WCHAR* in your case } return TRUE; } ``` Also you shouldn't need to be casting your buff as a LPWSTR. If your buff is somehow a CHAR buffer then you need to compile with the Unicode character set.
How to stop EnumWindows running infinitely win32
[ "", "c++", "windows", "winapi", "" ]
I have a byte[] array received in TCP Client.The array contains a 24-bit RGB Bitmap file.How to create that bitmap file with given Width ,Height and data? In C++ I use this ``` int WriteBitmapFile(const char *filename, int width, int height, unsigned char *imageData) { FILE *filePtr; // file pointer BITMAPFILEHEADER bitmapFileHeader; // bitmap file header BITMAPINFOHEADER bitmapInfoHeader; // bitmap info header DWORD imageIdx; // used for swapping RGB->BGR unsigned char tempRGB; // used for swapping // open file for writing binary mode filePtr = fopen(filename, "wb"); if (!filePtr) return 0; // define the bitmap file header bitmapFileHeader.bfSize = sizeof(BITMAPFILEHEADER); bitmapFileHeader.bfType = 0x4D42; bitmapFileHeader.bfReserved1 = 0; bitmapFileHeader.bfReserved2 = 0; bitmapFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); // define the bitmap information header bitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfoHeader.biPlanes = 1; bitmapInfoHeader.biBitCount = 32; // 24-bit bitmapInfoHeader.biCompression = BI_RGB; // no compression bitmapInfoHeader.biSizeImage = width * abs(height) * 4; // width * height * (RGB bytes) bitmapInfoHeader.biXPelsPerMeter = 0; bitmapInfoHeader.biYPelsPerMeter = 0; bitmapInfoHeader.biClrUsed = 0; bitmapInfoHeader.biClrImportant = 0; bitmapInfoHeader.biWidth = width; // bitmap width bitmapInfoHeader.biHeight = height; // bitmap height // switch the image data from RGB to BGR for(imageIdx = 0; imageIdx < bitmapInfoHeader.biSizeImage; imageIdx+=4) { tempRGB = imageData[imageIdx]; imageData[imageIdx] = imageData[imageIdx + 2]; imageData[imageIdx + 2] = tempRGB; } // write the bitmap file header fwrite(&bitmapFileHeader, 1, sizeof(BITMAPFILEHEADER), filePtr); // write the bitmap info header fwrite(&bitmapInfoHeader, 1, sizeof(BITMAPINFOHEADER), filePtr); // write the image data fwrite(imageData, 1, bitmapInfoHeader.biSizeImage, filePtr); // close our file fclose(filePtr); // Success return 1; } ``` How could I do that in C#?
If the array actually contains a bitmap file, then you can just save the bytes as a file: ``` File.WriteAllBytes(fileName, imageData); ``` If the array contains only raw pixel data, you can create a Bitmap object using the data: ``` unsafe { fixed (byte* ptr = imageData) { using (Bitmap image = new Bitmap(width, height, stride, PixelFormat.Format24bppRgb, new IntPtr(ptr))) { image.Save(fileName); } } } ``` The `stride` value is the number of bytes between the scan lines. If there is no padding between the scan lines, it's `width * 3` for a 24bpp format. This method uses the data in the array without creating another copy of the entire image in memory (which is why it needs the stride value). If the bitmap data is stored upside down in the array, the `stride` value should be negative, and the pointer should be the start of the last scan line in memory (`ptr + stride * (height - 1)`).
I can't test it using the stream you will be receiving, but this should work. ``` int WriteBitmapFile(string filename, int width, int height, byte[] imageData) { using (var stream = new MemoryStream(imageData)) using (var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb)) { BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); Marshal.Copy(imageData, 0, bmpData.Scan0, imageData.Length); bmp.UnlockBits(bmpData); bmp.Save(filename); } return 1; } ```
How to create a bmp file from byte[] in C#
[ "", "c#", "bitmap", "byte", "rgb", "24-bit", "" ]
Following are the two approaches: * constructor with all the class properties Pros: I have to put an exact number of types of parameters so if I make an error the compiler warns me (by the way, is there a way to prevent the problem of having erroneously switched two Integer on the parameter list?) Cons: if I have lots of properties the instantiation line can become really long and it could span over two or more lines * setters and the default empty constructor Pros: I can clearly see what I'm setting, so if I'm doing something wrong I can pinpoint it as soon as I'm typing it (I can't make the previuos error of switching two variables of the same type) Cons: the instantiation of an object with lots of properties could take several lines (don't know if this is really a con) and if I forget to set a property the compiler doesn't say anything. What will you do and why? Do you know of any light pattern (consider that it should be used everytime an object wth 7+ properties is instantiated) to suggest? I'm asking this because I tend to dislike large constructors where I can't figure out fast where is the variable I'm looking for, on the other hand I find the "set all properties" vulnerable to missing some of the properties. Feel free to argument my assumptions in pros and cons as they are only mine thoughts :) Update - a question I've found which is related to this: [Building big, immutable objects without using constructors having long parameter lists](https://stackoverflow.com/questions/2848938/building-big-immutable-objects-without-using-constructors-having-long-parameter)
You might look at the Builder pattern advocated by Joshua Bloch, and described in **Effective Java**. There's a presentation with the main points at <http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-2689.pdf>; no doubt you could dig up a better reference. Basically, you have another class, probably an inner class, which provides methods named after the properties being set, and which return the original builder so you can chain calls. It makes for quite a readable chunk of code. For example, let's suppose I have a simple `Message` with a few properties. The client code constructing this could use a builder to prepare a `Message` as follows: ``` Message message = new Message.Builder() .sender( new User( ... ) ) .recipient( new User( ... ) ) .subject( "Hello, world!" ) .text( messageText ) .build(); ``` A fragment of `Message.Builder` might look similar to the following: ``` public class Builder { private User sender = null; // Other properties public Builder sender( User sender ) { this.sender = sender; return this; } // Methods for other properties public Message build() { Message message = new Message(); message.setSender( sender ); // Set the other properties return message; } } ```
You've missed the biggest pro of having a constructor with loads of parameters: it lets you create immutable types. The normal way of creating immutable types *without* huge constructor nastiness is to have a helper type - a *builder* which maintains the values you'll want in your final object, then builds the immutable object when you're ready.
Constructor with all class properties or default constructor with setters?
[ "", "java", "constructor", "setter", "" ]
Hey, I want to know how to connect databases with C++? Any cross-platform solution which supports many databases? I know about SQLAPI++ but its a shareware... so any free one? What solutions do I have if I limit the OSes to Windows only? Thanks
[SOCI - The C++ Database Access Library](http://soci.sourceforge.net/)
Why not the Qt framework? its available under the LGPL now. Its simple to use, cross platform, free, provides an easy api to access several database engines without having to know about the underlying db.
C++ Database Connectivity?
[ "", "c++", "database", "connectivity", "" ]
When I run this program ``` OVERLAPPED o; int main() { .. CreateIoCompletionPort(....); for (int i = 0; i<10; i++) { WriteFile(..,&o); OVERLAPPED* po; GetQueuedCompletionStatus(..,&po); } } ``` it seems that the WriteFile didn't return until the writing job is done. At the same time , GetQueuedCompletionStatus() gets called. The behavior is like a synchronous IO operation rather than an asynch-IO operation. Why is that?
If the file handle and volume have write caching enabled, the file operation may complete with just a memory copy to cache, to be flushed lazily later. Since there is no actual IO taking place, there's no reason to do async IO in that case. Internally, each IO operation is represented by an [IRP](http://msdn.microsoft.com/en-us/library/ms795960.aspx) (IO request packet). It is created by the kernel and given to the filesystem to handle the request, where it passes down through layered drivers until the request becomes an actual disk controller command. That driver will make the request, mark the IRP as pending and return control of the thread. If the handle was opened for overlapped IO, the kernel gives control back to your program immediately. Otherwise, the kernel will wait for the IRP to complete before returning. Not all IO operations make it all the way to the disk, however. The filesystem may determine that the write should be cached, and not written until later. There is even a special path for operations that can be satisfied entirely using the cache, called [fast IO](http://msdn.microsoft.com/en-us/library/ms790753.aspx). Even if you make an asynchronous request, fast IO is always synchronous because it's just copying data into and out of cache. [Process monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx), in advanced output mode, displays the different modes and will show blank in the status field while an IRP is pending. There is a limit to how much data is allowed to be outstanding in the write cache. Once it fills up, the write operations will not complete immediately. Try writing a lot of data at once, with may operations.
I wrote a blog posting a while back entitled "When are asynchronous file writes not asynchronous" and the answer was, unfortunately, "most of the time". See the posting here: <http://www.lenholgate.com/blog/2008/02/when-are-asynchronous-file-writes-not-asynchronous.html> The gist of it is: * For security reasons Windows extends files in a synchronous manner * You can attempt to work around this by setting the end of the file to a large value before you start and then trimming the file to the correct size when you finish. * You can tell the cache manager to use your buffers and not its, by using `FILE_FLAG_NO_BUFFERING` * At least it's not as bad as if you're forced to use `FILE_FLAG_WRITE_THROUGH`
Is this program running Asynchronous or synchrounous?
[ "", "c++", "winapi", "visual-c++", "operating-system", "iocp", "" ]
I need to have following attribute value in my XML node: ``` CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt" ``` Actually this is part of a .vcproj file generated in VS2008. `&#x0D;&#x0A` means line break, as there should be 2 separate commands. I'm using Python 2.5 with minidom to parse XML - but unfortunately I don't know how to store sequences like `&#x0D;`, the best thing i can get is `&amp#x0D;`. How can I store exactly `&#x0D;`? UPD : Exactly speaking i have to store not &, but \r\n sequence in form of &#x0A
> I'm using Python 2.5 with minidom to parse XML - but unfortunately I don't know how to store sequences like Well, you can't specify that you want hex escapes specifically, but according to the DOM LS standard, implementations should change \r\n in attribute values to character references automatically. Unfortunately, minidom doesn't: ``` >>> from xml.dom import minidom >>> document= minidom.parseString('<a/>') >>> document.documentElement.setAttribute('a', 'a\r\nb') >>> document.toxml() u'<?xml version="1.0" ?><a a="a\r\nb"/>' ``` This is a bug in minidom. Try the same in another DOM (eg. [pxdom](http://www.doxdesk.com/software/py/pxdom.html)): ``` >>> import pxdom >>> document= pxdom.parseString('<a/>') >>> document.documentElement.setAttribute('a', 'a\r\nb') >>> document.pxdomContent u'<?xml version="1.0" ?><a a="a&#13;&#10;b"/>' ```
You should try storing the actual characters (ASCII 13 and ASCII 10) in the attribute value, instead of their already-escaped counterparts. --- EDIT: It looks like minidom does not handle newlines in attribute values correctly. Even though a literal line break in an attribute value is allowed, but it will face normalization upon document parsing, at which point it is converted to a space. I filed a bug in this regard: <http://bugs.python.org/issue5752>
How to write ampersand in node attribude?
[ "", "python", "xml", "" ]
What is the point of them? I've never used them for anything, and I can't see myself needing to use them at all. Am I missing something about them or are they pretty much useless? EDIT: I don't know much about them, so a description about them might be necessary...
A PMF (pointer to member function) is like a normal (static) function pointer, except, because non-static member functions require the `this` object to be specified, the PMF invocation syntax (`.*` or `->*`) allow the `this` object to be specified (on the left-hand side). Here's an example of PMFs in use (note the "magic" line with the `.*` operator being used: `(lhs.*opit->second)(...)`, and the syntax for creating a PMF, `&class::func`): ``` #include <complex> #include <iostream> #include <map> #include <stack> #include <stdexcept> #include <string> namespace { using std::cin; using std::complex; using std::cout; using std::invalid_argument; using std::map; using std::stack; using std::string; using std::underflow_error; typedef complex<double> complexd; typedef complexd& (complexd::*complexd_pmf)(complexd const&); typedef map<char, complexd_pmf> opmap; template <typename T> typename T::reference top(T& st) { if (st.empty()) throw underflow_error("Empty stack"); return st.top(); } } int main() { opmap const ops{{'+', &complexd::operator+=}, {'-', &complexd::operator-=}, {'*', &complexd::operator*=}, {'/', &complexd::operator/=}}; char op; complexd val; stack<complexd> st; while (cin >> op) { opmap::const_iterator opit(ops.find(op)); if (opit != ops.end()) { complexd rhs(top(st)); st.pop(); // For example of ->* syntax: complexd& lhs(top(st)); // complexd* lhs(&top(st)); (lhs.*opit->second)(rhs); // (lhs->*opit->second)(rhs); cout << lhs << '\n'; // cout << *lhs << '\n'; } else if (cin.unget() && cin >> val) { st.push(val); } else { throw invalid_argument(string("Unknown operator ") += op); } } } ``` [[Download](https://gist.githubusercontent.com/cky/871303/raw/8129852ff8d333fd71336edd6f6a9c841b505fed/rpn.cc)] It's a simple RPN calculator using complex numbers instead of real numbers (mostly because `std::complex` is a class type with overloaded operators). I've tested this with [clang](http://clang.llvm.org/); your mileage may vary with other platforms. Input should be of the form `(0,1)`. Spaces are optional, but can be added for readability.
Bind a pointer to a function is very useful in a variety of situations. Basically, it allows you to refer to functions as variables, which lets you choose, at runtime, which function you will call. One use for this is in "callbacks". Say I want some background process to work for a while, and let us know when it's done (so we can update the GUI, or something). But sometimes, we may want this background process to call one method, and sometimes, we want it to call a different method. Rather than writing two versions of this background process, we can write it so that the background process receives a pointer to the function we want it to "call back". Then, when the process is finished, it calls whichever function it was given in the first place. Basically, it just lets you have a heap more flexibility in deciding which method to call. In that way, it's quite similar to polymorphism. In fact, behind the scenes, I believe C++ uses pointers to functions to facilitate polymorphism (by storing a different table of pointers to functions for each class)
Bind pointer to member operators in C++
[ "", "c++", "operators", "" ]
Is there any way in ColdFusion code to determine on what server the code is executing? I have few load-balanced ColdFusion servers. I want to be able to know on which server the code is running when I catch an exception, so I can include that information in the logging / reporting code. The servers are Windows 2003/IIS, if that matters. I'd love to know how to do it in Linux/Apache too. :-)
This may help you further... ``` <cfscript> machineName = createObject("java", "java.net.InetAddress").localhost.getCanonicalHostName(); hostaddress = createObject("java", "java.net.InetAddress").localhost.getHostAddress(); </cfscript> <cfdump var="#machineName#"><br /> <cfdump var="#hostaddress#"><br /> ```
You can use [Server Variables](http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=sharedVars_19.html) like ``` server.coldfusion.appserver server.coldfusion.expiration server.coldfusion.productlevel server.coldfusion.productname server.coldfusion.productversion server.coldfusion.rootdir server.coldfusion.serialnumber server.coldfusion.supportedlocales server.os.additionalinformation server.os.arch server.os.buildnumber server.os.name server.os.version ``` to tweak your code to specific platforms. Do a `<cfdump var=”#SERVER#” />` to see what's applicable to your version of Coldfusion. You can get the hostname with a Java call: ``` <cfscript> machineName = createObject("java", "java.net.InetAddress").localhost.getHostName(); instanceName = createObject("java", "jrunx.kernel.JRun").getServerName(); </cfscript> ```
In ColdFusion, is there a way to determine what server the code is running on?
[ "", "java", "networking", "coldfusion", "" ]
I have the following python script and I would like to send "fake" header information along so that my application acts as if it is firefox. How could I do that? ``` import urllib, urllib2, cookielib username = '****' password = '****' login_user = urllib.urlencode({'password' : password, 'username' : username}) jar = cookielib.FileCookieJar("cookies") opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) response = opener.open("http://www.***.com") response = opener.open("http://www.***.com/login.php") response = opener.open("http://www.***.com/welcome.php", login_user) ```
Use the `addheaders()` function on your `opener` object. Just add this one line after you create your opener, before you start opening pages: ``` opener.addheaders = [('User-agent', 'Mozilla/5.0')] ``` <http://docs.python.org/library/urllib2.html> (it's at the bottom of this document)
You have to get a bit more low-level to be able to do that. ``` request = urllib2.Request('http://stackoverflow.com') request.add_header('User-Agent', 'FIREFOX LOL') opener = urllib2.build_opener() data = opener.open(request).read() print data ``` Not tested.
Send headers along in python
[ "", "python", "post", "http-headers", "" ]
I'm using C# with the XNA library and I'm getting NaNs cropping up in my Vector3 objects. Is there a way to break into the debugger when the offending calculation happens (e.g. a divide by zero)? Currently the program just continues running. I'm using VS2008 Professional. All the exceptions in the Exceptions dialog are selected in the "user-unhandled" column. Edit: To clarify, I can't work out where the bad calculation is. This is why I want the debugger to break automatically. Setting breakpoints is not a solution.
Firstly dividing a double/float by zero gives Infinity/-Infinity depending upon whether the double is positive or negative. Only a zero double/float divided by zero gives NaN. In either case, no exception will be thrown. You should be able to use conditional breakpoints to detect when a particular variable gets set to one of these values. Be careful when checking for NaN though, as NaN != NaN. ``` double a = double.NaN; Console.Out.WriteLine(a == double.NaN); // false Console.Out.WriteLine(a == a); // false Console.Out.WriteLine(double.IsNaN(a)); // true ```
Sounds like you're handling the exception somehow (like a catching a generic Exception) What you can do is press Ctrl+alt+E to bring up the exceptions dialog -- make sure you check the "when thrown" checkbox for the exception(s) you're interested in
Break into C# debugger for divide by zero
[ "", "c#", "exception", "debugging", "nan", "divide-by-zero", "" ]
What's the best way to round an HH:MM value to the closest 15 minute interval? I don't track seconds so they don't matter. ``` 00:08:00 becomes 00:15:00 00:07:00 becomes 00:00:00 01:59:00 becomes 02:00:00 ``` and so on. Is there an elegant, non UDF or Case statement method for doing this? **EDIT:** Here's the SQL I'm using to get the above values that I'd like to round: ``` CONVERT(CHAR(8), DATEADD(n, SUM(DATEDIFF(n, starttime, stoptime)), 0), 108) ``` `starttime` and `stoptime` are SQL `datetime`s.
This was answered here [How to Round a Time in T-SQL](https://stackoverflow.com/questions/249794/how-to-round-a-time-in-t-sql) and i think it should work for you to. ``` CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float) RETURNS datetime AS BEGIN DECLARE @RoundedTime smalldatetime, @Multiplier float SET @Multiplier = 24.0 / @RoundTo SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar, @Time, 121) AS datetime) AS float) * @Multiplier, 0) / @Multiplier RETURN @RoundedTime END -- Usage SELECT dbo.RoundTime('13:15', 0.5) ```
I am currently using a dateadd / datediff variant with a zero (0) date for this. No Casting required: ``` select dateadd(minute, datediff(minute,0,GETDATE()) / 15 * 15, 0) ``` GETDATE() is whatever your datetime is. This will work for dates at least up to the year 5500 before the datediff failes because of an overflow. However if you try to use second accuracy, above will fail right away. Using another fixed date, like '2009-01-01', or Today's date (warning, more ugly SQL) will fix that. A future date will also work. As long as it has a time part of 00:00:00 you can base another datetime on it. for example: round to the nearest 30 seconds: ``` select dateadd(second, round(datediff(second, '2010-01-01', GETDATE()) / 30.0, 0) * 30, '2010-01-01'); ```
T-SQL: Round to nearest 15 minute interval
[ "", "sql", "sql-server", "datetime", "" ]
We have a developer who is in the habit of committing non-java files (xsd, dtd etc) in the java packages under the src/java folder in our repository. Admittedly, these are relevant files to that package, but I just hate to see non-java files in the src folder. Is this is a common practice that I should get used to or are we doing something strange by maintaining these files like this?
The problem with putting non Java (or other languages) files that are closely tied to the code in a different place than the code is knowing where to find them. It is possible to standardize the locations then theoretically everyone will know where to go and what to do. But I find in practice that does not happen. Imagine your app still being maintained 5 or 10 years down the road by a team of junior - intermediate developers that do not work at the company now and will never talk to anyone who works on your project now. Putting files closely linked to the source in the source package structure could make their lives easier. I am a big proponent of eliminating as many ambiguities as possible within reason.
It's very common and even recommended as long as its justifiable. Generally it's justifiable when it's a static resource (DTD+XSLT for proprietary formats, premade scripts etc.) but it's not when the file is something that's likely to be updated by a third party like IP/geographic location database dump.
non-java files in package structure
[ "", "java", "" ]
I have a method that executes inside one form, but I need to retrieve data from another form to pass into the method. Whats the best way of doing this?
Assuming that formB is initialized in formA I would recommend adding a string to the constructor of formB sending the Texbox1.Text as in ``` class formB: Form{ private string data; public formB(string data) { InitializeComponent(); this.data = data; } //rest of your code for the class } ```
You can expose a property on one form and call it from the other. Of course you'll need some way of getting the instance of form1. You could keep it as a static property in the program class or some other parent class. Usually in this case I have a static application class that holds the instance. ``` public static class Application { public static MyForm MyFormInstance { get; set; } } ``` Then when you launch the first form, set the application MyFormInstance property to the instance of the first Form. ``` MyForm instance = new MyForm(); Application.MyFormInstance = instance; ``` Add a property to the second form. ``` public String MyText { get { return textbox1.Text; } set { textbox1.Text = value; } } ``` And then you can access it from your second form with: ``` Application.MyFormInstance.MyText ```
C# WinForms - How Do i Retrieve Data From A Textbox On One Form Via Another Form?
[ "", "c#", "winforms", "" ]
i am trying to postion the output to my aspx page by using response.write for that i am using this code: ``` Response.Write("&lt;<span id='Label1'' style='height:16px;width:120px;Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 144px'>Its not at the top left corner!</span>"); ``` this prints my message in the middle of the screen but also shows a "<" at the left corner. I have tried a few things but i am unable to get rid of it. please help any other way of positioning the output?
Try: ``` Response.Write("<span id='Label1' style='height:16px;width:120px;Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 144px'>Its not at the top left corner!</span>"); ``` You had a &lt; at the beginning, which is giving you the "<" , and a double '' after Label1 But there are LOTS of better ways of positioning with CSS and producing output with Response.Write directly is generally not needed... What are you trying to do?
[This](https://rads.stackoverflow.com/amzn/click/com/1590599594) or [this](https://rads.stackoverflow.com/amzn/click/com/0470128615) or something like it will help you.
positioning the output of response.write in asp.net C#
[ "", "c#", "asp.net", "response.write", "" ]
I have a decent understanding of C# and a very basic understanding of powershell. I'm using Windows PowerShell CTP 3, which has been really fun. But I want to go beyond writing scripts/functions. Is there any cool stuff to do with C#?
I think the most interesting thing you can do with C# and PowerShell is to build CmdLet's. These are essentially plugins to PowerShell that are written in managed code and act like normal functions. They have a verb-noun pair and many of the functions you already use are actually cmdlets under the hood. <http://msdn.microsoft.com/en-us/magazine/cc163293.aspx>
At the highest level you have two different options You can from a C# program host PowerShell and execute PowerShell commands via RunSpaces and pipelines. Or you can from within PowerShell run C# code. This can be done two ways. With a PowerShell snapin, a compiled dll which provides PowerShell cmdlets and navigation providers, or via the new cmdlet **Add-Type**, which lets you dynamically import C#, VB, F# code. From the help ``` $source = @" public class BasicTest { public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); } } "@ Add-Type -TypeDefinition $source [BasicTest]::Add(4, 3) $basicTestObject = New-Object BasicTest $basicTestObject.Multiply(5, 2) ```
What can I do with C# and Powershell?
[ "", "c#", "powershell", "powershell-2.0", "" ]
I'm looking for some applications or websites that minimize css and js files. Ideally, they could batch them all or if not, one at a time.
[YUI Compressor](http://yui.github.io/yuicompressor/) does both JavaScript and CSS. I'm not sure if you can send it a batch of files. You *can* batch process at [YUI Compressor Online (yui.2clics.net)](http://yui.2clics.net/), though that version only accepts JavaScript. Another [Online YUI Compressor (refresh-sf.com)](http://www.refresh-sf.com/yui/) accepts CSS, too, but doesn't batch. In terms of comparing the various minifiers, see [jQuery : Frequently Asked Questions (FAQ) : How do I compress my code?](http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_compress_my_code.3F) Also, check out [Microsoft Ajax Minifier](http://ajaxmin.codeplex.com). jQuery has switched from the YUI Compressor to [Google's Closure Compiler](https://developers.google.com/closure/compiler/) for the minified version that they distribute.
[YUI Compressor](http://developer.yahoo.com/yui/compressor/) is pretty cool. You can run it as part of a build process from the command line
What are some good css and js minimizers for production code?
[ "", "javascript", "css", "optimization", "jscompress", "" ]
I’m trying to convert XML data into PDF files from a web page and I was hoping I could do this entirely within JavaScript. I need to be able to draw text, images and simple shapes. I would love to be able to do this entirely in the browser.
I've just written a library called [jsPDF](https://github.com/MrRio/jsPDF) which generates PDFs using Javascript alone. It's still very young, and I'll be adding features and bug fixes soon. Also got a few ideas for workarounds in browsers that do not support Data URIs. It's licensed under a liberal MIT license. I came across this question before I started writing it and thought I'd come back and let you know :) [Generate PDFs in Javascript](https://github.com/MrRio/jsPDF) Example create a "Hello World" PDF file. ``` // Default export is a4 paper, portrait, using milimeters for units var doc = new jsPDF() doc.text('Hello world!', 10, 10) doc.save('a4.pdf') ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script> ```
Another javascript library worth mentioning is **pdfmake**. * [pdfmake playground](http://pdfmake.org/playground.html) * [pdfmake on github](https://github.com/bpampuch/pdfmake) The browser support does not appear to be as strong as jsPDF, nor does there seem to be an option for shapes, but the options for formatting text are more advanced then the options currently available in jsPDF.
Generating PDF files with JavaScript
[ "", "javascript", "pdf", "pdf-generation", "" ]
In what situations in java is explicit nulling useful. Does it in any way assist the garbage collector by making objects unreachable or something? Is it considered to be a good practice?
In Java it *can* help if you've got a very long-running method, and the only reference to the an object is via a local variable. Setting that local variable to null when you don't need it any more (but when the method is going to continue to run for a long time) *can* help the GC. (In C# this is very rarely useful as the GC takes "last possible use" into account. That optimization may make it to Java some time - I don't know.) Likewise if you've got a member field referring to an object and you no longer need it, you could potentially aid GC by setting the field to null. In my experience, however, it's rarely *actually* useful to do either of these things, and it makes the code messier. Very few methods *really* run for a long time, and setting a variable to null really has nothing to do with what you want the method to achieve. It's not good practice to do it when you don't need to, and if you *do* need to you should see whether refactoring could improve your design in the first place. (It's possible that your method or type is doing too much.) Note that setting the variable to null is entirely passive - it doesn't inform the garbage collector that the object can be collected, it just avoids the garbage collector seeing that reference as a reason to keep the object alive next time it (the GC) runs.
In general it isn't needed (of course that can depend on the VM implementation). However if you have something like this: ``` private static final Map<String, String> foo; ``` and then have items in the map that you no longer need they will not be eligible for garbage collection so you would need to explicitly remove them. There are many cases like this (event listeners is another area that this can happen with). But doing something like this: ``` void foo() { Object o; // use o o = null; // don't bother doing this, it isn't going to help } ``` Edit (forgot to mention this): If you work at it, you should find that 90-95% of the variables you declare can be made final. A final variable cannot change what it points at (or what its value is for primitives). In most cases where a variable is final it would be a mistake (bug) for it to receive a different value while the method is executing. If you want to be able to set the variable to null after use it cannot be final, which means that you have a greater chance to create bugs in the code.
Explicit nulling
[ "", "java", "" ]
I'm writing a daemon to monitor creation of new objects, which adds rows to a database table when it detects new things. We'll call the objects widgets. The code flow is approximately this: ``` 1: every so often: 2: find newest N widgets (from external source) 3: foreach widget 4: if( widget not yet in database ) 5: add rows for widget ``` The last two lines present a race condition, since if two instances of this daemon are running at the same time, they may both create a row for widget X if the timing lines up. The most obvious solution would be to use a `unique` constraint on the widget identifier column, but that isn't possible due to the database layout (it's actually allowed to have more than one row for a widget, but the daemon shouldn't ever do this automatically). My next thought would be to use a transaction, since this is what they're intended for. In the ADO.NET world, I believe I would want an isolation level of [`Serializable`](http://msdn.microsoft.com/en-us/library/system.enterpriseservices.transactionisolationlevel.aspx), but I'm not positive. Can someone point me in the right direction? **Update**: I did some experimentation, and the Serialized transaction doesn't appear to resolve the issue, or at least not very well. The interesting case is described below, and assumes that only one table is involved. Note that I'm not positive about the lock details, but I think I have it right: ``` Thread A: Executes line 4, acquiring a read lock on the table Thread B: Executes line 4, acquiring a read lock on the table Thread A: Tries to execute line 5, which requires upgrading to a write lock (this requires waiting until Thread B unlocks the table) Thread B: Tries to execute line 5, again requiring a lock upgrade (this requires waiting until Thread A unlocks) ``` This leaves us in a classic deadlock condition. Other code paths are possible, but if threads A and B don't interleave, there's no synchronization issue anyway. The end result is that a SqlException is thrown on one of the threads, after SQL detects the deadlock and terminates one of the statements. I can catch this exception and detect the particular error code, but that doesn't feel very clean. Another route I may take is to create a second table that tracks widgets seen by the daemon, where I can use a `unique` constraint. This still requires catching and detecting certain error codes (in this case, integrity constraint violations), so I'm still interested in a better solution, if somebody can think of one.
Generally, you should always use transactions if you have more then one process or thread using the database at the same time. Isolation level "serializable" should actually work. It does not allow that data read from one transaction is changed by another. But it locks a lot and should not generally be used, because it slows down the application and there is a higher risk of dead locks. Alternatives: * you only can **lock the whole table** to make sure that nobody writes into it while you are checking if something is (not) there. The problem is, only one can write to the table at the same time, which means that this slows downs everything a lot. (You could search for the data, if it is *not there*, lock the table and *search again* before inserting. This is a common pattern.) * Honestly, you should think about the fact that two transactions try to insert the same row at the same time. This is probably where you should start solving it. Only one daemon should be responsible for the same data. + make every daemon handling its own data + make every daemon calling a service instead of the database. There you can put things together before inserting it. By the way, you need a unique identifier for the data to clearly identify it anyway. How can you search for it in the database if you don't have a unique identifier?
How do you check 'if (widget not yet in database)'. If this is written in sql in form of 'Select', you can use 'Select for update' to allow only one daemon instance to be able to do that at a time. By using transaction for last two line, and use 'select for update' to lock, you will avoid race. I am sure there is an equivalent in ado.net.
using a transaction to avoid a race
[ "", "sql", "ado.net", "transactions", "" ]
I created my own build.xml which has: ``` <target name="compile"> <mkdir dir="build"/> <javac destdir="build"> <src path="src"/> </javac> </target> <target name="build" depends="compile"> <mkdir dir="dist"/> <jar destfile="dist/app.jar" basedir="build" /> </target> <target name="run" depends="compile"> <java classname="webserver.Loader" classpath="build" fork="true" /> </target> ``` It works great. When I call ant run so it compiles and runs my application, but my application has a package with icons and it isn't moved to a folder "build" so my application ends with an exception that it couldn't locate my icons. When I move them by myself then it works. I tried to use ``` <copy todir="build/app/icons"> <fileset dir="src/app/icons"/> </copy> ``` It works, but I would like to do it without the copy command. Is there any parameter to javac? Or something else? Thank you for answer.
Sorry, you will need to copy non-java files manually. Resources are technically not "source". The command-line javac will not copy resource files from your source directory to the output directory, neither will ant's javac task.
There is no such parameter. You can copy all sorts of files between your directories with: ``` <copy todir="build"> <fileset dir="src" includes="**/*.xml,**/*.properties,**/*.txt,**/*.ico" /> </copy> ```
Ant compile doesn't copy the resources
[ "", "java", "ant", "" ]
Is there a .NET obfuscator that fulfills all of the following requirements? **Strict requirements:** * The obfuscator must be free to use * The obfuscator must support command-line operation * The obfuscator must itself be written in a .NET language so that it can be run using Mono
[Obfuscar](http://code.google.com/p/obfuscar/) is free to use, supports command-line operation and can be run using Mono.
Try also babel obfuscator <http://code.google.com/p/babelobfuscator/>
Is there a free .NET obfuscator that supports command-line operation?
[ "", "c#", ".net", "obfuscation", "" ]
I have an internal application that I needs to have a drop down list for two date type elements: **Month** and **Year**. These values are not in a database or other repository of information. I know I could just setup a list with the values I need by adding them to a dictionary like object (I need to correlate the Month to the numerical representation, January => 01): ``` var months = new Dictionary<String,String>(); months.Add("01", "January"); ... ``` The drop down list for the year will be a bit easier as I can just choose a starting year and iterate up to the current or current+1 year in a generic list. Is there a better way to handle these data elements? Something built in, or a good design pattern that I should be implementing?
You could use this to get a list of all the Month names and loop through it. ``` CultureInfo.CurrentCulture.DateTimeFormat.MonthNames ``` You can use it like this...using the index of the Month as the value for your dropdown ``` var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames; for (int i = 0; i < months.Length; i++) { ddl.Items.Add(new ListItem(months[i], i.ToString())); } ```
Extending @Jesse Brown's answer... With a **using System.Globalization** directive, I have the following code: ``` for (int x = 0; x < 12; x++) { cboMonth.Items.Add ( (x+1).ToString("00") + " " + CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.GetValue(x) ); } ``` This produces a dropdown list that looks like: 01 January 02 February 03 March ... 12 December A further refinement might be to make the displayed month the current month by adding: ``` cboMonth.Text = DateTime.Now.Month.ToString("00") + " " + CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.GetValue(DateTime.Now.Month); ``` After the for loop.
What is the best way to code up a Month and Year drop down list for ASP.NET?
[ "", "c#", "asp.net", "vb.net", "webforms", "" ]
I have the following code: ``` class Foo { public Foo() { Size = true; } private bool _size; protected bool Size { get { _size; } set { _size = value; } } } class CrazyFoo : Foo { public void First() { if (!Size) return; } public void Second() { if (!Size) return; } public void Finished() { if (!Size) return; } } ``` What is the best way to implement this sort of pattern, as it drives me nuts to type ``` if(!Size) return; ``` perhaps I can do it with attributes or AOP? What is the best and simplest way? Thanks
From a "pattern" standpoint, though, this doesn't seem onerous to me. It seems perfectly reasonable to me to type: ``` if(!Size) return; ``` You're explicitly handling the cases you want. In your case, this check is pretty specific to what you are working with, from what I can tell (from your original + edits). I'd personally choose a more obvious name, since it does seem a little strange (even in your original), and not completely obvious what's happening. Even with AOP, you'd be adding some other information here on each method, to make sure your aspect was handled.
If you have the same guard statement at the beginning of too many methods, you can create a method called executeWithGuard: ``` private void executeWithGuard(Action method) { if (HeadSize) method(); } ``` Then you could do this: ``` public void ScreenFirstShot() { executeWithGuard(() => { // code here }); } public void ScreenSecondShot() { ExecuteWithGuard(() => { // code here }); } public void CrazyUp() { ExecuteWithGuard(() => { // code here }); } ``` There's no less code doing this... in fact, there's probably more code, but it does allow you to not have to do a find/replace if your guard condition ever changes. I'd only suggest it as a last resort, though. It's very possible that your real problem is that you're doing your validation too far down the call tree. If you can do it at a higher level, you may save yourself from all of this validation. **ALSO** Have a look at the [null object patttern](http://en.wikipedia.org/wiki/Null_Object_pattern). This pattern can be used in some special cases to prevent or simplify state checking. **ALSO (rev 2)** It's hard to know what your intent is since the question focuses on a specific solution, but if you're executing these methods sequentially, you can look at using the [strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern), and putting the check in your base strategy class.
Need a pattern to call Verify method for every instance method pattern
[ "", "c#", ".net", "design-patterns", "" ]
Instead of attaching a `PreviewKeyUp` event with each `TextBox` in my app and checking if the pressed key was an Enter key and then do an action, I decided to implement extended version of a `TextBox` that includes a DefaultAction event that fires when an Enter Key is pressed in a `TextBox`. What I did was basically create a new Class that extends from `TextBox` with a public event `DefaultAction`, like such: ``` public class DefaultTextBoxControl:TextBox { public event EventHandler<EventArgs> DefaultAction = delegate { }; public DefaultTextBoxControl() { PreviewKeyUp += DefaultTextBoxControl_PreviewKeyUp; } void DefaultTextBoxControl_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key != Key.Enter) { return; } DefaultAction(this, EventArgs.Empty); } } ``` I then use this custom textbox from my app like such (xaml): ``` <Controls:DefaultTextBoxControl DefaultAction="DefaultTextBoxControl_DefaultAction"> </Controls:DefaultTextBoxControl> ``` --- Now in my little experience I've had in learning WPF I've realized that almost most of the time there is a "cooler" (and hopefully easier) way to implement things ...so my question is, **How can I improve the above control?** Or maybe is there another way I can do the above control? ...maybe using only declarative code instead of both declarative (xaml) and procedural (C#) ?
Have a look at [this blog post](http://www.madprops.org/blog/wpf-textbox-selectall-on-focus/) from a few months back where I attach a 'global' event handler to `TextBox.GotFocus` to select the text. Essentially you can handle the `KeyUp` event in your App class, like this: ``` protected override void OnStartup(StartupEventArgs e) { EventManager.RegisterClassHandler(typeof(TextBox), TextBox.KeyUpEvent, new System.Windows.Input.KeyEventHandler(TextBox_KeyUp)); base.OnStartup(e); } private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key != System.Windows.Input.Key.Enter) return; // your event handler here e.Handled = true; MessageBox.Show("Enter pressed"); } ``` ... and now every `TextBox` in your application will call the `TextBox_KeyUp` method as users type into them. **Update** As you've pointed out in your comment, this is only useful if every `TextBox` needs to execute the same code. To add an arbitrary event like an Enter keypress, you might be better off looking into [Attached Events](http://msdn.microsoft.com/en-us/library/bb613550.aspx). I believe this can get you what you want.
Since this question was asked, there is now an `InputBindings` property on TextBoxes and other controls. With this, a purely XAML solution can be used, rather than using custom controls. Assigning `KeyBinding`s for `Return` and `Enter` to point to a command can do this. Example: ``` <TextBox Text="Test"> <TextBox.InputBindings> <KeyBinding Command="{Binding SomeCommand}" Key="Return" /> <KeyBinding Command="{Binding SomeCommand}" Key="Enter" /> </TextBox.InputBindings> </TextBox> ``` Some have mentioned that `Enter` does not always work, and `Return` may be used on some systems.
WPF: A TextBox that has an event that fires when the Enter Key is pressed
[ "", "c#", "wpf", "xaml", "custom-controls", "" ]
Does Dreamweaver CS 3 have a JavaScript debugger? The only information on anything close is that it says I need to click on the 'preview/debug in browser' button which does open the page, but no debugging ever happens when the page has an error. I also see no way to set breakpoints or walk through the code. MS [Visual Web Developer](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio_Express) ([Visual Studio Express](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio_Express#Visual_C.2B.2B_Express) - which is free) has a debugger that you can attach to a process. So even if you are not developing in it, you can debug the JavaScript in any browser. It also has a very rich variable watch that allows you to drill down through all the decendants of an object for its respective values. I was hoping that Dreamweaver could at least match Visual Web Developer... What is the experience using the Visual Studio debugger tools with non-Internet Explorer browsers? * Dreamweaver has no effective built-in debugger. * [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29) works great with non-Internet Explorer browsers * Visual Studio tools work great with ID browsers What is the one that works well across the board?
Debuggers are specific to a particular interpreter/compiler, not to a language. The same language - in this case, JavaScript - can have more than one interpreter/compiler. In particular, each browser has their own. So to debug JavaScript in Internet Explorer, you need an Internet Explorer debugger - either the one built into Internet Explorer, or one of the Visual Studio flavours. To debug JavaScript in Chrome, use Chrome's debugger. To debug JavaScript in Firefox, use [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29). (And so on.)
There is nothing native to Dreamweaver that handles debugging JavaScript, but there are several other options out there for free. The Firebug add-on for Firefox allows you to set breakpoints and step through JavaScript. Download and play with that, and you should find what you need. Here is a brief tutorial hitting on your points: [Debug Javascript with Firebug](http://thecodecentral.com/2007/08/01/debug-javascript-with-firebug)
Dreamweaver JavaScript debugger
[ "", "javascript", "debugging", "dreamweaver", "" ]
I want to make a class usable in `SortedSet` | `SortedMap`. ``` class MyClass implements Comparable<MyClass>{ // the only thing relevant to comparisons: private final String name; //... } ``` The class' instances must be sorted by their name property. However, I don't want equally named instances to be considered as equal. So a `SortedSet` content would look like **a, a, a, b, c**. (Normally, `SortedSet` would only allow **a, b, c**) **First of all: is this (philosophically) consistent?** If so, do I have to expect unpredictable behavior, when I don't override `equals(...)` and `hashCode()`? **Edit:** I am sorry, my question seems inconsistent: I want to put **multiple "equal" values** inside a **set**, which doesn't allow this by concept. So, please don't reply to my question anymore. Thanks to all who already replied.
Let me ask you a question: does it make sense to have `a.compareTo(b)` return 0 and `a.equals(b)` return `false`? I would use a [`Comparator<MyClass>`](http://java.sun.com/javase/6/docs/api/java/util/Comparator.html) instead. This is why all `SortedMap`/`SortedSet` implementations that I know of allow you to pass in a `Comparator` at creation.
From the Javadoc for Comparable > It is strongly recommended (though not > required) that natural orderings be > consistent with equals. This is so > because sorted sets (and sorted maps) > without explicit comparators behave > "**strangely**" when they are used with > elements (or keys) whose natural > ordering is inconsistent with equals If you want to have compareTo inconsistent with equals(), it is recommended that you instead use an explicit comparator by providing a class that implements Comparator. > If so, do I have to expect unpredictable behavior, when I don't override equals(...) and hashcode()? You should still override equals() and hashcode(). Whether or not equals() and hashcode() are consistent with compareTo is a different matter.
Does it make sense for equals and compareTo to be inconsistent?
[ "", "java", "collections", "" ]
What is the best way to share objects between other classes? For example; a "database" object with functions that are required by the "article" and "user" objects. I don't want to use globals (that includes singletons) or create a new instance of the object in each class, such as ``` function __construct() { $this->database = new database; $this->cache = new cache; } ``` Would passing the objects in, eg. ``` class test{ function __construct( $obj ) { $this->obj = $obj; } } $database = new database; $test = new test( $database ); ``` Be the way to go?
Yes. Passing the objects to the constructor - or to a setter - is the best way to go. This pattern is known as [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection). It has the added benefit that it makes your code easier to test (using stubs or mocks).
Yes, that's pretty much the way you want to do. If a class has external requirements, don't create them inside the class, but require them as arguments in the constructor.
Sharing objects between PHP classes
[ "", "php", "oop", "" ]
I have a WinForm TreeView Control that displays the Parent Child relationship of CaseNotes(I know that means nothing to most of you but it helps me visualize the answers). I have a DataTable of the CaseNotes that I need to display. The Parent/Child is defined as: If the row has a ParentNoteID then it is a childNode of that note otherwise it is a rootNode. It could also be a parent note(but not a rootNode) if another row has it's ID as it's ParentNoteID. To complicate(maybe simplify) things I have the below working(mostly) code that colors the nodes alternatingly. I manually created a static collection for the treeview and it colors them fairly correctly. Now I need to dynamically populate the Nodes from my DataTable. Since I already am going thru the treeview node by node shouldn't I be able to append the data into this process somehow? Maybe I need to build the nodes first and then color as a separate routine but the Recursion Method would still apply, correct? Lets say I want to display CaseNoteID for each Node. That is returned in the DataTable and is unique. ``` foreach (TreeNode rootNode in tvwCaseNotes.Nodes) { ColorNodes(rootNode, Color.MediumVioletRed, Color.DodgerBlue); } protected void ColorNodes(TreeNode root, Color firstColor, Color secondColor) { root.ForeColor = root.Index % 2 == 0 ? firstColor : secondColor; foreach (TreeNode childNode in root.Nodes) { Color nextColor = childNode.ForeColor = childNode.Index % 2 == 0 ? firstColor : secondColor; if (childNode.Nodes.Count > 0) { // alternate colors for the next node if (nextColor == firstColor) ColorNodes(childNode, secondColor, firstColor); else ColorNodes(childNode, firstColor, secondColor); } } } ``` ## EDIT My thoughts/attempts so far: ``` public void BuildSummaryView() { tvwCaseNotes.Nodes.Clear(); DataTable cNotesForTree = CurrentCaseNote.GetAllCNotes(Program._CurrentPerson.PersonID); foreach (var cNote in cNotesForTree.Rows) { tvwCaseNotes.Nodes.Add(new TreeNode("ContactDate")); } FormPaint(); } ``` Obviously this is flawed. One it just display's ContactDate over and over. Granted it shows it the correct number of times but I would like the Value of ContactDate(which is a Column in the database and is being returned in the DataTable. Second I need to add the ChildNode Logic. A `if (node.parentNode = node.CaseNoteID) blah...` ## EDIT 2 So I found this link, [here](http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.beginupdate(VS.85).aspx), and it makes it seem like I need to get my DataTable into an ArrayList. Is that correct? ## EDIT 3 Okay, thanks to Cerebus this is mostly working. I just have one more question. How do I take this--> ``` DataTable cNotesForTree = CurrentCaseNote.GetAllCNotes(Program._CurrentPerson.PersonID); ``` and use my returned DataTable in this? Do I just replace this --> ``` dt = new DataTable("CaseNotes"); dt.Columns.Add("NoteID", typeof(string)); dt.Columns.Add("NoteName", typeof(string)); DataColumn dc = new DataColumn("ParentNoteID", typeof(string)); dc.AllowDBNull = true; dt.Columns.Add(dc); // Add sample data. dt.Rows.Add(new string[] { "1", "One", null }); dt.Rows.Add(new string[] { "2", "Two", "1" }); dt.Rows.Add(new string[] { "3", "Three", "2" }); dt.Rows.Add(new string[] { "4", "Four", null }); dt.Rows.Add(new string[] { "5", "Five", "4" }); dt.Rows.Add(new string[] { "6", "Six", null }); dt.Rows.Add(new string[] { "7", "Seven", null }); dt.Rows.Add(new string[] { "8", "Eight", "7" }); dt.Rows.Add(new string[] { "9", "Nine", "8" }); ``` My confusion, I think, is do I still need to do the Column.Add and Row.Adds? Also how would the DataColumn translate to my real data structure? Sorry for the very ignorant questions, the good news is I never have to ask twice. ## EDIT 4 The following is providing a runtime error. ``` if (nodeList.Find(FindNode) == null) { DataRow[] childRows = dt.Select("ParentNoteID = " + dr["NoteID"]); if (childRows.Length > 0) { // Recursively call this function for all childRowsl TreeNode[] childNodes = RecurseRows(childRows); // Add all childnodes to this node. node.Nodes.AddRange(childNodes); } // Mark this noteID as dirty (already added). //doneNotes.Add(noteID); nodeList.Add(node); } ``` The error is as follows --> ***Cannot find column [ea8428e4]*** Which is the first 8 digits of the correct NoteID(I have to use a Guid). Should it be looking for a column of that name?? Because I am using a Guid is there something else I need to do? I changed all the references in mine and your code to Guid...
To attempt to solve this problem, I created a sample windows form and wrote the following code. I envisioned the datatable design as follows: ``` NoteID NoteName ParentNoteID "1" "One" null "2" "Two" "1" "3" "Three" "2" "4" "Four" null ... ``` This should create a Tree as (*sorry, I'm not very good with ASCII art!*): ``` One | ——Two | ————Three | Four ``` Pseudocode goes like this: 1. Iterate through all the rows in the datatable. 2. For each row, create a TreeNode and set it's properties. Recursively repeat the process for all rows that have a ParentNodeID matching this row's ID. 3. Each complete iteration returns a node that will contain all matching childnodes with infinite nesting. 4. Add the completed nodelist to the TreeView. The problem in your scenario arises from the fact the "foreign key" refers to a column in the same table. This means that when we iterate through the rows, we have to keep track of which rows have already been parsed. For example, in the table above, the node matching the second and third rows are already added in the first complete iteration. Therefore, we must not add them again. There are two ways to keep track of this: 1. Maintain a list of ID's that have been done (`doneNotes`). Before adding each new node, check if the noteID exists in that list. This is the faster method and should normally be preferred. (*this method is commented out in the code below*) 2. For each iteration, use a predicate generic delegate (`FindNode`) to search the list of added nodes (accounting for nested nodes) to see if the to-be added node exists in that list. This is the slower solution, but I kinda like complicated code! :P **Ok, here's the tried and tested code (C# 2.0):** --- ``` public partial class TreeViewColor : Form { private DataTable dt; // Alternate way of maintaining a list of nodes that have already been added. //private List<int> doneNotes; private static int noteID; public TreeViewColor() { InitializeComponent(); } private void TreeViewColor_Load(object sender, EventArgs e) { CreateData(); CreateNodes(); foreach (TreeNode rootNode in treeView1.Nodes) { ColorNodes(rootNode, Color.MediumVioletRed, Color.DodgerBlue); } } private void CreateData() { dt = new DataTable("CaseNotes"); dt.Columns.Add("NoteID", typeof(string)); dt.Columns.Add("NoteName", typeof(string)); DataColumn dc = new DataColumn("ParentNoteID", typeof(string)); dc.AllowDBNull = true; dt.Columns.Add(dc); // Add sample data. dt.Rows.Add(new string[] { "1", "One", null }); dt.Rows.Add(new string[] { "2", "Two", "1" }); dt.Rows.Add(new string[] { "3", "Three", "2" }); dt.Rows.Add(new string[] { "4", "Four", null }); dt.Rows.Add(new string[] { "5", "Five", "4" }); dt.Rows.Add(new string[] { "6", "Six", null }); dt.Rows.Add(new string[] { "7", "Seven", null }); dt.Rows.Add(new string[] { "8", "Eight", "7" }); dt.Rows.Add(new string[] { "9", "Nine", "8" }); } private void CreateNodes() { DataRow[] rows = new DataRow[dt.Rows.Count]; dt.Rows.CopyTo(rows, 0); //doneNotes = new List<int>(9); // Get the TreeView ready for node creation. // This isn't really needed since we're using AddRange (but it's good practice). treeView1.BeginUpdate(); treeView1.Nodes.Clear(); TreeNode[] nodes = RecurseRows(rows); treeView1.Nodes.AddRange(nodes); // Notify the TreeView to resume painting. treeView1.EndUpdate(); } private TreeNode[] RecurseRows(DataRow[] rows) { List<TreeNode> nodeList = new List<TreeNode>(); TreeNode node = null; foreach (DataRow dr in rows) { node = new TreeNode(dr["NoteName"].ToString()); noteID = Convert.ToInt32(dr["NoteID"]); node.Name = noteID.ToString(); node.ToolTipText = noteID.ToString(); // This method searches the "dirty node list" for already completed nodes. //if (!doneNotes.Contains(doneNoteID)) // This alternate method using the Find method uses a Predicate generic delegate. if (nodeList.Find(FindNode) == null) { DataRow[] childRows = dt.Select("ParentNoteID = " + dr["NoteID"]); if (childRows.Length > 0) { // Recursively call this function for all childRowsl TreeNode[] childNodes = RecurseRows(childRows); // Add all childnodes to this node. node.Nodes.AddRange(childNodes); } // Mark this noteID as dirty (already added). //doneNotes.Add(noteID); nodeList.Add(node); } } // Convert this List<TreeNode> to an array so it can be added to the parent node/TreeView. TreeNode[] nodeArr = nodeList.ToArray(); return nodeArr; } private static bool FindNode(TreeNode n) { if (n.Nodes.Count == 0) return n.Name == noteID.ToString(); else { while (n.Nodes.Count > 0) { foreach (TreeNode tn in n.Nodes) { if (tn.Name == noteID.ToString()) return true; else n = tn; } } return false; } } protected void ColorNodes(TreeNode root, Color firstColor, Color secondColor) { root.ForeColor = root.Index % 2 == 0 ? firstColor : secondColor; foreach (TreeNode childNode in root.Nodes) { Color nextColor = childNode.ForeColor = childNode.Index % 2 == 0 ? firstColor : secondColor; if (childNode.Nodes.Count > 0) { // alternate colors for the next node if (nextColor == firstColor) ColorNodes(childNode, secondColor, firstColor); else ColorNodes(childNode, firstColor, secondColor); } } } } ``` ---
I've created much simplier extension method for TreeView, involving use of new simple extending class that adds two useful properties to TreeNode. ``` internal class IdNode : TreeNode { public object Id { get; set; } public object ParentId { get; set; } } public static void PopulateNodes(this TreeView treeView1, DataTable dataTable, string name, string id, string parentId) { treeView1.BeginUpdate(); foreach (DataRow row in dataTable.Rows) { treeView1.Nodes.Add(new IdNode() { Name = row[name].ToString(), Text = row[name].ToString(), Id = row[id], ParentId = row[parentId], Tag = row }); } foreach (IdNode idnode in GetAllNodes(treeView1).OfType<IdNode>()) { foreach (IdNode newparent in GetAllNodes(treeView1).OfType<IdNode>()) { if (newparent.Id.Equals(idnode.ParentId)) { treeView1.Nodes.Remove(idnode); newparent.Nodes.Add(idnode); break; } } } treeView1.EndUpdate(); } public static List<TreeNode> GetAllNodes(this TreeView tv) { List<TreeNode> result = new List<TreeNode>(); foreach (TreeNode child in tv.Nodes) { result.AddRange(GetAllNodes(child)); } return result; } public static List<TreeNode> GetAllNodes(this TreeNode tn) { List<TreeNode> result = new List<TreeNode>(); result.Add(tn); foreach (TreeNode child in tn.Nodes) { result.AddRange(GetAllNodes(child)); } return result; } ``` Thanks to the [modiX](https://stackoverflow.com/users/1540350/modix) for his [methods](https://stackoverflow.com/a/24856090/2572796) to get all (nested) nodes.
Populate WinForms TreeView from DataTable
[ "", "c#", ".net", "winforms", "recursion", "treeview", "" ]
I am writing a decorator that needs to call other functions prior to call of the function that it is decorating. The decorated function may have positional arguments, but the functions the decorator will call can only accept keyword arguments. Does anyone have a handy way of converting positional arguments into keyword arguments? I know that I can get a list of the variable names of the decorated function: ``` >>> def a(one, two=2): ... pass >>> a.func_code.co_varnames ('one', 'two') ``` But I can't figure out how to tell what was passed in positionally and what was as keyword. My decorator looks like this: ``` class mydec(object): def __init__(self, f, *args, **kwargs): self.f = f def __call__(self, *args, **kwargs): hozer(**kwargs) self.f(*args, **kwargs) ``` Is there a way other than just comparing kwargs and co\_varnames, adding to kwargs anything not in there, and hoping for the best?
Note - co\_varnames will include local variables as well as keywords. This probably won't matter, as zip truncates the shorter sequence, but may result in confusing error messages if you pass the wrong number of args. You can avoid this with `func_code.co_varnames[:func_code.co_argcount]`, but better is to use the [inspect](http://docs.python.org/library/inspect.html) module. ie: ``` import inspect argnames, varargs, kwargs, defaults = inspect.getargspec(func) ``` You may also want to handle the case where the function defines `**kwargs` or `*args` (even if just to raise an exception when used with the decorator). If these are set, the second and third result from `getargspec` will return their variable name, otherwise they will be None.
Any arg that was passed positionally will be passed to \*args. And any arg passed as a keyword will be passed to \*\*kwargs. If you have positional args values and names then you can do: ``` kwargs.update(dict(zip(myfunc.func_code.co_varnames, args))) ``` to convert them all into keyword args.
Python convert args to kwargs
[ "", "python", "decorator", "" ]
I have a button that when clicked will run a stored procedure on a SQL Server and display the resulting data in a grid within the same window. In windows forms world, I'd create a datatable, use a dataadapter to fill it and then assign the datatable to the DataSource propert of my DataGridView and poof... there's my data. I'm tried something similar in WPF using a ListView with a Gridview and i cant seem to make it work. I have the following in my XAML: ``` <ListView Grid.Row="1" Name="Preview" ItemsSource="{Binding Path=Report}"> <GridView> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=FormalName}" /> </GridView> </ListView> ``` And in my C# code ``` private void CreateReport(object sender, RoutedEventArgs e) { DataTable dt = new DataTable("Report"); SqlConnection cn = new SqlConnection("Data Source=DailyTimesheets; Initial Catalog=DailyTimesheets;Integrated Security=SSPI"); SqlCommand cm = new SqlCommand("Reports.PayrollHoursInterface", cn); cm.Parameters.AddWithValue("@PayBatchID", 722); cm.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(cm); da.Fill(dt); Preview.DataContext=dt; } ``` When I clicka the button (that fires the CreateReport Method), my datatable gets filled and assigned to the Datacontext, but nothing displays.
I made a sample app and discovered you need to surround your GridView with ListView.View and set your ItemsSource to {Binding} just like the following: ``` <ListView Name="Preview" ItemsSource="{Binding}"> <ListView.View> <GridView> <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=FormalName}" /> </GridView> </ListView.View> </ListView> ```
I think part of the problem is you are still thinking WinForms. Instead of binding a Grid to a Table, how about binding the ListBox to a Collection? Try this instead: 1) Create another class that implements INotifyPropertyChanged. We are going to use this class for the DataContext. Think of it as your BindingEngine. I typically make this the DataContext of the Window itself, making it available anywhere in the Window. 2) Expose a property in the new class that is an ObservableCollection, where YourType is another class that implements INotifyPropertyChanged and exposes the data properties you wish to display. 3) Create a method in the Engine that populates your Collection. Then fire the PropertyChanged event when it is populated. 4) Bind the ListBox ItemsSource to the Property. 5) Create an ItemTemplate and use the property names from YourType for the Binding. This is psuedo-code, but should get you close: ``` <Window> <Window.Resources> <ObjectDataProvider x:Key="MyEngineDS" ObjectType="{x:Type MyEngine:MyEngineNamespace}" d:IsDataSource="True"/> <DataTemplate x:Key="ItemTemplate1"> <TextBlock Text="{Binding MyPropertyName}" /> </DataTemplate> </Window.Resources> <Window.DataContext> <Binding Mode="OneWay" Source="{StaticResource MyEngineDS}"/> </Window.DataContext> <Grid x:Name="LayoutRoot"> <ListBox ItemsSource="MyCollection" ItemTemplate="{DynamicResource ItemTemplate1}" /> </Grid> </Window> ``` Hope this helps.
WPF Databinding: How can I bind a stored procedure to a Listview
[ "", "c#", "wpf", "data-binding", "stored-procedures", "" ]
How do I protect the dlls of my project in such a way that they cannot be referenced and used by other people? Thanks
The short answer is that beyond the obvious things, there is not much you can do. The obvious things that you might want to consider (roughly in order of increasing difficulty and decreasing plausibility) include: * Static link so there is no DLL to attack. * Strip all symbols. * Use a .DEF file and an import library to have only anonymous exports known only by their export ids. * Keep the DLL in a resource and expose it in the file system (under a suitably obscure name, perhaps even generated at run time) only when running. * Hide all real functions behind a factory method that exchanges a secret (better, proof of knowledge of a secret) for a table of function pointers to the real methods. * Use anti-debugging techniques borrowed from the malware world to prevent reverse engineering. (Note that this will likely get you false positives from AV tools.) Regardless, a sufficiently determined user can still figure out ways to use it. A decent disassembler will quickly provide all the information needed. Note that if your DLL is really a COM object, or worse yet a CLR Assembly, then there is a huge amount of runtime type information that you can't strip off without breaking its intended use. **EDIT:** Since you've retagged to imply that C# and .NET are the environment rather than a pure Win32 DLL written in C, then I really should revise the above to "You Can't, But..." There has been a market for obfuscation tools for a long time to deal with environments where delivery of compilable source is mandatory, but you don't want to deliver useful source. There are C# products that play in that market, and it looks like at least one has chimed in. Because loading an Assembly requires so much effort from the framework, it is likely that there are permission bits that exert some control for honest providers and consumers of Assemblies. I have not seen any discussion of the real security provided by these methods and simply don't know how effective they are against a determined attack. A lot is going to depend on your use case. If you merely want to prevent casual use, you can probably find a solution that works for you. If you want to protect valuable trade secrets from reverse engineering and reuse, you may not be so happy.
You're facing the same issue as proponents of DRM. If *your* program (which you wish to be able to run the DLL) is runnable by some user account, then **there is nothing that can stop a sufficiently determined programmer who can log on as that user from isolating the code that performs the decryption and using that to decrypt your DLL and run it.** You can of course make it inconvenient to perform this reverse engineering, and that may well be enough.
How to protect dlls?
[ "", "c#", "dll", "" ]
Does anyone know any way that I can use javascript to check when the browser window is closed and pop-up a confirmation dialog to ask whether the user is confirm to exit the browser or change his mind to stay?
``` window.onbeforeunload = function (e) { var e = e || window.event; //IE & Firefox if (e) { e.returnValue = 'Are you sure?'; } // For Safari return 'Are you sure?'; }; ``` <https://developer.mozilla.org/en/DOM/window.onbeforeunload>
The documentation [here](https://developer.mozilla.org/en/DOM/window.onbeforeunload) encourages listening to the `onbeforeunload` *event* and/or adding an event listener on `window`. ``` window.addEventListener('beforeunload', function(e) {}, false); ``` You can also just populate the `.onunload` or `.onbeforeunload` properties of `window` with a *function* or a *function reference*. Though behaviour is not standardized across browsers, the *function* may return a value that the browser will display when confirming whether to leave the page.
javascript to check when the browser window is closed
[ "", "javascript", "" ]
My coworkers and I cannot seem to agree on a solution to the following issue: We are working on moving our application to the .net framework. It will be a standalone application (not a web application) that will consist of many custom forms used for making changes to our extensive database. So, in summary, without a database connection, the application is pretty much useless. Oh--and there's no need to suggest making this a web application because there is really no choice in the matter. I am responsible for building the "main menu"--I've decided on a tree structure that will list all the custom forms (categorized by team). It will also include a "My Forms" section and a "Recent Forms" section that will be changed by the user (my forms) and the system (recent forms) on a regular basis. My question is this: what is the best place for storing these custom user-specific-settings? An XML file located locally or in tables located database? Maybe it's because I'm a former web app developer but I'm totally for having this stored on the database. What do y'all think? Thanks for your opinions
If the user can function without the database they should be a local xml file. If the app requires the database to be functional, I'd add them to the database. Why add some new concept to the app, just keep storage of data in a single place. Your app will be able to run with lower privileges as well. If you're using the asp.net membership model (yes, for the desktop app) then you'll be able to take advantage of the profiling. I vote database!
Another advantage of keeping them in the database is that when the user logs in to your application from another computer, all of their settings will be preserved. If they are stored on the local machine, moving to another machine would cause them to lose their settings.
User-specific settings files for a windows form application: local xml file or database
[ "", "c#", "winforms", "" ]
BitConverter.ToUInt16() expects the bytes to be reversed, i guess that's how they are stored in memory. But how can I convert it when it's not reversed, w/o modifying the array? ``` Byte[] ba = { 0, 0, 0, 6, 0, 0 }; BitConverter.ToUInt16(ba, 2); // is 1536/0x0600, but I want 6/0x0006 ```
It sounds like you want my `EndianBitConverter` in [`MiscUtil`](http://pobox.com/~skeet/csharp/miscutil), which lets you specify whether you want to use big or little endianness. Basically it provides the same functionality as `BitConverter` but as instance methods. You then get the appropriate kind of `EndianBitConverter` and do what you want with it. (It provides a bit more functionality for working efficiently with arrays, which may or may not be useful to you.) The library is open sourced under a fairly permissive licence.
You can also use IPAddress.HostToNetworkOrder.
Converting Byte array to Int-likes in C#
[ "", "c#", "integer", "arrays", "" ]
We need some simple ad-hoc reporting solution for our ASP.NET web-site. Just an ability to build a query with user friendly interface, then show the result of this query in some table and maybe export it to Excel or print. The solution must be quite easy for end users (our site visitors) who know nothing about databases, SQL and other tech stuff.
[EasyQuery.NET](http://devtools.korzh.com/eq/dotnet/) may suit your needs. It is proprietary but they have free version as well.
Though not .NET (yet) - but embeddable using an iframe - I'd recommend **[i-net Clear Reports](http://www.inetsoftware.de/products/crystal-clear)** (used to be i-net Crystal-Clear) sporting an ad-hoc reporting component that is made to be an easy-to-use thing for non-technical users. Your users won't have to know anything about reporting at all. They simply select the kind of report, the data et voila there is a report suiting the needs. Besides the web embeddability of the HTML output you could offer a standalone component and/or Java applet (i-net Clear Reports is entirely Java, but we're working hard to port the server side over to [.NET](http://www.inetsoftware.de/products/clear-reports-dot-net)). The upcoming version even supports web-skins so your users / customers won't recognise it's "third party". ;) Disclosure: Yep. I work for the company who built this.
Need ad-hoc reporting component
[ "", ".net", "asp.net", "sql", "reporting", "adhoc", "" ]
EDIT: See my answer below for the hotfix. ORIGINAL QUESTION: In setting up for our boat-programming adventure I have to set up source control and fix project files for a team to use them. (the project was previously only being worked on by one person who took shortcuts with setting up the project includes, etc) I am fixing those SLN and Proj files. When trying to do a build on an external USB drive (I have not tried it on the primary hard drive) I am getting odd errors (lots of them for various files): > fatal error C1083: Cannot open > compiler generated file: > '.\Debug\.sbr': Permission > denied These files are referenced in the vcproj file with relative paths in double quotes: > RelativePath="..\..\Source\.cpp" I get the same errors form within a sln file in the IDE or if I call msbuild with the sln file. The files are kind of "shared" for a few sln files (projects). The person who originally created the SLN files is not known for being a wizard at configuring MSDev or making things work for teams. Is this an issue with the way the source files are referenced? Any suggestions on how to fix these? This URL does not seem to have helpful information: [Fatal Error C1083 on MSDN](http://msdn.microsoft.com/en-us/library/et4zwx34.aspx) Note - there were/are still hardcoded paths in the proj file, but i don;t see them for these files. They were mostly for the include and lib dirs. I think I removed them all. I also get these errors: > ..\..\Source\.cpp : error C2471: > cannot update program database '\debug\vc90.pdb' > > ..\..\Source\.cpp(336) : fatal > error C1903: unable to recover from > previous error(s); stopping > compilation > > ..\..\Source\.cpp(336) : error > C2418: cannot delete browser file: > .\Debug\.sbr
**Title: You may receive a "PRJ0008" or "C2471" or "C1083" or "D8022" or "LNK1103" or similar error message when you try to build a solution in Visual C++** **Symptoms:** * D8022 : Cannot open 'RSP00000215921192.rsp' * PRJ0008 : Could not delete file 'vc90.idb'. * C1083 : Cannot open program database file 'vc90.pdb' * C2471 : Cannot update program database 'vc90.pdb' * LNK1103 : debugging information corrupt. **Cause:** This problem occurs when all of the following conditions are true: 1. You have a solution with more than one project in it. 2. Two or more of the projects are not dependent on each other. 3. You have parallel builds enabled. (Tools -> Options: Projects and Solutions, Build and Run: "maximum number of parallel project builds" is set to a value greater than 1) 4. You are building on a system with multiple CPUs (cores). 5. Two or more of the non-dependent projects are configured to use the same Intermediate and/or Output directory. 6. A specific race condition in mspdbsrv.exe remains uncorrected. **Resolution:** To resolve the problem do one or more of the following: * Reconfigure the non-dependent projects to specify an Intermediate and Output directory that is different from one another, e.g. Output Directory = "$(SolutionDir)$(ProjectName)\$(ConfigurationName)", Intermediate Directory = "$(OutDir)". * Adjust your solution's project dependencies (Project -> Project Dependencies...) so that each is dependent on another. * Disable parallel builds. * Add the "/onecpu" boot option to your boot.ini file. * Change you BIOS settings to enable/use only one CPU. * File a problem report with Microsoft Technical Support and keep bugging the crap out of them until they eventually fix mspdbsrv. **Status:** The problem is a combination of both a user project configuration error as well as a race condition in Microsoft's "mspdbsrv.exe" utility that does not properly handle more than one thread calling it at the same time for the same file resulting in the file's HANDLE being left open. Additionally Visual Studio itself and/or its build system (VCBUILD and/or MSBUILD) (or all three!) should be made smart enough to detect and alert the user of such user errors so that corrective action can be taken. This problem has been around for a LOOOOOONG time. **Applies to:** * Microsoft Visual C++ 2005 * Microsoft Visual C++ 2008 * Others? **Respectfully submitted:** "Fish" (David B. Trout) fish@infidels.org **p.s:** You're welcome. :)
Hmmm. Perhaps: <http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/0ceac3c6-62f6-4fdf-82e1-d41e1b4fcd20/> there is a hotfix from MS <http://code.msdn.microsoft.com/KB946040> <http://support.microsoft.com/kb/946040> That might be my problem. I think it might only be on one machine I have. EDIT: I downloaded and ran the hotfix installer. It seems to have fixed it.
VC2008 compiler errors opening sbr files (C2418 C1903 C2471)
[ "", "c++", "visual-studio-2008", "" ]
Does anyone know how to pass multiple parameters into a Thread.Start routine? I thought of extending the class, but the C# Thread class is sealed. Here is what I think the code would look like: ``` ... Thread standardTCPServerThread = new Thread(startSocketServerAsThread); standardServerThread.Start( orchestrator, initializeMemberBalance, arg, 60000); ... } static void startSocketServerAsThread(ServiceOrchestrator orchestrator, List<int> memberBalances, string arg, int port) { startSocketServer(orchestrator, memberBalances, arg, port); } ``` BTW, I start a number of threads with different orchestrators, balances and ports. Please consider thread safety also.
Try using a lambda expression to capture the arguments. ``` Thread standardTCPServerThread = new Thread( unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000) ); ```
Here is a bit of code that uses the object array approach mentioned here a couple times. ``` ... string p1 = "Yada yada."; long p2 = 4715821396025; int p3 = 4096; object args = new object[3] { p1, p2, p3 }; Thread b1 = new Thread(new ParameterizedThreadStart(worker)); b1.Start(args); ... private void worker(object args) { Array argArray = new object[3]; argArray = (Array)args; string p1 = (string)argArray.GetValue(0); long p2 = (long)argArray.GetValue(1); int p3 = (int)argArray.GetValue(2); ... }> ```
thread with multiple parameters
[ "", "c#", ".net", "multithreading", "parameters", "thread-safety", "" ]
How to get "GET" variables from request in JavaScript? Does jQuery or YUI! have this feature built-in?
**Update June 2021:** Today's browsers have built-in APIs for working with URLs ([URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)) and query strings ([URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)) and these should be preferred, unless you need to support some old browsers or Opera mini ([Browser support](https://caniuse.com/?search=URLSearchParams)). **Original:** All data is available under ``` window.location.search ``` you have to parse the string, eg. ``` function get(name){ if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search)) return decodeURIComponent(name[1]); } ``` just call the function with GET variable name as parameter, eg. ``` get('foo'); ``` this function will return the variables value or undefined if variable has no value or doesn't exist
You could use `jquery.url` I did like this: ``` var xyz = jQuery.url.param("param_in_url"); ``` [Check the source code](https://github.com/allmarkedup/jQuery-URL-Parser/blob/master/jquery.url.js) Updated Source: <https://github.com/allmarkedup/jQuery-URL-Parser>
How to get "GET" request parameters in JavaScript?
[ "", "javascript", "" ]
In my app I have an Administrator role, and these kind of users can change the role of a user(client, manager...). I am using the built in Membership provider. Here is what I tried to do... ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditRole(string usernameID, FormCollection formValues) { var db = new AppDataContext(); var user = db.Users.SingleOrDefault(d => d.UserName == usernameID); string choosenRole = Request.Form["Roles"]; var tuple = db.UsersInRoles.SingleOrDefault(d => d.UserId == user.UserId); var roleNameID = db.Roles.SingleOrDefault(d => d.RoleName == choosenRole).RoleId; tuple.RoleId = roleNameID; db.SubmitChanges(); return RedirectToAction("Index"); } ``` But, I got this error.. > Value of member 'RoleId' of an object of type 'UsersInRole' changed. > A member defining the identity of the object cannot be changed. > Consider adding a new object with new identity and deleting the existing one instead. I'm stucked. Any ideas?
Rather than trying to access the membership tables directly from the db (datacontext) you should be using the `User`, `Roles`, and `Membership` static classes provided within your action code there. Like this: ``` System.Web.Security.Roles.AddUserToRole(usernameID, choosenRole); ``` Assuming that your usernameID is the string key of the user you want to change and choosenRole contains the role name key you want to add the user to: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditRole(string usernameID, FormCollection formValues) { string choosenRole = Request.Form["Roles"]; System.Web.Security.Roles.AddUserToRole(usernameID, choosenRole); return RedirectToAction("Index"); } ```
`UsersInRole.RoleId` is part of the primary key of the `UsersInRole` table and can therefore not be changed. You should follow the suggestion given by the error message and delete the existing `UsersInRole` instance and create a new one.
ASP .NET MVC: How can I change the role of an user?
[ "", "c#", "asp.net-mvc", "" ]
I'm trying to write a simple SNPP (Simple Network Paging Protocol) client using sockets. Everything seems to be working well, except for a small inconsistency between servers. When I send a command, I need to read the reply, which is usually a single chunk of data. However, Sprint's SNPP server sends replies in two parts. The first chunk of data is the first digit of the status code. The second chunk is the remainder. For example, when I attempt to receive the "220 Gateway ready" reply, it arrives like this: ``` 2 ``` I have to send another empty command to retrieve the rest: ``` 20 Gateway ready ``` For the moment, I'm using: ``` byte[] buffer = new byte[256]; socket.Receive(buffer); ``` How can I make sure that I receive all of the available data after issuing a command without allocating a separate buffer for each chunk of data?
For chunked responses I would recommend you reading data like this: ``` using (var resultStream = new MemoryStream()) { const int CHUNK_SIZE = 2 * 1024; // 2KB, could be anything that fits your needs byte[] buffer = new byte[CHUNK_SIZE]; int bytesReceived; while ((bytesReceived = socket.Receive(buffer, buffer.Length, SocketFlags.None)) > 0) { byte[] actual = new byte[bytesReceived]; Buffer.BlockCopy(buffer, 0, actual, 0, bytesReceived); resultStream.Write(actual, 0, actual.Length); } // Do something with the resultStream, like resultStream.ToArray() ... } ```
Try to check Socket.Available property to determine if do you need to call Receive again.
Receiving chunked data from a Socket to a single buffer
[ "", "c#", "sockets", "buffer", "" ]
Is there a list somewhere of recommendations of different Python-based REST frameworks for use on the serverside to write your own RESTful APIs? Preferably with pros and cons. Please feel free to add recommendations here. :)
Something to be careful about when designing a RESTful API is the conflation of GET and POST, as if they were the same thing. It's easy to make this mistake with [Django](http://www.djangoproject.com/)'s [function-based views](https://docs.djangoproject.com/en/dev/topics/http/views/) and [CherryPy](http://www.cherrypy.org/)'s default dispatcher, although both frameworks now provide a way around this problem ([class-based views](https://docs.djangoproject.com/en/dev/topics/class-based-views/) and [MethodDispatcher](http://docs.cherrypy.org/dev/refman/_cpdispatch.html#cherrypy._cpdispatch.MethodDispatcher), respectively). [HTTP-verbs are very important](http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_web_services) in REST, and unless you're very careful about this, you'll end up falling into a [REST anti-pattern](http://www.infoq.com/articles/rest-anti-patterns). Some frameworks that get it right are [web.py](http://webpy.org/), [Flask](http://flask.pocoo.org) and [Bottle](http://bottlepy.org). When combined with the [mimerender](https://github.com/martinblech/mimerender) library (full disclosure: I wrote it), they allow you to write nice RESTful webservices: ``` import web import json from mimerender import mimerender render_xml = lambda message: '<message>%s</message>'%message render_json = lambda **args: json.dumps(args) render_html = lambda message: '<html><body>%s</body></html>'%message render_txt = lambda message: message urls = ( '/(.*)', 'greet' ) app = web.application(urls, globals()) class greet: @mimerender( default = 'html', html = render_html, xml = render_xml, json = render_json, txt = render_txt ) def GET(self, name): if not name: name = 'world' return {'message': 'Hello, ' + name + '!'} if __name__ == "__main__": app.run() ``` The service's logic is implemented only once, and the correct representation selection (Accept header) + dispatch to the proper render function (or template) is done in a tidy, transparent way. ``` $ curl localhost:8080/x <html><body>Hello, x!</body></html> $ curl -H "Accept: application/html" localhost:8080/x <html><body>Hello, x!</body></html> $ curl -H "Accept: application/xml" localhost:8080/x <message>Hello, x!</message> $ curl -H "Accept: application/json" localhost:8080/x {'message':'Hello, x!'} $ curl -H "Accept: text/plain" localhost:8080/x Hello, x! ``` **Update (April 2012)**: added information about Django's class-based views, CherryPy's MethodDispatcher and Flask and Bottle frameworks. Neither existed back when the question was asked.
Surprised no one mentioned [flask](http://flask.pocoo.org/). ``` from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() ```
Recommendations of Python REST (web services) framework?
[ "", "python", "web-services", "rest", "frameworks", "" ]
I have a class that takes objects from a `BlockingQueue` and processes them by calling `take()` in a continuous loop. At some point I know that no more objects will be added to the queue. How do I interrupt the `take()` method so that it stops blocking? Here's the class that processes the objects: ``` public class MyObjHandler implements Runnable { private final BlockingQueue<MyObj> queue; public class MyObjHandler(BlockingQueue queue) { this.queue = queue; } public void run() { try { while (true) { MyObj obj = queue.take(); // process obj here // ... } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } ``` And here's the method that uses this class to process objects: ``` public void testHandler() { BlockingQueue<MyObj> queue = new ArrayBlockingQueue<MyObj>(100); MyObjectHandler handler = new MyObjectHandler(queue); new Thread(handler).start(); // get objects for handler to process for (Iterator<MyObj> i = getMyObjIterator(); i.hasNext(); ) { queue.put(i.next()); } // what code should go here to tell the handler // to stop waiting for more objects? } ```
If interrupting the thread is not an option, another is to place a "marker" or "command" object on the queue that would be recognized as such by MyObjHandler and break out of the loop.
``` BlockingQueue<MyObj> queue = new ArrayBlockingQueue<MyObj>(100); MyObjectHandler handler = new MyObjectHandler(queue); Thread thread = new Thread(handler); thread.start(); for (Iterator<MyObj> i = getMyObjIterator(); i.hasNext(); ) { queue.put(i.next()); } thread.interrupt(); ``` However, if you do this, the thread might be interrupted while there are still items in the queue, waiting to be processed. You might want to consider using [`poll`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#poll(long,%20java.util.concurrent.TimeUnit)) instead of `take`, which will allow the processing thread to timeout and terminate when it has waited for a while with no new input.
How to interrupt a BlockingQueue which is blocking on take()?
[ "", "java", "concurrency", "blockingqueue", "" ]
I'm trying to make a constructor for a graph class that accepts a string as a parameter and uses it to build the graph. The string is formatted as follows: `|vertex list|Edges list|` e.g. `|1,2,3,4,15|(1->2),(3->2),(4->15)|` The idea is that the constructor will take the values from the string and then know to perform the following actions (inserting the vertexes into the vertex list and then inserting the edges into the edges list): ``` addVertex(1) addVertex(2) addVertex(3) addVertex(4) addVertex(15) addEdge(1,2) addEdge(3,2) addEdge(4,15) ``` I would have just made a couple of "for" loops to scan the string, but I don't know what to do about double(or more) digit numbers. I'm starting to imagine all sorts of seriously complicated for loops and I'm wondering if anyone here could share with me any more intelligent ways to extract and use this data.
You can use a `stringstream` and use the stream extraction operator to get your integers. ``` string s("12 34"); istringstream ss(s); int x, y; ss >> x >> y; ``` Since this is homework, I urge you to explore the possibilities and figure out the complete code for yourself.
You seem to be getting overwhelmed looking at the whole thing. Break it into pieces...tasks. What you're trying to do seems to be separate functionalities here. 1. Tokenizing 2. Parsing Vertices 3. Parsing Edges 4. Execution on Vertices 5. Execution on Edges That's 5 functions more-or-less. You're wanting to tokenize based on the pipe (|) so take a substring based on the pipe and pass each side to the appropriate parser, parse on the commas and so on. Not going to do it for you, but hopefully I can get you thinking in the right direction. Learning to program isn't so much about any particular language, but about changing the way you think.
Parsing a string in C++
[ "", "c++", "string", "parsing", "casting", "integer", "" ]
I've just recently started using VS2008 for a new tools project, and have been spending a lot of time in Eclipse/Java. The one thing I am missing is the thing I could have sworn was in VS2005 the last time I worked with it - the class outline. I'm speaking of the basic outline in Eclipse, where you can see the class members, methods, etc and click on them to navigate to them. The only thing that sounds like it might be it (but is not) is the Class View. Any help?
This is probably the closest addin that you'll find that has it: * [Source Code Outliner Power Toy](http://sourcecodeoutliner.codeplex.com/) (The window on the left is what it adds to Visual Studio) [alt text http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=SourceCodeOutliner&DownloadId=3493](http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=SourceCodeOutliner&DownloadId=3493) * "You can dock the Source Code Outliner anywhere, like to the left side of the Visual Studio window next to the Code Editor window." * "Click a method or variable name in Source Outliner and the code associated with what you clicked displays near the top of the Code Editor window."
JetBrains Reshaper.
How to get an Eclipse-like class outline in VS 2008/C#?
[ "", "c#", "visual-studio-2008", "eclipse", "user-interface", "" ]
Is there a setting by which I can get some scripts to load/execute automatically once the PHP starts like getting a few constant up into global memory. Also is there a global memory which is accessible across users? Also about memory is there no memory which is accessible by all users? One person set that another person access's it or should I have to read and write to file every time for some thing to be shared across or rather a database temp table. Surprised PHP doesn't have this ? Thanks.
If I understand correctly, you want PHP to execute some script when you start Apache, to store some globally shared values. If I'm wrong, please edit/comment. The short answer is: no, you can't do that. PHP isn't exactly a server that stays running waiting for client requests. It handles each HTTP request individually. The long answer is: well... you could do auto\_prepend\_file to do it on each request. You could create some simple bash script and use that to start Apache then call a PHP script, but it wouldn't execute in Apache. As for shared memory, there are a few choices. Using flat files, a database, or memcached is probably the most portable. Some installs have the [Shared Memory](https://www.php.net/shmop) functions enabled, but it's not guaranteed.
PHP does not provide a global cache that is shared across scripts. You can work around this in different ways depending on your requirements. If you want to setup global constants that are not expensive to compute, you can write a script that defines these constants, and then automatically get this script to run before the requested file. This is done using the [auto\_prepend\_file option](http://php.net/ini.core#ini.auto-prepend-file) in php.ini. If you are computing expensive values, you can use [memcached](http://www.danga.com/memcached/) as a global cache that is accessible by all PHP scripts. There are [multiple client APIs](http://code.google.com/p/memcached/wiki/Clients) to connect to memcached using PHP. Of course, you can also store global values in the [user session](http://php.net/manual/en/features.sessions.php) if these values are per-user. Or even use MySQL.
PHP autostart with loading script
[ "", "php", "autostart", "" ]
Right... this one had me baffled for a while today so maybe one of you SQL Server bright sparks can shed some light on this behaviour. We have a table `Phones`. In it, the phone numbers are stored as nvarchars and it contains numbers in International format, in only numeric format... so a US number `+1-(212)-999-9999` is stored as `12129999999` For reasons that are beyond, me someone had written a SPROC, that took the phone number as a bigint, did no casting, did a simple where clause = comparison, and this worked absolutely fine, until some junk data got into the nvarchar column on the table which caused it to break. Consider the following test script. ``` IF EXISTS (SELECT * FROM sys.tables WHERE name = 'Phones') BEGIN DROP TABLE Phones END GO CREATE TABLE [dbo].[Phones] ( [ID] [int] IDENTITY(1,1) NOT NULL, [Mobile] [nvarchar](50) NOT NULL, CONSTRAINT [PK_Phones] PRIMARY KEY CLUSTERED ( [ID] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY] ) ON [PRIMARY] GO DECLARE @biMobile_1 bigint DECLARE @biMobile_2 bigint SET @biMobile_1 = 12121111111 SET @biMobile_2 = 12129999999 Print 'Inserting Phone Number' INSERT INTO Phones (Mobile) VALUES ('12121111111') Print 'Selecting Phone Number' SELECT * FROM Phones WHERE Mobile = @biMobile_1 --Select #1 Print 'Inserting Junk Data' INSERT INTO Phones (Mobile) VALUES ('JUNK DATA') INSERT INTO Phones (Mobile) VALUES ('12129999999') Print 'Selecting From Table Containing Junk' SELECT * FROM Phones WHERE Mobile = @biMobile_1 -- Select #2 SELECT * FROM Phones WHERE Mobile = @biMobile_2 -- Select #3 ``` The first select (marked #1) will work The second select (marked #2) will work but will give an error immediately after The third select (marked #3) returns nothing. The error returned is ``` Error converting data type nvarchar to bigint. ``` Now this seems completely bonkers behaviour. What I thought would happen is 1. SQL realises its comparing 2 different data types in the `WHERE` clause 2. It would attempt to convert the @variable to the datatype of the column 3. If it fails, throw an error, it it works, GREAT!!! What actually seems to be happening is 1. SQL realises its comparing 2 different data types in the `WHERE` clause 2. On a row by row basis, it converts the value in the column to the datatype of the @variable 3. For each successful conversion, it does the comparison, and will return that row. 4. If it hits a value in the column, that it can't convert, it bombs, returns whatever data it has found so far, and doesn't continue on through the table. **Can anyone clarify what the reasoning is behind this logic, and if theres any particular order of precedence that SQL Server gives to Data Types when it's deciding what to compare/cast** Note. I did this test in SQL 2005 but it's replicable behaviour in SQL2K also.
Data type precedence is well defined - <http://msdn.microsoft.com/en-us/library/ms190309.aspx> Edit - to clarify, it is not that sql always converts the column type to the param type. It just follows the type precedence in the link I gave. This could mean the param gets converted to the column type, if the type precedence dictates so.
I don't see what the problem is. Why would SQL server know that record #232 out of #1000 would bomb? It doesn't until it gets to that record. In the meantime, it's streaming the results back to the client as they are generated. This is to help with performance. What else would you expect?
SQL Server, where clauses comparisons with different types & default casting behaviour
[ "", "sql", "sql-server", "casting", "types", "" ]
I'm looking for an open source, pure Python library that supports the [SyncML](http://en.wikipedia.org/wiki/SyncML) protocol, at least enough to implement a SyncML client.
There's <https://sourceforge.net/projects/pysyncml/>: "The pysyncml library is a pure-python implementation of the SyncML adapter framework and protocol." Haven't tried it yet.
I don't know of any pure Python implementations, but there are python bindings for C libraries: * pysyncml (google for it, can only post 1 link) and * a [ctypes-based wrapper](http://github.com/Jc2k/conduit/blob/8beabdb62bccda57a9d49917ead305e611203a26/conduit/modules/SyncmlModule/pysyncml.py) that's used by the conduit project.
Looking for a pure Python library for the SyncML protocol
[ "", "python", "syncml", "" ]
I saw some code as below during a peer-code-review session: ``` char *s = new char[3]; *s++ = 'a'; *s++ = 'b'; *s++='\0'; delete []s; // this may or may not crash on some or any day !! ``` Firstly, I know that in Standard C++, pointing to one-past the array-size is O.K. though accessing it results in undefined behaviour. So I believe the last line `*s++='\0'` is fine. But if I recall correctly, the C++ standard mandates that `delete` should be supplied the same pointer that `new` returned. This I believe means that the returned pointer must not be tampered-with. I guess it is because `new` might keep some housekeeping info before the returned address that `delete` might use. Moving the `new`'d pointer might make this inaccessible. Is it undefined behaviour or implementation-defined or unspecified? Can anyone confirm this please? Preferably by pointing to the correct place in the C++ Standard. In the freely available draft version of the draft C++ Standard (Draft\_SC22-N-4411.pdf) has the details in section 5.3.5. I got it from Bjarne's homepage.
From the C++ Standard, section 5.3.5/2: > the value of the operand of delete shall be the pointer value > which resulted from a previous array > new-expression. If not, the behaviour > is undefined
Yes, you must delete[] the original pointer you were given by new; in this case, that would be a pointer to the head of the array, rather than the tail. The code here is deleting some other unspecified random object.
delete[] supplied a modified new-ed pointer. Undefined Behaviour?
[ "", "c++", "memory-management", "new-operator", "standards-compliance", "" ]
I have been trying all afternoon to get the jQuery Sifr Plugin (<http://jquery.thewikies.com/sifr/>) to work, without success. The plugin's site has limited documentation and for something so apparently easy, I'm sure I must be nearly there. I also found some info at <http://www.eona.com/sifr/> but I think it's for an older version of the plugin. I have made my own font files using the online Sifr Generator (<http://www.sifrgenerator.com/>) and also on my own using Flash CS4 and neither seem to work. Here's my code: ``` $(document).ready(function(){ $.sifr({ path: 'http://**.com/js/', save: true }); $('.pageInfo h1').sifr({ font: 'soho', debug: true }); }); ``` Now, the "save: true" is not in the docs for this plugin but I did find it elsewhere on the plugin's site, the funny thing is, that without it, nothing happens but with it included, all I get is the default "Rendered with sIFR3" message instead of the text of my element. The plugin's site also says "It supports sIFR version 2 and version 3 fonts.", what does this mean? Could my font files be in the newer v3 type? I would really appreciate any and all help. Thank you in advance
Here I Am! Sorry for delay. :) You must specify at least build and version. Here's a sample: ``` $.sifr({ build: 436, version: 3, path: 'http://**.com/js/', save: true }); ```
I had the same issue using the jQuery plugin (which uses sIFR 3 now), for me it was that the pre-published swf's were < version 436 - specifically fonts from sifrvault. Likely your font needs to be re-published, grab the ttf and use OpensIFRr. -Jay
How do I implement jQuery Sifr Plugin properly?
[ "", "javascript", "jquery", "fonts", "sifr", "" ]
I've written recursive functions with the guidance of a friend who is teaching me C++ (as a first language). However, I don't really understand what is going on. He helped me (and the SO community, as well) write a merge sort function. ``` std::vector<int> mergeSort(std::vector<int> original) //code here to create two vectors, farray and sarray, out of the //original std::vector<int> original ; each is half the length, //note: if the size % 2 != 0, sarray takes the odd int farray = mergeSort(farray); sarray = mergeSort(sarray); //code here merges the two into a single, final sorted std::vector ``` In this function, I assign: ``` farray = mergeSort(farray); sarray = mergeSort(sarray); ``` What exactly is happening here? It calls mergeSort with farray and sarray as parameters and changes the value. How far does mergeSort execute into itself recursively? Just upto the recursive function call?
Each time you call a function recursively, it effectively makes a new copy of the information it needs, and goes on. You could have a program that recurs "infinitely", ie, until it runs out of resources, usually stack space — the space in which those copies are going. That would look like ``` void recur(){ recur(); } int main(){ recur(); exit(0); /* won't ever really get here.*/ } ``` Obviously, this isn't very useful, so you want to write a program that has some limit on how often it recurs. Here's a really simple program that manages that: ``` #include <iostream> using namespace std; void recurSome(int count){ cout << "RecurSome called with " << count << endl; if (count > 0){ recurSome(count-1); cout << "Back at " << count << endl; }else{ cout << "Bottom." << endl; } return; } int main(){ recurSome(10); exit(0); /* now it will get here. */ } ``` If you compile and run that, say with: ``` bash $ g++ -Wall -o rc recursome.cpp bash $ ./rc ``` You'll get the results: ``` RecurSome called with 10 RecurSome called with 9 RecurSome called with 8 RecurSome called with 7 RecurSome called with 6 RecurSome called with 5 RecurSome called with 4 RecurSome called with 3 RecurSome called with 2 RecurSome called with 1 RecurSome called with 0 Bottom. Back at 1 Back at 2 Back at 3 Back at 4 Back at 5 Back at 6 Back at 7 Back at 8 Back at 9 Back at 10 bash $ ``` See how it gets called for 10, then 9, and so on, and then after it reaches the bottom, it shows it coming back for 1, then 2, and so on back up to 10? The basic rule is that *every* recursive function should have something that makes a base case, one which *does* call itself again. In this one, the base case is `count == 0` and in fact we could have written this as a recursive definition > recursome: > if c = 0 : print bottom > if c > 0 : print count, and recursome(c-1) You'll see many recursive definitions of that sort as you move on in math. Here's a somewhat niftier C version with better output: ``` #include <stdio.h> #include <stdlib.h> int max = 10; void recurSome(int count){ printf("RecurSome %*c Called with %d\n", max-count+1, ' ', count); if (count > 0){ recurSome(count-1); printf("RecurSome %*c Back at %d\n", max-count+1, ' ', count); }else{ printf("RecurSome %*c Bottom.\n", 2*max, ' '); printf("RecurSome %*c Back at %d\n", max-count+1, ' ', count); } return; } int main(){ recurSome(max); exit(0); /* now it will get here. */ } ``` Output: ``` RecurSome Called with 10 RecurSome Called with 9 RecurSome Called with 8 RecurSome Called with 7 RecurSome Called with 6 RecurSome Called with 5 RecurSome Called with 4 RecurSome Called with 3 RecurSome Called with 2 RecurSome Called with 1 RecurSome Called with 0 RecurSome Bottom. RecurSome Back at 0 RecurSome Back at 1 RecurSome Back at 2 RecurSome Back at 3 RecurSome Back at 4 RecurSome Back at 5 RecurSome Back at 6 RecurSome Back at 7 RecurSome Back at 8 RecurSome Back at 9 RecurSome Back at 10 ```
Check it out in the dictionary: **recursion**: noun. see *recursion* Now, being serious, in the joke above, the definition of recursion is given in terms of recursion itself. That is recursion. A recursive algorithm is an algorithm whose implementation is based on the algorithm itself. The process of developing such an algorithm starts with the most basic case, whose solution is either known in advance or can be trivially calculated. Then you define the algorithm in terms of itself. As a simple example, calculating the n-th power of a given integer i could be a function `power( int number, int power )`. How could you implement it? in many ways. The simplest being a call to a library, followed by a loop, or you could define the function in terms of itself: ``` int power( int number, unsigned int pow ) { // Basic trivial case, cuts the recursion: if ( pow == 0 ) return 1; // Implement power in terms of itself: return number * power( number, pow-1 ); } int main() { int power = power( 2, 10 ); } ``` We have defined the function in terms of itself. You start with the most basic case (n^0 = 1). If we are not in the simplest case, you can express your algorithm in terms of itself. The program would start in main by calling `power( 2, 10 )` that would recurse and call `power( 2, 9 )` reducing the problem to a *smaller* problem and would then compose the final answer in terms of the simpler problem. The actuall call trace would be: ``` power( 2, 5 ) power( 2, 4 ) power( 2, 3 ) power( 2, 2 ) power( 2, 1 ) power( 2, 0 ) // simplest case: return 1 return 2 * 1 -> 2 // obtain next solution in terms of previous return 2 * 2 -> 4 return 2 * 4 -> 8 return 2 * 8 -> 16 return 2 * 16 -> 32 ``` While developing recursive algorithms it usually helped me believing that I already had the algorithm up and running and just work on the reduction/composition of the new result.
How far does recursion execute into your function in C++?
[ "", "c++", "recursion", "mergesort", "" ]
Duplicate of: [In what cases do I use malloc vs new?](https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new/) Just re-reading this question: [What is the difference between "new" and "malloc" and "calloc" in C++?](https://stackoverflow.com/questions/807939/what-is-the-difference-between-new-and-malloc-and-calloc-in-c-closed) I checked the answers but nobody answered the question: * When would I use malloc instead of new? There are a couple of reasons (I can think of two). Let the best float to the top.
A couple that spring to mind: * When you need code to be portable between C++ and C. * When you are allocating memory in a library that may be called from C, and the C code has to free the allocation.
From the Stroustrup FAQ on `new/malloc` I posted on that thread: > Whenever you use malloc() you must consider initialization and convertion of the return pointer to a proper type. You will also have to consider if you got the number of bytes right for your use. There is no performance difference between malloc() and new when you take initialization into account. This should answer your question.
When to use Malloc instead of New
[ "", "c++", "malloc", "new-operator", "dynamic-memory-allocation", "" ]