Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've been asked to implement some code that will update a row in a MS SQL Server database and then use a stored proc to insert the update in a history table. We can't add a stored proc to do this since we don't control the database. I know in stored procs you can do the update and then call execute on another stored pr...
Either run them both in the same statement (separate the separate commands by a semi-colon) or a use a transaction so you can rollback the first statement if the 2nd fails.
You don't really need a stored proc for this. The question really boils down to whether or not you have control over all the inserts. If in fact you have access to all the inserts, you can simply wrap an insert into datatable, and a insert into historytable in a single transasction. This will ensure that both are compl...
Execute an insert and then log in one SQL command
[ "", "sql", "sql-server", "" ]
I need to make an ArrayList of ArrayLists thread safe. I also cannot have the client making changes to the collection. Will the unmodifiable wrapper make it thread safe or do I need two wrappers on the collection?
It depends. The wrapper will only prevent changes to the collection it wraps, not to the objects in the collection. If you have an ArrayList of ArrayLists, the global List as well as each of its element Lists need to be wrapped separately, and you may also have to do something for the contents of those lists. Finally, ...
On a related topic - I've seen several replies suggesting using synchronized collection in order to achieve thread safety. Using synchronized version of a collection doesn't make it "thread safe" - although each operation (insert, count etc.) is protected by mutex when combining two operations there is no guarantee tha...
Does the unmodifiable wrapper for java collections make them thread safe?
[ "", "java", "multithreading", "collections", "unmodifiable", "" ]
I have a column containing the strings 'Operator (1)' and so on until 'Operator (600)' so far. I want to get them numerically ordered and I've come up with ``` select colname from table order by cast(replace(replace(colname,'Operator (',''),')','') as int) ``` which is very very ugly. Better suggestions?
It's that, InStr()/SubString(), changing Operator(1) to Operator(001), storing the n in Operator(n) separately, or creating a computed column that hides the ugly string manipulation. What you have seems fine.
If you really *have* to leave the data in the format you have - and adding a numeric sort order column is the better solution - then consider wrapping the text manipulation up in a user defined function. select colname from table order by dbo.udfSortOperator(colname) It's less ugly and gives you some abstraction. The...
Force numerical order on a SQL Server 2005 varchar column, containing letters and numbers?
[ "", "sql", "sql-server", "sql-order-by", "" ]
I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one. My right div typically has a lot of content. Here's a paired down example of my template to illustrate the problem. ``` <div style="float:left; width: 150px; b...
Use jQuery for this problem; just call this function in your ready function: ``` function setHeight(){ var height = $(document).height(); //optionally, subtract some from the height $("#leftDiv").css("height", height + "px"); } ```
Your simplest answer lies in the next version of css (3), which currently no browser supports. For now you are relegated to calculating heights in javascript and setting them on the left side. If the navigation is so important to be positioned in such a way, run it along the top. you could also do a visual trick by ...
On a two-column page, how can I grow the left div to the same height of the right div using CSS or Javascript?
[ "", "javascript", "html", "css", "" ]
I'm working on some production software, using C# on the .NET framework. I really would like to be able to use LINQ on the project. I believe it requires .NET version 3.5 (correct me if I'm wrong). This application is a commercial software app, required to run on a client's work PC. Is it reasonable to assume they have...
To use LINQ, as you have said, you need to have .NET 3.5. Just to confirm this, the Wikipedia page for LINQ says: > Language Integrated Query (LINQ, > pronounced "link") is a Microsoft .NET > Framework component that adds native > data querying capabilities to .NET > languages using a syntax reminiscent > of SQL. Many...
I would say that it isn't safe to assume they have .NET 3.5. Where as it is very, very unlikely they will have any problems when upgrading, changing anything always carries a risk. I know I wouldn't mind upgrading, but I am a developer. I think it's one of those things that could go either way, they either won't thin...
Requiring users to update .NET
[ "", "c#", ".net", "linq", "client-applications", "" ]
I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have: ``` <p height="30"> ``` I want to apply a `class="h30"` to that paragraph so that I can style it in my style sheet. I can't find any informa...
I would highly recommend using something like jquery where adding classes is trivial: ``` $("#someId").addClass("newClass"); ``` so in your case: ``` $("p[height='30']").addClass("h30"); ``` so this selects all paragraph tags where the height attribute is 30 and adds the class h30 to it.
See: [getAttribute()](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-666EE0F9). Parameter is the name of the attribute (case insensitive). Return value is the value of the attribute (a string). Be sure to see the [Remarks](http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx) in MSDN before dealing with IE...
Javascript - Applying class to an HTML tag given an attribute/value
[ "", "javascript", "html", "" ]
I'm trying to write a Wordpress plug-in that automatically posts a blog post at a certain time of day. For example, read a bunch of RSS feeds and post a daily digest of all new entries. There are plug-ins that do something similar to what I want, but many of them rely on a cron job for the automated scheduling. I'll d...
<http://codex.wordpress.org/Function_Reference/wp_schedule_event>
pseudo-cron is good but the two issues it has is 1, It requires someone to "hit" the blog to execute. Low volume sites will potentially have wide ranging execution times so don't be two specific about the time. 2, The processing happens before the page loads. So if teh execution time happens and you have lots of "cro...
Running a scheduled task in a Wordpress plug-in
[ "", "php", "wordpress", "" ]
I would like to be able to do such things as ``` var m1 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Pounds); var m2 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Liters); m1.ToKilograms(); m2.ToPounds(new Density(7.0, DensityType.PoundsPerGallon); ``` If there isn't something like this already, any...
Check out the [Measurement Unit Conversion Library](http://www.codeproject.com/KB/library/Measurement_Conversion.aspx) on The Code Project.
We actually built one in-house where I work. Unfortunately, it's not available for the public. This is actually a great project to work on and it's not that hard to do. If you plan on doing something by yourself, I suggest you read about [Quantity](http://en.wikipedia.org/wiki/Physical_quantity), [Dimension](http://en...
Does anyone know a library for working with quantity/unit of measure pairs?
[ "", "c#", ".net", "vb.net", "metric", "" ]
I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When ...
(Apart from the observer pattern) you can also use [`call_user_func()`](http://php.net/manual/function.call-user-func.php) or [`call_user_func_array()`](http://php.net/manual/function.call-user-func-array.php). If you pass an `array(obj, methodname)` as first parameter it will invoked as `$obj->methodname()`. ``` <?p...
How do you feel about using the [Observer](http://en.wikipedia.org/wiki/Observer_Pattern) pattern? If not, you can implement a true callback this way: ``` // This function uses a callback function. function doIt($callback) { $data = "this is my data"; $callback($data); } // This is a sample callback fun...
Something like a callback delegate function in php
[ "", "php", "oop", "" ]
I'm working on a command line application for Solaris, written in Java6. I'd like to be able to scroll through a history of previous commands using the up and down arrows like many Unix tools allow (shells, VIM command mode prompt, etc). Is there any standard way of achieving this, or do I have to roll my own?
Yes, use the [GNU readline](http://tiswww.case.edu/php/chet/readline/rltop.html) library.
I think you are looking for something like [JLine](http://jline.sourceforge.net/) but I've never used it so cannot attest to its quality. She can apparently deal with autocompletion and command line history, and the last release was recently (feb this year) so it's by no means dead.
Adding command recall to a Unix command line application
[ "", "java", "unix", "command-line", "command-prompt", "ledit", "" ]
What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form.
``` private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar == 'm') this.WindowState = FormWindowState.Minimized; } ```
``` FormName.WindowState = FormWindowState.Minimized; ```
Is there a way to programmatically minimize a window
[ "", "c#", ".net", "vb.net", "winforms", "" ]
So I have a function that looks something like this: ``` float function(){ float x = SomeValue; return x / SomeOtherValue; } ``` At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the functi...
Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold ...
Printing a value to cout should not change the value of the paramter in any way at all. However, I have seen similar behaviour, adding debugging statements causes a change in the value. In those cases, and probably this one as well my guess was that the additional statements were causing the compiler's optimizer to be...
Can cout alter variables somehow?
[ "", "c++", "floating-point", "cout", "cpu-registers", "floating-point-precision", "" ]
I have 2 time values which have the type `datetime.time`. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type `datetime.datetime` but not for `datetime.time`. So what is the best way to do this?
Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours. One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference. ``` t1, t2 = dateti...
Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using `datetime.datetime.combine`, then subtracting: ``` >>> import datetime >>> t1 = datetime.time(2,3,4) >>> t2 = datetime.time(18,20,59) >>> dummydate = datetime.date(2000,1,1) >>> datetime.datetime.combine(dummydate,t2) ...
What is the simplest way to find the difference between 2 times in python?
[ "", "python", "datetime", "time", "" ]
I want to use SQL Profiler to trace the queries executed agains my database, track performance, etc. However it seems that the SQL Profiler is only available in the Enterprise edition of SQL Server 2005. Is this the case indeed, and can I do something about it?
You don't need **any** SQL license to run the client tools (Management Studio, Profiler, etc). If your organization has a copy of the installation media for Developer, Standard, or Enterprise, you can install the client tools on your local machine under the same license. If you're working solo, I would recommend [purc...
If you are open to using third party profilers, I have used [xSQL Profiler](http://www.xsqlsoftware.com/Product/xSQL_Profiler.aspx) and it performed well enough.
SQL Profiler on SQL Server 2005 Professional Edition
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I would prefer that a console app would default to multithreaded debug. warning level 4. build browse information. no resource folder. Does anyone know of any technique that would allow me to create a console app, with my desired options, without manually setting it.
Yes, you can do that. What you want is to create your own project template. You can then select that template from the New Project wizard. I wasn't able to location documentation on how to create a project template in Visual Studio 6, but [this MSDN article](http://msdn.microsoft.com/en-us/library/ms247120(VS.80).aspx)...
I have concluded this is impossible. The is support for custom appwizards for windows projects, but not console projectcs. This is where I did research. <http://www.codeproject.com/KB/cpp/genwiz.aspx?fid=15478&df=90&mpp=25&noise=3&> sort=Position&view=Quick&select=1266895 <http://msdn.microsoft.com/en-us/library...
Changing the default settings for a console application
[ "", "c++", "visual-studio", "visual-c++-6", "" ]
I have this line in a javascript block in a page: ``` res = foo('<%= @ruby_var %>'); ``` What is the best way to handle the case where `@ruby_var` has a single-quote in it? Else it will break the JavaScript code.
I think I'd use a ruby [JSON](http://json.org) library on @ruby\_var to get proper js syntax for the string and get rid of the '', fex.: ``` res = foo(<%= @ruby_var.to_json %>) ``` (after require "json"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templatin...
Rails has method specifically dedicated to this task found in [ActionView::Helpers::JavaScriptHelper](http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html) called [escape\_javascript](http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript). In your...
Javascript with embedded Ruby: How to safely assign a ruby value to a javascript variable
[ "", "javascript", "ruby", "" ]
I'm writing a J2SE desktop application that requires one of its components to be pluggable. I've already defined the Java interface for this plugin. The user should be able to select at runtime (via the GUI) which implementation of this interface they want to use (e.g. in an initialisation dialog). I envisage each plug...
After many tries for plugin-based Java architectures (what is precisely what you seem to look for), I finally found [JSPF](http://code.google.com/p/jspf/) to be the best solution for Java5 code. it do not have the huge needs of OSGI like solutions, but is instead rather easy to use.
OSGI is certainly a valid way to go. But, assuming you dont need to unload to reload the plugin, it might be using a hammer to crack a nut. You could use the classes in 'java.util.jar' to scan each JAR file in your plugins folder and then use a 'java.net.URLClassLoader' to load in the correct one.
Best technology for adding plugin support to a J2SE application?
[ "", "java", "plugins", "plugin-architecture", "" ]
I'm looking for a way of getting a **concurrent collection** in **C#** or at least a collection which supports a **concurrent enumerator**. Right now I'm getting an `InvalidOperationException` when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I...
Other than doing a deep-copy your best bet might be to lock the collection: ``` List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings); lock(theList.SyncRoot) { foreach(string s in theList) { // Do some Jazz } } ```
So I'm not quite sure what you're asking, but the Parallel Extensions team has put together some stuff that might fit the bill. See this blog post in particular, about [enumerating parallel collections](http://blogs.msdn.com/pfxteam/archive/2008/08/12/8852005.aspx). It also contains a link to download the Parallel CTP,...
Concurrent collections in C#
[ "", "c#", "concurrency", "" ]
Hey, I'm using [Levenshteins](http://en.wikipedia.org/wiki/Levenshtein_distance) algorithm to get distance between source and target string. also I have method which returns value from 0 to 1: ``` /// <summary> /// Gets the similarity between two strings. /// All relation scores are in the [0, 1] range, /// which me...
Your problem here may be distinguishing between noise words and useful data: * Rolling\_Stones.Best\_of\_2003.Wild\_Horses.mp3 * Super.Quality.Wild\_Horses.mp3 * Tori\_Amos.Wild\_Horses.mp3 You may need to produce a dictionary of noise words to ignore. That seems clunky, but I'm not sure there's an algorithm that can...
Kind of old, but It might be useful to future visitors. If you're already using the Levenshtein algorithm and you need to go a little better, I describe some very effective heuristics in this solution: [Getting the closest string match](https://stackoverflow.com/questions/5859561/getting-the-closest-string-match/58598...
Fuzzy text (sentences/titles) matching in C#
[ "", "c#", "algorithm", "string", "fuzzy-search", "" ]
I'm looking for a tool to generate a JavaScript stub from a WSDL. Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP. I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I d...
I had to do this myself in the past and I found this [CodeProject article](http://www.codeproject.com/KB/ajax/JavaScriptSOAPClient.aspx). I changed it up some, but it gave me a good foundation to implement everything I needed. One of the main features it already has is generating the SOAP client based off the WSDL. It ...
Apache CXF has tools that generate JavaScript clients that talk soap. Actually, any CXF service can have a javascript client autogenerated by doing a get to the URL with ?js appended. (just like ?wsld produces the wsdl) There are command line tools as well, but the dynamic generated stuff is kind of neat.
Generating JavaScript stubs from WSDL
[ "", "javascript", "soap", "wsdl", "" ]
The exact error is as follows > Could not load file or assembly 'Microsoft.SqlServer.Replication, > Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' > or one of its dependencies. An attempt was made to load a program with > an incorrect format. I've recently started working on this project again a...
I've found the solution. I've recently upgraded my machine to Windows 2008 Server 64-bit. The SqlServer.Replication namespace was written for 32-bit platforms. All I needed to do to get it running again was to set the Target Platform in the Project Build Properties to X86.
The [answer by baldy](https://stackoverflow.com/a/41451/148412) below is correct, but you may also need to enable 32-bit applications in your AppPool. Source: <http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-wit...
I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project
[ "", "c#", "sql-server", "replication", "" ]
What is a smart pointer and when should I use one?
**UPDATE** This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/uni...
Here's a simple answer for these days of modern C++ (C++11 and later): * **"What is a smart pointer?"** It's a type whose values can be used like pointers, but which provides the additional feature of automatic memory management: When a smart pointer is no longer in use, the memory it points to is deallocated (se...
What is a smart pointer and when should I use one?
[ "", "c++", "pointers", "c++11", "smart-pointers", "c++-faq", "" ]
I have a button that I would like to disable when the form submits to prevent the user submitting multiple times. I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled. How do I disable the button when the form successfully submit...
Give this a whirl: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Threading; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Id...
I'm not a huge fan of writing all that javascript in the code-behind. Here is what my final solution looks like. Button: ``` <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="doSubmit(this)" /> ``` Javascript: ``` <script type="text/javascript"><!-- function doSubmit(b...
Disable button on form submission
[ "", "asp.net", "javascript", "webforms", "" ]
The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments. Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewh...
You need to enable warning 4365 to catch the assignment. That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.
You can change the level of any specific warning by using /W[level][code]. So in this case /W34365 will make warning 4365 into a level 3 warning. If you do this a lot you might find it useful to put these options in a text file and use the @[file] option to simplify the command line.
Make VS compiler catch signed/unsigned assignments?
[ "", "c++", "c", "visual-studio", "" ]
I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?
[Ponder](http://billyquith.github.io/ponder/) is a C++ reflection library, in answer to this question. I considered the options and decided to make my own since I couldn't find one that ticked all my boxes. Although there are great answers to this question, I don't want to use tonnes of macros, or rely on Boost. Boost...
What you need to do is have the preprocessor generate reflection data about the fields. This data can be stored as nested classes. First, to make it easier and cleaner to write it in the preprocessor we will use typed expression. A typed expression is just an expression that puts the type in parenthesis. So instead of...
How can I add reflection to a C++ application?
[ "", "c++", "reflection", "templates", "sfinae", "" ]
I am looking for a drop-down JavaScript menu. It should be the simplest and most elegant accessible menu that works in IE6 and Firefox 2 also. It would be fine if it worked on an unnumbered list (`ul`) so the user can use the page without JavaScript support. Which one do you recommend and where can I find the code to...
I think the jquery superfish menu is fantastic and easy to use: <http://users.tpg.com.au/j_birch/plugins/superfish/> Javascript is **not required**, and it is based on simple valid ul unorder lists.
[A List Apart - Dropdowns](https://alistapart.com/article/dropdowns/) I'd use a css-only solution like the above so the user still gets dropdown menus even with javascript disabled.
Best Javascript drop-down menu?
[ "", "javascript", "menu", "dhtml", "" ]
How do I get an element or element list by it's tag name. Take for example that I want all elements from `<h1></h1>`. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
document.getElementsByTagName('a') returns an array. Look here for more information: <http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName> Amendment: If you want a real array, you should use something like `Array.from(document.getElementsByTagName('a'))`, or thes...
Use `$$()` and pass in a CSS selector. Read the [Prototype API documentation for `$$()`](http://www.prototypejs.org/api/utility/dollar-dollar) This gives you more power beyond just tag names. You can select by class, parent/child relationships, etc. It supports more CSS selectors than the common browser can be expect...
Prototype get by tag function
[ "", "javascript", "prototypejs", "" ]
What does the `volatile` keyword do? In C++ what problem does it solve? In my case, I have never knowingly needed it.
`volatile` is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did...
`volatile` is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the `volatile` keyword to ensure that such accesses aren't optimised away by the compiler.
Why does volatile exist?
[ "", "c++", "volatile", "c++-faq", "" ]
For example, if passed the following: ``` a = [] ``` How do I check to see if `a` is empty?
``` if not a: print("List is empty") ``` Using the [implicit booleanness](https://docs.python.org/library/stdtypes.html#truth-value-testing) of the empty `list` is quite Pythonic.
The Pythonic way to do it is from the [PEP 8 style guide](https://www.python.org/dev/peps/pep-0008). > For sequences, (strings, lists, tuples), use the fact that empty sequences are false: > > ``` > # Correct: > if not seq: > if seq: > > # Wrong: > if len(seq): > if not len(seq): > ```
How do I check if a list is empty?
[ "", "python", "list", "" ]
I need to extract data from a .mpp file on the network and combine it with other data from several different databases. The application can be written in Perl, VB6, VB.net or C# but must be easily scheduled from a Windows based server. What would you recommend to extract the MS Project data with no user intervention? ...
I would recommend using MPXJ ([mpxj.sf.net](http://mpxj.sf.net)) to extract data from Microsoft Project files. Don't be put off by the fact that it was originally a Java library - the current release of MPXJ includes native .net dlls as well as the original Java JAR file, thanks to the magic of IKVM. Disclaimer: I mai...
MPP does have its own object model that can be used to access data in it. The info should be available here: <http://msdn.microsoft.com/en-us/office/aa905469.aspx>
How would you extract data from a MS Project .mpp file?
[ "", "c#", "vb.net", "perl", "vb6", "project-management", "" ]
What is the fastest way of transferring few thousand rows of data from one DataTable to another? Would be great to see some sample code snippets. Edit: I need to explain a bit more. There is a filtering condition for copying the rows. So, a plain Copy() will not work.
You can't copy the whole table, you need to copy one rows. From <http://support.microsoft.com/kb/308909> (sample code if you follow the link) "How to Copy DataRows Between DataTables Before you use the ImportRow method, you must ensure that the target table has the identical structure as the source table. This sample ...
What is wrong with [DataTable.Copy](http://msdn.microsoft.com/en-us/library/system.data.datatable.copy.aspx)?
Copying data from one DataTable to another
[ "", "c#", "ado.net", "" ]
User [kokos](https://stackoverflow.com/users/1065/kokos) answered the wonderful *[Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)* question by mentioning the `using` keyword. Can you elaborate on that? What are the uses of `using`?
The reason for the `using` statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens. As in *[Understanding the 'using' statement in C# (codeproject)](https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-i...
Since a lot of people still do: ``` using (System.IO.StreamReader r = new System.IO.StreamReader("")) using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) { //code } ``` I guess a lot of people still don't know that you can do: ``` using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2...
What are the uses of "using" in C#?
[ "", "c#", "using", "using-statement", "" ]
At work today, I came across the `volatile` keyword in Java. Not being very familiar with it, I found [this explanation](http://web.archive.org/web/20210221170926/https://www.ibm.com/developerworks/java/library/j-jtp06197/). Given the detail in which that article explains the keyword in question, do you ever use it or...
`volatile` has semantics for memory visibility. Basically, the value of a `volatile` field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without `volatile`, readers could see some non-updated value. To answer your question: Yes, I use a `volatile` variable to con...
*“… the volatile modifier guarantees that any thread that reads a field will see the most recently written value.”* **- Josh Bloch** If you are thinking about using `volatile`, read up on the package [`java.util.concurrent`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html) which...
What is the volatile keyword useful for?
[ "", "java", "multithreading", "keyword", "volatile", "" ]
I would like to serialize and deserialize objects without having to worry about the entire class graph. Flexibility is key. I would like to be able to serialize any object passed to me without complete attributes needed throughout the entire object graph. > That means that Binary Serialization > is not an option as i...
Have you considered serializing to JSON instead of XML? [Json.NET](http://james.newtonking.com/projects/json-net.aspx) has a really powerful and flexible serializer that has no problems with Hashtables/generic dictionaries and doesn't require any particular attributes. I know because I wrote it :) It gives you heaps ...
If I recall it works something like this with a property: ``` [XmlArray("Foo")] [XmlArrayItem("Bar")] public List<BarClass> FooBars { get; set; } ``` If you serialized this you'd get something like: ``` <Foo> <Bar /> <Bar /> </Foo> ``` Of course, I should probably defer to the experts. Here's more info from...
What is the most flexible serialization for .NET objects, yet simple to implement?
[ "", "c#", ".net", "serialization", "" ]
I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality: The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database. Although I am mainly inter...
This is the LibraryThing founder. We have nothing to offer here, so I hope my comments will not seem self-serving. First, the comment about Amazon, ASINs and ISBN numbers is wrong in a number of ways. In almost every circumstance where a book has an ISBN, the ASIN and the ISBN are the same. ISBNs are not now 13 digits...
Google has it's own [API for Google Books](https://developers.google.com/books/docs/v1/reference/) that let's you query the Google Book database easily. The protocol is JSON based and you can view the technical information about it [here](https://developers.google.com/books/docs/v1/using?hl=en#WorkingVolumes). You ess...
How to fetch a Book Title from an ISBN number?
[ "", "php", "language-agnostic", "" ]
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var? For example I rather lazily used var in questionable circumstances, e.g.:- ``` foreach(var item in someList) { // ... } // Type of 'item' not clear....
I still think `var` can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this: ``` var orders = cust.Orders; ``` I don't care if Customer.Orders is `IEnumerable<Order>`, `ObservableCollection<Order>` or `BindingList<Orde...
I use `var` extensively. There has been criticism that this diminishes the readability of the code, but no argument to support that claim. Admittedly, it may mean that it's not clear what type we are dealing with. So what? This is actually the point of a decoupled design. When dealing with interfaces, you are emphatic...
Use of var keyword in C#
[ "", "c#", "type-inference", "var", "" ]
I am using URLDownloadToFile to retrieve a file from a website. Subsequent calls return the original file rather than an updated version. I assume it is retrieving a cached version.
Call DeleteUrlCacheEntry with the same URL just prior to calling URLDownloadToFile. You will need to link against Wininet.lib
Yes, it is pulling a cached version of the file by default. To avoid the cache file completely, pass an IBindStatusCallback object in the lpfnCB parameter of URLDownloadToFile(). In your implemented IBindStatusCallback::GetBindInfo() method, include the BINDF\_GETNEWESTVERSION flag, and optionally also the BINDF\_NOWRI...
How can I prevent URLDownloadToFile from retrieving from the cache?
[ "", "c++", "winapi", "wininet", "" ]
Hello again ladies and gents! OK, following on from my other question on [ASP.NET Web Service Results, Proxy Classes and Type Conversion](https://stackoverflow.com/questions/6681/aspnet-web-service-results-proxy-classes-and-type-conversion). I've come to a part in my project where I need to get my thinking cap on. Ba...
The .Net XML (de)serialisation is pretty nicely implemented. At first thought, I don't think this is a bad idea at all. If the two applications import the same C# class(es) definition(s), then this is a relatively nice way of getting copy-constructor behaviour for free. If the class structure changes, then everything ...
I'm loving `JSON` for this kind of thing. I just finished a POC drop-things type portal for my company using `jQuery` to contact web services with script service enabled. The messages are lightweight and parsing etc is pretty much handled. The `jQuery ajax` stuff I read was here (loving it!) : [jquery ajax article](htt...
Large, Complex Objects as a Web Service Result
[ "", "c#", "asp.net", "xml", "web-services", "serialization", "" ]
I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid. Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the...
The node label editing is performed with a text box and when that text box loses focus the change in name will be committed as the new label for the node. So if the 'Save' button you are clicking on takes the focus then it will cause the update automatically because the text box will lose focus. If the 'Save' button d...
I'll accept the answer even though it's not really documented: does it or does it not have such a method? You actually didn't answer to this, just passed the question back to me. Meanwhile found the same hack-ish solution with forcing the focus to some other control (not very elegant but works), even though it's a bit...
Hot to commit changes for a TreeView while editing a node (C#)?
[ "", "c#", "treeview", "commit", "editing", "" ]
I'm kind of interested in getting some feedback about this technique I picked up from somewhere. I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the t...
I agree with the others who have stated that this is a little on the WTFy side. If it's clearly documented functionality, then it's less of an issue, but I think it'd be safer to take an alternate route of returning 0 for success and integers for error codes. If you don't like that idea or the idea of a global last err...
As long as it's documented and contracted, and not too WTFy, then there shouldn't be a problem. Then again, I would recommend using exceptions for something like this. It makes more sense. If you can use PHP5, then that would be the way to go. Otherwise you don't have much choice.
Multiple return values to indicate success/failure.
[ "", "php", "" ]
I have a Java program that loads thirdparty class files (classes I did not write) and executes them. These classes often use `java.util.Random`, which by default generates random starting seed values every time it gets instantiated. For reasons of reproducability, I want to give these classes the same starting seed eve...
Consider modifying the third party libraries to have them use a seen for their Random instances. Though you do not have the source code, you can probably edit the bytecode to do it. One helpful toolkit for doing such is [ASM](http://asm.objectweb.org/).
Your option 2 will actually work, with the following directions. You will need ( as anjab said ) to change the bootstrap class path . In the command line of the program you need to add the following: java -Xbootclasspath/p:C:\your\random\_impl.jar YourProgram Assuming you're on Windown machine or the path for that ...
How can I give java.util.Random a specific seed in thirdparty classes?
[ "", "java", "random", "jvm", "classloader", "" ]
In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, `static int MYINT = 3;` causes the serialVersionUID to change. In this example, it makes sense because different versions of the class woul...
You can find some information about that in the [bug 4365406](https://bugs.java.com/bugdatabase/view_bug?bug_id=4365406) and in the [algorithm for computing **serialVersionUID**](http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/class.html#4100). Basically, when changing the initialization of your `static` m...
Automatic serialVersionUID is calculated based on members of a class. These can be shown for a class file using the javap tool in the Sun JDK. In the case mentioned in the question, the member that is added/removed is the static initialiser. This appears as ()V in class files. The contents of the method can be disasse...
Java serialization with static initialization
[ "", "java", "serialization", "" ]
I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the string are the same, and the middle part that differs is an integer, then compare based on the numeric values of those integers. For example, I want the ...
[The Alphanum Algorithm](https://web.archive.org/web/20210803201519/http://www.davekoelle.com/alphanum.html) From the website "People sort strings with numbers differently than software. Most sorting algorithms compare ASCII values, which produces an ordering that is inconsistent with human logic. Here's how to fix i...
Interesting little challenge, I enjoyed solving it. Here is my take at the problem: ``` String[] strs = { "eee 5 ddd jpeg2001 eee", "eee 123 ddd jpeg2000 eee", "ddd", "aaa 5 yy 6", "ccc 555", "bbb 3 ccc", "bbb 9 a", "", "eee 4 ddd jpeg2001 eee", "ccc 11", "bbb 12 ccc", "aaa 5 yy 22", "aaa", ...
Sort on a string that may contain a number
[ "", "java", "algorithm", "string", "sorting", "comparison", "" ]
Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collec...
I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that. ``` if (item is IEnumerable) { foreach (object o in (item as IEnumerable)) { } } else { // reflect over item } ```
I've tried to use a similar technique as Darren suggested, however just beware that not just collections implement IEnumerable. `string` for instance is also IEnumerable and will iterate over the characters. Here's a small function I'm using to determine if an object is a collection (which will be enumerable as well s...
Accessing a Collection Through Reflection
[ "", "c#", "reflection", "collections", "" ]
I came across [this article](http://www.ddj.com/cpp/184403758) written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates e...
It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a `catch` block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ *is* done by resource acquisition and garbage collection is done by implicit destructor calls. O...
Yes. If there is one single piece of C++ code that I could recommend every C++ programmer spend 10 minutes learning, it is ScopeGuard (now part of the freely available [Loki library](http://loki-lib.sourceforge.net/)). I decided to try using a (slightly modified) version of ScopeGuard for a smallish Win32 GUI program...
Does ScopeGuard use really lead to better code?
[ "", "c++", "raii", "scopeguard", "" ]
I have an app that I've written in C#/WinForms ([my little app](http://www.thekbase.com "TheKBase")). To make it cross-platform, I'm thinking of redoing it in Adobe AIR. Are there any arguments in favor of WinForms as a cross-platform app? Is there a cross-platform future for Winforms (e.g., Mono, etc.)? Suggestions fo...
> I'm thinking of redoing it in Adobe AIR Not having spent much time with AIR, my personal opinion is that it is best for bringing a webapp to the desktop and provide a shell to it or run your existing flash/flex project on the desktop. Btw, if you don't know ActionScript, I mean its details, quirks, etc, don't forge...
As far as my experience in Flex/AIR/Flash actionscripting goes, Adobe AIR development environment and coding/debugging toolsets are far inferior to the Visual Studio and .NET SDK as of the moment. The UI toolsets are superior though. But as *you already have a working C# code*, porting it to ActionScript might require...
Making a C#/Winform application cross-platform - should I use AIR, Mono, or something else?
[ "", "c#", "winforms", "cross-platform", "" ]
The Interface Segregation Principle (ISP) says that many client specific interfaces are better than one general purpose interface. Why is this important?
ISP states that: > Clients should not be forced to depend > on methods that they do not use. ISP relates to important characteristics - [cohesion](http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29) and [coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29). Ideally your components must ...
The interface segregation is the “I” on the SOLID principle, before digging too deep with the first, let’s explain what’s does the latter mean. SOLID can be considered a set of best practices and recommendations made by experts (meaning they have been proved before) in order to provide a reliable foundation in how we ...
What is the reasoning behind the Interface Segregation Principle?
[ "", "java", "oop", "solid-principles", "design-principles", "interface-segregation-principle", "" ]
I'm porting old VB6 code that uses the Winsock control to C#. I haven't done any socket programming and I wonder if anyone has a good reference/tutorial/howto that I can use to start getting up to speed. I'm appealing to the hive mind while I proceed with my generally unproductive googling. I'm using UDP, not TCP at ...
The August 2005 MSDN Magazine had an article about System.Net.Sockets and WinSock: <http://msdn.microsoft.com/en-us/magazine/cc300760.aspx>
* I recommend the asynchronous model for most applications, especially if you want performance or applications that don't hang as soon there is a network problem. For this the MSDN articles on [Socket.BeginConnect](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.beginconnect.aspx) and [Socket.BeginRec...
What is a good tutorial/howto on .net / c# socket programming
[ "", "c#", "sockets", "network-programming", "winsock", "" ]
Are there any good database schema comparison tools out there that support Sybase SQL Anywhere version 10? I've seen a litany of them for SQL Server, a few for MySQL and Oracle, but nothing that supports SQL Anywhere correctly. I tried using DB Solo, but it turned all my non-unique indexes into unique ones, and I didn...
If you are willing to download SQL Anywhere Version 11, and Compare It!, check out the comparison technique shown here: <http://sqlanywhere.blogspot.com/2008/08/comparing-database-schemas.html> You don't have to upgrade your SQL Anywhere Version 10 database.
The new kid on the block is [Qwerybuilder](http://www.werysoft.com/Features.aspx). It supports SQL Server, Sybase ASE, Sybase SQL Anywhere and Oracle. I've used it successfully with SQL Anywhere to track schema changes.
Any good SQL Anywhere database schema comparison tools?
[ "", "sql", "comparison", "schema", "sqlanywhere", "" ]
For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client? Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I ...
If you have a Linux system available to you use [wget](http://www.gnu.org/software/wget/): ``` wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/ ``` Options * -k : convert links to relative * -K : keep an original versions of files without the conversions made by wget * -E : rename html files to .html (if the...
build your site, then use a mirroring tool like [wget](http://www.gnu.org/software/wget/) or [lwp-mirror](http://search.cpan.org/dist/libwww-perl/bin/lwp-mirror) to grab a static copy
How can I create a site in php and have it generate a static version?
[ "", "php", "html", "wget", "" ]
I have three unordered lists that have been created as Scriptaculous Sortables so that the user can drag items within the lists and also between them: ``` var lists = ["pageitems","rowitems","columnitems"]; Sortable.create("pageitems", { dropOnEmpty: true, containment: lists, constraint: false }); Sortable.cre...
Maybe the empty list has no height, and therefore no droppable area available. If that's the case, perhaps you just need to set a minimum height, or some padding on the block.
add dropOnEmpty:true to the options parameters.
Can't Drag Items Onto An Empty List Using Scriptaculous Sortables
[ "", "javascript", "drag-and-drop", "scriptaculous", "" ]
I need to enumerate though generic IList<> of objects. The contents of the list may change, as in being added or removed by other threads, and this will kill my enumeration with a "Collection was modified; enumeration operation may not execute." What is a good way of doing threadsafe foreach on a IList<>? prefferably ...
Cloning the list is the easiest and best way, because it ensures your list won't change out from under you. If the list is simply too large to clone, consider putting a lock around it that must be taken before reading/writing to it.
There is no such operation. The best you can do is ``` lock(collection){ foreach (object o in collection){ ... } } ```
Threadsafe foreach enumeration of lists
[ "", "c#", "multithreading", "" ]
I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?
Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding. I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather cre...
From LINQ in action (page 76 section 2.6.3): > ... anonymous types [are] a great tool for quick and simple temporary results. We don't need to declare classes to hold temporary results thanks to temporary types. basically they're useful to hold information in the local scope temporarily. Anything more requires the us...
How should anonymous types be used in C#?
[ "", "c#", "anonymous-types", "" ]
In C#, what is the difference (if any) between these two lines of code? ``` tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick); ``` and ``` tmrMain.Elapsed += tmrMain_Tick; ``` Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?
I did this ``` static void Hook1() { someEvent += new EventHandler( Program_someEvent ); } static void Hook2() { someEvent += Program_someEvent; } ``` And then ran ildasm over the code. The generated MSIL was exactly the same. So to answer your question, yes they are the same thing. The compiler is just...
It used to be (.NET 1.x days) that the long form was the only way to do it. In both cases you are newing up a delegate to point to the Program\_someEvent method.
Difference between wiring events with and without "new"
[ "", "c#", "events", "syntax", "delegates", "" ]
What method do I call to get the name of a class?
``` In [1]: class Test: ...: pass ...: In [2]: Test.__name__ Out[2]: 'Test' ```
It's not a method, it's a field. The field is called `__name__`. `class.__name__` will give the name of the class as a string. `object.__class__.__name__` will give the name of the class of an object.
How do I get the string with name of a class?
[ "", "python", "" ]
Why does the use of temp tables with a SELECT statement improve the logical I/O count? Wouldn't it increase the amount of hits to a database instead of decreasing it. Is this because the 'problem' is broken down into sections? I'd like to know what's going on behind the scenes.
There's no general answer. It depends on how the temp table is being used. The temp table may reduce IO by caching rows created after a complex filter/join that are used multiple times later in the batch. This way, the DB can avoid hitting the base tables multiple times when only a subset of the records are needed. T...
I'm going to assume by temp tables you mean a sub-select in a WHERE clause. (This is referred to as a semijoin operation and you can usually see that in the text execution plan for your query.) When the query optimizer encounter a sub-select/temp table, it makes some assumptions about what to do with that data. Essent...
Temp tables and SQL SELECT performance
[ "", "sql", "performance", "" ]
I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers. I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm real...
In most browsers, this can be achieved using CSS: ``` *.unselectable { -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; /* Introduced in IE 10. See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/ */ -ms-user-select: none; user-select: none; } ``` ...
``` <script type="text/javascript"> /*********************************************** * Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com) * This notice MUST stay intact for legal use * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code **********************...
Is there a way to make text unselectable on an HTML page?
[ "", "javascript", "html", "css", "cross-browser", "textselection", "" ]
I'm using the After Effects CS3 Javascript API to dynamically create and change text layers in a composition. Or at least I'm trying to because I can't seem to find the right property to change to alter the actual text of the TextLayer object.
Hmm, must read docs harder next time. ``` var theComposition = app.project.item(1); var theTextLayer = theComposition.layers[1]; theTextLayer.property("Source Text").setValue("This text is from code"); ```
I'm not an expert with After Effects, but I have messed around with it. I think [reading this](http://library.creativecow.net/articles/ebberts_dan/ae6_exp.php) might help you out.
Programmatically change the text of a TextLayer in After Effects
[ "", "javascript", "after-effects", "" ]
I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces. **Example**: ``` Project = Tully.Saps.Data Folder = DataAccess/Interfaces Namespace = Tully.Saps.Data.DataAccess.Interfaces Folder = DataAccess/MbNetRepositories Namespace = Tully.Saps.Data.DataAccess.MbN...
Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
Leave it. It's one great example of how your IDE is dictating your coding style.
Namespaces in C#
[ "", "c#", "" ]
I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but **not** in the parent class. Essentially, I am trying to accomplish the following: ``` class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = ...
I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with "self" being the class), then you can acheive this with: ``` def convert_to_classmethod(method): return classmethod(method.im_func) class bar...
What are you trying to accomplish? If I saw such a construct in live Python code, I would consider beating the original programmer.
Decorating a parent class method
[ "", "python", "oop", "inheritance", "" ]
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown? See the example below: ``` try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // other...
Set a flag variable, then check for it in the finally clause, like so: ``` boolean exceptionThrown = true; try { mightThrowAnException(); exceptionThrown = false; } finally { if (exceptionThrown) { // Whatever you want to do } } ```
If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks: ``` try { doSomethingDangerous(); // ca...
Fail fast finally clause in Java
[ "", "java", "exception", "fault-tolerance", "" ]
I'm looking for a tool that will reverse engineer Java into a sequence diagram BUT also provides the ability to filter out calls to certain libraries. For example, the Netbeans IDE does a fantastic job of this but it includes all calls to String or Integer which clutter up the diagram to the point it is unusable. Any...
I think [jtracert](http://code.google.com/p/jtracert/) is what you are looking for. It generates a sequence diagram from a running Java program. Also, because its output is a text description of the diagram (in the formats of several popular SD tools), you can use grep to filter for only the classes you are interested ...
Try [MaintainJ](http://maintainj.com). MaintainJ generates sequence diagrams at runtime for a use case. It provides [multiple ways to filter out unwanted calls](http://maintainj.com/userGuide.jsp?param=faq#filtergetset). Yes, filtering out unwanted calls is the most important feature needed in sequence diagram generati...
Sequence Diagram Reverse Engineering
[ "", "java", "uml", "reverse-engineering", "sequence-diagram", "" ]
The Visual Studio refactoring support for C# is quite good nowadays (though not half as good as some Java IDE's I've seen already) but I'm really missing C++ support. I have seen [Refactor!](http://www.devexpress.com/Products/Visual_Studio_Add-in/RefactorCPP/index.xml) and am currently trying it out, but maybe one of ...
Visual Assist X by Whole Tomato software is not free, but it's absolutely worth the money if you use Visual Studio for C++. <http://www.wholetomato.com/>
I have tried Refactor!, as its features seemed promising, as did its testing with a simple testing project, but it failed to work with our real project at all - a lots of CPU activity, sometimes even frozen VS IDE, Refactoring UI not appearing at all for most of the code. We are using Visual Assist X instead. While it...
Good refactoring support for C++
[ "", "c++", "visual-studio", "refactoring", "" ]
Say I have several JavaScript includes in a page: ``` <script type="text/javascript" src="/js/script0.js"></script> <script type="text/javascript" src="/js/script1.js"></script> <script type="text/javascript" src="/js/script2.js"></script> <script type="text/javascript" src="/js/script3.js"></script> <script type="tex...
If you get the [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843 "Firebug") firefox plugin and enable the consoles it should tell you when there are errors retrieving resources in the console.
I don't use other browsers enough to know where to find a similar feature in them, but Safari has an *Activity* window that displays all of the included files for a given web page and which ones were unable to be retrieved.
Find Missing Javascript Includes in Website
[ "", "javascript", "include", "" ]
I am trying to do something I've done a million times and it's not working, can anyone tell me why? I have a table for people who sent in resumes, and it has their email address in it... I want to find out if any of these people have NOT signed up on the web site. The aspnet\_Membership table has all the people who A...
We had a very similar problem recently where the subquery was returning null values sometimes. Then, the in statement treats null in a weird way, I think always matching the value, so if you change your query to: ``` select j.email from jobseeker j where j.email not in (select email from aspnet_Membership ...
You could have a lot of duplicates out there. I'm not seeing the query error off the top of my head, but you might try writing it this way: ``` SELECT j.email FROM jobseeker j LEFT JOIN aspnet_Membership m ON m.email = j.email WHERE m.email IS NULL ``` You might also throw a GROUP BY or DISTINCT in there to get rid o...
Finding missing emails in SQL Server
[ "", "sql", "join", "anti-join", "" ]
I have an exe with an `App.Config` file. Now I want to create a wrapper dll around the exe in order to consume some of the functionalities. The question is how can I access the app.config property in the exe from the wrapper dll? Maybe I should be a little bit more in my questions, I have the following app.config con...
After some testing, I found a way to do this. 1. Add the App.Config file to the test project. Use "Add as a link" option. 2. Use `System.Configuration.ConfigurationManager.AppSettings["myKey"]` to access the value.
The [ConfigurationManager.OpenMappedExeConfiguration Method](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openmappedexeconfiguration(VS.80).aspx) will allow you to do this. Sample from the MSDN page: ``` static void GetMappedExeConfigurationSections() { // Get the machine.conf...
Get the App.Config of another Exe
[ "", "c#", ".net", "configuration-files", "appsettings", "system.configuration", "" ]
I have an Eclipse RCP app running on Java 6. When I try to run the product configuration from within Eclipse, it silently terminates almost immediately. No error is reported in the console. I've tried setting breakpoints in the IApplication and in the Activator, and neither are reached. I know I don't have much specif...
Have you checked the logs in runtime/.metadata folder?, Also make sure to validate all plugins in the runtime. Having them as a dependency doesn't necessarily mean they are added to the runtime. This is probably the biggest gotcha when launching an rcp app.
I wasn't able to locate the runtime/.metadata folder, but [this very helpful post](http://www.eclipsezone.com/eclipse/forums/t99010.rhtml) directed me to add -consoleLog and -noExit to my runtime arguments, which dumped the errors to the console. Configuration problems.
Eclipse RCP app fails to start
[ "", "java", "eclipse", "rcp", "" ]
I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transa...
A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them. However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That g...
JSPs: To present data to the user. No business logic should be here, and certainly no database access. Servlets: To handle input from a form or specific URL. Usually people will use a library like Struts/Spring on top of Servlets to clear up the programming. Regardless the servlet should just validate the data that ha...
When do you use a JSP and when a Servlet?
[ "", "java", "jsp", "servlets", "" ]
I am looking for some JavaScript plugin (preferably jQuery) to be able to scroll through an image, in the same way that [Google Maps](http://maps.google.com) works. I can make the image draggable but then I see the whole image while dragging even if the parent div is `overflow:hidden`. Any help would be greatly appre...
I may be a little late to the party, but I was just looking for the same thing. What I stumbled upon is [scrollview](http://code.google.com/p/jquery-scrollview/) for jquery, it works perfect and does exactly this google maps-like drag-to-scroll for overflowed divs.
(I'm super late to this now dead party, but hey, I found this page via a search so...) Scrollview plugin suggested by mooware didn't work for me. However **Dragscrollable** did: <http://plugins.jquery.com/project/Dragscrollable> [Try out the demonstration](http://hitconsultants.com/dragscroll_scrollsync/scrollpane.h...
Google Maps style scrolling anyone?
[ "", "javascript", "jquery", "ajax", "" ]
Let's say I have the following HTML: ``` <table id="foo"> <th class="sortasc">Header</th> </table> <table id="bar"> <th class="sortasc">Header</th> </table> ``` I know that I can do the following to get all of the **th** elements that have class="sortasc" ``` $$('th.sortasc').each() ``` However that gives me t...
table#foo th.sortasc
This is how you'd do it with straight-up JS: ``` var table = document.getElementById('tableId'); var headers = table.getElementsByTagName('th'); var headersIWant = []; for (var i = 0; i < headers.length; i++) { if ((' ' + headers[i].className + ' ').indexOf(' sortasc ') >= 0) { headersIWant.push(headers[i]); }...
How do I select all <th> elements of class "sortasc" within a table with a specific id?
[ "", "javascript", "prototypejs", "" ]
I decided to try <http://www.screwturn.eu/> wiki as a code snippet storage utility. So far I am very impressed, but what irkes me is that when I copy paste my code that I want to save, '<'s and '[' (<http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Character_references>) invariably screw up the output as the wi...
Surround your code in <nowiki> .. </nowiki> tags.
You can use the **@@...@@** tag to escape the code and automatically wrap it in **PRE** tags.
Converting C++ code to HTML safe
[ "", "c++", "wiki", "" ]
I don't want to take the time to learn Obj-C. I've spent 7+ years doing web application programming. Shouldn't there be a way to use the WebView and just write the whole app in javascript, pulling the files right from the resources of the project?
I found the answer after searching around. Here's what I have done: 1. Create a new project in XCode. I think I used the view-based app. 2. Drag a WebView object onto your interface and resize. 3. Inside of your WebViewController.m (or similarly named file, depending on the name of your view), in the viewDidLoad metho...
Check out PhoneGap at <http://www.phonegap.com> they claim it allows you to embed JavaScript, HTML and CSS into a native iPhone app.
How can I write an iPhone app entirely in JavaScript without making it just a web app?
[ "", "javascript", "ios", "objective-c", "" ]
I am working with a large Java web application from a commercial vendor. I've received a patch from the vendor in the form of a new .class file that is supposed to resolve an issue we're having with the software. In the past, applying patches from this vendor have caused new and completely unrelated problems to arise, ...
It's possible that they just compiled it with a new version of the java compiler, or with different optimization settings etc, so that the functionality is the same, and the code is the same, but the output bytecode is slightly different.
If you are looking for API level differences the [javap](http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javap.html) tool can be a big help. It will output the method signatures and those can be output to a plain text files and compared using normal diff tools.
Finding differences between versions of a Java class file
[ "", "java", "decompiling", "" ]
Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)
The following query replace each and every `a` character with a `b` character. ``` UPDATE YourTable SET Column1 = REPLACE(Column1,'a','b') WHERE Column1 LIKE '%a%' ``` This will not work on SQL server 2003.
like so: ``` BEGIN TRANSACTION; UPDATE table_name SET column_name=REPLACE(column_name,'text_to_find','replace_with_this'); COMMIT TRANSACTION; ``` Example: Replaces <script... with <a ... to eliminate javascript vulnerabilities ``` BEGIN TRANSACTION; UPDATE testdb SET title=REPLACE(title,'script','a'); COMMIT TR...
How do I do a simple 'Find and Replace" in MsSQL?
[ "", "sql", "sql-server", "" ]
Anybody know of a way to copy a file from path A to path B and suppressing the Windows file system cache? Typical use is copying a large file from a USB drive, or server to your local machine. Windows seems to swap everything out if the file is really big, e.g. 2GiB. Prefer example in C#, but I'm guessing this would ...
Even more important, there are FILE\_FLAG\_WRITE\_THROUGH and FILE\_FLAG\_NO\_BUFFERING. MSDN has a nice article on them both: <http://support.microsoft.com/kb/99794>
In C# I have found something like this to work, this can be changed to copy directly to destination file: ``` public static byte[] ReadAllBytesUnbuffered(string filePath) { const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000; var fileInfo = new FileInfo(filePath); long fileL...
Copy a file without using the windows file cache
[ "", "c#", "windows", "winapi", "filesystems", "file-copying", "" ]
I'd like know what people think about using RAISERROR in stored procedures to pass back user messages (i.e. business related messages, not error messages) to the application. Some of the senior developers in my firm have been using this method and catching the SqlException in our C# code to pick up the messages and di...
I've done this, but it was usually to pass along business "error" messages, essentially a data configuration had to be in place that couldn't be enforced with standard FK constraints for whatever reason. If they are actually "errors", I don't have much of a problem with it. If it's inserting a record and using RAISERR...
Using RAISERROR like this is really not a good idea. It's just like using Exceptions as flow control logic, which is generally frowned upon. Why not use an OUT parameter instead? That's exactly what they are for. I can't think of a database or a client API that doesn't support OUT parameters.
Stored Procs - Best way to pass messages back to user application
[ "", "sql", "sql-server", "t-sql", "raiserror", "" ]
How can you determine the performance consequences of your PHP code if you are not familiar with the internals? Are there ways to figure out how your code is being executed (besides simply load testing it)? I am looking for things like memory usage, the execution time for algorithms. Perhaps Joel would say, "learn C, ...
Use the [Xdebug](http://www.xdebug.org/) extension to profile PHP code.
If you're not familiar with valgrind or similar, then to add to @Jordi Bunster's answer... When you've had profiling on in Xdebug, you can open the dumped profile files in KCacheGrind or WinCacheGrind to get a graphical view of what is taking the time in your code. Fortunately the xdebug documentation also explains t...
Determining the performance consequences of PHP code
[ "", "php", "performance", "" ]
There doesn't seem to be a dictionary.AddRange() method. Does anyone know a better way to copy the items to another dictionary without using a foreach loop. I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0.
There's nothing wrong with a for/foreach loop. That's all a hypothetical AddRange method would do anyway. The only extra concern I'd have is with memory allocation behaviour, because adding a large number of entries could cause multiple reallocations and re-hashes. There's no way to increase the capacity of an existin...
There's the `Dictionary` constructor that takes another `Dictionary`. You'll have to cast it `IDictionary`, but there is an `Add()` overload that takes `KeyValuePair<TKey, TValue>`. You're still using foreach, though.
What's the fastest way to copy the values and keys from one dictionary into another in C#?
[ "", "c#", "dictionary", "copy", "foreach", "" ]
Are there any good recommendations anyone can provide for a good Javascript editor on Windows? I currently use combinations of FireBug and TextPad but would hate to miss out on the party if there are better options out there. Thanks.
In case you're a .Net programmer: VS 2008 has pretty great JS support including [intellisense](http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx) on dynamically added methods/properties and comfortable [debugging](http://weblogs.asp.net/scottgu/archive/2007/07/19/vs-2008-javascript-...
I know [jsight](https://stackoverflow.com/questions/26897/recommendations-for-javascript-editor-on-windows#26905) already mentioned this, but [**Aptana Studio**](http://aptana.com/) really is a great, free editor for JavaScript if you find yourself doing a lot of work with it - it has great support for most of the well...
Recommendations for Javascript Editor on Windows?
[ "", "javascript", "editor", "" ]
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup...
In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own [context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors). From the docs: > A context processor has a very simple interface: It's j...
There is **no need** to write a context processor for the user object if you already have the [`"django.core.context_processors.auth"`](https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates) in [`TEMPLATE_CONTEXT_PROCESSORS`](https://docs.djangoproject.com/en/dev/ref/settings/#std:...
Always including the user in the django template context
[ "", "python", "django", "authentication", "session", "cookies", "" ]
I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, *not* a source code file -- but embed that file in the executable file like a resource. (This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect i...
You can use objcopy to bind the contents of the file to a symbol your program can use. See, for instance, [here](http://www.linuxjournal.com/content/embedding-file-executable-aka-hello-world-version-5967) for more information.
Use macros. Technically that file would be *source code* file but it wouldn't look like this. Example: ``` //queries.incl - SQL queries Q(SELECT * FROM Users) Q(INSERT [a] INTO Accounts) //source.cpp #define Q(query) #query, char * queries[] = { #include "queries.incl" }; #undef Q ``` Later on you could do all sort...
Embed data in a C++ program
[ "", "c++", "linux", "sqlite", "" ]
It's known that you should declare events that take as parameters `(object sender, EventArgs args)`. Why?
This allows the consuming developer the ability to write a single event handler for multiple events, regardless of sender or event. **Edit:** Why would you need a different pattern? You can inherit EventArgs to provide any amount of data, and changing the pattern is only going to serve to confuse and frustrate any dev...
Actually this is debatable whether or not this is the best practice way to do events. There is the school of thought that as events are intended to decouple two segments of code, the fact that the event handler gets the sender, and has to know what type to cast the sender into in order to do anything with it is an anti...
Why should events in C# take (sender, EventArgs)?
[ "", "c#", ".net", "events", "" ]
Is there a framework that can be used to enable a C# Windows Service to automatically check for a newer version and upgrade itself? I can certainly write code to accomplish this, but I am looking for a framework that has already been implemented and (most importantly) tested. [edit] Here is a link to a similar questio...
The only way to unload types is to destroy the appdomain. To do this would require separation of your hosting layer from your executing service code - this is pretty complex. (sort of like doing keyhole surgery) May be easier to either a) run a batch task or b) in-service detect updates then launch a seperate process ...
I've had good experiences with [Google Omaha](https://github.com/google/omaha) for updating Windows Services. It can generally be used to update any Windows application but there is a [tutorial](https://omaha-consulting.com/update-windows-service) for using it to update a Windows Service. In comparison to other update...
I want my C# Windows Service to automatically update itself
[ "", "c#", "windows-services", "upgrade", "" ]
A common task in programs I've been working on lately is modifying a text file in some way. (Hey, I'm on Linux. Everything's a file. And I do large-scale system admin.) But the file the code modifies may not exist on my desktop box. And I probably don't want to modify it if it IS on my desktop. I've read about unit t...
You're talking about testing too much at once. If you start trying to attack a testing problem by saying "Let's verify that it modifies its environment correctly", you're doomed to failure. Environments have dozens, maybe even millions of potential variations. Instead, look at the pieces ("units") of your program. For...
You have two levels of testing. 1. Filtering and Modifying content. These are "low-level" operations that don't really require physical file I/O. These are the tests, decision-making, alternatives, etc. The "Logic" of the application. 2. File system operations. Create, copy, rename, delete, backup. Sorry, but those ar...
Unit Testing File Modifications
[ "", "python", "linux", "unit-testing", "" ]
It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution. Is there a better way...
As toolkit mentions above, Apache Commons IO is the way to go, specifically [FileUtils](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html).[copyFile()](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#copyFile(jav...
I would avoid the use of a mega api like apache commons. This is a simplistic operation and its built into the JDK in the new NIO package. It was kind of already linked to in a previous answer, but the key method in the NIO api are the new functions "transferTo" and "transferFrom". <http://java.sun.com/javase/6/docs/a...
Standard concise way to copy a file in Java?
[ "", "java", "file", "copy", "" ]
I'm converting an application to use Java 1.5 and have found the following method: ``` /** * Compare two Comparables, treat nulls as -infinity. * @param o1 * @param o2 * @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2 */ protected static int nullCompare(Comparable o1, Comparable o2) { if (o1 ...
Change it to: ``` protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) { ``` You need that because Comparable is itself a generic type.
Here's an odd case: ``` static class A { ... } static class B extends A implements Comparable<A> { public int compareTo(A o) { return ...; } } ``` Luckily code like the one above is rare, but nullCompare() will not support comparison of Bs unless it is stated that Comparable may apply to T *or an...
Can I convert the following code to use generics?
[ "", "java", "generics", "comparison", "" ]
Can anybody recommend a reliable and decently documented code highlighter for WordPress 2.6.1? I have tried Code Snippet by Roman Roan and Developer Formatter by Gilberto Saraiva. But they don't seem to work as described in the documentation and are mangling the code snippets instead of prettifying them.
I use [WP-Syntax](http://wordpress.org/extend/plugins/wp-syntax/) and it's worked very well for me. It's supported every language I've thrown at it so far, and the colors can be customized for a particular theme (though the defaults look just fine too)
You should also checkout [syntaxhighlighter](http://code.google.com/p/syntaxhighlighter/) from Google Code.
Seeking code highlighter recommendation for WordPress
[ "", "php", "wordpress", "codehighlighter", "geshi", "" ]
Say I have a `Textbox` nested within a `TabControl`. When the form loads, I would like to focus on that `Textbox` (by default the focus is set to the `TabControl`). Simply calling `textbox1.focus()` in the `Load` event of the form does not appear to work. I have been able to focus it by doing the following: ``` pr...
The following is the solution: ``` private void frmMainLoad(object sender, EventArgs e) { ActiveControl = textBox1; } ``` The better question would however be why... I'm not entirely sure what the answer to that one is. Edit: I suspect it is something to do with the fact that both the form, and the TabControl ar...
Try putting it in the `Form_Shown()` event. Because it's in a container, putting in the Form\_Load or even the Form() constructor won't work.
Winforms c# - Set focus to first child control of TabPage
[ "", "c#", ".net", "winforms", "focus", "" ]
Is there a way? I need all types that implement a specific interface to have a parameterless constructor, can it be done? I am developing the base code for other developers in my company to use in a specific project. There's a proccess which will create instances of types (in different threads) that perform certain ...
[Juan Manuel said:](https://stackoverflow.com/questions/26903/how-can-you-require-a-constructor-with-no-parameters-for-types-implementing-an#27386) > that's one of the reasons I don't understand why it cannot be a part of the contract in the interface It's an indirect mechanism. The generic allows you to "cheat" and ...
Not to be too blunt, but you've misunderstood the purpose of interfaces. An interface means that several people can implement it in their own classes, and then pass instances of those classes to other classes to be used. Creation creates an unnecessary strong coupling. It sounds like you really need some kind of regi...
How can you require a constructor with no parameters for types implementing an interface?
[ "", "c#", ".net", "constructor", "interface", "oop", "" ]
What GUI should use to run my JUnit tests, and how exactly do I do that? My entire background is in .NET, so I'm used to just firing up my NUnit gui and running my unit tests. If the lights are green, I'm clean. Now, I have to write some Java code and want to run something similar using JUnit. The JUnit documentation ...
Eclipse is by-far the best I've used. Couple JUnit with a [code coverage](http://www.eclemma.org/) plug-in and Eclipse will probably be the best unit-tester.
JUnit stopped having graphical runners following the release of JUnit 4. If you do have an earlier version of JUnit you can use a graphical test runner by entering on the command line[1]: ``` java junit.swingui.TestRunner [optional TestClass] ``` With the optional test class the specified tests will run straight awa...
What GUI should I run with JUnit(similar to NUnit gui)
[ "", "java", "ide", "junit", "" ]
I have read about JavaFX, and like all new technologies I wanted to get my hands "dirty" with it. However, although it talks of multiplatform support, I can't find specifics on this. What platforms support a JavaFX application? All those with Java SE? ME? Does it depend upon the APIs in JavaFX that I use?
JavaFX has three planned distributions. * JavaFX Desktop will run on Windows, Mac, ~~Linux, and Solaris~~ at FCS and will require Java SE. Support for Linux and Solaris will be forthcoming. * JavaFX TV and JavaFX Mobile have no announce target platforms. Also unannounced is whether they will run on ME or SE, and if ME...
From what I can see JavaFX is a whole new runtime and compiler so is not a subset of Java. Sun will support it on mobile phones and on the desktop. OS-wise it is currently released for Windows/Mac but Solaris/Linux are in the works.
What platforms JavaFX is/will be supported on?
[ "", "java", "javafx", "" ]
this kind of follows on from another [question](https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app) of mine. Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to **test** it? I am thinking of cr...
In .NET, `ThreadPool` threads won't return without setting up `ManualResetEvent`s or `AutoResetEvent`s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such. Something I have found that works...
@ajmastrean, since unit test result must be predictable we need to synchronize threads somehow. I can't see a simple way to do it without using events. I found that `ThreadPool.QueueUserWorkItem` gives me an easy way to test such use cases ``` ThreadPool.QueueUserWorkItem(x => { File.Open(fileName, FileMode.Ope...
Whats the best way to unit test from multiple threads?
[ "", "c#", "multithreading", "unit-testing", "testing", "" ]
I have a form element that contains multiple lines of inputs. Think of each line as attributes of a new object that I want to create in my web application. And, I want to be able to create multiple new objects in one HTTP POST. I'm using Javascript's built-in cloneNode(true) method to clone each line. The problem is th...
Don't put handler on each link (this really should be a button, BTW). Use [event bubbling](http://www.quirksmode.org/js/events_order.html) to handle *all* buttons with one handler: ``` formObject.onclick = function(e) { e=e||event; // IE sucks var target = e.target||e.srcElement; // and sucks again // tar...
You could try cloning using the innerHTML method, or a mix: ``` var newItem = $(item).cloneNode(false); newItem.innerHTML = $(item).innerHTML; ``` Also: I think cloneNode doesn't clone events, registered with addEventListener. But IE's attachEvent events *are* cloned. But I might be wrong.
How to Maintain Correct Javascript Event After Using cloneNode(true)
[ "", "javascript", "events", "dom", "prototypejs", "clonenode", "" ]
Intel's [Threading Building Blocks (TBB)](http://www.threadingbuildingblocks.org/) open source library looks really interesting. Even though there's even an [O'Reilly Book](http://oreilly.com/catalog/9780596514808/) about the subject I don't hear about a lot of people using it. I'm interested in using it for some multi...
I've introduced it into our code base because we needed a bettor malloc to use when we moved to a 16 core machine. With 8 and under it wasn't a significant issue. It has worked well for us. We plan on using the fine grained concurrent containers next. Ideally we can make use of the real meat of the product, but that re...
# Portability TBB is portable. It supports Intel and AMD (i.e. x86) processors, IBM PowerPC and POWER processors, ARM processors, and possibly others. If you look in the [build directory](https://github.com/01org/tbb/tree/tbb_2018/build), you can see all the configurations the build system support, which include a wid...
Any experiences with Intel's Threading Building Blocks?
[ "", "c++", "multithreading", "intel", "tbb", "" ]
Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships. We then have a separate jvm that is the server using this data. As it is running continuously we just h...
A Hibernate session loads all data it reads from the DB into what they call the *first-level cache*. Once a row is loaded from the DB, any subsequent fetches for a row with the same PK will return the data from this cache. Furthermore, Hibernate gaurentees reference equality for objects with the same PK in a single Ses...
Chris, I'm a little confused about your circumstances. If I understand correctly, you have a both a web app (read/write) a standalone application (read-only?) using Hibernate to access a shared database. The changes you make with the web app aren't visible to the standalone app. Is that right? If so, have you consider...
How to maintain Hibernate cache consistency running two Java applications?
[ "", "java", "hibernate", "caching", "" ]
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire ap...
Namespaces are packages essentially. They can be used like this: ``` namespace MyNamespace { class MyClass { }; } ``` Then in code: ``` MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); ``` Or, if you want to always use a specific namespace, you can do this: ``` using namespace MyNamespace; MyClass...
To avoid saying everything Mark Ingram already said a little tip for using namespaces: Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (\*.cpp) this is normally no big problem - altough I prefer to use ...
How do you properly use namespaces in C++?
[ "", "c++", "namespaces", "" ]
How do you ensure, that you can checkout the code into Eclipse or NetBeans and work there with it? Edit: If you not checking in ide-related files, you have to reconfigure buildpath, includes and all this stuff, each time you checkout the project. I don't know, if ant (especially an ant buildfile which is created/expor...
The smart ass answer is "by doing so" - unless you aren't working with multiple IDEs you don't know if you are really prepared for working with multiple IDEs. Honest. :) I always have seen multiple platforms as more cumbersome, as they may use different encoding standards (e.g. Windows may default to ISO-8859-1, Linux...
We actually maintain a Netbeans and an Eclipse project for our code in SVN right now with no troubles at all. The Netbeans files don't step on the Eclipse files. We have our projects structured like this: ``` sample-project + bin + launches + lib + logs + nbproject + src + java .classpath .project build.x...
How do you handle different Java IDEs and svn?
[ "", "java", "eclipse", "svn", "ide", "collaboration", "" ]
I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.
A Python file is called a "module" and it's one way to organize your software so that it makes "sense". Another is a directory, called a "package". A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be ...
Since there is no artificial limit, it really depends on what's comprehensible. If you have a bunch of fairly short, simple classes that are logically grouped together, toss in a bunch of 'em. If you have big, complex classes or classes that don't make sense as a group, go one file per class. Or pick something in betwe...
Possibilities for Python classes organized across files?
[ "", "python", "class", "project-structure", "" ]
I have a user interface in .net which needs to receive data from a server, on a request/reply/update model. The only constraint is to use Java only on the server box. What is the best approach to achieve this ? Is it by creating a Webservice in Java and then accessing it in .net, or should I create Java proxies and co...
I recommend the web service route. It offers a standard interface that can be consumed by other client platforms in the future. .NET clients interact with Java web services pretty well, though there are some gotchas. The best two technologies available for you for the .NET client are Microsoft Web Service Enhancements...
Write webservice in Java and access it in .net
What is the best way to make a .net client consume service from a Java server?
[ "", "java", ".net", "interop", "" ]
We put all of our unit tests in their own projects. We find that we have to make certain classes public instead of internal just for the unit tests. Is there anyway to avoid having to do this. What are the memory implication by making classes public instead of sealed?
If you're using .NET, the [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) assembly attribute allows you to create "friend" assemblies. These are specific strongly named assemblies that are allowed to access internal classes and members of th...
Below are ways to use in **.NET Core** applications. 1. Add **AssemblyInfo.cs** file and add `[assembly: InternalsVisibleTo("AssemblytoVisible")]` 2. Add this in **.csproj** file *(the project which contains the Internal classes)* ``` <ItemGroup> <AssemblyAttribute Include="System.Runtime.CompilerServices.Internals...
Making code internal but available for unit testing from other projects
[ "", "c#", "unit-testing", "scope", "" ]