Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Given some JS code like that one here: ``` for (var i = 0; i < document.getElementsByName('scale_select').length; i++) { document.getElementsByName('scale_select')[i].onclick = vSetScale; } ``` Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the ...
Definitely. The memory required to store that would only be a pointer to a DOM object and that's ***significantly*** less painful than doing a DOM search each time you need to use something! Idealish code: ``` var scale_select = document.getElementsByName('scale_select'); for (var i = 0; i < scale_select.length; i++)...
Caching the property lookup might help some, but c[aching the length of the array before starting the loop has proven to be faster.](http://www.robertnyman.com/2008/04/11/javascript-loop-performance/) So declaring a variable in the loop that holds the value of the scale\_select.length would speed up the entire loop so...
How expensive are JS function calls (compared to allocating memory for a variable)?
[ "", "javascript", "function", "optimization", "" ]
I'm a Engineering student and I'm attending a Database and Information Systems class this semester. It's required that I produce a website/application that uses a database, using PHP/PGSQL. My questions are: * which IDE would you recommend? * does anyone have good tips and advices for a new developer? * it would help ...
* which IDE would you recommend? Anything that supports remote debugging. You will save yourselves hours and hours and learn so much quicker if you can actually step through your code. It always amazes me that more people don't use good debugging tools for PHP. The tools are there, not using them is crazy. FWIW I've a...
This is probably the only time in your career when you have the full freedom to chose what tools to use, so make the best use of it. Learn some of the classic tools that will go with you a long long way. So instead of using an IDE which you'll probably do all your professional life get a taste of using old school edit...
PHP Development - lot of (newbie) questions
[ "", "php", "ide", "" ]
Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it.
You can construct [`javax.mail.Message`](https://javaee-spec.java.net/nonav/javadocs/javax/mail/internet/MimeMessage.html) object (or have it already constructed from the mail server) and then you can use [`writeTo()`](https://javaee-spec.java.net/nonav/javadocs/javax/mail/internet/MimeMessage.html#writeTo%28java.io.Ou...
You can create eml files with the following code. It works fine with thunderbird and probably with other email clients: ``` public static void createMessage(String to, String from, String subject, String body, List<File> attachments) { try { Message message = new MimeMessage(Session.getInstance(System.getP...
Create a .eml (email) file in Java
[ "", "java", "email", "outlook", "eml", "" ]
I was reading [this article](http://www.ibm.com/developerworks/java/library/j-dcl.html) about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom: > Listing 7. Attempting to solve the out-of-order write problem > > ``` > publ...
The point of locking twice was to *attempt* to prevent out-of-order writes. The memory model specifies where reorderings can occur, partly in terms of locks. The lock ensures that no writes (including any within the singleton constructor) appear to happen after the "instance = inst;" line. However, to go deeper into t...
The article refers to the pre-5.0 Java memory model (JMM). Under that model leaving a synchronised block forced writes out to main memory. So it appears to be an attempt to make sure that the Singleton object is pushed out before the reference to it. However, it doesn't quite work because the write to instance can be m...
Double checked locking Article
[ "", "java", "synchronization", "locking", "double-checked-locking", "" ]
I'm a web-guy stuck in "application world" in VS 2005. I created my windows forms program and want to give my end users the ability to install it (and some of it's resources) into a standard Program Files/App Directory location along with a start menu/desktop launcher. The help files don't give any instructions (that ...
You're looking for a "Setup Project" which should be under the "Other Project Types" -> "Setup and Deployment" category in the "New Project" dialog.
I would suggest using something WiX (windows installer XML). Its the toolkit most products from codeplex or OOB code drops use, and its pretty easy to get the hang of. There's also (in version 3) an IDE add-in called Votive to help make things 'easier'. Personally I find using WiX more flexible then using the built i...
Create program installer in Visual Studio 2005?
[ "", "c#", "visual-studio", "winforms", "" ]
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
Try `Context.User.Identity.AuthenticationType` Go for PB's answer folks
The mode property from the authenticationsection: [AuthenticationSection.Mode Property (System.Web.Configuration)](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx). And you can even modify it. ``` // Get the current Mode property. AuthenticationMode currentMode =...
Detecting Web.Config Authentication Mode
[ "", "c#", "asp.net", "authentication", "web-config", "" ]
How should I determine what to use for a listening socket's backlog parameter? Is it a problem to simply specify a very large number?
From the [docs](http://msdn.microsoft.com/en-us/library/ms739168(VS.85).aspx): > A value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for socket s to set the length of the queue of pending connections to a maximum reasonable value.
There's a very long answer to this in the [Winsock Programmer's FAQ](http://tangentsoft.net/wskfaq/advanced.html#backlog). It details the standard setting, and the dynamic backlog feature added in a hotfix to NT 4.0.
How to determine the value of socket listen() backlog parameter?
[ "", "c++", "c", "sockets", "tcp", "listen", "" ]
``` #include <vector> std::vector<long int> as; long int a(size_t n){ if(n==1) return 1; if(n==2) return -2; if(as.size()<n+1) as.resize(n+1); if(as[n]<=0) { as[n]=-4*a(n-1)-4*a(n-2); } return mod(as[n], 65535); } ``` The above code sample using memoization to calculate a recursive formula based...
`if (as[n] <= 0)` is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test `if (as[n] == 0)`. This makes your code easier to write, because by default vectors of `int`s are filled with zeroes.
The code appears to be incorrectly checking is (as[n] <= 0), and recalculates the negative values of the function(which appear to be approximately every other value). This makes the work scale linearly with n instead of 2^n with the recursive solution, so it runs a lot faster. Still, a better check would be to test if...
How does this C++ function use memoization?
[ "", "c++", "dynamic-programming", "memoization", "" ]
I have a LAMP (PHP) web app which need to interface with programs on an IBM 3270 mainframe (via Microsoft SNA Server). One solution I'm looking at is screen-scraping via 3270. (I'm integrating the present with the past!) Many years ago, I wrote C code which used HLLAPI as the basis for such a task. 1. Is HLLAPI still...
I haven't used it but maybe look at <http://x3270.bgp.nu/> which says has a version: > s3270 is a displayless version for > writing screen-scraping scripts
I'm currently trying to do a similar thing but with a command line Python script. I open a pipe to the s3270 (on Windows the exe name is ws3270) to connect to the server and send all commands. Read carefully those part of the documentation for scripting: <http://x3270.bgp.nu/wc3270-man.html#Actions> <http://x3270.bg...
How to 3270 screen-scrape from a Linux-based web app
[ "", "php", "c", "mainframe", "3270", "hllapi", "" ]
Does anybody know, if closures will be in Java 7?
At Devoxx 2008, [Mark Reinhold made it clear](http://java.dzone.com/articles/java-7-update-mark-reinhold-de) that closures *will not* be included in Java 7. --- Wait! Closures *will* be included in Java 7. Mark Reinhold [announced this reversal](http://blogs.oracle.com/mr/entry/closures) at Devoxx 2009. --- Belay t...
It is unknown until the Java SE 7 JSR is created (presumably by Danny Coward) and an expert group is formed and the contents selected. My Java 7 page is a good collection of links about Java 7 in general and has links to all of the closures proposals and blog entries: <http://tech.puredanger.com/java7#closures> And ...
What’s the current state of closures in Java?
[ "", "java", "closures", "" ]
Most people say *never* throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that *"the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails... There is really no good...
Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate. **But** said "terminate" is a very well specified behaviour of majority of compilers, hence it's almost never "Undefined Behaviour" (depending on compiler). ``` #include <iostream> c...
Throwing out of a destructor can result in a crash, because this destructor might be called as part of "Stack unwinding". Stack unwinding is a procedure which takes place when an exception is thrown. In this procedure, all the objects that were pushed into the stack since the "try" and until the exception was thrown, w...
If you shouldn't throw exceptions in a destructor, how do you handle errors in it?
[ "", "c++", "exception", "destructor", "raii", "" ]
I'm writing a Winforms application and I've been writing these awful HTML reports where I have templates set up and use String.Replace to get my variables into the templates, then output the results to a WebBrowser control. I really don't like this set up. I'd love to be able to use ASP.NET for my reports, but my clie...
Like was said earlier, use the report viewer with client side reporting. You can create reports the same way as you do for sql reporting services, except you dont need sql server(nor asp.net). Plus you have complete control over them(how you present, how you collect data, what layer they are generated in, etc). You can...
Have you tried the [reportviewer control](http://www.gotreportviewer.com/)? Your customers will be happy with the fancy new reports. It is template based and can include data from database or from code data, you can use parameters, images, and the result can be exported to Excel or to PDF. Plus the control has some ba...
Reports in a .NET Winforms App
[ "", "c#", ".net", "winforms", "report", "" ]
So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++. But, what if you're starting with a native C++ app? What options do you have if you want to write ...
As [Aaron Fischer](https://stackoverflow.com/questions/147378/options-for-refactoring-bits-of-code-away-from-native-c#147446) suggests, try recompiling your C++ application with the /clr option turned on and then start leveraging the .Net platform. CLI/C++ is pretty easy to pick up if you know C# and C++ already and i...
If you want to work between C++ and Python, than [Boost Python](http://www.boost.org/doc/libs/1_36_0/libs/python/doc/index.html) is what you're looking for. You can write C Python bindings by hand for Cython, but that limits in many ways how you're going to write your code. This is the easiest way, as seen in some snip...
Options for refactoring bits of code away from native C++?
[ "", "c++", "performance", "refactoring", "native", "" ]
Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).
Use StringTemplate, see <http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf> for details of why. There is nothing better, and it supports both Java and Python (and .NET, etc.).
Have you tried [Cheetah](http://www.cheetahtemplate.org/), I don't have direct experience running it under Jython but there seem to be some people that do.
Template Lib (Engine) in Python running with Jython
[ "", "python", "jython", "template-engine", "" ]
I have a form with some radio buttons that are disabled by default. When a value gets entered into a text box, the radio buttons are enabled via javascript. The user then selects one of the radio buttons and clicks on a submit button which posts back to the server. When I get back to the server, the radio button that...
This has to do with how ASP.NET postback data. If a control is disabled `control.enabled = false` when the page is rendered than the values will not be posted back to the server. How I have solved it in the past is to set the disabled flag using attributes tags instead of using the Enabled property. So instead of `cont...
This isn't working for me. I added: ``` Me.rbSolid.Style.Add("background-color", "red") Me.rbSolid.Style.Add("disabled", "true") ``` and the background style works but the `disabled` did not. It's still editable when the form renders. Here's the source after load: ``` <span style="font-family:Verdana;font-size:8p...
ASP.NET not seeing Radio Button value change
[ "", "asp.net", "javascript", "" ]
Relating to my [earlier question](https://stackoverflow.com/questions/48733/javahibernate-jpa-designing-the-server-data-reload), I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to...
Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed. I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderlin...
I'm not sure about using the fetch keyword in your EJBQL, you might be getting it confused with the annotation... Have you tried adding the FetchType property to your relationship attribute? @OneToMany(fetch=FetchType.EAGER)? See: <http://java.sun.com/javaee/5/docs/api/javax/persistence/FetchType.html> <http://www....
Hibernate (JPA) how to do an eager query, loading all child objects
[ "", "java", "hibernate", "jpa", "ejbql", "" ]
I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that). I've been using datetime.now() as a first stab, but this i...
You're unlikely to get sufficiently fine-grained control that you can completely eliminate the possibility of duplicate timestamps - you'd need resolution smaller than the time it takes to generate a datetime object. There are a couple of other approaches you might take to deal with it: 1. Deal with it. Leave your tim...
time.clock() only measures wallclock time on Windows. On other systems, time.clock() actually measures CPU-time. On those systems time.time() is more suitable for wallclock time, and it has as high a resolution as Python can manage -- which is as high as the OS can manage; usually using gettimeofday(3) (microsecond res...
Accurate timestamping in Python logging
[ "", "python", "logging", "timer", "timestamp", "" ]
In particular, wouldn't there have to be some kind of function pointer in place anyway?
Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter. ``` struct A { void foo (); void bar () const; }; ``` is basically the same as: ``` struct A { }; void foo (A * this); void bar (A const * this...
I think that the phrase "*classes with virtual functions are implemented with vtables*" is misleading you. The phrase makes it sound like classes with virtual functions are implemented "*in way A*" and classes without virtual functions are implemented "*in way B*". In reality, classes with virtual functions, ***in ad...
If classes with virtual functions are implemented with vtables, how is a class with no virtual functions implemented?
[ "", "c++", "virtual-functions", "" ]
I have a program that uses the mt19937 random number generator from boost::random. I need to do a random\_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers. I tried something like thi...
In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs). This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++...
In the comments, Robert Gould asked for a working version for posterity: ``` #include <algorithm> #include <functional> #include <vector> #include <boost/random.hpp> struct bar : std::unary_function<unsigned, unsigned> { boost::mt19937 &_state; unsigned operator()(unsigned i) { boost::uniform_int<> rn...
Using boost::random as the RNG for std::random_shuffle
[ "", "c++", "stl", "boost-random", "" ]
I want to discover all xml files that my ClassLoader is aware of using a wildcard pattern. Is there any way to do this?
It requires a little trickery, but here's an relevant [blog entry](http://bill.burkecentral.com/2008/01/14/scanning-java-annotations-at-runtime/). You first figure out the URLs of the jars, then open the jar and scan its contents. I think you would discover the URLs of all jars by looking for `/META-INF/MANIFEST.MF'. D...
A Spring `ApplicationContext` can do this trivially: ``` ApplicationContext context = new ClassPathXmlApplicationContext("applicationConext.xml"); Resource[] xmlResources = context.getResources("classpath:/**/*.xml"); ``` See [ResourcePatternResolver#getResources](http://static.springframework.org/spring/docs/2.5.x...
How can I discover resources in a Java jar with a wildcard name?
[ "", "java", "classpath", "" ]
What's the difference between `file` and `open` in Python? When should I use which one? (Say I'm in 2.5)
You should always use `open()`. As the [documentation](http://docs.python.org/2/library/functions.html#file "BuiltinFuncs Doc") states: > When opening a file, it's preferable > to use open() instead of invoking this > constructor directly. file is more > suited to type testing (for example, > writing "isinstance(f, f...
Two reasons: The python philosophy of "There ought to be one way to do it" and `file` is going away. `file` is the actual type (using e.g. `file('myfile.txt')` is calling its constructor). `open` is a factory function that will return a file object. In python 3.0 `file` is going to move from being a built-in to being...
Python - When to use file vs open
[ "", "python", "file", "" ]
I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? ``` a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], ...
You can't sort dictionaries. You have to sort the list of items. Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric. ``` a = { 'key':1, 'another':2, 'key2':1 } b= a.items() b.sort( k...
``` data = { 'keyC':1, 'keyB':2, 'keyA':1 } for key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])): print key, value ```
Python 2.5 dictionary 2 key sort
[ "", "python", "" ]
I'm having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediately precedes a block element causes the selection to be shifted to the right one character and appear where it shouldn't. I've submitted a bug to Micr...
I've figured out a few methods for dealing with IE ranges like this. If all you want to do is save where the cursor is, and then restore it, you can use the pasteHTML method to insert an empty span at the current position of the cursor, and then use the moveToElementText method to put it back at that position again: ...
I've had a bit of a dig & unfortunately can't see a workaround... Although one thing I noticed while debugging the javascript, it seems like the problem is actually with the range object itself rather than with the subsequent `range.select()`. If you look at the values on the range object that `selection.createRange()`...
IE TextRange select method not working properly
[ "", "javascript", "internet-explorer", "" ]
My application is preparing a cover-sheet for submitting documents by fax. I identify the batch by printing a [Code39](http://en.wikipedia.org/wiki/Code_39) on it. The incoming faxes are received as tif files and my small c# service is polling for new faxes and calling a decoding function. Currently I use a Win32 dll...
[BarBara](http://sourceforge.net/projects/barbara/) is an open source barcode recognition library. It certainly isn't perfect, but I have gotten it to work (if I remember it needed some twiddling to get it to compile in VS2008) pretty well.
I've used this java libarary with good results, and have gotten it to compile in .Net with minimal effort. It's been around for a while and works pretty well. It had some minor issues with EAN codes, but that has probably been resolved now. <http://barbecue.sourceforge.net/>
Fax barcode recognition software to integrate in a c# application
[ "", "c#", ".net", "barcode", "" ]
I'm trying to create a Zip file from .Net that can be read from Java code. I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncomp...
I have used [DotNetZip library](http://www.codeplex.com/DotNetZip) and it seems to work properly. Typical code: ``` using (ZipFile zipFile = new ZipFile()) { zipFile.AddDirectory(sourceFolderPath); zipFile.Save(archiveFolderName); } ```
I had the same problem creating zips with SharpZipLib (latest version) and extracting with java.utils.zip. Here is what fixed the problem for me. I had to force the exclusion of the zip64 usage: ``` ZipOutputStream s = new ZipOutputStream(File.Create(someZipFileName)) s.UseZip64 = UseZip64.Off; ```
Help in creating Zip files from .Net and reading them from Java
[ "", "java", ".net", "interop", "zip", "" ]
I have a products table... [alt text http://img357.imageshack.us/img357/6393/productscx5.gif](http://img357.imageshack.us/img357/6393/productscx5.gif) and a revisions table, which is supposed to track changes to product info [alt text http://img124.imageshack.us/img124/1139/revisionslz5.gif](http://img124.imageshack...
Here's how I'd do it: ``` SELECT p.*, r.* FROM products AS p JOIN revisions AS r USING (product_id) LEFT OUTER JOIN revisions AS r2 ON (r.product_id = r2.product_id AND r.modified < r2.modified) WHERE r2.revision_id IS NULL; ``` In other words: find the revision for which no other revision exists with the sa...
Begin and end dates on your history table would make this possible.(leaving the most recent end date null and stamping end dates on the previous record as you insert a new one) Otherwise you will have to use a sub-query.
Problem joining on the highest value in mysql table
[ "", "mysql", "sql", "" ]
I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM). I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in you...
I haven't found a simple solution either. There are examples using CreateObject and the WinNT ADSI provider. But eventually they all bump into [User authentication issues with the Active Directory Service Interfaces WinNT provider](http://support.microsoft.com/kb/218497). I'm not 100% sure but I *guess* the WSH/network...
Good Question! I've given this some thought... and I can't think of a good solution. What I can think of is a horrible horrible hack that just might work. After seeing that no one has posted an answer to this question for nearly a day, I figured a bad, but working answer would be ok. The SAM file is off limits while ...
PHP Forms-Based Authentication on Windows using Local User Accounts
[ "", "php", "windows", "apache", "authentication", "sam", "" ]
I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use ``` s=difflib.SequenceMatcher(isjunk,text1,text2) ratio =s.ratio() ``` for this purpose. So...
If you match all whitespaces the similarity is better: ``` difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio() ``` However, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many. Try ...
Using your sample strings: ``` >>> s=difflib.SequenceMatcher(lambda x: x == '\n', s1, s2) >>> s.ratio() 0.94669848846459825 ``` Interestingly if ' ' is also included as junk: ``` >>> s=difflib.SequenceMatcher(lambda x: x in ' \n', s1, s2) >>> s.ratio() 0.7653142402545744 ``` Looks like the new lines are having a mu...
Difflib.SequenceMatcher isjunk optional parameter query: how to ignore whitespaces, tabs, empty lines?
[ "", "python", "lambda", "difflib", "" ]
I started using subversion for one of my projects and it would be absolutely amazing if I could just export the latest version from the repository on my production server by for example running a php or perl script. The production site is hosted with a shared hosting provider who doesn't allow shell access or for exam...
As far as I know there is no SVN client fully written in PHP or Perl. SO without exec you're out of luck. Workarounds: * Depending on your own OS and what methods you have to access your web space you might be able to mount the web space in your local file system and just use your system's SVN client for checking out...
SVN supports access over WebDAV (i.e. HTTPS). This means for simple read access you don't actually need an SVN client to access an SVN repository. You can even use a web browser, or in your case any PHP function that accepts a URL as its argument. SVN has to be set up on the server side to work with apache, for more in...
Is it possible to do a SVN export without shell access?
[ "", "php", "svn", "export", "" ]
I have an Open Source app and I currently only post the binary for the Windows build. At this point Linux users have to get the source and compile it. Is there a standard way for posting a Linux binary? My app is in c / c++ and compiled with gcc, the only external Linux code I use is X Windows and CUPS.
The most common way would be to package it in a [.rpm file](http://en.wikipedia.org/wiki/RPM_Package_Manager) for [RedHat](http://www.redhat.com/)-based distros like [Fedora](http://fedoraproject.org/), or a [.deb file](http://en.wikipedia.org/wiki/Deb_(file_format)) for [Debian](http://www.debian.org/)-based distros l...
Find someone skilled with Debian and get their help to set up a build process to build .deb packages for Debian and Ubuntu.
How to package a Linux binary for my Open Source application?
[ "", "c++", "linux", "binary", "publish", "" ]
I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like: ``` $total = $value1 + $value2 + ... + $value11; ``` All the values I want to add together are comin...
``` for ($i = 1 ; $i <= 3 ; $i++){ $varName = "pBalance".$i; $tempTotal += $$varName; } ``` This will do what you want. However you might indeed consider using an array for this kind of thing.
I would use @unexist's solution.. give the input fields names like: ``` <input name="myInput[]" /> <input name="myInput[]" /> <input name="myInput[]" /> ... ``` Then in your PHP get the sum like this: ``` $total = array_sum($_REQUEST['myInput']); ``` Because of the '[]' at the end of each input name, PHP will make ...
Can I use a generated variable name in PHP?
[ "", "php", "" ]
Is it possible, in Java, to make a `JPanel` skip drawing its background thus being transparent except for the components on it?
`setOpaque(false)` It'll pass off painting the background to its parent, which may draw its own background. You can do a screen capture and then use that to paint the background of the panel.
This article seems to have some handy info on how to create shaped and transparent windows in Java: <https://docs.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html>
Make a JPanel not draw its background (Transparent)
[ "", "java", "user-interface", "" ]
How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like: ``` //MySQL SELECT foo FROM table LIMIT 10, 10 ``` But I can't find a way to define offset.
I ended up doing the paging in code. I just skip the first records in loop. I thought I made up an easy way for doing the paging, but it seems that pervasive sql doesn't allow order clauses in subqueries. But this should work on other DBs (I tested it on firebird) ``` select * from (select top [rows] * from (select t...
Tested query in PSQL: ``` select top n * from tablename where id not in( select top k id from tablename ) ``` for all n = no.of records u need to fetch at a time. and k = multiples of n(eg. n=5; k=0,5,10,15,....)
Paging in Pervasive SQL
[ "", "sql", "pervasive", "" ]
How come this doesn't work (operating on an empty select list `<select id="requestTypes"></select>` ``` $(function() { $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes); } ); function showRequestTypes(data, textStatus) { $.each(data, function() { va...
`$("#requestTypes")` returns a jQuery object that contains all the selected elements. You are attempting to call the `add()` method of an individual element, but instead you are calling the `add()` method of the jQuery object, which does something very different. In order to access the DOM element itself, you need to ...
By default, jQuery selectors return the jQuery object. Add this to get the DOM element returned: ``` var dropdownList = $("#requestTypes")[0]; ```
jQuery create select list options from JSON, not happening as advertised?
[ "", "javascript", "jquery", "drop-down-menu", "html-select", "" ]
**C#6 Update** In [C#6 `?.` is now a language feature](https://msdn.microsoft.com/en-us/magazine/dn802602.aspx): ``` // C#1-5 propertyValue1 = myObject != null ? myObject.StringProperty : null; // C#6 propertyValue1 = myObject?.StringProperty; ``` The question below still applies to older versions, but if developi...
We independently came up with the exact same extension method name and implementation: [Null-propagating extension method](http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html). So we don't think it's confusing or an abuse of extension methods. I would write your "multiple levels" example with chaini...
Here's another solution, for chained members, including extension methods: ``` public static U PropagateNulls<T,U> ( this T obj ,Expression<Func<T,U>> expr) { if (obj==null) return default(U); //uses a stack to reverse Member1(Member2(obj)) to obj.Member1.Member2 var memb...
Possible pitfalls of using this (extension method based) shorthand
[ "", "c#", ".net", "extension-methods", "" ]
I would like to code a little program which visually illustrates the behavior of the `volatile` keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that. Adding the volatile keyword in the same program should fix the prob...
I've achieved a working example! The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# always carefully compile requests to static fields... and i make example with non static one: If you run this example in **Release** mode and...
Yes, it's hardware dependent (you are unlikely to see the problem without multiple processors), but it's also implementation dependent. The memory model specifications in the CLR spec permit things which the Microsoft implementation of the CLR do not necessarily do.
Illustrating usage of the volatile keyword in C#
[ "", "c#", ".net", "volatile", "" ]
I have a *JComboBox* and would like to have a separator in the list of elements. How do I do this in Java? A sample scenario where this would come in handy is when making a combobox for font-family-selection; similar to the font-family-selection-control in Word and Excel. In this case I would like to show the most-use...
There is a pretty short tutorial with an example that shows how to use a custom ListCellRenderer on java2s <http://www.java2s.com/Code/Java/Swing-Components/BlockComboBoxExample.htm> Basically it involves inserting a known placeholder in your list model and when you detect the placeholder in the ListCellRenderer you r...
By the time I wrote and tested the code below, you probably got lot of better answers... I don't mind as I enjoyed the experiment/learning (still a bit green on the Swing front). [EDIT] Three years later, I am a bit less green, and I took in account the valid remarks of bobndrew. I have no problem with the key navig...
How do I add a separator to a JComboBox in Java?
[ "", "java", "swing", "jcombobox", "jseparator", "" ]
It is much more convenient and cleaner to use a single statement like ``` import java.awt.*; ``` than to import a bunch of individual classes ``` import java.awt.Panel; import java.awt.Graphics; import java.awt.Canvas; ... ``` What is wrong with using a wildcard in the `import` statement?
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need `java.awt.Event`, and are also interfacing with the company's calendaring system, which has `com.mycompany.calendar.Event`. If you import both using the wildcard method, one of these th...
Here's a vote **for** star imports. An import statement is intended to import a *package*, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. `java.sql.Date` vs `java.util.Date`) are easily remedied by other means, not **really** addressed by specific imports and certainly do no...
Why is using a wild card with a Java import statement bad?
[ "", "java", "import", "wildcard", "" ]
In new C++ code, I tend to use the C++ iostream library instead of the C stdio library. I've noticed some programmers seem to stick to stdio, insisting that it's more portable. Is this really the case? What is better to use?
To answer the original question: Anything that can be done using stdio can be done using the iostream library. ``` Disadvantages of iostreams: verbose Advantages of iostreams: easy to extend for new non POD types. ``` The step forward the C++ made over C was type safety. * iostreams was designed to be explicitl...
It's just too verbose. Ponder the iostream construct for doing the following (similarly for scanf): ``` // nonsense output, just to examplify fprintf(stderr, "at %p/%s: mean value %.3f of %4d samples\n", stats, stats->name, stats->mean, stats->sample_count); ``` That would requires something like: ``` std::cerr...
Which C I/O library should be used in C++ code?
[ "", "c++", "iostream", "stdio", "" ]
The Python list comprehension syntax makes it easy to filter values within a comprehension. For example: ``` result = [x**2 for x in mylist if type(x) is int] ``` Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result?...
If the calculations are already nicely bundled into functions, how about using `filter` and `map`? ``` result = filter (None, map (expensive, mylist)) ``` You can use `itertools.imap` if the list is very large.
Came up with my own answer after a minute of thought. It can be done with nested comprehensions: ``` result = [y for y in (expensive(x) for x in mylist) if y] ``` I guess that works, though I find nested comprehensions are only marginally readable
How do I efficiently filter computed values within a Python list comprehension?
[ "", "python", "list-comprehension", "" ]
[PMD](https://pmd.github.io/) would report a violation for: ``` ArrayList<Object> list = new ArrayList<Object>(); ``` The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead". The following line would correct the violation: ``` List<Object> list = new ArrayList<Object>(); ```...
Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code. It's even a good idea to follow this practice when writing your own APIs. If you do, you'll find later that it's easier to add unit tests to your code (using Mocking techniques), and to change the underlying implem...
This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.
Why should the interface for a Java class be preferred?
[ "", "java", "collections", "interface", "" ]
Given this data: ``` CREATE TABLE tmpTable( fldField varchar(10) null); INSERT INTO tmpTable SELECT 'XXX' UNION ALL SELECT 'XXX' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'ZZZ' UNION ALL SELECT 'YYY' SELECT CASE WHEN fldField like 'YYY' THEN 'OTH' ELSE 'XXX' END AS newField FROM tmpTable ``` The expected resultse...
Check your service pack. After upgrading my SQL 2000 box to SP4 I now get the correct values for your situation. I'm still getting the swapped data that I reported in my earlier post though :( If you do `SELECT @@version` you should get 8.00.2039. Any version number less than that and you should install SP4.
I ran the code on a SQL 2000 box and got identical results. Not only that, but when I ran some additional code to test I got some VERY bizarre results: ``` CREATE TABLE dbo.TestLike ( my_field varchar(10) null); GO CREATE CLUSTERED INDEX IDX_TestLike ON dbo.TestLike (my_field) GO INSERT INTO dbo.TestLike (my_field) VA...
Like in CASE statement not evaluating as expected
[ "", "sql", "sql-server", "" ]
I have a server that sends data via a socket, the data is a wav 'file'. I can easily write the data to disk and then play it in WMP, but I have no idea how I can play it as I read it from the socket. Is it possible? Bonus question: how would I do it if the stream was in mp3 or other format? This is for windows in nat...
Because you've said WMP, I'm assuming the question applies to trying to play a wav file on a windows machine. If not, this answer isn't relevant. What you want to do isn't trivial. There is a good article [here](http://www.codeproject.com/KB/audio-video/wavefiles.aspx) on code project that describes the windows audio ...
Mark is right about this being a tricky problem. It may be less tricky if you use DirectSound instead of waveOut. [Here's an article](http://www.gamedev.net/reference/articles/article710.asp) on streaming wave files from disk: streaming from the network is essentially the same process. Make sure you collect enough data...
streaming wav files
[ "", "c++", "stream", "wav", "" ]
**Update**: Looks like the query does not throw any timeout. The connection is timing out. This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception. I **cannot** use any of these techniques: 1) Increase timeout. 2) Run it asynchronously with a callb...
Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback) but the application will wait (inside a while loop) until the query is complete. From [MSDN](http://msdn.microsoft.com/en-us/library/ca56w9se(VS.80).asp...
You should first check your query to see if it's optimized and it isn't somehow running on missing indexes. **30 seconds is allot for most queries**, even on large databases if they are properly tuned. If you have solid proof using the query plan that the query can't be executed any faster than that, then you should in...
Connection Timeout exception for a query using ADO.Net
[ "", "c#", ".net", "ado.net", "timeout", "" ]
I have to work on an old 1.3 JVM and I'm asked to create a secure connection to another server. Unfortunately the HttpsURLConnection only appears sinc JVM 1.4. Is there another way to create a secure connection? Is there a library that I could you to add this fonctionnality?
You need to install the Java Secure Socket Extension (JSSE), which used to be required because Sun wouldn't ship it with the JDK because of comedy export restrictions. I had a look on Sun's web site, but the JDK 1.3 instructions are preving elusive. Bear in mind that JDK 1.3 is now end-of-lifed by Sun, so they may not ...
Check out the [BouncyCastle](http://www.bouncycastle.org/java.html) implementation. It works all the way down to Java 1.1 and J2ME.
Is there a way to establish a HTTPS Connection with Java 1.3?
[ "", "java", "https", "" ]
I have a `Dictionary<string, someobject>`. EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references in a loop but to update different values based on differnt threads need to update/get the data. I changed the loop to a method. I need to update items in my dictionar...
Locking on an object that is accessible outside of the code locking it is a big risk. If any other code (anywhere) ever locks that object you could be in for some deadlocks that are hard to debug. Also note that you lock the *object*, not the reference, so if I gave you a dictionary, I may still hold references to the ...
No, this would not work. The reason is [string interning](http://en.wikipedia.org/wiki/String_intern_pool). This means that: ``` string a = "Something"; string b = "Something"; ``` are both the same object! Therefore, you should never lock on strings because if some other part of the program (e.g. another instance o...
Using lock on the key of a Dictionary<string, object>
[ "", "c#", "dictionary", "locking", "" ]
I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.
After messing around awhile longer I finally found something that worked and saw there still wasn't a solution posted here yet, so here's what I found: ``` try { String fileName = "file.xls"; WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName)); workbook.createSheet("Sheet1", 0); wor...
I know that it's a very old question. However, I think I can contribute with an example that also adds the cell values: ``` /** * * @author Almir Campos */ public class Write01 { public void test01() throws IOException, WriteException { // Initial settings File file = new File( "c:/tmp/genex...
How Do I Create a New Excel File Using JXL?
[ "", "java", "jxl", "" ]
This is along similar lines as these recent questions: [Best Java Obfuscation Application For Size Reduction](https://stackoverflow.com/questions/93290/best-java-obfuscation-application-for-size-reduction) [Creating non-reverse-engineerable Java programs](https://stackoverflow.com/questions/149937/creating-non-reverse...
Proguard is a better product; especially if you take the time to go through the settings for J2ME. Specifically for J2ME there is a far better (commercial) product called [mBooster](http://www.innaworks.com/mBooster.html) I've been getting around 25% improvement in size on my application *after* its been through Prog...
Results for my project. * **Obfuscation** - both fine. * **Optimisation** - ProGuard produced 20% faster code (for the measured app bottleneck). * **Compactness** - ProGuard about 5% smaller. * **Configuration / Ant** - YGuard is much easier to configure. So, I'd advise ProGuard - but configuration and ant integratio...
Java obfuscation - ProGuard/yGuard/other?
[ "", "java", "java-me", "obfuscation", "proguard", "yguard", "" ]
I've got a XmlNodeList which I need to have it in a format that I can then re-use within a XSLT stylesheet by calling it from a C# extension method. Can anyone help? I have read that it might have something to do with using a XPathNavigator but I'm still a bit stuck.
I had to solve this issue myself a couple of years ago. The only way I managed it was to create an XML fragment containing the nodes in the node list and then passing in the children of the fragment. ``` XsltArgumentList arguments = new XsltArgumentList(); XmlNodeList nodelist; XmlDocument nodesFrament = new XmlDocume...
The note at the end was the most useful, I had infact transformed the XmlNodeList into a XmlDocument already so could just use the Navigator on there and create it as a XPathNodeIterator. Thanks for you help!
How do I convert an XmlNodeList into a NodeSet to use within XSLT?
[ "", "c#", "xml", "xslt", "" ]
In VB.Net, I can declare a variable in a function as Static, like this: ``` Function EncodeForXml(ByVal data As String) As String Static badAmpersand As Regex = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)") data = badAmpersand.Replace(data, "&amp;") ''// more processing return data End Function ``` ...
Ha! In posting the question, I found the answer! Rather than googling for C# I should have been looking for details on how VB.Net implements it, and typing up the question made that apparent to me. After applying that insight, I found this: <http://weblogs.asp.net/psteele/articles/7717.aspx> That article explains th...
Personally I'm glad that C# *doesn't* have this. Logically, methods don't have state: types and instances do. C# makes that logical model clearer, IMO.
C# functions with static data
[ "", "c#", ".net", "vb.net", "" ]
Given a string with a module name, how do you import everything in the module as if you had called: ``` from module import * ``` i.e. given string S="module", how does one get the equivalent of the following: ``` __import__(S, fromlist="*") ``` This doesn't seem to perform as expected (as it doesn't import anything...
Please reconsider. The only thing worse than `import *` is *magic* `import *`. If you really want to: ``` m = __import__ (S) try: attrlist = m.__all__ except AttributeError: attrlist = dir (m) for attr in attrlist: globals()[attr] = getattr (m, attr) ```
Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '\_\_' from the imported file. The `__name__` global was being overwritten with the module name of the local settings file, which caused `setup_environ()`, used in manage.py,...
How does one do the equivalent of "import * from module" with Python's __import__ function?
[ "", "python", "python-import", "" ]
I am working on a ASP.net application written in C# with Sql Server 2000 database. We have several PDF reports which clients use for their business needs. The problem is these reports take a while to generate (> 3 minutes). What usually ends up happening is when the user requests the report the request timeout kills th...
Using the filesystem here is probably a good bet. Have a request that immediately returns a url to the report pdf location. Your server can then either kick off an external process or send a request to itself to perform the reporting. The client can poll the server (using http HEAD) for the PDF at the supplied url. If ...
I would consider making this report somehow a little bit more offline from the processing point of view. Like creating a queue to put report requests into, process the reports from there and after finish, it can send a message to the user. Maybe I would even create a separate Windows Service for the queue handling. ...
Handling Long Running Reports
[ "", "c#", "asp.net", "ajax", "reporting", "" ]
On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day *after* the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me. Is there some way to use JSP or JS...
I'm not a fan of putting java code in your jsp. I'd use a static method and a taglib to accomplish this. Just my idea though. There are many ways to solve this problem. ``` public static Date addDay(Date date){ //TODO you may want to check for a null date and handle it. Calendar cal = Calendar.getInstance(); ...
While this does not answer your initial question, you could perhaps eliminate the hassle of going through java.util.Calendar by doing this: ``` // Date d given d.setTime(d.getTime()+86400000); ```
In JSTL/JSP, given a java.util.Date, how do I find the next day?
[ "", "java", "jsp", "jstl", "" ]
Do you know any libraries similar to java.util.Properties that support more advanced features like grouping properties, storing arrays, etc? I am not looking for some heavy super-advanced solution, just something light and useful for any project. Thanks.
[Commons Configuration](http://commons.apache.org/configuration/) from the apache group sounds a lot like what you're looking for.
I've used [`java.util.prefs`](http://java.sun.com/javase/6/docs/api/java/util/prefs/package-summary.html) before, and it seems to do the trick for me. Your mileage may vary.
Can you suggest something a little more advanced than java.util.Properties?
[ "", "java", "configuration", "properties", "" ]
I have an Xtext/Xpand (oAW 4.3, Eclipse 3.4) generator plug-in, which I run together with the editor plug-in in a second workbench. There, I'd like to run Xpand workflows programmatically on the model file I create. If I set the model file using the absolute path of the IFile I have, e.g. with: ``` String dslFile = fi...
I found help at the [openArchitectureWare forum](http://openarchitectureware.org/forum/viewtopic.php?showtopic=10197). Basically using ``` properties.put("modelFile", file.getLocation().makeAbsolute().toOSString()); ``` works, but you need to specify looking it up via URI in the workflow you are calling: ``` <compon...
2 important things for people looking in here...the TE used a IFLE for the "file.get....", and the correct syntax for paths is "file:/c:/myOSbla".
How to programmatically run an Xpand workflow on a model in a second workbench?
[ "", "java", "eclipse", "xtext", "xpand", "oaw", "" ]
I have a JavaScript widget which provides standard extension points. One of them is the `beforecreate` function. It should return `false` to prevent an item from being created. I've added an Ajax call into this function using jQuery: ``` beforecreate: function (node, targetNode, type, to) { jQuery.get('http://examp...
From the [jQuery documentation](https://api.jquery.com/jquery.ajax/): you specify the **asynchronous** option to be **false** to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds. Here's what your code would look like if changed as suggested: ``` beforecreate: f...
You can put the jQuery's Ajax setup in synchronous mode by calling ``` jQuery.ajaxSetup({async:false}); ``` And then perform your Ajax calls using `jQuery.get( ... );` Then just turning it on again once ``` jQuery.ajaxSetup({async:true}); ``` I guess it works out the same thing as suggested by @Adam, but it might ...
How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
[ "", "javascript", "jquery", "ajax", "asynchronous", "" ]
I'm trying to design some tables to store some data, which has to be converted to different languages later. Can anybody provide some "best practices" or guidelines for this? Thanks
Let's say you have a products table that looks like this: ``` Products ---------- id price Products_Translations ---------------------- product_id locale name description ``` Then you just join on product\_id = product.id and where locale='en-US' of course this has an impact on performance, since you now need a joi...
Can you describe the nature of the 'dynamic data'? One way to implement this would be to have 3 different tables: * Language Table + This table would store the language and a key : ``` [1, English], [2, Spanish] ``` * Data Definition Table + When dynamic data is first entered make a record in this tabl...
Good database table design for storing localized versions of data
[ "", "sql", "sql-server", "database-design", "localization", "" ]
I've just solved another \*I-though-I-was-using-this-version-of-a-library-but-apparently-my-app-server-has-already-loaded-an-older-version-of-this-library-\*issue (sigh). Does anybody know a good way to verify (or monitor) whether your application has access to all the appropriate jar-files, or loaded class-versions? ...
If you happen to be using JBoss, there is an MBean (the class loader repository iirc) where you can ask for all classloaders that have loaded a certain class. If all else fails, there's always `java -verbose:class` which will print the location of the jar for every class file that is being loaded.
If you've got appropriate versions info in a jar manifest, there are methods to retrieve and test the version. No need to manually read the manifest. [java.lang.Package](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Package.html).getImplementationVersion() and getSpecificationVersion() and isC...
Classloader issues - How to determine which library versions (jar-files) are loaded
[ "", "java", "jar", "classloader", "" ]
I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#. In my C++ source I can write LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar); The macro & supporting library code then passes the (possibly var...
Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference: ``` System.Diagnostics.Trace ``` This includes listeners that listen for your `Trace()` methods, and then write to a log file/output window/event log, ones in the framework that are included are `DefaultTraceListener`, `T...
I would highly recommend looking at [log4Net](http://logging.apache.org/log4net/). This [post](https://mitchwheat.com/2007/04/29/log4net-net-logging-tool/) covers the majority of what you need to get started.
Error logging in C#
[ "", "c#", "error-reporting", "error-logging", "" ]
I have a pretty basic windows form app in .Net. All the code is C#. I'd like to turn it into an Asp.net web app. How can I easily do this? I think there's an easy way since the controls I drag/drop onto the windows form designer are pretty much the same that I drag/drop onto the aspx design page. Note: the windows fo...
There are two big problems here; first - they might look the same, but they are implemented completely differently - all of the UI work will need to be redone, largely from scratch. You will probably be able to re-use your actual "doing" code, though (i.e. the logic that manipulates the files). Second - define "local ...
You'll likely have issues reading files from the local machine via ASP.Net: for an ASP.Net app, the local machine is the web server, not the computer where the user is sitting. Also, there's a lot more to it than you'd think. odds are somewhere in your app you're relying on the fact the a windows forms app is inherent...
How can I easily turn a .Net Windows Form app into an Asp.net app using Visual Studio 2005?
[ "", "c#", "asp.net", "winforms", "" ]
I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions? Here is a copy of the class that is passing the member function: `...
To call a member function by pointer, you need two things: A pointer to the object and a pointer to the function. You need both in `MenuButton::SetButton()` ``` template <class object> void MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, ...
I'd strongly recommend `boost::bind` and `boost::function` for anything like this. See [Pass and call a member function (boost::bind / boost::function?)](https://stackoverflow.com/questions/5245072/pass-and-call-a-member-function-boostbind-boostfunction)
How do you pass a member function pointer?
[ "", "c++", "class", "function", "pointers", "member", "" ]
I am currently suffering a brain fart. I've done this before but I can't remember the exact syntax and I can't look at the code I wrote because I was working at another company at the time. I have this arrangement: ``` class P { // stuff }; class PW : public P { // more stuff }; class PR : public P { // more stuff }...
If you want to get this part to compile: ``` // ... P p = c.GetP( ); // valid PW p = c.GetP( ); // invalid PR p = c.GetP( ); // invalid // ... ``` You need to be able to construct/convert a P into a PW or a PR. You need to do something like this: ``` class PW : public P { PW(const P &); // more stuff...
You're trying to coerce actual variables, rather than pointers. To do that would require a cast. However, if your class definition looked like this: ``` class C { public: P* GetP() const { return p; } private: P* p; } ``` Then, whether p was a pointer to a P, a PW, or...
Automatic casts
[ "", "c++", "casting", "" ]
I have an ext combobox which uses a store to suggest values to a user as they type. An example of which can be found here: [combobox example](http://extjs.com/deploy/ext/examples/form/combos.html) Is there a way of making it so the **suggested text list** is rendered to an element in the DOM. Please note I do not mea...
You can use plugin for this, since you can call or even override private methods from within the plugin: ``` var suggested_text_plugin = { init: function(o) { o.onTypeAhead = function() { // Original code from the sources goes here: if(this.store.getCount() > 0){ ...
@qui Another thing to consider is that initList is not part of the API. That method could disappear or the behavior could change significantly in future releases of Ext. If you never plan on upgrading, then you don't need to worry.
Rendering suggested values from an ext Combobox to an element in the DOM
[ "", "javascript", "extjs", "" ]
I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in. Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling ...
On your home and work machines, set an environment variable `LOCATION` that is either "1" for home or "2" for work. Then in the preprocessor options, add a preprocessor define /DLOCATION=$(LOCATION). This will evaluate to either the "home" or "work" string that you set in the environment variable. Then in your code: ...
If the only difference between work and home is where the test files are located... then (IMHO) you shouldn't pollute your build files with a bunch of static paths & IPs. For the example you showed, I would simply map drives on both work and home. I.e. at work map a drive T: that points to \\212.45.68.43\Project\Blah\...
Conditional compilation for working at home
[ "", "c++", "" ]
``` class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; } } int main() { ...
Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one). This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destru...
Both new's will be leaked. Assign the address of the heap created objects to **named** smart pointers so that it will be deleted inside the smart pointers destructor that get call when the exception is thrown - ([RAII](http://en.wikipedia.org/wiki/RAII)). ``` class base { int a; boost::shared_ptr<int> pint; ...
Will the below code cause memory leak in c++
[ "", "c++", "exception", "memory-leaks", "constructor", "" ]
is there an alternative for `mysql_insert_id()` php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....
From the PostgreSQL point of view, in pseudo-code: ``` * $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2. * INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1 * $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older Pos...
You also can use: ``` $result = pg_query($db, "INSERT INTO foo (bar) VALUES (123) RETURNING foo_id"); $insert_row = pg_fetch_result($result, 0, 'foo_id'); ``` You have to specify in pg\_fetch\_result the number of the row and the name of the field that you are looking for, this is a more precise way to get the data t...
mysql_insert_id alternative for postgresql
[ "", "php", "postgresql", "insert-id", "" ]
I am writing a C# control that wraps DirectX 9 and provides a simplified interface to perform 2D pixel level drawing. .NET requires that I wrap this code in an unsafe code block and compile with the allow unsafe code option. I'm locking the entire surface which then returns a pointer to the locked area of memory. I ca...
Using unsafe pointers is the fastest way to do direct memory manipulation in C# (definitely faster than using the Marshal wrapper functions). Just out of curiosity, what sort of 2D drawing operations are you trying to perform? I ask because locking a DirectX surface to do pixel level manipulations will defeat most of...
Yes, that is probably the fastest way. A few years ago I had to compare two 1024x1024 images at the pixel level; the get-pixel methods took 2 minutes, and the unsafe scan took 0.01 seconds.
Unsafe C# and pointers for 2D rendering, good or bad?
[ "", "c#", "graphics", "pointers", "" ]
Why does the `sizeof` operator return a size larger for a structure than the total sizes of the structure's members?
This is because of padding added to satisfy alignment constraints. [Data structure alignment](http://en.wikipedia.org/wiki/Data_structure_alignment) impacts both performance and correctness of programs: * Mis-aligned access might be a hard error (often `SIGBUS`). * Mis-aligned access might be a soft error. + Either ...
Packing and byte alignment, as described in the C FAQ [here](http://www.c-faq.com/struct/align.html): > It's for alignment. Many processors can't access 2- and 4-byte > quantities (e.g. ints and long ints) if they're crammed in > every-which-way. > > Suppose you have this structure: > > ``` > struct { > char a[3];...
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
[ "", "c++", "c", "struct", "sizeof", "c++-faq", "" ]
How do I get the caller's IP address in a WebMethod? ``` [WebMethod] public void Foo() { // HttpRequest... ? - Not giving me any options through intellisense... } ``` using C# and ASP.NET
[HttpContext.Current.Request.UserHostAddress](http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress.aspx) is what you want.
Just a caution. IP addresses can't be used to uniquely identify clients. NAT Firewalls and corporate proxies are everywhere, and hide many users behind a single IP.
How do I get the caller's IP address in a WebMethod?
[ "", "c#", "asp.net", "web-services", "" ]
I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a ``` List<int> ``` and ``` Dictionary<int, bool> ``` With the dictionary I found slightly better performance, even though I never need the Boolean tagged ...
They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than say a 100 elements a List will probably perform better.
**Edit: Nevermind my comment. I thought you're talking about C++. I have no idea if my post is relevant in the C# world..** A hash-table could be a tad faster. Binary trees (that's what used in the dictionary) tend to be relative slow because of the way the memory gets accessed. This is especially true if your tree be...
Performance when checking for duplicates
[ "", "c#", "performance", "collections", ".net-2.0", "" ]
What are some suggestions for easy to use C++ compilers for a beginner? Free or open-source ones would be preferred.
GCC is a good choice for simple things. Visual Studio Express edition is the free version of the major windows C++ compiler. If you are on Windows I would use VS. If you are on linux you should use GCC. \*I say GCC for simple things because for a more complicated project the build process isn't so easy
G++ is the GNU C++ compiler. Most \*nix distros should have the package available.
What are some good compilers to use when learning C++?
[ "", "c++", "compiler-construction", "" ]
We have various php projects developed on windows (xampp) that need to be deployed to a mix of linux/windows servers. We've used [capistrano](http://www.capify.org/) in the past to deploy from windows to the linux servers, but recent changes in architecture and windows servers left the old config not working. The reci...
I use 4 different approaches depending on the client environment: 1. Capistrano and similar tools (effective, but complex) 2. `rsync` from + to Windows, Linux, Mac (simple, doesn't enforce discipline) 3. `svn` from + to Windows, Linux, Mac (simple, doesn't enforce discipline) 4. On-server scripts (run through the brow...
This will probably sound silly but... I used to have this kind of problem all the time until I decided in the end that if I'm always *deploying* on Linux, I ought really to at least try *developing* on Linux also. I did. It was pain free. I never went back. Now. I am not suggesting this is for everyone. But, if you in...
PHP Deployment to windows/unix servers
[ "", "php", "windows", "linux", "deployment", "automation", "" ]
Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. ``` a = re.compile("a.*b") b = re.compile("c.*d") ... ``` Question: Is it possible to store these regular expressions in a ca...
> Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Not easily. You'd have to write a custom serializer that hooks into the C `sre` implementation of the Python regex engine. Any performance benefits would be ...
Note that each module initializes itself only once during the life of an app, no matter how many times you import it. So if you compile your expressions at the module's global scope (ie. not in a function) you should be fine.
Caching compiled regex objects in Python?
[ "", "python", "regex", "caching", "" ]
I need some software to explore and modify some SQLite databases. Does anything similar to SQL Server Management Studio or MySQLAdmin exist for it?
[As a Firefox plugin](https://addons.mozilla.org/en-US/firefox/addon/5817) (aimed mainly at gears, but should work) [As a (sucky) web based app](http://www.sqlitemanager.org) And [a big list of management tools](http://www.sqlite.org/cvstrac/wiki?p=ManagementTools)
I also discovered some SQLite software for Visual Studio at <http://sqlite.phxsoftware.com/> which allows you to use the Visual Studio Server Explorer to create connections to SQLite databases.
Is there a MySQLAdmin or SQL Server Management Studio equivalent for SQLite databases on Windows?
[ "", "sql", "windows", "sqlite", "" ]
This is sort of SQL newbie question, I think, but here goes. I have a SQL Query (SQL Server 2005) that I've put together based on an example user-defined function: ``` SELECT CASEID, GetNoteText(CASEID) FROM ( SELECT CASEID FROM ATTACHMENTS GROUP BY CASEID ) i GO `...
When you use a subquery in the FROM clause, you need to give the query a name. Since the name doesn't really matter to you, something simple like 'i' or 'a' is often chosen. But you could put any name there you wanted- there's no significance to 'i' all by itself, and it's certainly not a keyword. If you have a really...
The i names the (subquery), which is required, and also needed for further joins. You will have to prefix columns in the outer query with the subquery name when there are conflicting column names between joined tables, like: ``` SELECT c.CASEID, c.CASE_NAME, a.COUNT AS ATTACHMENTSCOUNT, o.COUNT as OTHERCOUNT...
Unfamiliar character in SQL statement
[ "", "sql", "sql-server", "t-sql", "derived-table", "" ]
Imagine this sample java class: ``` class A { void addListener(Listener obj); void removeListener(Listener obj); } class B { private A a; B() { a = new A(); a.addListener(new Listener() { void listen() {} } } ``` Do I need to add a finalize method to B to call a.r...
I just found a huge memory leak, so I am going to call the code that created the leak to be *wrong* and my fix that does not leak as *right*. Here is the old code: (This is a common pattern I have seen all over) ``` class Singleton { static Singleton getInstance() {...} void addListener(Listener listener) {.....
There is a cycle in the reference graph. A references B and B references A. The garbage collector will detect cycles and see when there are no external references to A and B, and will then collect both. Attempting to use the finaliser here is wrong. If B is being destroyed, the reference to A is also being removed. -...
Do Java listeners need to be removed? (In general)
[ "", "java", "" ]
I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary `#include` directives. Sometimes the `#include`s are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the `.c...
While it won't reveal unneeded include files, Visual studio has a setting `/showIncludes` (right click on a `.cpp` file, `Properties->C/C++->Advanced`) that will output a tree of all included files at compile time. This can help in identifying files that shouldn't need to be included. You can also take a look at the p...
[PC Lint](http://www.gimpel.com/html/pcl.htm "PC Lint") works quite well for this, and it finds all sorts of other goofy problems for you too. It has command line options that can be used to create External Tools in Visual Studio, but I've found that the [Visual Lint](http://www.riverblade.co.uk/products/visual_lint/in...
How should I detect unnecessary #include files in a large C++ project?
[ "", "c++", "visual-studio-2008", "include", "header", "dependencies", "" ]
I know how to test an object to see if it is of a type, using the IS keyword e.g. ``` if (foo is bar) { //do something here } ``` but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result. BTW - I have a horrible feeling this is soooo obvious, so a...
``` if (!(foo is bar)) { } ```
You can also use the [as operator](http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.71).aspx). > The as operator is used to perform > conversions between compatible types. ``` bar aBar = foo as bar; // aBar is null if foo is not bar ```
Test an object for NOT being a type
[ "", "c#", "syntax", "object", "testing", "" ]
I am writing a simple Python web application that consists of several pages of business data formatted for the iPhone. I'm comfortable programming Python, but I'm not very familiar with Python "idiom," especially regarding classes and objects. Python's object oriented design differs somewhat from other languages I've w...
The empty Record class and the free-floating function that (generally) applies to an individual Record is a hint that you haven't designed your class properly. ``` class Record( object ): """Assuming rtda and pnl must exist.""" def __init__( self ): self.da= 0 self.rt= 0 self.rtda= 0 # ...
Have you considered using an ORM? [SQLAlchemy](http://www.sqlalchemy.org/features.html "SQL Alchemy features") is pretty good, and [Elixir](http://elixir.ematia.de/trac/wiki "Elixir Wiki") makes it beautiful. It can really reduce the ammount of boilerplate code needed to deal with databases. Also, a lot of the *gotchas...
Best practices for manipulating database result sets in Python?
[ "", "python", "database", "" ]
I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive. As part of some UI polish, I was hoping to implement a 'highlight' t...
Thanks for the answers guys, ajryan, you seem to always come up with help for my questions so extra thanks. Thankfully this time the answer was fairly straightforward.... ``` ImageList_DragShowNolock(FALSE); m_pDragDropTargetWnd->SendMessage(WM_USER_DRAG_DROP_OBJECT_DRAG_ENTER, (WPARAM)pDragDropObject, (LPARAM)(&drag...
Remote debugging is a godsend for debugging visual issues. It's a pain to set up, but having a VM ready for remote debugging will pay off for sure. What I like to do is set a ton of breakpoints in my paint handling, as well as in the framework paint code itself. This allows you to effectively "freeze frame" the painti...
How to fix an MFC Painting Glitch?
[ "", "c++", "mfc", "paint", "" ]
What is the difference between **`const`** and **`readonly`** in C#? When would you use one over the other?
Apart from the apparent difference of * having to declare the value at the time of a definition for a `const` VS `readonly` values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen. * `const`'s are implicitly `static`. You use a `ClassName.ConstantName` notation ...
There is a gotcha with consts! If you reference a constant from another assembly, its value will be compiled right into the calling assembly. That way when you update the constant in the referenced assembly it won't change in the calling assembly!
What is the difference between const and readonly in C#?
[ "", "c#", ".net", "constants", "readonly", "" ]
How do you return 1 value per row of the max of several columns: **TableName** ``` [Number, Date1, Date2, Date3, Cost] ``` I need to return something like this: ``` [Number, Most_Recent_Date, Cost] ``` Query?
This is an old answer and broken in many way. See <https://stackoverflow.com/a/6871572/194653> which has way more upvotes and works with sql server 2008+ and handles nulls, etc. **Original but problematic answer**: Well, you can use the CASE statement: ``` SELECT CASE WHEN Date1 >= Date2 AND Date1 >= Da...
Here is another nice solution for the `Max` functionality using T-SQL and SQL Server ``` SELECT [Other Fields], (SELECT Max(v) FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate] FROM [YourTableName] ``` Values is the [Table Value Constructor](https://learn.microsoft.com/en-us/sql/t-sql/querie...
SQL MAX of multiple columns?
[ "", "sql", "sql-server", "t-sql", "" ]
We try to use Java and UTF-8 on Windows. The application writes logs on the console, and we would like to use UTF-8 for the logs as our application has internationalized logs. It is possible to configure the JVM so it generates UTF-8, using `-Dfile.encoding=UTF-8` as arguments to the JVM. It works fine, but the output...
Try `chcp 65001 && start.bat` The `chcp` command changes the code page, and 65001 is the Win32 code page identifier for UTF-8 under Windows 7 and up. A code page, or character encoding, specifies how to convert a Unicode code point to a sequence of bytes or back again.
Java on windows does NOT support unicode ouput by default. I have written a workaround method by calling Native API with JNA library.The method will call WriteConsoleW for unicode output on the console. ``` import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna...
Java, UTF-8, and Windows console
[ "", "java", "windows", "utf-8", "console", "" ]
I've started to "play around" with PowerShell and am trying to get it to "behave". One of the things I'd like to do is to customize the PROMPT to be "similar" to what "$M$P$\_$+$G" do on MS-Dos: A quick rundown of what these do: **Character****| Description** **$m** The remote name associated with the current dri...
See if this does what you want: ``` function prompt { ## Get the history. Since the history may be either empty, ## a single item or an array, the @() syntax ensures ## that PowerShell treats it as an array $history = @(get-history) ## If there are any items in the history, find out the ## Id of th...
This will get you the count of the locations on the pushd stack: ``` $(get-location -Stack).count ```
Customizing PowerShell Prompt - Equivalent to CMD's $M$P$_$+$G?
[ "", "c#", "powershell", "command", "prompt", "customization", "" ]
I need to convert a value which is in a `DateTime` variable into a `varchar` variable formatted as `yyyy-mm-dd` format (without time part). How do I do that?
With Microsoft Sql Server: ``` -- -- Create test case -- DECLARE @myDateTime DATETIME SET @myDateTime = '2008-05-03' -- -- Convert string -- SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10) ```
Here's some test sql for all the styles. ``` DECLARE @now datetime SET @now = GETDATE() select convert(nvarchar(MAX), @now, 0) as output, 0 as style union select convert(nvarchar(MAX), @now, 1), 1 union select convert(nvarchar(MAX), @now, 2), 2 union select convert(nvarchar(MAX), @now, 3), 3 union select convert(nvar...
How to convert DateTime to VarChar
[ "", "sql", "sql-server", "datetime", "sql-convert", "" ]
I was able to implement a thread-safe Dictionary in C# by deriving from IDictionary and defining a private SyncRoot object: ``` public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue> { private readonly object syncRoot = new object(); private Dictionary<TKey, TValue> d = new Dictionary<TKey, TValu...
As Peter said, you can encapsulate all of the thread safety inside the class. You will need to be careful with any events you expose or add, making sure that they get invoked outside of any locks. ``` public class SafeDictionary<TKey, TValue>: IDictionary<TKey, TValue> { private readonly object syncRoot = new obje...
The .NET 4.0 class that supports concurrency is named [`ConcurrentDictionary`](http://msdn.microsoft.com/en-us/library/dd287191.aspx).
What's the best way of implementing a thread-safe Dictionary?
[ "", "c#", ".net", "thread-safety", "collections", "" ]
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when I...
[Base64 encoding](https://docs.python.org/3/library/base64.html) is in the standard library and will do to stop shoulder surfers: ``` >>> import base64 >>> print(base64.b64encode("password".encode("utf-8"))) cGFzc3dvcmQ= >>> print(base64.b64decode("cGFzc3dvcmQ=").decode("utf-8")) password ```
Here is a simple method: 1. Create a python module - let's call it peekaboo.py. 2. In peekaboo.py, include both the password and any code needing that password 3. Create a compiled version - peekaboo.pyc - by importing this module (via python commandline, etc...). 4. Now, delete peekaboo.py. 5. You can now happily imp...
Hiding a password in a python script (insecure obfuscation only)
[ "", "python", "security", "" ]
``` Element[] array = {new Element(1), new Element(2), new Element(3)}; ``` How do I convert the above variable of type `Element[]` into a variable of type [`ArrayList<Element>`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/ArrayList.html)? ``` ArrayList<Element> arrayList = ...; ```
You can use the following instruction: ``` new ArrayList<>(Arrays.asList(array)); ```
Given: ``` Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) }; ``` The simplest answer is to do: ``` List<Element> list = Arrays.asList(array); ``` This will work fine. But some caveats: 1. The list returned from asList has **fixed size**. So, if you want to be able to add or remove...
Create ArrayList from array
[ "", "java", "arrays", "arraylist", "type-conversion", "" ]
Hi i want to write a game with a main game form and lot of other normal forms. What is the best way to manage update-paint cycle in that case? Should the game form paint loop only should be overriden? or should i do an application.do events() in the main method? Please guide me regarding this. i am new to windows for...
Your logic thread should be separate from the form, so you won't need DoEvents(). If you're using GDI+, then you should force an Update() on a loop. Windows Forms doesn't do double buffering very well, so depending on how sophisticated your graphics will be you might have some difficulties with flicker. My suggestion ...
The body of the question doesn't mention Compact Framework, just Winforms. This is pretty much the accepted answer for Winforms from Tom Miller (Xna Game Studio and Managed DirectX guy from Microsoft): [Winforms Game Loop](http://blogs.msdn.com/tmiller/archive/2005/05/05/415008.aspx) @Rich B: The game loop is indepen...
Game Loop and GDI over .NET CF
[ "", "c#", "game-loop", "" ]
I am trying to use the `import random` statement in python, but it doesn't appear to have any methods in it to use. Am I missing something?
You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my\_random.py and/or remove the random.pyc file. To tell for sure what's going on, do this: ``` >>> import random >>> print random.__file__ ``` ...
This is happening because you have a random.py file in the python search path, most likely the current directory. Python is searching for modules using sys.path, which normally includes the current directory before the standard site-packages, which contains the expected random.py. This is expected to be fixed in Pyth...
Random in python 2.5 not working?
[ "", "python", "" ]
Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the *actual* name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)? Some ways I know, all of which seem quite backwards: 1. Given the full path, search for each folder on the path (via Find...
And hereby I answer my own question, based on [original answer from *cspirz*](https://stackoverflow.com/questions/74451/getting-actual-file-name-with-proper-casing-on-windows#74588). Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on ...
Have you tried using [SHGetFileInfo?](http://msdn.microsoft.com/en-us/library/bb762179(VS.85).aspx)
Getting actual file name (with proper casing) on Windows
[ "", "c++", "c", "windows", "winapi", "" ]
Is there a way to use constants in **JavaScript**? If not, what's the common practice for specifying variables that are used as constants?
Since [ES2015](https://www.ecma-international.org/ecma-262/6.0/), JavaScript has a notion of [`const`](https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations): ``` const MY_CONSTANT = "some-value"; ``` This will work in [pretty much all browsers except IE 8, 9 and 10](https://caniuse.com/#sea...
Are you trying to protect the variables against modification? If so, then you can use a module pattern: ``` var CONFIG = (function() { var private = { 'MY_CONST': '1', 'ANOTHER_CONST': '2' }; return { get: function(name) { return private[name]; } }; })(); alert('MY_CONST:...
Are there constants in JavaScript?
[ "", "javascript", "constants", "" ]
I have a function that takes, amongst others, a parameter declared as *int privateCount*. When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call. So, curious as I am, I remove the ToString(), and the code still builds! How can a C# compiler allow this, where *str* is a st...
The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus: ``` string x = "123" + 45; ``` Gets compiled to: ``` String.Concat("123", 45); ``` Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it...
It is not only bad practice, but also less performant: The integer has to be boxed because String.Concat expectes an object while int.ToString() does not require boxing.
Redundant Call to Object.ToString()
[ "", "c#", ".net", "resharper", "" ]
I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging. I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be...
I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue. Here is the "simple" version: ``` function DumpObject(obj) { var od...
Use [**Crockford's JSON.stringify**](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) like this: ``` var myArray = ['e', {pluribus: 'unum'}]; var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation... ``` Variable `t...
JavaScript data formatting/pretty printer
[ "", "javascript", "debugging", "json", "" ]
Implementing Equals() for reference types is harder than it seems. My current canonical implementation goes like this: ``` public bool Equals( MyClass obj ) { // If both refer to the same reference they are equal. if( ReferenceEquals( obj, this ) ) return true; // If the other object is null they are not eq...
I wrote a fairly comprehensive guide to this a while back. For a start your equals implementations should be shared (i.e. the overload taking an object should pass through to the one taking a strongly typed object). Additionally you need to consider things such as your object should be immutable because of the need to ...
Better hope that this.\_data is not null if it's also a reference type. ``` public bool Equals( MyClass obj ) { if (obj == null) { return false; } else { return (this._data != null && this._data.Equals( obj._data )) || obj._data == null; } } public override boo...
What is the "best" canonical implementation of Equals() for reference types?
[ "", "c#", ".net", "equals", "" ]
I don't want a discussion about when to and not to throw exceptions. I wish to resolve a simple issue. 99% of the time the argument for not throwing exceptions revolves around them being slow while the other side claims (with benchmark test) that the speed is not the issue. I've read numerous blogs, articles, and posts...
I'm on the "not slow" side - or more precisely "not slow enough to make it worth avoiding them in normal use". I've written two [short](http://pobox.com/%7Eskeet/csharp/exceptions.html) [articles](http://pobox.com/%7Eskeet/csharp/exceptions2.html) about this. There are criticisms of the benchmark aspect, which are most...
There is the definitive answer to this from the guy who implemented them - Chris Brumme. He wrote an [excellent blog article](https://devblogs.microsoft.com/cbrumme/the-exception-model/) about the subject (warning - its very long)(warning2 - its very well written, if you're a techie you'll read it to the end and then h...
How slow are .NET exceptions?
[ "", "c#", ".net", "performance", "exception", "" ]
I've discovered that any time I do the following: ``` echo '<a href="http://" title="bla">huzzah</a>'; ``` I end up with the following being rendered to the browser: ``` <a href="http:///" title="bla">huzzah</a> ``` This is particularly annoying when I link to a file with an extension, as it breaks the link. Any i...
Firefox, especially, shows you the html source the way it's seeing it which is rarely the way you've sent it. Clearly something about your link or it's context is making the browser interpret a trailing slash. I wonder if it's a side effect of the url encoding. If you rawurldecode it will that help. If there are parts...
Ive never had that, how ecactly are you echoing the link? All the following should work. ``` echo '<a href="http://someothersite.com">Link</a>'; echo '<a href="anotherpage.php">Some page</a>'; echo '<a href="../pageinparentdir.php">Another page</a>'; etc ``` edit, since you added the info. You can't just have http:/...
Echo A Link, Get A Trailing Slash?
[ "", "php", "jfilechooser", "" ]
Using the Sun Java VM 1.5 or 1.6 on Windows, I connect a non-blocking socket. I then fill a `ByteBuffer` with a message to output, and attempt to `write()` to the SocketChannel. I expect the write to complete only partially if the amount to be written is greater than the amount of space in the socket's TCP output buff...
I managed to reproduce a situation that might be similar to yours. I think, ironically enough, your recipient is consuming the data faster than you're writing it. ``` import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) thro...
I've been working with UDP in Java and have seen some really "interesting" and completely undocumented behavior in the Java NIO stuff in general. The best way to determine what is happening is to look at the source which comes with Java. I also would wager rather highly that you might find a better implementation of w...
Why do SocketChannel writes always complete for the full amount even on non-blocking sockets?
[ "", "java", "sockets", "network-programming", "nio", "" ]
I've got a generic dictionary `Dictionary<string, T>` that I would like to essentially make a Clone() of ..any suggestions.
Okay, the .NET 2.0 answers: If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.) If you *do* need to clone the values, you can use something like this: ``` public stati...
(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.) How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, wi...
What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?
[ "", "c#", "generics", "collections", "clone", "" ]
I have the following code: ``` info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args)); info.CreateNoWindow = true; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; info.RedirectStandardOutput = true; info.UseShellExecute = false; System.Diagnostics.Process p = System.D...
The problem is that if you redirect `StandardOutput` and/or `StandardError` the internal buffer can become full. Whatever order you use, there can be a problem: * If you wait for the process to exit before reading `StandardOutput` the process can block trying to write to it, so the process never ends. * If you read fr...
The [documentation](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx) for `Process.StandardOutput` says to read before you wait otherwise you can deadlock, snippet copied below: ``` // Start the child process. Process p = new Process(); // Redirect the output stream of the chil...
ProcessStartInfo hanging on "WaitForExit"? Why?
[ "", "c#", "processstartinfo", "" ]