Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How are objects stored in memory in C++? For a regular class such as ``` class Object { public: int i1; int i2; char i3; int i4; private: }; ``` Using a pointer of Object as an array can be used to access i1 as follows? ``` ((Object*)&myObject)[0] === i1? ``` Other questions on SO seem to s...
Almost. You cast to an Object\*, and neglected to take an address. Let's re-ask as the following: ``` ((int*)&myObject)[0] == i1 ``` You have to be really careful with assumptions like this. As you've defined the structure, this should be true in any compiler you're likely to come across. But all sorts of other prope...
Classes without virtual members and without inheritance are laid out in memory just like structs. But, when you start getting levels of inheritance things can get tricky and it can be hard to figure out what order things are in memory (particularly multiple inheritance). When you have virtual members, they have a "vta...
How are objects stored in memory in C++?
[ "", "c++", "memory", "memory-management", "" ]
I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO\_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0: ``` MySqlCommand comm = connect.Creat...
[Edit: added "select" before references to last\_insert\_id()] What about running "`select last_insert_id();`" after your insert? ``` MySqlCommand comm = connect.CreateCommand(); comm.CommandText = insertInvoice; comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + ...
``` MySqlCommand comm = connect.CreateCommand(); comm.CommandText = insertStatement; // Set the insert statement comm.ExecuteNonQuery(); // Execute the command long id = comm.LastInsertedId; // Get the ID of the inserted item ```
Get the id of inserted row using C#
[ "", "c#", "mysql", "last-insert-id", "" ]
What do you see as benefits for one over the other? As far as I know, it's just preference. I have way more experience with C# than I do with Visual Basic and was wondering if I should dabble in Visual Basic for certain types of projects?
I personally prefer C#, I love the syntax and I feel really comfortable with the language. Some say that [C# programmers are paid better](http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=503) than VB programmers, but I think you should try both languages and see on which you fell better. * [Top 10 reasons C# ...
VB4 was my first language, with VB6 being the last time I touched it. I have moved to c# and wouldnt consider going back. VB just feels too fat and fluffy for me (preference). All the .NET languages compile to IL though... Note: c# is "closer" to java...
Do you prefer C# or Visual Basic .Net?
[ "", "c#", ".net", "vb.net", "" ]
Inspired by this [question](https://stackoverflow.com/questions/404899/scope-of-variables-in-a-delegate) I began wondering why the following examples are all illegal in c#: ``` VoidFunction t = delegate { int i = 0; }; int i = 1; ``` and ``` { int i = 0; } int i = 1; ``` I'm just wondering if anyone knew the e...
This behavior is covered in section 3 of the C# language specification. Here is the quote from the spec > Similarly, any expression that > occurs as the body of an anonymous > function in the form of a > lambda-expression creates a > declaration space which contains the > parameters of the anonymous function. > It is ...
I think it is done this way so that the inner scope can access variables declared in the outer scope. If you were allowed to over-write variables existing in the outer scope, there may be confusion about what behavior was intended. So they may have decided to resolve the issue by preventing it from happening.
Why is the scope of if and delegates this way in c#
[ "", "c#", "language-design", "" ]
I want to format an int as a currency in C#, but with no fractions. For example, 100000 should be "$100,000", instead of "$100,000.00" (which 100000.ToString("C") gives). I know I can do this with 100000.ToString("$#,0"), but that's $-specific. Is there a way to do it with the currency ("C") formatter?
Use format "C0".
Possible to use n0 which provide commas like 1,234. Currency sign won't be there
How to format an int as currency in C#?
[ "", "c#", "formatting", "currency", "" ]
According to [MSDN](http://msdn.microsoft.com/en-us/library/system.drawing.aspx), it is not a particularly good idea to use classes within the **System.Drawing** namespace in a Windows Service or ASP.NET Service. Now I am developing a class library which might need to access this particular namespace (for measuring fon...
To clear up any confusion, System.Drawing does *work* under ASP.NET and Services, it's just not *supported*. There can be issues with high load (running out of unmanaged resources), memory or resource leaks (badly implemented or called dispose patterns) and/or dialogs being popped when there's no desktop to show them o...
Even though it's not officially supported, I've used the System.Drawing classes extensively on a high-volume web server (both web application and web services) for years without it causing any performance or reliability problems. I think the only way to determine if the code is safe to use is to test, monitor, and wra...
System.Drawing in Windows or ASP.NET services
[ "", "c#", ".net", "windows-services", "system.drawing", "" ]
I know there is a method for a Python list to return the first index of something: ``` >>> xs = [1, 2, 3] >>> xs.index(2) 1 ``` Is there something like that for NumPy arrays?
Yes, given an array, `array`, and a value, `item` to search for, you can use [`np.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) as: ``` itemindex = numpy.where(array == item) ``` The result is a tuple with first all the row indices, then all the column indices. For example, if an arra...
If you need the index of the first occurrence of **only one value**, you can use `nonzero` (or `where`, which amounts to the same thing in this case): ``` >>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8]) >>> nonzero(t == 8) (array([6, 8, 9]),) >>> nonzero(t == 8)[0][0] 6 ``` If you need the first index of each of **many...
Is there a NumPy function to return the first index of something in an array?
[ "", "python", "arrays", "numpy", "" ]
I'm writing a webapp that will only be used by authenticated users. Some temporary databases and log files will be created during each user session. I'd like to erase all these temp files when the session is finished. Obviously, a logout or window close event would be sufficient to close the session, but in some cases...
User sessions should have a timeout value and should be closed when the timeout expires or the user logs out. Log out is an obvious time to do this and the time out needs to be there in case the user navigates away from your application without logging out.
A cron job to clean up any expired session data in the database is a good thing. Depending on how long your sessions last, and how big your database is, you might want to cleanup more often than once per day. But one cleanup pass per day is usually fine.
when to delete user's session
[ "", "python", "session", "" ]
Is it possible to generate the database tables and c# classes from NHibernate config files? Afterwards, is it possible to change the config files and update the tables and config files non-destructively? Do you recommend any tools to do this? (preferably free...)
As mentioned by Joachim, it's the "hbm2ddl.auto" setting that you're looking for. You can set it by code like this: ``` var cfg = new NHibernate.Cfg.Configuration(); cfg.SetProperty("hbm2ddl.auto", "create"); cfg.Configure(); ``` And you can also set it in your App.config file: ``` <hibernate-configuration xmln...
Yes it is possible to generate the database tables and C# classes from the NHibernate config files. Let me explain with this example here . 1 : Address.hbm.xml ``` <?xml version="1.0" encoding="UTF-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0" default-cascade="none"> <class name="Yo...
Generate Database from NHibernate config files
[ "", "c#", "nhibernate", "" ]
Simply put, I have a table with, among other things, a column for timestamps. I want to get the row with the most recent (i.e. greatest value) timestamp. Currently I'm doing this: ``` SELECT * FROM table ORDER BY timestamp DESC LIMIT 1 ``` But I'd much rather do something like this: ``` SELECT * FROM table WHERE tim...
``` SELECT * from foo where timestamp = (select max(timestamp) from foo) ``` or, if SQLite insists on treating subselects as sets, ``` SELECT * from foo where timestamp in (select max(timestamp) from foo) ```
There are many ways to skin a cat. If you have an Identity Column that has an auto-increment functionality, a faster query would result if you return the last record by ID, due to the indexing of the column, unless of course you wish to put an index on the timestamp column. ``` SELECT * FROM TABLE ORDER BY ID DESC LI...
Aggregate functions in WHERE clause in SQLite
[ "", "sql", "sqlite", "where-clause", "aggregate-functions", "" ]
I have a problem with a flash object placing itself on top over everything in IE6 and IE7. Firefox renders the page correctly. I bet somebody else has had this problem and found some kinda solution to it.
Because Flash runs inside an ActiveX control in IE browsers, it doens't follow the stack rules since ActiveX controls are always rendered on to of normal HTML content (except for drop down, annoyingly). There is a workaround though to force Flash to obey, set the wmode="transparent" in your object tag, and optionally ...
[wmode=transparent](https://stackoverflow.com/search?q=wmode+transparent) is the way to go.
Problem with flash positioning itself over a javascript lightwindow in IE6 & IE7
[ "", "javascript", "flash", "internet-explorer", "" ]
Is there a way to get the name of the currently executing method in Java?
`Thread.currentThread().getStackTrace()` will usually contain the method you’re calling it from but there are pitfalls (see [Javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#getStackTrace())): > Some virtual machines may, under some circumstances, omit one or more stack frame...
Technically this will work... ``` String name = new Object(){}.getClass().getEnclosingMethod().getName(); ``` However, a new anonymous inner class will be created during compile time (e.g. `YourClass$1.class`). So this will create a `.class` file for each method that deploys this trick. Additionally, an otherwise unu...
Getting the name of the currently executing method
[ "", "java", "reflection", "methods", "" ]
I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs. Has anyone done anything like that? Do you k...
You could try using the perl module [Lingua::EN::Tagger](http://search.cpan.org/~acoburn/Lingua-EN-Tagger-0.15/Tagger.pm) for a quick and easy solution. A more complicated module [Lingua::EN::Semtags::Engine](http://code.google.com/p/lingua-en-semtags-engine/) uses Lingua::EN::Tagger with a WordNet database to get a m...
The name for the "high frequency English words" is [stop words](http://en.wikipedia.org/wiki/Stop_words) and there are many lists available. I'm not aware of any python or perl libraries, but you could encode your stop word list in a binary tree or hash (or you could use python's frozenset), then as you read each word ...
What is a simple way to generate keywords from a text?
[ "", "python", "perl", "metadata", "" ]
Is there any GUI toolkit for Python with form designer similar to Delphi, eg where one can drag and drop controls to form, move them around etc.
I recommend [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro) (now from Nokia), which uses [Qt Designer](http://www.qtsoftware.com/products/appdev/developer-tools/developer-tools?currentflipperobject=73543fa58dda72c632a376b97104ff78). Qt designer produces XML files (.ui) which you can either convert to Py...
Use Glade + PyGTk to do GUI programming in Python. Glade is a tool which allows you to create graphical interfaces by dragging and dropping widgets. In turn Glade generates the interface definition in XML which you can hook up with your code using libglade. Check the website of [Glade](http://glade.gnome.org/) for more...
Delphi-like GUI designer for Python
[ "", "python", "user-interface", "form-designer", "" ]
In a C++ physics simulation, I have a class called Circle, and Square. These are Shapes, and have a method called push(), which applies force to it. There is then a special case of Circle, call it SpecialCircle, in which push() should exhibit slightly different properties. But in fact, there is also SpecialSquare() whi...
Another solution (it may or may not fit your needs, it depends on the details of your implementation): * Have the class Behavior, and let NormalBehavior and SpecialBehavior inherit from it. * Have the class Shape, and let Square and Circle inherit from it. Let Shape be an aggregate type, with a Behavior member (i.e. y...
It's said that every problem in software can be solved by adding an additional layer of indirection. Herb Sutter has an excellent article on how to solve your problem: [Multiple Inheritance - Part III](http://www.gotw.ca/gotw/039.htm) In short, you use intermediate classes to 'rename' the virtual functions. As Herb s...
Multiple inheritance in C++ leading to difficulty overriding common functionality
[ "", "c++", "inheritance", "class", "" ]
I'm looking for an AJAX function to dynamically request an HTML page. I already found the following: ``` function ajaxinclude(url) { var page_request = false if (window.XMLHttpRequest) // if Mozilla, Safari etc page_request = new XMLHttpRequest() else if (window.ActiveXObject) // if IE { try...
I would have to agree, don't go reinventing the wheel, or in this case, AJAX. JQuery and Prototype do an excellent job of letting you NOT have to deal with cross-browser support, and greatly simplifying Javascript type programming. I fell into JQuery first so I'm biased towards it, and from what I've seen the library ...
Or you can try this if you don't need an entire framework: <http://www.hunlock.com/blogs/The_Ultimate_Ajax_Object>
Cross browser AJAX function to dynamically load HTML
[ "", "javascript", "ajax", "" ]
For a project I have a specification with formulas, I have to implement. In these formulas a cumulative standard normal distribution function exists, that takes a float and outputs a probability. The function is symbolized by a Φ. Exists a Java-library, that computes this function?
A co-worker suggested [colt](http://acs.lbl.gov/~hoschek/colt/), as he used it before. This [function](http://acs.lbl.gov/~hoschek/colt/api/cern/jet/random/Normal.html#cdf(double)) has exactly the result as the example in the reference document.
[Apache Commons - Math](http://commons.apache.org/math/) has what you are looking for. More specifically, check out the [`NormalDistribution`](http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/distribution/NormalDistribution.html) class.
Which java-library computes the cumulative standard normal distribution function?
[ "", "java", "statistics", "probability", "computation", "" ]
Bjarne Stroustrup writes in his [C++ Style and Technique FAQ](http://www.research.att.com/~bs/bs_faq2.html#finally), emphasis mine: > Because C++ supports an alternative that is ***almost always better***: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a r...
The only reason I can think of that a finally block would be "better" is when it takes less code to accomplish the same thing. For example, if you have a resource that, for some reason doesn't use RAII, you would either need to write a class to wrap the resource and free it in the destructor, or use a finally block (if...
The difference between them is that destructors emphasise reuse of the cleanup solution by associating it with the type being used, whereas try/finally emphasises one-off cleanup routines. So try/finally is more immediately convenient when you have a unique one-off cleanup requirement associated with the point of use, ...
Are there cases where a "finally" construct would be useful in C++?
[ "", "c++", "raii", "finally", "" ]
Do you consider this a code smell? ``` foreach((array)$foo as $bar) { $bar->doStuff(); } ``` Should i use that instead? ``` if (isset($foo) && is_array($foo)) { foreach($foo as $bar) { $bar->doStuff(); } } ``` Any other good practices to cover not set variables and assert an array?
They're both code smells. The second one is just evading all the error messages, kind of like turning off the fire alarm before you set your kitchen on fire. Both of those tell you that you have no idea what's in the variable `$foo` or if it's even been defined in the code above. You need to go back up through the code...
If you are testing if variables are set, you can initialize them: ``` if (! $foo or !is_array($foo)) $foo = array(); foreach($foo as $bar) { $bar->doStuff(); } ```
Do you consider foreach((array)$foo as $bar) a code smell?
[ "", "php", "" ]
When clicking on the text box part of an `<input type="file" />` in FireFox3, a file browsing window opens. This doesn't happen in IE7. You have to click the "browse" button to open the file browsing window. How can I prevent the file browsing window from opening in FireFox when a user clicks on the textbox area? I'd...
> How can I prevent the file browsing window from opening in FireFox when a user clicks on the textbox area? Obscure it with another element. ``` <div style="position: relative"> <input type="file" /> <div style="position: absolute; top: 0; left: 0; width: 11em; height: 2em;"> </div> </div> ``` But don't do ...
Why can't you leave expected behavior alone? Most people who use FireFox will expect it to happen. Unless there is an actual "design" reason that you did not state for making this happen please don't try and change it.
<input type="file" /> opens file browse window in FireFox3 when clicking the form field part?
[ "", "javascript", "css", "file", "input", "" ]
I'm a MySQL guy working on a SQL Server project, trying to get a datetime field to show the current time. In MySQL I'd use NOW() but it isn't accepting that. ``` INSERT INTO timelog (datetime_filed) VALUES (NOW()) ```
`getdate()` or `getutcdate()`.
``` getdate() ``` is the direct equivalent, *but you should always use UTC datetimes* ``` getutcdate() ``` whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions
SQL Server equivalent of MySQL's NOW()?
[ "", "sql", "sql-server", "" ]
Hi I need some help with the following scenario in php. I have a db with users every user has an ID, have\_card and want\_card. I know how to make a direct match (one user trades with another user). But if there is no direct match but there is a circular swap like: User #1 has card A wants card B User #2 has card B w...
This is a challenging scenario. I had to build this for a book swapping application a while back and using a white board I was able to more easily visual and solve the problem. What I did was use the same table inside the query multiple times, just using a different name. In my scenario, the books that were needed we...
Interestingly, I came across a similar thing to this with the [BoardGameGeek Maths Trade](http://www.boardgamegeek.com/thread/93555). Basically, everyone specifies that they either want a game or have a game and the algorithm maximises trades including circular dependencies. This is exactly what you want. Here is an ...
Circular matching. PHP / MySql
[ "", "php", "mysql", "" ]
So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this? --- Well ...
I'd suggest using `virtualenv`'s [bootstrapping](http://pypi.python.org/pypi/virtualenv#creating-your-own-bootstrap-scripts) support. This allows you to execute arbitrary Python after the virtualenv is created, such as installing new packages.
I know where you're coming from with the no-sites-option. I want to use pip freeze to generate requirements lists and don't want a lot of extra cruft in site-packages. I also need to use multiple versions of django as I have legacy projects I haven't upgraded (some old svn checkouts (pre1.0), some 1.0, and some new svn...
Installing certain packages using virtualenv
[ "", "python", "virtualenv", "buildout", "" ]
I was having a look at [this](http://java.sun.com/docs/books/tutorial/essential/io/cl.html) tutorial at Sun on command line I/O. It stated that: > You might expect the Standard Streams > to be character streams, but, for > historical reasons, they are byte > streams. System.out and System.err are > defined as PrintStr...
The "historical reasons" are that character streams did not exist in Java 1.0. Apparently Sun realized that the character translation model was insufficient and the Character oriented Reader/Writer class hierarchy was added in Java 1.1. But it was too late for System.out and friends.
I would guess that the reason is to be backwards-compatible with POSIX C/C++ standard I/O, in which stdin, stdout, and stderr (the C/C++ equivalent of System.in, System.out, and System.err respectively) are byte streams. In Windows, those streams perform CRLF translation, but in POSIX systems, no such conversions occur...
Why are System.out/err implemented as Byte Streams in Java?
[ "", "java", "iostream", "" ]
I have the same expression in Javascript but it won't work in PHP for server side validation. Here's the code ``` if (ereg('/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+/',$_POST['email-address'])) echo "valid email"; else echo "invalid email"; ```
use preg\_match, not ereg. ereg regex strings do not use an enclosing slash character. Also the double-backslash may not be necessary in a single-quoted string in PHP (not sure about that, though)
filter which comes with PHP: ``` if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "E-mail is not valid"; } else { echo "E-mail is valid"; } ```
Why doesn't my email regex for PHP work?
[ "", "php", "regex", "" ]
How can I convert an `str` to a `float`? ``` "545.2222" -> 545.2222 ``` Or an `str` to a `int`? ``` "31" -> 31 ``` --- For the reverse, see [Convert integer to string in Python](https://stackoverflow.com/questions/961632) and [Converting a float to a string without rounding it](https://stackoverflow.com/questions/...
``` >>> a = "545.2222" >>> float(a) 545.22220000000004 >>> int(float(a)) 545 ```
## Python2 method to check if a string is a float: ``` def is_float(value): if value is None: return False try: float(value) return True except: return False ``` For the Python3 version of is\_float see: [Checking if a string can be converted to float in Python](https://stackoverflow.com...
How do I parse a string to a float or int?
[ "", "python", "parsing", "floating-point", "type-conversion", "integer", "" ]
I understand that the question is rather hard to understand, I didn't know how to ask it better, so I'll use this code example to make things more clear: If I have the following files: test.php: ``` <?php include('include.php'); echo myClass::myStaticFunction(); ?> ``` include.php ``` <?php __autoload($classna...
in case you need to get "test.php" see `$_SERVER['SCRIPT_NAME']`
I ended up using: ``` $file = basename(strtolower($_SERVER['SCRIPT_NAME'])); ```
Howto get filename from which class was included in PHP
[ "", "php", "include", "filenames", "" ]
I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways: ``` sorted(a) == sorted(b) ``` and ``` all(a.c...
heuristically you're probably better to split them off based on string size. Pseudocode: ``` returnvalue = false if len(a) == len(b) if len(a) < threshold returnvalue = (sorted(a) == sorted(b)) else returnvalue = naminsmethod(a, b) return returnvalue ``` If performance is critical, and string size...
Here is a way which is O(n), asymptotically better than the two ways you suggest. ``` import collections def same_permutation(a, b): d = collections.defaultdict(int) for x in a: d[x] += 1 for x in b: d[x] -= 1 return not any(d.itervalues()) ## same_permutation([1,2,3],[2,3,1]) #. True...
Checking if two strings are permutations of each other in Python
[ "", "algorithm", "python", "" ]
Is it possible to determine which submit button was used? I have a confirmation form with 2 submit buttons. The first would confirm the order, do some DB tasks, then redirect. The second, which is a Cancel button, will just redirect to the same page, without doing any DB tasks. Is it possible in the servlet, preferabl...
``` <button name="someName" value="someValue" type="submit">Submit</button> <button name="otherName" value="otherValue" type="submit">Cancel</button> ``` You'll have `someName=someValue` or `otherName=otherValue` in your request data
Sure, just give each of your `submit` buttons a `name` attribute, and whichever one was clicked will appear in the submitted variables: ``` <input type="submit" name="doConfirm" value="Confirm" /> <input type="submit" name="doCancel" value="Cancel" /> ```
Determining which submit button was used?
[ "", "java", "html", "http", "forms", "servlets", "" ]
I'm working on a project that uses an MDI application with a navigation panel on the side. Currently it is a ListView. However, I would like to redesign it to be similar to the toolbox in visual studio 2008. If this is something that would require overriding the default paint method, it would also help if you could pr...
You want to be using a ToolBox control. A few freely available ones are available the most friendly that i've used being by Gordon Robinson at: <http://gordondrobinson.com/post/Toolbox-control-written-in-C.aspx>
Have a look at the Nevron User Interface: <http://www.nevron.com/Products.UserInterfaceFor.NET.Overview.aspx>
Looking for a Visual Studio toolbox style navigation for desktop applications
[ "", "c#", ".net-2.0", "navigation", "mdi", "" ]
I know the question title isn't the best. Let me explain. I do a TON of text processing which converts natural language to xml. These text files get uploaded fairly fast and thrown into a queue. From there they are pulled one-by-one into a background worker that calls our parser (using boost spirit) to transform the t...
I would buy a couple of cheap computers and do the text processing on those. As Jeff says in his [latest post](http://www.codinghorror.com/blog/archives/001198.html), "Always try to **spend your way out of a performance problem first** by throwing faster hardware at it."
Perhaps just placing the background worker at a lower scheduling priority (e.g. using [nice](http://en.wikipedia.org/wiki/Nice_(Unix))) would help. This means that your server can handle requests when it needs to, but when it's not busy you can go full blast with the text processing. Methinks it will give you much mor...
How do I do lots of processing without gobbling cpu?
[ "", "c++", "ruby", "memory", "cpu", "scaling", "" ]
I'm trying to recreate the iPhone flick / scroll event in a window using JavaScript. Starting with JQuery, I'm measuring the mouse's acceleration and offset during click - drag - release events using a timer: ``` var MouseY = { init: function(context) { var self = this; self._context = context ||...
Hit up this link for the full explanation of one approach that seems to be what you're looking for. <http://www.faqts.com/knowledge_base/view.phtml/aid/14742/fid/53> Here's an excerpt: > This handler then sets up event > capture for mouse movement and stores > mouse cursor positions in variables > mouseX and mouseY....
Here's what I found when looking for kinetic/momentum scrolling libraries: * [iScroll](http://cubiq.org/iscroll) * [Zynga Scroller](https://github.com/zynga/scroller) * [Overscroll](http://www.azoffdesign.com/plugins/js/overscroll) * [TouchScroll](http://uxebu.com/blog/2010/09/15/touchscroll-0-2-first-alpha-available/...
Javascript iPhone Scroll Effect in an iFrame / Javascript Mouse Acceleration
[ "", "javascript", "jquery", "iphone", "iframe", "acceleration", "" ]
I have the following code, which splits up a Vector into a string vector (to use as a key) and an integer at the end (to use as value). ``` payoffs.put(new Vector<String>(keyAndOutput.subList(0, keyAndOutput.size() - 1)), Integer.parseInt(keyAndOutput.lastElement())); ``` The TreeMap in question is constructed using ...
Answering Not answering the question, with but a couple minor points besides about your code: 1. You should not do the compareTo twice; compare once and assign the result to sgn; then break if !=0 2. Your else continue is redundant. 3. You should not compare for -1 or 1, but <0 or >0; many compareTo methods return bas...
I don't know if this is the cause of your problem, but compare functions in Java usually return negative or positive or 0, not necessarily 1 or -1. I am willing to bet that you are somehow getting a nonzero value from compareToIgnoreCase, but because it's not 1 or -1 you fall through, and end up returning 0 even thoug...
Strange behavior of Java's TreeMap put() method
[ "", "java", "collections", "vector", "treemap", "" ]
I'm writing a component and would like to insert images from the template folder. How do you get the correct path to the template folder?
IIRC, the $mainframe global object is eventually going away. Here is a way to do it through the framework: ``` $app = JFactory::getApplication(); $templateDir = JURI::base() . 'templates/' . $app->getTemplate(); ```
What kind of path... On filesystem: ``` $templateDir = JPATH_THEMES.DS.JFactory::getApplication()->getTemplate().DS; ```
How to get the path to the current template in Joomla 1.5?
[ "", "php", "joomla", "joomla1.5", "" ]
I'm currently searching for a Java networking library. What I want to do is sending XML, JSON or other serialized messages from a client to another client and/or client to server. My first attempt was to create an POJO for each message, plus a MessageWriter for sending and a MessageReader for receiving it. Plus socket...
Ah... gotcha. But rather than using code gen. to marshall and unmarshall, if you have Java on both ends, could you use simple object serialization ? If performance and/or message size is a concern, you could make your Message class externalizable. I had not looked at Protobuf before. Looks pretty decent. Using that, y...
You have several options depending on how abstracted from raw sockets you want to get. Once you depart from socket level programming, you're pretty much into *remoting* territory, * Standard Remoting Options for Java: RMI or JMS * Implement JMX Mbeans in each client and the servers and use JMX remoting to invoke messa...
Is there a good Java networking library?
[ "", "java", "networking", "serialization", "" ]
As I understand the standard, a trivial destructor is one which is implicitly declared and whose class has only base and non-static members with trivial destructors. Given the recursivity of this definition, it seems to me that the only "recursion-stopping" condition is to find a base or non-static member with a non-im...
No. An implicitly defined, trivial destructor is by definition trivial :) The difference between the declare and define thingy is that in order for the compiler to even *see* that a destructor is available, there must always a declaration. So if you don't provide one, it will implicitly provide one. But now, it will a...
Your wording is a bit unfortunate. E.g. the recursion of course also ends when you run out of members and base classes. Those wording problems also seem to get you more confused. Anyway, all implicitly-declared destructors, whether they are trivial or not, are defined if and only if they are used. *Used* is a specific...
destructors: triviality vs implicit definition
[ "", "c++", "destructor", "" ]
I have been noticing `__construct` a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP. I was wondering if someone could give me a general idea of what it is, and then a simple example of how it is used with PHP?
`__construct` was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor). You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one. An example could go li...
`__construct()` is the method name for the [constructor](https://www.php.net/manual/en/language.oop5.decon.php). The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc. ``` class Person { public function __construct() { // Code called for ...
What is the function __construct used for?
[ "", "php", "constructor", "" ]
If I use null as a representation of everything in a database table is that bad practice ? i.e. I have the tables: myTable(ID) and myRelatedTable(ID,myTableID) myRelatedTable.myTableID is a FK of myTable.ID What I want to accomplish is: if myRelatedTable.myTableID is null then my business logic will interpret that ...
I don't think NULL is the best way to do it but you might use a separate tinyInt column to indicate that the row in MyRelatedTable is related to everything in MyTable, e.g. MyRelatedTable.RelatedAll. That would make it more explicit for other that have to maintain it. Then you could do some sort of Union query e.g. ``...
I think you might agree that it would be bad to use the number **3** to represent a value other an **3**. By the same reasoning it is therefore a bad idea to use NULL to represent anything other than the absence of a value. If you disagree and twist NULL to some other purpose, the maintenance programmers that come af...
Is using Null to represent a Value Bad Practice?
[ "", "sql", "database-design", "" ]
I wish to create a very simple web app that simply displays an Image(s) from a database based upon either a date (from a calendar click event) or from a keyword search, getting the image(s) is no problem but I don't know how to display the resulting image. Preferably I would like to display the image in a table or grid...
Take a look at the DynamicImageHandler for ASP.NET up on the CodePlex ASP.NET Futures site: <http://www.hanselman.com/blog/ASPNETFuturesGeneratingDynamicImagesWithHttpHandlersGetsEasier.aspx>
If you don't have the physical file on hand, try using: `Response.OutputStream.Write(bitmapbuffer, bitmapbuffer.Length)` I've done this in the past to dynamically serve pdfs and tifs, and it works quite nicely. You'll need to set your img's src attribute to contain the information you need. This web site has an examp...
displaying an image from a bitmap variable using codebehind
[ "", "c#", "asp.net", "image", "code-behind", "" ]
I find it funny that Java (or the java.util library) does not have a built-in function to calculate difference in dates. I want to subtract one date from another to get the elapsed time between them. What is the best way to do this? I know the simple way is to take the difference of the time in milliseconds and then c...
> I know the simple way is to take the > difference of the time in milliseconds > and then convert that into days. > However, i wanted to know if this > works in all cases (with daylight > saving, etc.). If your times are derived from UTC dates, or they are just the difference between two calls to System.getCurrentTim...
Java's not missing much, if you look at open source: try [Joda-Time](http://www.joda.org/joda-time/).
Calculating difference in dates in Java
[ "", "java", "date", "datetime", "date-arithmetic", "" ]
I've got a small app that searches for and stores the names of a large number of files at start-up. I'm splitting this search into several Thread objects that each search one directory, and push results back to the main thread. When the app loads, I go through each thread and load it: ``` foreach(Thread t in m_thread...
It may not be exactly related to why things are freezing, but your implementation is quite questionable. You enumerate over a collection of threads, start each one, but then block until the thread is finished? I think what you may have meant to do is start all threads, then block until all threads have finished. (Note:...
The thread may have finished processing before your check against IsAlive. WHy are you waiting by checking the IsAlive flag anyway? Why not, instead, fire up all the threads, then in another loop, call [Join()](http://msdn.microsoft.com/en-us/library/system.threading.thread.join.aspx) to wait for the threads to finis...
c# thread starts from debugger, but won't start stand-alone
[ "", "c#", "multithreading", "" ]
The current class library I am working on will have a base class (Field) with over 50 specific "field" types which will inherit from "Field" and nested for maintain readability. For example... ``` abstract class Field { public int Length { get; set; } public class FieldA : Field { public static vo...
Sounds like you wanted something like: ``` abstract class Field { public int Length { get; set; } } public class FieldA : Field { public static void DoSomething() { Console.WriteLine("Did something."); } } ``` Otherwise you're defining a base class with an inner class in it, which inheritorrs...
1. `Field` has a *public* nested-class named `FieldA` 2. `FieldA` inherits from `Field` 3. thus you can always access `FieldA` from `FieldA`. The reference isn't creating infinite chains, it is simply pointing to the same class. ([some test code](http://pastebin.com/f6d5f0e5f)) When you access `FieldA.FieldA`, the la...
.NET Nested Classes
[ "", "c#", ".net", "boo", "nested-class", "class-structure", "" ]
I have some AJAX work that brings across an additional form element that I don't need in the DOM. I don't have the ability to remove it server side, so I'm looking for some jQuery or classic JavaScript that will allow me to capture all the child elements of the form, remove the form I don't need and finally re-append t...
Rather than using the `.html()` method (which will cause you to lose any events associated with form elements) you should move the child nodes: ``` // grab the child nodes var children = $('#badForm').children(); // or var children = $('#badForm > *'); // move them to the body $(body).append(children); // remove the...
If you have ajax code like this: ``` $.ajax({ type: "get", url: "url", data: , cache: false, success: function(data){ } }); ``` You can add on `success` function this: ``` $(data).find('#whatYouNeed').appendTo('#whereYouNeed') ``` In this way you can extract anything you want from that page...
Using jQuery to remove a second form element without losing the child elements
[ "", "javascript", "jquery", "" ]
What's difference between **shadowing** and **overriding** a method in C#?
Well inheritance... suppose you have this classes: ``` class A { public int Foo(){ return 5;} public virtual int Bar(){return 5;} } class B : A{ public new int Foo() { return 1;} //shadow public override int Bar() {return 1;} //override } ``` then when you call this: ``` A clA = new A(); B clB = new...
Shadowing is actually VB parlance for what we would refer to as hiding in C#. Often hiding (shadowing in VB) and overriding are shown as in answer by [Stormenet](https://stackoverflow.com/users/2090/stormenet). A virtual method is shown to be overridden by a sub-class and calls to that method even on the super-class ...
Difference between shadowing and overriding in C#?
[ "", "c#", "" ]
I have been testing out the `yield return` statement with some of the code I have been writing. I have two methods: ``` public static IEnumerable<String> MyYieldCollection { get { wrapper.RunCommand("Fetch First From Water_Mains"); for (int row = 0; row < tabinfo.GetNumberOfRow...
How have you done your timings? Are you in the debugger? In debug mode? It looks like you are using `DataTable`, so I used your code as the template for a test rig (creating 1000 rows each time), and used the harness as below, in release mode **at the command line**; the results were as follows (the number in brackets ...
What happens if one iteration of your loop is expensive and you only need to iterate over a few items in your collection? With yield you only need to pay for what you get ;) ``` public IEnumerable<int> YieldInts() { for (int i = 0; i < 1000; i++) { Thread.Sleep(1000) // or do some other work y...
Why is my IEnumerable<String> using yield return slower to iterate then List<String>
[ "", "c#", "ienumerable", "" ]
For web development what are some standard/good java tools. That apply to all aspects of development. For example, The IDE (Eclipse, RAD, Intellij) is important, but what else is there. Ant is a good one. Cygwin, Linux OS possibly.
Another good IDE for Java web development I use is [Netbeans](http://www.netbeans.org/). Has many useful features version control, debugger, profiler, api access etc ... You can edit, build, test, and run all inside of the IDE.
Before trying to write a piece of code check if it is implemented in some library. Great source of common programming task solutions can be found in [Apache Commons libraries](http://commons.apache.org).
What are some good Java web development tools (across the board)
[ "", "java", "" ]
Consider this code (Java, specifically): ``` public int doSomething() { doA(); try { doB(); } catch (MyException e) { return ERROR; } doC(); return SUCCESS; } ``` Where `doB()` is defined as: ``` private void doB() throws MyException ``` Basically, `MyException` exists only...
It entirely depends on what that error condition is, and what the method's job is. If returning `ERROR` is a valid way of handling that error for the calling function, why would it be bad? Often, however, it *is* a smell. Consider this: ``` bool isDouble(string someString) { try { double d = Convert.Parse...
Is it really important for doC() to be executed when doB() fails? If not, why not simply let the Exception propagate up the stack to where it can be handled effectively. Personally, I consider using error codes a code smell. **Edit:** In your comment, you have described exactly the scenarion where you should simply de...
Throwing exceptions to control flow - code smell?
[ "", "java", "exception", "" ]
I'm aware of the risks of rolling your own user authentication scripts, but I'm also wary of using packages that don't seem to be actively maintained: the [current version of PEAR LiveUser](http://pear.php.net/package/LiveUser/download/) is almost a year old. Please recommend (and argue the case for) an actively-maint...
It looks to me like PEAR hasn't changed much because it's stable. I wouldn't be afraid of using it.
It sounds like what you want is a user control library, rather than an authentication library. For example, in the [Zend Framework](http://framework.zend.com) there are two classes: [`Zend_Auth`](http://framework.zend.com/manual/en/zend.auth.html) (which handles user authentication: logins (e.g. [simple database table...
Actively maintained PHP libraries for user authentication?
[ "", "php", "security", "authentication", "" ]
I am working on my first project using ExtJS. I have a Data Grid sitting inside a Tab that is inside a Window. I want to add a link or button to the each element of the grid (I am using extended elements at the moment with HTML content through the RowExpander) that will make an AJAX call and open another tab.
I actually worked this out in the end. Pretty convoluted, and let's just say I will not be involving myself with ExtJS again if I can help it. I am using the Grid.RowExpander to place HTML inside the Grid using XTemplate. My links are therefore fairly straight forward: ``` <a href="#" class="add_cart_btn" id="{produc...
If you are looking to add the link to the grid itself, you can specify another column in your ColumnModel and apply a renderer to the column. The function of the renderer is to return formatted content to be applied to that cell, which can be tailored according to the value of the dataIndex of the column (you should ha...
ExtJS: AJAX Links in Grid in Tab in Window
[ "", "javascript", "extjs", "" ]
I rewrite URLs to include the title of user generated travelblogs. I do this for both readability of URLs and SEO purposes. ``` http://www.example.com/gallery/280-Gorges_du_Todra/ ``` The first integer is the id, the rest is for us humans (but is irrelevant for requesting the resource). Now people can write titles...
Ultimately, you're going to have to give up on the idea of "correct", for this problem. Translating the string, no matter how you do it, destroys accuracy in the name of compatibility and readability. All three options are equally compatible, but #1 and #2 suffer in terms of readability. So just run with it and go for ...
To me the third is most readable. You could use a little dictionary e.g. `ï -> i` and `ü -> ue` to specify how you'd like various charcaters to be translated.
How to handle diacritics (accents) when rewriting 'pretty URLs'
[ "", "php", "url-rewriting", "diacritics", "" ]
I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv. What's the quickest way to get something up? If it ...
Have a look at [werkzeug](http://werkzeug.pocoo.org/). Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache...
[web.py](http://webpy.org/) is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something. "Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command di...
Best way to create a simple python web service
[ "", "python", "web-services", "" ]
I understand that const\_cast to remove constness of objects is bad, I have the following use case, ``` //note I cannot remove constness in the foo function foo(const std::vector<Object> & objectVec) { ... int size = (int) objectVec.size(); std::vector<Object> tempObjectVec; //Indexing here is to just sh...
Well, that depends on Object. But the Objects *are* being copied, when you pass them to push\_back. You can check this by adding some debug code to the copy constructor. So if Object is well-behaved and keeps distinct copies separate, then foo1 can change the vector it gets all it likes. A more efficient way to do thi...
Your `tempObjectVec` can't be a vector of references, so I presume it should be declared as something like: ``` std::vector<Object> tempObjectVec; ``` When you execute the `tempObjectVec.push_back(a)`, a copy of the object will be made to push it into the `tempObjectVec` vector. Since this is making a copy, you shoul...
const_cast for vector with object
[ "", "c++", "" ]
Is it possible to call a [VBScript](http://en.wikipedia.org/wiki/VBScript) function from a [JavaScript](http://en.wikipedia.org/wiki/JavaScript) call, or alternately call JavaScript from a VBScript call?
Yes, if your main script is a [Windows Script File](http://msdn.microsoft.com/en-us/library/15x4407c.aspx) (WSF). WSF files can include other script files and execute code from multiple engines.
**Calling a VBScript function from Javascript** Your VBScript: ``` Function myVBFunction() ' here comes your vbscript code End Function ``` Your Javascript: ``` function myJavascriptFunction(){ myVBFunction(); // calls the vbs function } window.onload = myJavascriptFunction; ``` **Calling a Javascrip...
Calling VBScript from JavaScript or vice versa?
[ "", "javascript", "asp-classic", "vbscript", "" ]
in terms of both parsing (serializing, deserializing) and sending packets over the network is there any good estimation of performance differences between binary and xml serialization?
Nope. It depends highly on what sort of data is inside the XML document itself. If you have a lot of structured data, the overhead for XML will be large. For example, if your data looks like: ``` <person> <name>Dave</dave> <ssn>000-00-0000</ssn> <email1>xxxxxx/email1> </person> ... ``` You'll have a lot more o...
The biggest difference between `BinaryFormatter` and xml serialization is portability; BinaryFormatter is hard to guarantee between versions, so is only really suitable for shortterm storage or transfer. However, you can get the best of both, *and* have it smaller *and* have it quicker, by using bespoke binary seriali...
Is there any perfomormance differences between binary and XML serialization?
[ "", "c#", "xml", "binary-data", "" ]
I often use an `ArrayList` instead of a 'normal' `array[]`. I feel as if I am cheating (or being lazy) when I use an `ArrayList`, when is it okay to use an `ArrayList` over an array?
Arrays are strongly typed, and work well as parameters. If you know the length of your collection and it is fixed, you should use an array. ArrayLists are not strongly typed, every Insertion or Retrial will need a cast to get back to your original type. If you need a method to take a list of a specific type, ArrayList...
In addition to Bob's and Frederick's response, I would like to point it out that while arrays have covariance, generic lists do not. For example, an array of type `MyChildClass[]` can be easily casted to `MyParentClass[]`, while `List<MyChildClass>` cannot be casted to `List<MyParentClass>`, at least not directly. If ...
When to use ArrayList over array[] in c#?
[ "", "c#", "arrays", "arraylist", "" ]
Years ago I learned the hard way about precision problems with floats so I quit using them. However, I still run into code using floats and it make me cringe because I know some of the calculations will be inaccurate. So, when is it appropriate to use a float? **EDIT:** As info, I don't think that I've come across a ...
Short answer: You only have to use a **float** when you know exactly what you're doing and why. Long answer: **floats** (as opposed to **doubles**) aren't really used anymore outside 3D APIs as far as I know. Floats and doubles have the same performance characteristics on modern CPUs, doubles are somewhat bigger and t...
All floating point calculations are inaccurature in a general case, floats just more so than doubles. If you want more information have a read of [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) As for when to use floats - they are often...
When to use a Float
[ "", "c#", "types", "floating-point", "" ]
Are there any good tools available to track memory usage In a tomcat java webapp? I'm looking for something that can give a breakdown by class or package. Thanks, J
I use the Netbeans IDE and it is able to profile any type of Java project including webapps. Once you have the project setup in Netbeans you just click Profile and answer a few easy questions. It is very easy to create a new project and import your existing code into it. You can see screenshots of this here: <http://...
[jconsole](http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html#memory) can give you summary statistics. I've used it in the past while load testing to infer the size of loaded classes (by noting the before and after usage when loading LOTS of objects.) Note that the usage keeps going UP until a garbage c...
Tracking memory usage in a tomcat webapp
[ "", "java", "memory", "" ]
How can I achieve the following with a format string: Do 01.01.2009 ? It has to work in all languages (the example would be for Germany). So there should only be the short weekday and then the short date. I tried 'ddd d' (without the '). However, this leads to 'Do 01'. Is there maybe a character I can put before the '...
``` DateTime.Now.ToString("ddd dd/MM/yyyy") ```
You should be using the [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) standard if you are targeting audiences with varied spoken languages. ``` DateTime.Now.ToString("ddd yyyy-MM-dd"); ``` Alternatively, you can target the current culture with a short date: ``` DateTime.Now.ToString("d", Thread.CurrentThread.Cur...
How to format a Date without using code - Format String Question
[ "", "c#", "datetime", "formatting", "" ]
I have a C#/.Net job that imports data from Excel and then processes it. Our client drops off the files and we process them. I don't have any control over the original file. I use the OleDb library to fill up a dataset. The file contains some numbers like 30829300, 30071500, etc... The data type for those columns is "...
The OleDb library **will**, more often than not, mess up your data in an Excel spreadsheet. This is largely because it forces everything into a fixed-type column layout, *guessing* at the type of each column from the values in the first 8 cells in each column. If it guesses wrong, you end up with digit strings converte...
One workaround to this issue is to change your select statement, instead of SELECT \* do this: ``` "SELECT Format([F1], 'General Number') From [Sheet1$]" -or- "SELECT Format([F1], \"#####\") From [Sheet1$]" ``` However, doing so will blow up if your cells contain more than 255 characters with the following error: ...
Scientific notation when importing from Excel in .Net
[ "", "c#", ".net", "excel", "oledb", "" ]
I am trying to read CSS selectors in my stylesheets with the `document.styleSheets` array. It works fine with `<link>` and `<style>` tags, but when I use `@import` inside a `<style>` it doesn't show up in the array - only as a cssRule (style is "Undefined" in Safari 3 and FF 3). So: How can I parse the css in an @impo...
Assuming that our document contains an @import-rule as first rule in the first stylesheet, here's the code for standards compliant browsers ``` document.styleSheets[0].cssRules[0].styleSheet.cssRules; ``` and the special case for our all-beloved IE ``` document.styleSheets[0].imports[0].rules; ``` You could have ea...
> Check this page - which further links to this one on quirksmode.org. Thanks, but I have tried that... the Quirksmode examples never parse stylesheets embedded with @import. If I have this HTML/CSS: ``` <link rel="stylesheet" type="text/css" href="css/test1.css" /> <style type="text/css"> @import url('css/tes...
How do I parse @import stylesheets with Javascript
[ "", "javascript", "css", "" ]
I am writing an application to manage user access to files. The short version of a very long story is that I have to use directory and file priveleges to do it. No document management system for our cheap CEO... Anyway... I have everything working except the case where the user can view which files are in the director...
The FileSystemRights enum maps both ReadData and ListDirectory to the value 1, so the two are 100% equivalent as far as .NET is concerned. Have you tried Traverse as opposed to ListDirectory? Edit: Based on [this](http://support.microsoft.com/kb/308419) KB article it appears that Windows XP considers them to be the s...
The files are probably inheriting the security properties from parent. You may try calling [DirectorySecurity.SetAccessRuleProtection(true, false)](http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.objectsecurity.setaccessruleprotection.aspx) to prevent the files from inheriting, before calling Dir...
C# File/Directory Permissions
[ "", "c#", "" ]
For domain entities, should property names be prefaced with the entity name? I.E. my class Warehouse has a property WarehouseNumber. Should that property be named WarehouseNumber or simply Number? Thoughts?
I prefer not using the prefix, I find it easier to type, and more readable, the context of what the entity is almost always apparent.
Think of the concepts you are representing, the context in which they appear, and their relative frequency. In this case, the pieces of data are `Warehouse` and `Number`. In the context of a `Warehouse`, `Number` is properly qualified. Outside of a `Warehouse`, `WarehouseNumber` would be properly qualified, i.e. `Orde...
Domain Entity Property Names
[ "", "c#", "class", "dns", "" ]
I am writing code to migrate data from our live Access database to a new Sql Server database which has a different schema with a reorganized structure. This Sql Server database will be used with a new version of our application in development. I've been writing migrating code in C# that calls Sql Server and Access and...
I personally would divide the process into two steps. 1. I would create an exact copy of Access DB in SQLServer and copy all the data 2. Copy the data from this temporary SQLServer DB to your destination database In that way you can write set of SQL code to accomplish second step task Alternatively use [SSIS](http:/...
Generally when you convert data to a new database that will take it's place in porduction, you shut out all users of the database for a period of time, run the migration and turn on the new database. This ensures no changes to the data are made while doing the conversion. Of course I never would have done this using c#...
Queries for migrating data in live database?
[ "", "sql", "sql-server", "ms-access", "migration", "" ]
I need to create a structure or series of strings that are fixed lenght for a project I am working on. Currently it is written in COBOL and is a communication application. It sends a fixed length record via the web and recieves a fixed length record back. I would like to write it as a structure for simplicity, but so f...
As an answer, you should be able to use char arrays of the correct size, without having to marshal. Also, the difference between a class and a struct in .net is minimal. A struct cannot be null while a class can. Otherwise their use and capabilities are pretty much identical. Finally, it sounds like you should be min...
Add the MarshalAs tag to your structure. Here is an example: ``` <StructLayout (LayoutKind.Sequential, CharSet:=CharSet.Auto)> _ Public Structure OSVERSIONINFO Public dwOSVersionInfoSize As Integer Public dwMajorVersion As Integer Public dwMinorVersion As Integer Public dwBuildNumber As Integer Pub...
Fixed length strings or structures in C#
[ "", "c#", ".net", "vb.net", "" ]
Can anyone point me to a site, or give me some wisdom on how you go about choosing names for interfaces, classes and perhaps even methods and properties relating to what that object or method does? This is specifically for Microsoft development, so Java-esque "doGet" and so on isn't really used, however some general r...
Look at the [MSDN articles](http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx) for naming guidelines. In short: * Use nouns for class names and property names (it's obvious) * For interface names, start with I and use nouns and/or adjectives to describe behavior * Use verbs for method names to describe acti...
Interfaces are things a class is capable of doing. Not what it **is**, but what it can **do**. ``` IGroupableItem ``` Other names describe what things are or are too vague to be useful. Specifically, "IDataEntity" is largely meaningless. After all, everything's a data entity.
Naming conventions: Guidelines for verbs/nouns and english grammar usage
[ "", "c#", ".net", "naming-conventions", "" ]
I am C# developer. I really love the curly brace because I came from C, C++ and Java background. However, I also like the other programming languages of the .NET Family such as VB.NET. Switching back and forth between C# and VB.NET is not really that big of deal if you have been programming for a while in .NET. That is...
I wouldn't be suprised if "With" or a similar feature is added to C# eventually along with other heretofore popular exclusively VB features. There was a lot of talk in the C# 4.0 preview presentations recently at PDC and elsewhere of the increased "focus on language parity" starting with C# 4.0 and VB 10.
Personally I don't like WITH when it's used after construction - if you need to do several things with an object after it's initialized, usually that behaviour should be encapsulated in the type itself. If you really want to do something like WITH, it's only a matter of declaring a short variable and optionally introdu...
Why is the with() construct not included in C#, when it is really cool in VB.NET?
[ "", "c#", "vb.net", "with-statement", "" ]
How do you manage your php codes? Do you prefer functioning within one php file or including larger blocks of "raw code"? Edit: In fact, my code is pretty nasty, as I don't use any namespaces and classes - only functions and including. I shall look the classes up ^^.
If you are using php classes, this will sort itself out. If you are not, then it's really hard to give an acceptable answer, except that you should learn to. All php code I've seen done either way without classes seems to become quickly messy.
Use them as you need them. I use include for chunks of big code doing processing, and functions for "utility" functions. Sometines i use includes within function also... it really depends on how clean you like your code. Think that many includes means more fopen() from the PHP module, and those can slow doewn the whol...
Do you prefer functioning or including within one php file?
[ "", "php", "function", "include", "" ]
I am looking to find a librray that emulates part of the capabilities of Ruby's ERB library. ie substitute text for variables between <% and %>. I dont need the code execution part that ERB provides but if you know of something that has this I would be super appreciative.
Have a look at [TemplateMachine](http://www.stefansarstedt.com/templatemaschine.html), I haven't tested it, but it seems to be a bit ERB-like.
I modified a class I used to test some things a while ago. It's not even nearly as good as ERB but it gets the job done substituting text. It only works with properties though, so you might want to fix that. **Usage:** ``` Substitutioner sub = new Substitutioner( "Hello world <%=Wow%>! My name is <%=Name%>"); My...
ERB like library for C#
[ "", "c#", "ruby", "templates", "erb", "" ]
How do I set Java's min and max heap size through environment variables? I know that the heap sizes can be set when launching java, but I would like to have this adjusted through environment variables on my server.
You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.) Some products like Ant or Tomcat mi...
If you want any `java` process, not just ant or Tomcat, to pick up options like `-Xmx` use the environment variable `_JAVA_OPTIONS`. In bash: `export _JAVA_OPTIONS="-Xmx1g"`
How do I set Java's min and max heap size through environment variables?
[ "", "java", "environment-variables", "heap-memory", "" ]
I have a Visual Studio solution that comprises of several projects and are separated into different directories. In my C# or VB.NET code, I want to determine the base directory (or the directory that the solution is in). A dirty solution would be to call the directory `parent.parent.parent` until I find a file \*.sln...
As the sln file does not need to be deployed on the target machine - why are you trying to find it at all? If you still want to use the sln- try at [EnvDTE Namespace](http://msdn.microsoft.com/en-us/library/envdte._solution_members(VS.80).aspx) > EnvDTE.DTE dte = (EnvDTE.DTE) System.Runtime.InteropServices.Marshal.G...
Even though you have solutions in other directories, presumably those aren't directories within your original solution, are they? What situation do you envisage where the "recurse up until you find a .sln file" would fail (other than running from the wrong directory)? One alternative would be to pass the solution dire...
How to return the Visual Studio currently open soution directory
[ "", "c#", ".net", "vb.net", "visual-studio", "ide", "" ]
For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can g...
ImageMagic is a huge library and will do everything under the sun, but many report memory issues with the RMagick variant and I have personally found it to be an overkill for my needs. As you say ruby-gd is a little thin on the ground when it comes to English documentation.... but GD is a doddle to install on post pla...
PIL is a good library, use it. ImageMagic (what RMagick wraps) is a very heavy library that should be avoided if possible. Its good for doing local processing of images, say, a batch photo editor, but way too processor inefficient for common image manipulation tasks for web. **EDIT:** In response to the question, PIL ...
PIL vs RMagick/ruby-gd
[ "", "python", "ruby", "python-imaging-library", "rmagick", "" ]
How to script a constraint on a field in a table, for an acceptable range of values is between 0 and 100?
``` ALTER TABLE Table ADD CONSTRAINT CK_Table_Column_Range CHECK ( Column >= 0 AND Column <= 100 --Inclusive ) ```
Try: ``` ALTER TABLE myTableName ADD CONSTRAINT myTableName_myColumnName_valZeroToOneHundred CHECK (myColumnName BETWEEN 0 AND 100) ``` This check would be inclusive - here is some info about BETWEEN from MSDN: [BETWEEN (Transact SQL)](http://msdn.microsoft.com/en-us/library/ms187922(SQL.90).aspx)
Script SQL constraint for a number to fall within a Range?
[ "", "sql", "sql-server", "constraints", "" ]
I am conducting some throughput testing. My application has to 1. read from JMS 2. do some processing 3. write to JMS My goal here is to simulate #2, 'some processing'. That is, introduce a delay and occupy the CPU for a given time (e.g. 500ms) before forwarding the event. The naive approach would be to `Thread.slee...
Encrypt a string (in a loop) by calling Cipher.update(). Encryption algorithms are by definition very difficult to optimize. The only problem is that there is some non-trivial setup you need to perform. I'm marking this answer as community wiki, so that somebody who's written it recently can fill it in.
You could try something simple like ``` private static void spin(int milliseconds) { long sleepTime = milliseconds*1000000L; // convert to nanoseconds long startTime = System.nanoTime(); while ((System.nanoTime() - startTime) < sleepTime) {} } ``` Test: ``` public static void main(String[] args) { fi...
generate CPU load in Java
[ "", "java", "encryption", "load", "cpu", "" ]
I'm working on a program that uses PHP's internal array pointers to iterate along a multidimensional array. I need to get an element from the current row, and I've been doing it like so: ``` $arr[key($arr)]['item'] ``` However, I'd much prefer to use something like: ``` current($arr)['item'] // invalid syntax ``` I...
I very much doubt there is such a function, but it's trivial to write ``` function getvalue($array, $key) { return $array[$key]; } ``` Edit: As of PHP 5.4, you can index array elements directly from function expressions, `current($arr)['item']`.
Have you tried using one of the [iterator classes](http://php.net/manual/en/spl.iterators.php) yet? There might be something in there that does exactly what you want. If not, you can likely get what you want by extending the ArrayObject class.
Access PHP array element with a function?
[ "", "php", "arrays", "" ]
I have an ASP.NET web application that calls a .NET DLL, that in turn calls a web service. The web service call is throwing an exception: > Unable to generate a temporary class > (result=1). error CS0001: Internal > compiler error (0xc00000fd) error > CS0003: Out of memory > > Stack Trace: at > System.Xml.Serializatio...
Well, I'm not sure exactly **why** this worked (which is frustrating), but I did come up with something... My previous install of Windows was 32-bit, but when I rebuilt my PC recently, I went with the 64-bit version. So, I changed the "Enable 32-Bit Applications" setting on my application pool in IIS to "True", and ev...
Thanks for adding more detail. Have a look at this link: <http://support.microsoft.com/?kbid=908158> It's similiar to the problem you're having. It recommends the following: To resolve this issue, grant the user account the List Folder Contents and Read permissions on the %windir%\Temp folder. This one: <http://...
"Out of memory" exception on call to web service
[ "", "c#", "asp.net", "web-services", "" ]
Hopefully the title is self explanatory, what is the advantage of using the .call() method in Javascript compared with just writing functionName(); ?
[`functionName.call()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/call) takes an object instance as its first parameter. It then runs `functionName` within the context of that object instance (ie "this" is the specified instance)
If you don't pass anything into `call()`, it will be the same; the function will be run with the same scope that the call to `call()` is made: ``` function test() { alert(this); } test(); // alerts the window object test.call(); // alerts the window object ``` But if you pass an object into `call()`, that object...
difference between functionName() and functionName.call() in javascript
[ "", "javascript", "" ]
So I'm refactoring a legacy codebase I've inherited, and in the process I found a static class that encapsulates the logic for launching 3rd party applications. It essentially looks like this (shortened for brevity to only show one application): ``` using System.IO; using System.Configuration; public static class Exte...
Here is another way of refactoring this: ``` using System.IO; public class ExternalApplication { public ExternalApplication(string path) { this.Path = path; } public string Path { get; protected set; } public bool Exists() { if(string.IsNullOrEmpty(this.Path)) throw new Config...
Seems reasonable to me. I did something similar in the past, but I didn't have an abstract base class. Instead I passed in the application path in the constructor.
.NET Class Refactoring Dilemma
[ "", "c#", ".net", "oop", "refactoring", "" ]
I am building an application that queries a web service. The data in the database varies and changes over time. How do I build a unit test for this type of application? The web service sends back xml or a no search results html page. I cannot really change the web service. My application basically queries the web serv...
Abstract out the web service using a proxy that you can mock out. Have your mock web service return various values representing normal data and corner cases. Also simulate getting exceptions from the web service. Make sure you code works under these conditions and you can be reasonably certain that it will work with an...
Strictly speaking of unit-testing, you can only test units that have a **deterministic behavior**. A test that connects to an external web server is an **integration test**. The solution is to mock the HTTPURLConnection - that is, create a class in your unit tests that derives from HTTPURLConnection class and that re...
How do you make a unit test when the results vary?
[ "", "java", "unit-testing", "integration-testing", "" ]
i need help with disk\_total\_space function.. i have this on my code ``` <?php $sql="select * from users order by id"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)) { ?> Name : <?php echo $row['name']; ?> Email : <?php echo $row['email']; ?> Diskspace Available : <?p...
I think what you want is something like this: ``` function foldersize($path) { $total_size = 0; $files = scandir($path); foreach($files as $t) { if (is_dir(rtrim($path, '/') . '/' . $t)) { if ($t<>"." && $t<>"..") { $size = foldersize(rtrim($path, '/') . '/' . $t); ...
<https://www.php.net/disk_total_space> says, > "Given a string containing a directory, this function will return the total number of bytes on the **corresponding filesystem** or **disk partition**." You're likely seeing the total\_space of C: [Alternative solutions do exist for both Windows and Linux](http://forums....
php disk_total_space
[ "", "php", "directory", "" ]
I have coordinates from some source and want to tag my jpg files with them. What is the best python library for writing geotags into exif data?
[pexif](https://github.com/bennoleslie/pexif) was written with geotags as a goal (my emphasis): > pexif is a Python library for parsing and more importantly editing EXIF data in JPEG files. > > This grew out of **a need to add GPS tagged data to my images**, Unfortunately the other libraries out there couldn't do upda...
Here is an example how to set GPS position using pyexiv2 library. I've tested this script by uploading geotagged image to Panoramio ``` #!/usr/bin/env python import pyexiv2 import fractions from PIL import Image from PIL.ExifTags import TAGS import sys def to_deg(value, loc): if value < 0: loc_va...
What is the best way to geotag jpeg-images with python?
[ "", "python", "jpeg", "exif", "geotagging", "" ]
I've done quite a bit of research into this but it seems that the methods used are inconsistent and varied. Here are some methods I have used in the past: ``` /* 1: */ typeof myFunc === 'function' /* 2: */ myFunc.constructor === Function /* 3: */ myFunc instanceof Function ``` As part of my research I had a look ...
The best way to test if an object is a function is `typeof myFunc === 'function'`. If you are using a library, use that library's function test: `jQuery.isFunction(myFunc)`. Things *can* be misreported as functions when using `typeof`. This is very rare but a library is there to remove these inconsistencies. jQuery wo...
John Resig the developer of jQuery does seem to have made some bizarre choices in the internals of jQuery. ``` toString.call(obj) === "[object Function]" ``` looks quite neat but I can't think of any situation where the above would be true where the simple `typeof` approach would fail but perhaps he knows something t...
Best method of testing for a function in JavaScript?
[ "", "javascript", "function", "" ]
I have 3 byte arrays in C# that I need to combine into one. What would be the most efficient method to complete this task?
For primitive types (including bytes), use [`System.Buffer.BlockCopy`](https://learn.microsoft.com/en-us/dotnet/api/system.buffer.blockcopy) instead of [`System.Array.Copy`](https://learn.microsoft.com/en-us/dotnet/api/system.array.copy). It's faster. I timed each of the suggested methods in a loop executed 1 million ...
Many of the answers seem to me to be ignoring the stated requirements: * The result should be a byte array * It should be as efficient as possible These two together rule out a LINQ sequence of bytes - anything with `yield` is going to make it impossible to get the final size without iterating through the whole seque...
Best way to combine two or more byte arrays in C#
[ "", "c#", "arrays", "" ]
My experience with MySQL is very basic. The simple stuff is easy enough, but I ran into something that is going to require a little more knowledge. I have a need for a table that stores a small list of words. The number of words stored could be anywhere between 1 to 15. Later, I plan on searching through the table by t...
C) use a [normal form](http://en.wikipedia.org/wiki/Database_normalization); use multiple rows with appropriate keys. an example: ``` mysql> SELECT * FROM blah; +----+-----+-----------+ | K | grp | name | +----+-----+-----------+ | 1 | 1 | foo | | 2 | 1 | bar | | 3 | 2 | hydrogen | | 4 | ...
What other data is associated with these words? One typical way to handle this kind of problem is best described by example. Let's assume your table captures certain words found in certain documents. One typical way is to assign each document an identifier. Let's pretend, for the moment, that each document is a web UR...
MySQL design with dynamic number of fields
[ "", "php", "mysql", "database", "" ]
Is it possible to have a switch in C# which checks if the value is null or empty not "" but `String.Empty`? I know i can do this: ``` switch (text) { case null: case "": break; } ``` Is there something better, because I don't want to have a large list of IF statements? I'mm trying to replace: ``` if...
You can use pattern matching to test for string length (or other things). This code was tested in .NET 6 and .NET 7. ``` // Program.cs Console.WriteLine(PatternMatch(null)); Console.WriteLine(PatternMatch("")); Console.WriteLine(PatternMatch("Hello world!")); Console.WriteLine(PatternMatch("Blah!")); Console.WriteLin...
I would suggest something like the following: ``` switch(text ?? String.Empty) { case "": break; case "hi": break; } ``` Is that what you are looking for?
C# Switch with String.IsNullOrEmpty
[ "", "c#", "string", "switch-statement", "semantics", "" ]
Take the following class as an example: ``` class Sometype { int someValue; public Sometype(int someValue) { this.someValue = someValue; } } ``` I then want to create an instance of this type using reflection: ``` Type t = typeof(Sometype); object o = Activator.CreateInstance(t); ``` Normal...
I originally posted this answer [here](https://stackoverflow.com/questions/178645/how-does-wcf-deserialization-instantiate-objects-without-calling-a-constructor#179486), but here is a reprint since this isn't the exact same question but has the same answer: `FormatterServices.GetUninitializedObject()` will create an i...
Use this overload of the CreateInstance method: ``` public static Object CreateInstance( Type type, params Object[] args ) ``` > Creates an instance of the specified > type using the constructor that best > matches the specified parameters. See: <http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx>
Creating instance of type without default constructor in C# using reflection
[ "", "c#", "reflection", "instantiation", "default-constructor", "" ]
Curious if anyone has opinions on which method would be better suited for asp.net caching. Option one, have fewer items in the cache which are more complex, or many items which are less complex. For sake of discussion lets imagine my site has SalesPerson and Customer objects. These are pretty simple classes but I don’...
You are best off to create many, smaller items in the cache than to create fewer, larger items. Here is the reasoning: 1) If your data is small, then the number of items in the cache will be relatively small and it won't make any difference. Fetching single entities from the cache is easier than fetching a dictionary ...
We have built an application that uses Caching for storing all resources. The application is multi-language, so for each label in the application we have at least three translations. We load a (Label,Culture) combination when first needed and then expire it from cache only if it was changed by and admin in the database...
Efficiency of persistence methods for large asp.net cache store
[ "", "c#", "asp.net", "caching", "" ]
Say I'm working with Sharepoint (this applies to other object models as well) and in the middle of my statement, I call a method, in this case "OpenWeb()", which creates an IDisposable SPWeb object. Now, I cannot call Dispose() on the SPWeb object because I don't have the reference to it. **So do I need to be concerned...
"what happens to the IDisposable object that I cannot explicitly call Dispose() on?" In general you can call Dispose (either implicitly with a using statement or explicitly) on all disposable objects, however in the hypothetical scenario where you **can not**, it **depends** on the way the object was implemented. In ...
The following is more idiomatic and reads better as well: ``` using (SPWeb spWeb = SPControl.GetContextSite(HttpContext.Current).OpenWeb()) { SPUser spUser = spWeb.SiteUsers[@"foo\bar"]; } ```
What happens to an IDisposable object created in the middle of a statement that I cannot explicity call Dispose() on?
[ "", "c#", "sharepoint", "garbage-collection", "dispose", "" ]
Is it possible to pass parts of a linq Query into a function? I want create a common interface for my DAL that always uses the same query interface. For example, ``` List<T> Get(Join j, Where w, Select s){ return currentDataContext<T>.Join(j).Where(w).Select(s).ToList(); } ``` Is this sort of thing possib...
Well, the "join" is tricky, because it is very hard to express a join - but things like where / select / orderby are pretty easy... Really, it is just a case of combining the various LINQ methods on `IQueryable<T>`, which generally accept `Expression<Func<...>>` for some combination. So a basic select with an optional...
Check this generic class: [TableView.cs](http://blogs.msdn.com/kfarmer/archive/2007/11/13/encapsulation-and-linq-to-sql.aspx). It basically uses a Func<TEntity, bool> delegate to apply the Where predicate: ``` //... public TableView(DataContext dataContext, Expression<Func<TEntity, bool>> predicate) { this.table ...
In LINQ to SQL, how do you pass parts of a LINQ query into a function
[ "", "c#", "linq", "linq-to-sql", "expression-trees", "" ]
The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory). It's too slow. Profiling says all the time is spent in `operator new`. Notes: The application already uses a custom memory allocator that does pooling. The compiler is V...
The only way is to reduce the number of memory allocations. Have you used a profiler that will tell you exactly what is doing the allocation? Are you possibly doing some string manipulation? If all the time is spent allocating the objects the factory is creating, you may need to go to a pool.
Have you tried using a custom allocator for objects of known size? This is a good technique for speeding up allocations.
How to improve performance of an Abstract Factory when all the time appears to be spent in memory allocation
[ "", "c++", "optimization", "" ]
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature. Which one is closer to LISP: Python or Ruby? I can...
I'd go with Ruby. It's got all kinds of metaprogramming and duck punching hacks that make it really easy to extend. Features like blocks may not seem like much at first, but they make for some really clean syntax if you use them right. Open classes can be debugging hell if you screw them up, but if you're a responsible...
[Peter Norvig](http://norvig.com), [a famous and great lisper](http://norvig.com/paip.html), converted to Python. He wrote the article [Python for Lisp Programmers](http://norvig.com/python-lisp.html), which you might find interesting with its detailed comparison of features. Python looks like executable pseudo-code. ...
Please advise on Ruby vs Python, for someone who likes LISP a lot
[ "", "python", "ruby", "lisp", "" ]
In ANSI C++, how can I assign the cout stream to a variable name? What I want to do is, if the user has specified an output file name, I send output there, otherwise, send it to the screen. So something like: ``` ofstream outFile; if (outFileRequested) outFile.open("foo.txt", ios::out); else outFile = cout; ...
Use a reference. Note that the reference must be of type `std::ostream`, not `std::ofstream`, since `std::cout` is an `std::ostream`, so you must use the least common denominator. ``` std::ofstream realOutFile; if(outFileRequested) realOutFile.open("foo.txt", std::ios::out); std::ostream & outFile = (outFileRequ...
I assume your program behaves like standard unix tools, that when not given a file will write to standard output, and when given a file will write into that file. You can redirect `cout` to write into another stream buffer. As long as your redirection is alive, everything written to cout is transparently written to the...
Assigning cout to a variable name
[ "", "c++", "cout", "ofstream", "" ]
What is the difference between storing a datatable in Session vs Cache? What are the advantages and disadvantages? So, if it is a simple search page which returns result in a datatable and binds it to a gridview. If user 'a' searches and user 'b' searches, is it better to store it in Session since each user would most...
One important difference is, that items in the cache can expire (will be removed from cache) after a specified amount of time. Items put into a session will stay there, until the session ends. ASP.NET can also remove items from cache when the amount of available memory gets small. Another difference: the session stat...
AFAIK, The key difference is session is per user, while cache will be for application scoped items. As noted in the other answers you can store per user info in the cache, providing you provide a key (either by session or cookie). Then you'd have more control to expire items in the cache and also set dependencies on t...
Advantages of Cache vs Session
[ "", "c#", "asp.net", "session", "caching", "viewstate", "" ]
what will happen with the overlapping portion of boost once C++0x becomes mainstream? Will boost still contain everything it used to, or will they adapt the library to update it with the new std:: stuff? Will boost have both a normal c++ version and a c++0x version that they will maintain?
One would *hope* that Boost continues to support existing classes, for a couple of reasons. First, there is a body of code that uses the overlapping features in Boost that needs to be supported, for some time. Second, overlapping implementations allow me to select which one I'd prefer to use. There might be some diff...
I am not affiliated with Boost and have no they idea what they will do but it seems like Boost will be left untouched. There already has been released TR1 (VS 2008 feature pack) and Boost was left untouched. Since many users have not adopted Boost or TR1 yet, my prediction is that for at least next five years boost an...
what will happen with the overlapping portion of boost once C++0x becomes mainstream?
[ "", "c++", "boost", "c++11", "" ]
How can I change the Text for a CheckBox without a postback? ``` <asp:CheckBox ID="CheckBox1" runat="server" Text="Open" /> ``` I would like to toggle the Text to read "Open" or "Closed" when the CheckBox is clicked on the client.
``` function changeCheckboxText(checkbox) { if (checkbox.checked) checkbox.nextSibling.innerHTML = 'on text'; else checkbox.nextSibling.innerHTML = 'off text'; } ``` called as: ``` <asp:CheckBox runat="server" ID="chkTest" onclick="changeCheckboxText(this);" /> ``` Just FYI, it's usually bad practice to ...
If you're interested to use a framework javascript like jQuery, i propose a solution ilke this: ``` $("input[id$=CheckBox1]").click(function() { if ($(this).attr("checked")) { $(this).next("label:first").text("Open"); } else { $(this).next("label:first").text("Close"); } }); ```
Change the Text of an asp:CheckBox when clicked
[ "", "asp.net", "javascript", "checkbox", "" ]
In several questions I've seen recommendations for the [Spirit](http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/index.html) parser-generator framework from [boost.org](http://www.boost.org/), but then in the comments there is grumbling from people using Spirit who are not happy. Will those people please stand ...
It is a quite cool idea, and I liked it; it was especially useful to really learn how to use C++ templates. But their documentation recommends the usage of spirit for small to medium-size parsers. A parser for a full language would take ages to compile. I will list three reasons. * Scannerless parsing. While it's qui...
In boost 1.41 a new version of Spirit is being released, and it beats of pants off of spirit::classic: > After a long time in beta (more than 2 > years with Spirit 2.0), Spirit 2.1 > will finally be released with the > upcoming Boost 1.41 release. The code > is very stable now and is ready for > production code. We ar...
What are the disadvantages of the Spirit parser-generator framework from boost.org?
[ "", "c++", "parsing", "boost", "boost-spirit", "parser-generator", "" ]
I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handlin...
Which version of HTML are you using? In HTML 5, it is totally valid to have [custom attributes prefixed with data-](https://www.w3schools.com/tags/att_global_data.asp), e.g. ``` <div data-internalid="1337"></div> ``` In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain...
If you are using jQuery already then you should leverage the "data" method which is the recommended method for storing arbitrary data on a dom element with jQuery. To store something: ``` $('#myElId').data('nameYourData', { foo: 'bar' }); ``` To retrieve data: ``` var myData = $('#myElId').data('nameYourData'); ```...
How to store arbitrary data for some HTML tags
[ "", "javascript", "html", "" ]
How do I split a number by the decimal point in php? I've got $num = 15/4; which turns $num into 3.75. I would like to split out the 3 and the 75 parts, so $int = 3 and $dec = 75. My non-working code is: ``` $num = 15/4; // or $num = 3.75; list($int, $dec) = split('.', $num); ``` but that results in empty $int and $...
If you `explode` the decimal representation of the number, you lose precision. If you don't mind, so be it (that's ok for textual representation). Take the locale into account! We Belgians use a comma (at least the non-programming ones :). If you *do* mind (for computations e.g.), you can use the `floor` function: ``...
``` $num = 15/4; // or $num = 3.75; list($int, $dec) = explode('.', $num); ```
Split a number by decimal point in php
[ "", "php", "split", "" ]
I am using the singleton pattern in all my PHP class files. Would it by any chance cause a user's action on the site to conflict with other user's action? For instance, when the application goes live and we have several users on the site at the same time, doing similar things hereby calling the same PHP classes (behi...
The short answer is no. Each page request is handled as a unique instance and the only thing that tie them together for each user is the session cookie. Try to think of PHP as an application which starts when you call a script and dies when the script finishes. It does not maintain any state and is not inherently awar...
Each request is self contained and does not share data with other requests (unless you use specific extensions for that, like memcache). So having singletons in your application would not affect separate requests from separate users. What should be of concern to you is your overuse of the singleton pattern. A singleto...
Are PHP singleton classes somehow shared between requests?
[ "", "php", "class", "singleton", "" ]
What is used instead of [Maven](http://en.wikipedia.org/wiki/Apache_Maven) for C# Windows Forms projects? We have developers all over the world and are trying to come up with some dependency management system that is clean simple and fast.
There is [Byldan](http://byldan.codeplex.com/), but the project seems quite young. (See also Stack Overflow question *[Is there a Maven alternative or port for the .NET world?](https://stackoverflow.com/questions/652583/is-there-a-maven-alternative-or-port-for-the-net-world)*.)
I wrote a tutorial on the subject, *[Using Maven to manage .NET projects](https://web.archive.org/web/20110830022107/http://docs.codehaus.org/display/MAVENUSER/Using+Maven+to+manage+.NET+projects)*.
Is there an alternative to Maven for .NET/Windows Forms projects?
[ "", "c#", "dependencies", "" ]
I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views? regards chriss
Personally, I'd use one view to handle each form's POST. On the other hand, you could use a hidden input element that indicate which form was used ``` <form action="/blog/" method="POST"> {{ blog_form.as_p }} <input type="hidden" name="form-type" value"blog-form" /> <!-- set type --> <input type="submit" ...
like ayaz said, you should give unique name to form submit button ``` <form action="." method="post"> ...... <input type="submit" name="form1"> </form> <form action="." method="post"> ...... <input type="submit" name="form2"> </form> #view if "form1" in request.POST: ... if "form2" in request.POST: ... ``...
How to process two forms in one view?
[ "", "python", "django", "django-forms", "django-templates", "" ]