Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
"this" is a text field, "new\_id" is an integer. When I apply the following snippet: ``` $(this).attr('id', this.id + '_' + new_id); $(this).attr('name', this.name + '_' + new_id); $(this).attr('value', 'test'); ``` the id changes, the name changes too, but not the value. If I change the last line to this (and therefore use a string literal) ``` $('#mytextfield_3').attr('value', 'test'); ``` it works. Any ideas? -- EDIT -- Thanks to Steerpike for the quick plugin test - i believe it should work, but i can't find the error. Here's some more code: I create the clone using ``` clone = $(this).find('.clone_fields_container:first').clone(); ``` "clone" now contains a div which has embedded input fields. After generating a new id: ``` /** Iterate over input and select fields in container */ clone.children('input,select,textarea').each(function() { $(this).attr('id', this.id + '_' + new_id); $(this).attr('name', this.name + '_' + new_id); $(this).val('test'); console.log(this); }); ``` The text fields do not have any values.
I just wrote a quick plugin to run a test using your same snippet and it works fine ``` $.fn.test = function() { return this.each(function(){ var new_id = 5; $(this).attr('id', this.id + '_' + new_id); $(this).attr('name', this.name + '_' + new_id); $(this).attr('value', 'test'); }); }; $(document).ready(function() { $('#field_id').test() }); <body> <div id="container"> <input type="text" name="field_name" id="field_id" value="meh" /> </div> </body> ``` So I can only presume something else is going on in your code. Can you provide some more details?
Did you try ``` $(this).val('test'); ``` instead of ``` $(this).attr('value', 'test'); ``` `val()` is generally easier, since the attribute you need to change may be different on different DOM elements.
Set new id with jQuery
[ "", "javascript", "jquery", "" ]
I want to sort a ListView control in C# based on columns. I have created ColumnClickEventHandler: ``` private void contactsListView_ColumnClick(object sender, ColumnClickEventArgs e) { contactsListView.ListViewItemSorter = new ListViewItemComparer(e.Column); contactsListView.Sort(); } ``` Where ListViewItemComparer class looks like this: ``` class ListViewItemComparer : IComparer<ListViewItem> { private int col; public ListViewItemComparer() { col = 0; } public ListViewItemComparer(int column) { col = column; } public int Compare(ListViewItem x, ListViewItem y) { int returnVal = -1; returnVal = String.Compare(x.SubItems[col].Text, y.SubItems[col].Text); return returnVal; } } ``` This code won't compile cause contactsListView.ListViewItemSorter is type IComparer and class ListViewItemComparer is IComparer. Is there a way to explicitly cast one to the other? Or just do sorting another way? Thanks in advance
The generic `IComparer<T>` and the non-generic `IComparer` aren't convertible from one another. Maybe your `ListViewItemComparer` should implement the non-generic `IComparer` instead?
I believe that the comparer class should be I`Comparer, not IComparer<type>`. [here is an article](http://blogs.interknowlogy.com/joelrumerman/archive/2007/04/03/12497.aspx) that might help, it uses the SortDescriptions.
assigning comparer to ListViewItemSorter
[ "", "c#", "sorting", "listview", "" ]
Keep in mind that I am a rookie in the world of sql/databases. I am inserting/updating thousands of objects every second. Those objects are actively being queried for at multiple second intervals. What are some basic things I should do to performance tune my (postgres) database?
It's a broad topic, so here's lots of stuff for you to read up on. * [EXPLAIN and EXPLAIN ANALYZE](http://www.postgresql.org/docs/current/static/sql-explain.html) is extremely useful for understanding what's going on in your db-engine * Make sure relevant columns are indexed * Make sure irrelevant columns are *not* indexed (insert/update-performance can go down the drain if too many indexes must be updated) * Make sure your postgres.conf is tuned properly * Know what work\_mem is, and how it affects your queries (mostly useful for larger queries) * Make sure your database is properly normalized * [VACUUM](http://www.postgresql.org/docs/current/static/sql-vacuum.html) for clearing out old data * [ANALYZE](http://www.postgresql.org/docs/current/static/sql-analyze.html) for updating statistics (statistics target for amount of statistics) * Persistent connections (you could use a connection manager like pgpool or pgbouncer) * Understand how queries are constructed (joins, sub-selects, cursors) * Caching of data (i.e. memcached) is an option And when you've exhausted those options: add more memory, faster disk-subsystem etc. Hardware matters, especially on larger datasets. And of course, read all the other threads on postgres/databases. :)
First and foremost, read the official manual's [Performance Tips](http://www.postgresql.org/docs/8.3/interactive/performance-tips.html). Running [EXPLAIN](http://www.postgresql.org/docs/8.3/interactive/using-explain.html) on all your queries and understanding its output will let you know if your queries are as fast as they could be, and if you should be adding indexes. Once you've done that, I'd suggest reading over the [Server Configuration](http://www.postgresql.org/docs/8.3/interactive/runtime-config.html) part of the manual. There are many options which can be fine-tuned to further enhance performance. Make sure to understand the options you're setting though, since they could just as easily hinder performance if they're set incorrectly. Remember that *every time* you change a query or an option, **test** and **benchmark** so that you know the effects of each change.
Performance Tuning PostgreSQL
[ "", "sql", "postgresql", "indexing", "performance-testing", "" ]
I need to convert any letter that occur twice or more within a word with a single letter of itself. For example: ``` School -> Schol Google -> Gogle Gooooogle -> Gogle VooDoo -> Vodo ``` I tried the following, but stuck at the second parameter in eregi\_replace. ``` $word = 'Goooogle'; $word2 = eregi_replace("([a-z]{2,})", "?", $word); ``` If I use `\\\1` to replace ?, it would display the exact match. How do I make it single letter? Can anyone help? Thanks
See [regular expression to replace two (or more) consecutive characters by only one?](https://stackoverflow.com/questions/106067/regular-expression-to-replace-two-or-more-consecutive-characters-by-only-one) By the way: you should use the `preg_*` (PCRE) functions instead of the deprecated `ereg_*` functions (POSIX). [Richard Szalay](https://stackoverflow.com/questions/801545/how-to-replace-double-more-letters-to-a-single-letter/801554#801554)'s answer leads the right way: ``` $word = 'Goooogle'; $word2 = preg_replace('/(\w)\1+/', '$1', $word); ```
Not only are you capturing the entire thing (instead of just the first character), but `{2,}` rematching [a-z] (not the original match). It should work if you use: ``` $word2 = eregi_replace("(\w)\1+", "\\1", $word); ``` Which backreferences the original match. You can replace \w with [a-z] if you wish. The + is required for your Goooogle example (for the JS regex engine, anyway), but I'm not sure why. Remember that you will need to use the "global" flag ("g").
How to replace double/more letters to a single letter?
[ "", "php", "regex", "" ]
This might be an unusual question, but is there any framework or at least some helper classes that would help me use GNU Gettext for localizing a C# ASP.NET MVC website? I've been using Gettext in a previous (managed code) project and really appreciate the possibility to use PoEdit for translating the resources. I guess this would mean coding a few HtmlHelper extension methods that can extract the resource strings from Gettext. There even seems to be some kind of C# gettext wrapper, but I wasn't able to find a manual or tutorial. Any pointers would be greatly appreciated. Thanks, Adrian
FairlyLocal is also nice. I modified it to my own needs and am pretty happy with what it offered: <http://www.fairtutor.com/fairlylocal/>
The Mono Project website has a [tutorial](http://www.mono-project.com/I18nGettext) on how to use gettext in a C# application.
Localization of ASP.NET MVC websites with GNU Gettext?
[ "", "c#", "asp.net-mvc", "localization", "gettext", "" ]
I'm trying to read UTF-8 from a text file and do some tokenization, but I'm having issues with the encoding: ``` try { fis = new FileInputStream(fName); } catch (FileNotFoundException ex) { //... } DataInputStream myInput = new DataInputStream(fis); try { while (thisLine = myInput.readLine()) != null) { StringTokenizer st = new StringTokenizer(thisLine, ";"); while (st.hasMoreElements()) { // do something with st.nextToken(); } } } catch (Exception e) { //... } ``` and DataInputStream doesn't have any parameters to set the encoding!
Let me quote the Javadoc for this method. DataInputStream.readLine() > Deprecated. This method does not > properly convert bytes to characters. > As of JDK 1.1, the preferred way to > read lines of text is via the > BufferedReader.readLine() method. > Programs that use the DataInputStream > class to read lines can be converted > to use the BufferedReader class by > replacing code of the form: ``` DataInputStream d = new DataInputStream(in); ``` with: ``` BufferedReader d = new BufferedReader(new InputStreamReader(in)); ``` BTW: JDK 1.1 came out in Feb 1997 so this shouldn't be new to you. Just think how much time everyone would have saved if you had read the Javadoc. ;)
You can use InputStreamReader: ``` BufferedReader br = new BufferedReader (new InputStreamReader (source, charset); while (br.readLine () != null) { ... } ``` You can also try Scanner, but I'm not sure that it would work fine
Reading data from UTF-8 text file and tokenize
[ "", "java", "encoding", "file-io", "" ]
I'm trying to parse a text file that has a heading and the body. In the heading of this file, there are line number references to sections of the body. For example: ``` SECTION_A 256 SECTION_B 344 SECTION_C 556 ``` This means, that SECTION\_A starts in line 256. What would be the best way to parse this heading into a dictionary and then when necessary read the sections. Typical scenarios would be: 1. Parse the header and read only section SECTION\_B 2. Parse the header and read fist paragraph of each section. The data file is quite large and I definitely don't want to load all of it to the memory and then operate on it. I'd appreciate your suggestions. My environment is VS 2008 and C# 3.5 SP1.
Well, obviously you can store the name + line number into a dictionary, but that's not going to do you any good. Well, sure, it will allow you to know which line to start reading from, but the problem is, where in the file is that line? The only way to know is to start from the beginning and start counting. The best way would be to write a wrapper that decodes the text contents (if you have encoding issues) and can give you a line number to byte position type of mapping, then you could take that line number, 256, and look in a dictionary to know that line 256 starts at position 10000 in the file, and start reading from there. Is this a one-off processing situation? If not, have you considered stuffing the entire file into a local database, like a SQLite database? That would allow you to have a direct mapping between line number and its contents. Of course, that file would be even bigger than your original file, and you'd need to copy data from the text file to the database, so there's some overhead either way.
You can do this quite easily. There are three parts to the problem. 1) How to find where a line in the file starts. The only way to do this is to read the lines from the file, keeping a list that records the start position in the file of that line. e.g ``` List lineMap = new List(); lineMap.Add(0); // Line 0 starts at location 0 in the data file (just a dummy entry) lineMap.Add(0); // Line 1 starts at location 0 in the data file using (StreamReader sr = new StreamReader("DataFile.txt")) { String line; int lineNumber = 1; while ((line = sr.ReadLine()) != null) lineMap.Add(sr.BaseStream.Position); } ``` 2) Read and parse your index file into a dictionary. ``` Dictionary index = new Dictionary(); using (StreamReader sr = new StreamReader("IndexFile.txt")) { String line; while ((line = sr.ReadLine()) != null) { string[] parts = line.Split(' '); // Break the line into the name & line number index.Add(parts[0], Convert.ToInt32(parts[1])); } } ``` Then to find a line in your file, use: ``` int lineNumber = index["SECTION_B";]; // Convert section name into the line number long offsetInDataFile = lineMap[lineNumber]; // Convert line number into file offset ``` Then open a new FileStream on DataFile.txt, Seek(offsetInDataFile, SeekOrigin.Begin) to move to the start of the line, and use a StreamReader (as above) to read line(s) from it.
Parsing a textfile in C# with skipping some contents
[ "", "c#", ".net", "file-io", "text-parsing", "" ]
I have classes ``` public class FooKeyedCollection : KeyedCollection<FooType,Foo> { } public enum FooType { FooType1, FooType2, FooType3 } public Foo { public FooType Type { get; set; } public string Value { get; set; } } ``` When I add items to my FooKeyedCollection, I can index them by FooType, but when I attempt to index them int, the int is interpretted as the FooType enum. As a result, it leads to a confusing error, i.e. ``` public static void main() { FooKeyedCollection fkc = new FooKeyedCollection(); Foo myFoo = new Foo(); myFoo.Type = FooType.FooType3; myFoo.Value = "someValue"; foo.Add( myFoo ); Foo myFooByType = foo[FooType.FooType3]; Foo myFooByIndex = foo[0]; // <-- exception thrown here } ``` The result of executing this code is an exception when attempting to retrieve the item by integer index. I hope to expose the FooKeyedCollection as part of a public API, and I want to protect the consumers of this API from this error. Is there any way that I can modify the FooKeyedCollection class to get proper behavior?
You might consider using the "new" keyword here: ``` public new Foo this[int index] { get { IList<Foo> self = this; return self[index]; } set { (IList<Foo>)[index] = value; } } ``` This will allow you to index by integer value. Using the enum explicitly will fall back to the KeyedCollection implementation.
Here's a helpful extension method to avoid these cases where the two indexers overlap - it also helps if the key is `int`: ``` static class CollectionUtils { public static TValue GetByIndex<TKey,TValue> (this KeyedCollection<TKey, TValue> collection, int index) { return collection[index]; } } ``` then call `fkc.GetByIndex(0)` and it will work fine. Inside the generic method it can *only* resolve `index` to the `int` indexer.
KeyedCollection with enum key type will not index by int
[ "", "c#", ".net", "" ]
My application (the bootstrap application for an installer that I'm working on needs to launch some other applications (my installer and third party installers for my installer's prerequisites) and wait for them to complete. In order to allow the GUI to do screen updates while waiting for an app to complete, I put a message pump in the wait loop using the 'MFC-compatible' example in the Visual Studio documentation on idle loop processing as a guideline. My code (which is in a member function of a CWinApp-derived class) is as follows: ``` if (::CreateProcess(lpAppName, szCmdLineBuffer, NULL, NULL, TRUE, 0, NULL, NULL, &StartupInfo, &ProcessInfo)) { ::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode); if (bWait) while (dwExitCode == STILL_ACTIVE) { // In order to allow updates of the GUI to happen while we're waiting for // the application to finish, we must run a mini message pump here to // allow messages to go through and get processed. This message pump // performs much like MFC's main message pump found in CWinThread::Run(). MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!PumpMessage()) { // a termination message (e.g. WM_DESTROY) // was processed, so we need to stop waiting dwExitCode = ERROR_CANT_WAIT; ::PostQuitMessage(0); break; } } // let MFC do its idle processing LONG nIdle = 0; while (OnIdle(nIdle++)) ; if (dwExitCode == STILL_ACTIVE) // was a termination message processed? { // no; wait for .1 second to see if the application is finished ::WaitForSingleObject(ProcessInfo.hProcess, 100); ::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode); } } ::CloseHandle(ProcessInfo.hProcess); ::CloseHandle(ProcessInfo.hThread); } else dwExitCode = ::GetLastError(); ``` The problem that I'm having is that, at some point, this message pump seems to free up window and menu handles on the window that I have open at the time this code is run. I did a walk through in the debugger, and at no time did it ever get into the body of the if (!PumpMessage()) statement, so I don't know what's going on here to cause the window and menu handles to go south. If I don't have the message pump, everything works fine, except that the GUI can't update itself while the wait loop is running. Does anyone have any ideas as to how to make this work? Alternatively, I'd like to launch a worker thread to launch the second app if bWait is TRUE, but I've never done anything with threads before, so I'll need some advice on how to do it without introducing synchronization issues, etc. (Code examples would be greatly appreciated in either case.)
I've also posted this question on the Microsoft forums, and thanks to the help of one Doug Harris at Microsoft, I found out my problem with my HWND and HMENU values was, indeed due to stale CWwnd\* and CMenu\* pointers (obtained using GetMenu() and GetDialogItem() calls. Getting the pointers again after launching the second app solved that problem. Also, he pointed me to a web site\* that showed a better way of doing my loop using MsgWaitForMultipleObjects() to control it that doesn't involve the busy work of waiting a set amount of time and polling the process for an exit code. My loop now looks like this: ``` if (bWait) { // In order to allow updates of the GUI to happen while we're // waiting for the application to finish, we must run a message // pump here to allow messages to go through and get processed. LONG nIdleCount = 0; for (;;) { MSG msg; if (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) PumpMessage(); else //if (!OnIdle(nIdleCount++)) { nIdleCount = 0; if (!PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { DWORD nRes = ::MsgWaitForMultipleObjects(1, &ProcessInfo.hProcess, FALSE, INFINITE, QS_ALLEVENTS); if (nRes == WAIT_OBJECT_0) break; } } } } ::GetExitCodeProcess(ProcessInfo.hProcess, &dwExitCode); ``` \*That Web site, if you're curious, is: <http://members.cox.net/doug_web/threads.htm>
I think your problem is in `WaitForSingleObject` Looking in [MSDN](http://msdn.microsoft.com/en-us/library/ms687032.aspx) you see this > Use caution when calling the wait functions and code that directly or indirectly creates windows. If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. A thread that uses a wait function with no time-out interval may cause the system to become deadlocked. Two examples of code that indirectly creates windows are DDE and the CoInitialize function. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than WaitForSingleObject. In my code in the message pump use use `MsgWaitForMultipleObjects` ([doc](http://msdn.microsoft.com/en-us/library/ms684242(VS.85).aspx)). With a call this call. ``` MsgWaitForMultipleObjects(1, &ProcessInfo.hProcess, FALSE, 100, QS_ALLEVENTS); ``` This should stop your problem with the resources dissapearing.
I need a message pump that doesn't mess up my open window
[ "", "c++", "windows", "multithreading", "mfc", "message", "" ]
I'd like to serve django application on windows XP/Vista. The application is an at hoc web interface to a windows program so it won't be put under heavy load (around 100 requests per second). Do you know any small servers that can be easily deployed on windows to serve a django app? (IIS is not an option as the app should work on all versions of windows)
[cherrypy](http://cherrypy.org) includes a good server. [Here](http://lincolnloop.com/blog/2008/mar/25/serving-django-cherrypy/)'s how you set it up to work with django and some benchmarks. [twisted.web](http://twistedmatrix.com/trac/wiki/TwistedWeb) has [wsgi](http://wsgi.org) support and that could be used to run your django application. [Here](http://blog.dreid.org/2009/03/twisted-django-it-wont-burn-down-your.html)'s how you do it. In fact any [wsgi](http://wsgi.org) server will do. Here's one more example, this time using [spawning](http://pypi.python.org/pypi/Spawning): ``` $ spawn --factory=spawning.django_factory.config_factory mysite.settings ``` And for using [paste](http://pythonpaste.org/), the info is gathered [here](http://pythonpaste.org/djangopaste/). Of course, you could use apache with [mod\_wsgi](http://code.google.com/p/modwsgi/). It would be just another wsgi server. [Here](http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango) are the setup instructions.
If you want to give Apache a go, check out [XAMPP](http://www.apachefriends.org/en/xampp.html) to see if it'll work for you. You can do a lightweight (read: no installation) "installation." Of course, you'll also want to install [mod\_python](http://www.modpython.org/) to run Django. [This](http://jyotirmaya.blogspot.com/2008/11/xampp-python-django.html) post may help you set everything up. (Note: I have not used python/Django with XAMPP myself.) Edit: Before someone points this out, XAMPP is not generally a production-ready tool. It's simply a useful way to see whether Apache will work for you. Also, I saw that you're using SQLite after the fact.
A production ready server to serve django on win32
[ "", "python", "windows", "django", "" ]
Assume that a solution only contains classes and that those classes are all written to .NET 2.0 specifications. If that solution were to be opened, converted and saved in Visual Studio 2008, would it be possible to reopen the solution later in Visual Studio 2005 with some minimal modifications to the .SLN file? How would one go about doing that? Is there a tool that will "down convert" .SLN files from 2008 to 2005 if all of the classes contained within the solution are already written to .NET 2.0 specifications?
Uusally, the only thing you need to do with .SLN files is to change the version number at the top of the file. Your CS project files will also be almost OK, and if they're not, it's possible to tweak them so that they are OK with both 2005 and 2008. We ran for a while with two solution files (05 and 08) sharing the same set of CS project files. Be aware though, that you can't share VC project files between the two versions like this. The 'tweak' for the project files is as follows: CS Projects created on VS2008 will contain the line: ``` <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> ``` VS2005 will choke on this, and you need to change it to the following: ``` <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> ``` The latter will work with both 2005 and 2008.
If you're not using any "fancy" features in 2008, in my experience the only thing which changes is the version number in a couple of places. That can be manually edited (it's at the top of the file IIRC). It's at least worth a try. If you're used VS2008-specific features (designers etc) it may well not work but for simple class libraries I've had success doing this. You may be interested in a [blog post about VS2005 and VS2008 co-existing](http://msmvps.com/blogs/jon_skeet/archive/2007/11/20/vs2005-and-vs2008-co-existence.aspx) that I wrote a while ago.
How does one convert a Visual Studio .NET 2008 solution to Visual Studio .NET 2005?
[ "", "c#", "visual-studio-2008", "visual-studio-2005", "solution", "" ]
I'm using Perl's [CGI::Session](http://search.cpan.org/dist/CGI-Session) with MySQL. No problems there. I want to incorporate some other languages, most notably PHP, to use the same session cookie. How would I do that? Almost the entire site is in Perl, but I want to use free PHP things, like forums and mediawiki, and still use the same session cookie.
I've never tried this, but see the [session\_set\_save\_handler](http://www.php.net/manual/en/function.session-set-save-handler.php) function. Some frameworks ([like CakePHP](https://trac.cakephp.org/browser/branches/1.2.x.x/cake/libs/session.php)) use this to store the session in a database. Maybe you could write some code to use the same session as perl, prepending this script to your forum, wiki, etc.
You could use the [PHP::Session](http://search.cpan.org/~miyagawa/PHP-Session-0.27/lib/PHP/Session.pm) module. Check out [Using Perl Code from PHP](http://devzone.zend.com/node/view/id/1712) for other ideas.
Can I use Perl CGI::Sessions data in PHP?
[ "", "php", "perl", "cgi", "session", "" ]
I feel that this is likely a common problem, but from my google searching I can't find a solution quite as specific to my problem. I have a list of Organizations (table) in my database and I need to be able to run queries based on their hierarchy. For example, if you query the highest Organization, I would want to return the Id's of all the Organizations listed under that Organization. Further, if I query an organization sort of mid-range, I want only the Organization Id's listed under that Organization. What is the best way to a) set up the database schema and b) query? I want to only have to send the topmost Organization Id and then get the Id's under that Organization. I think that makes sense, but I can clarify if necessary.
One simple way is to store the organization's parentage in a text field, like: SALES-EUROPE-NORTH To search for every sales organization, you can query on SALES-%. For each European sales org, query on SALES-EUROPE-%. If you rename an organization, take care to update its child organizations as well. This keeps it simple, without recursion, at the cost of some flexibility.
As promised in my comment, I dug up an [article](http://www.sitepoint.com/article/hierarchical-data-database/2/) on how to store hierarchies in a database that allows constant-time retrieval of arbitrary subtrees. I think it will suit your needs much better than the answer currently marked as accepted, both in ease of use and speed of access. I could swear I saw this same concept on wikipedia originally, but I can't find it now. It's apparently called a "modified preorder tree traversal". The gist of it is you number each node in the tree twice, while doing a depth-first traversal, once on the way down, and once on the way back up (i.e. when you're unrolling the stack, in a recursive implementation). This means that the children of a given node have all their numbers in between the two numbers of that node. Throw an index on those columns and you've got really fast lookups. I'm sure that's a terrible explanation, so read the article, which goes into more depth and includes pictures.
SQL Query for an Organization Chart?
[ "", "sql", "database", "hierarchy", "" ]
First of all I have to admit that these are very basic and primitive questions... I want to demonstrate different Algorithms in Java for sorting and searching, and to get a value for the runtime. There're issues I cannot solve: 1. there's Hotspot compiling - which is a runtime optimization I need to deactivate (I guess). 2. How do I get time-values (seconds) for runtimes? Starting a timer before the execution and stopping it afterwards... seems a little primitive. And the timer-object itself consumes runtime... I need to avoid that. Is there anything in the Java API one could utilize to solve these problems? Thanks, Klaus
1. Use `-Xint` JVM flag. Other options can be seen [here](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp). 2. Use the [**`ThreadMXBean`**](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBean.html) API to get CPU/User times for your thread. An example can be seen [here](http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking).
You can disable HotSpot with `-Xint` on the command line, to get an order of magnitude decrease in performance. However, why don't you want to measure real world performance? Different things can become bottlenecks when you compile. Generally for microbenchmarks: * use `System.nanoTime` to get a time measurement at the start and end * run for a reasonable length of time * do the measurement a number of times over (there's some "warm up") * don't interleave measurements of different algorithms * don't do any I/O in the measured segment * use the result (HotSpot can completely optimise away trivial operations) * do it in a real world situation (or a cloae as possible) * remember dual core is the norm, and more cores will become normal
Java task runtime
[ "", "java", "algorithm", "runtime", "jvm-hotspot", "" ]
How can update a input hidden inside an UpdatePanel on an AsyncPostBack? The user click a button outside the panel. The method associated with click event update the value of the input (it has runat="server" property). I can't update the value of this input. I need to store a value to use in the following postback. Maybe I can use session to store this value. Any advice? Thank you!
No way. The only way to update an input is to do a complete post. It's better to use the object Session.
Because its a postback, you might have to perform a check in the post back event and perform the update. If not, you might have to override an earlier event. See <http://msdn.microsoft.com/en-us/library/dct97kc3.aspx>
input hidden and updatePanel (a story of ASP.NET AJAX)
[ "", "c#", "asp.net-ajax", "input", "" ]
Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python? Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2.5.
[This article](http://code.activestate.com/recipes/66517/) shows you can do it with [`socket`](http://docs.python.org/library/socket.html) and [`struct`](http://docs.python.org/library/struct.html) modules without too much extra effort. I added a little to the article as follows: ``` import socket,struct def makeMask(n): "return a mask of n bits as a long integer" return (2L<<n-1) - 1 def dottedQuadToNum(ip): "convert decimal dotted quad string to long integer" return struct.unpack('L',socket.inet_aton(ip))[0] def networkMask(ip,bits): "Convert a network address to a long integer" return dottedQuadToNum(ip) & makeMask(bits) def addressInNetwork(ip,net): "Is an address in a network" return ip & net == net address = dottedQuadToNum("192.168.1.1") networka = networkMask("10.0.0.0",24) networkb = networkMask("192.168.0.0",24) print (address,networka,networkb) print addressInNetwork(address,networka) print addressInNetwork(address,networkb) ``` This outputs: ``` False True ``` If you just want a single function that takes strings it would look like this: ``` import socket,struct def addressInNetwork(ip,net): "Is an address in a network" ipaddr = struct.unpack('L',socket.inet_aton(ip))[0] netaddr,bits = net.split('/') netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1) return ipaddr & netmask == netmask ```
Using [ipaddress](http://code.google.com/p/ipaddress-py/) ([in the stdlib since 3.3](http://docs.python.org/3.3/library/ipaddress.html), [at PyPi for 2.6/2.7](https://pypi.python.org/pypi/ipaddress)): ``` >>> import ipaddress >>> ipaddress.ip_address('192.168.0.1') in ipaddress.ip_network('192.168.0.0/24') True ``` --- If you want to evaluate a *lot* of IP addresses this way, you'll probably want to calculate the netmask upfront, like ``` n = ipaddress.ip_network('192.0.0.0/16') netw = int(n.network_address) mask = int(n.netmask) ``` Then, for each address, calculate the binary representation with one of ``` a = int(ipaddress.ip_address('192.0.43.10')) a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0] a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0] # IPv4 only ``` Finally, you can simply check: ``` in_network = (a & mask) == netw ```
How can I check if an ip is in a network in Python?
[ "", "python", "networking", "ip-address", "cidr", "" ]
I'm interested in learning to use OpenGL and I had the idea of writing a music visualizer. Can anyone give me some pointers of what elements I'll need and how I should go about learning to do this?
If you use C++/CLI, here's [an example](https://web.archive.org/web/20121006142849/http://blogs.windowsclient.net/ricciolocristian/archive/2008/02/16/audio-spectrum-using-wpf-and-c-cli.aspx) that uses WPF four (fourier that is;) display. He references [this site](http://www.relisoft.com/science/physics/sound.html) ([archived](https://web.archive.org/web/2/http://www.relisoft.com/science/physics/sound.html)) that has considerable information about what your asking, here's anoutline from the specific page; > How do we split sound into > frequencies? Our ears do it by > mechanical means, mathematicians do it > using Fourier transforms, and > computers do it using FFT. > > 1. The Physics of Sound > * Harmonic Oscillator > 2. Sampling Sounds > 3. Fourier Analysis > 4. Complex Numbers > 5. Digital Fourier Transform > 6. FFT Ahhh, I found [this](http://www.relisoft.com/freeware/index.htm) ([archived](https://web.archive.org/web/2/http://www.relisoft.com/freeware/index.htm)) a few minutes later, it's a native C++ analyzer. Code included, that should get you off and running.
My approach for creating BeatHarness (<http://www.beatharness.com>) : * record audio in real time * have a thread that runs an FFT on the audio to get the frequency intensities * calculate audio-volume for left and right channel * filter the frequencies in bands (bass, midtones, treble) now you have some nice variables to use in your graphics display. For example, show a picture where the size is multiplied by the bass - this will give you a picture that'll zoom in on the beat. From there on it's your own imagination ! :)
How to start writing a music visualizer in C++?
[ "", "c++", "opengl", "audio", "visualization", "" ]
I have an .html file (X) that depending on some value should immediately open another .html file (Y) when opening the .html file (X). What's the best way to implement this within javascript? Also I want that when the user presses 'Refresh (F5)' on Y .html the page that should be loaded again to be the one that started the current one (X).
> I have an .html file (X) that > depending on some value should > immediately open another .html file > (Y) when opening the .html file (X). > What's the best way to implement this > within javascript? You can do this using [window.open](http://www.javascript-coder.com/window-popup/javascript-window-open.phtml). > Also I want that when the user presses > 'Refresh (F5)' on Y .html the page > that should be loaded again to be the > one that started the current one (X). You can do this in the [onbeforeunload](http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx) event of page (Y) using ``` window.parent.window.location.href = window.parent.window.location.href; ```
Using jQuery it might look like this: ``` <input type="text" id="whatPage" value="somepagename"> <input type="button" id="someinput" value="getPage"> <div id="targetDiv"> I will be filled with the resulting HTML. </div> <script> $('#someinput').click(function() { $.ajax({ url: $('#whatPage').val()+'.htm', success: function(response) { $('#targetDiv').html(response); } }); }); </script> ```
How to open HTML page in JavaScript
[ "", "javascript", "html", "" ]
What is the maximum amount of data I can load onto a form control? My application consumes too much memory and hangs when more than 500,000 records are added to any windows forms control in my experience. Any clues?
Yes, that will cause problems. Don't add that many records. Nobody needs that many. What you need to do instead is add filtering capabilities so that the user can specify which range of the data he/she wants to use. For instance, let the user narrow the search by date (if it's time-sensitive data), or order number range, or ... well, whatever. But I can guarantee you that finding a way to add 500K rows to a grid or whatever is **not a solution**.
Looks like you've found the maximum memory footprint of your app. There is no single measure. Application memory includes also GDI handles, File Handles, Threads that your app is using. Make sure you don't have a GDI handle leak using Task Manager and likes. Also it's not a good practice to load 500,000 records to the UI, the user can never handle so much information, please change your practice by using paging or other ways for that tasks.
What is the maximum amount of data that can be loaded into a Windows form control?
[ "", "c#", "windows", "datagridview", "listbox", "" ]
I am working on a practical scenario related with Java;a socket program. The existing system and the expected system are as follows. **Existing System** - The system checks that a certain condition is satisfied. If so It will create some message to be sent and put it into a queue. The queue processor is a separate thread. It periodically check the queue for existence of items in it. If found any items (messages) it just sends the message to a remote host (hardcoded) and remove the item from queue. **Expected System** - This is something like that. The message is created when a certain condition is satisfied but in every case the recipient is not same. So there are many approaches. 1. putting the message into the same queue but with its receiver ID. In this case the 2nd thread can identify the receiver so the message can be sent to that. 2. Having multiple threads. In this case when the condition is satisfied and if the receiver in "New" it creates a new queue and put the message into that queue. And a new thread initializes to process that queue. If the next messages are directed to same recipient it should put to the same queue and if not a new queue and the thread should be created. Now I want to implement the 2nd one, bit stucked. How should I do that? A skeleton would be sufficient and you won't need to worry to put how to create queues etc... :) Update : I also think that the approach 1 is the best way to do that. I read some articles on threading and came to that decision. But it is really worth to learn how to implement the approach 2 as well.
First of all, if you are planning to have a lot of receivers, I would not use the ONE-THREAD-AND-QUEUE-PER-RECEIVER approach. You could end up with a lot of threads not doing anything most of the time and I could hurt you performance wide. An alternative is using a thread pool of worker threads, just picking tasks from a shared queue, each task with its own receiver ID, and perhaps, a shared dictionary with socket connections to each receiver for the working threads to use. Having said so, if you still want to pursue your approach what you could do is: 1) Create a new class to handle your new thread execution: ``` public class Worker implements Runnable { private Queue<String> myQueue = new Queue<String>(); public void run() { while (true) { string messageToProcess = null; synchronized (myQueue) { if (!myQueue.empty()) { // get your data from queue messageToProcess = myQueue.pop(); } } if (messageToProcess != null) { // do your stuff } Thread.sleep(500); // to avoid spinning } } public void queueMessage(String message) { synchronized(myQueue) { myQueue.add(message); } } } ``` 2) On your main thread, create the messages and use a dictionary (hash table) to see if the receiver's threads is already created. If is is, the just queue the new message. If not, create a new thread, put it in the hashtable and queue the new message: ``` while (true) { String msg = getNewCreatedMessage(); // you get your messages from here int id = getNewCreatedMessageId(); // you get your rec's id from here Worker w = myHash(id); if (w == null) { // create new Worker thread w = new Worker(); new Thread(w).start(); } w.queueMessage(msg); } ``` Good luck. Edit: you can improve this solution by using [BlockingQueue](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html) Brian mentioned with this approach.
Consider using [Java Message Services (JMS)](http://java.sun.com/products/jms/) rather than re-inventing the wheel?
How should I handle Multi-threading in Java?
[ "", "java", "multithreading", "queue", "" ]
A stored procedure that runs a SELECT on a large table is timing out. The where clause is causing the timeout, because I am selecting only cities that are in another table. ``` AND city IN (SELECT DISTINCT city from tOH where clientId = @clientId) AND state IN (SELECT DISTINCT state from tOH where clientId = @clientId) ``` \*note almost always only one state will be returned I am trying to put the cities into a table and then use the table to populate the cities, but I am getting an error that @cities is not declared. ``` DECLARE @cities TABLE ( city varchar(200) ); INSERT INTO @cities (city) SELECT city FROM tOH WHERE clientId = @clientId GROUP BY city ``` Then my where clause changes to ``` AND city IN (SELECT city from @cities) ``` Can anyone figure out a good way of optimizing this stored procedure? ---------------------------- UPDATE ------------------------------------ The joins are all too slow. I think a solution with a temp table or table variable will work.
You've probably tried this, but my first reaction would be to use populate a temp table with your cities. That may be what you're doing and I'm just not familiar with the syntax, but I've always used: ``` Create Table #Cities(City varchar(200)) ``` Then you'll fill the temp table and query from it as in your example (INSERT INTO... and AND city IN (SELECT city from #Cities))
Not only is it slow, it's *incorrect.* Say your city is "Evansville, WI", but your `tOH` table only has entries for "Evansville, IN" and "Milwaukee, WI". You currently check the city and state portions separately, so your existing query will find matches for both "Evansville" and "WI". It will allow that city, even though it really shouldn't. Do this instead: ``` INNER JOIN ( SELECT DISTINCT City AS tOHCity, State AS tOHState FROM tOH WHERE ClientID= @ClientID ) cs ON cs.tOHCity = city AND cs.tOHState = state ``` Note that the subquery is based on the assumption that the DISTINCT from your original post is necessary because you could have more than one of the same city in that table per client. If that's not the case, you can just join to the `tOH` table directly. Combine this with proper indexing and you should be good.
Optimize SQL Stored Procedure
[ "", "sql", "optimization", "stored-procedures", "select", "" ]
In IE exists .setCapture(); .releaseCapture() functions. What's the equivalent of these functions in Firefox without using jQuery? (my client does not want to use it)
There is no such function in FF / JavaScript. The capture functions only exists in JScript.
As it has been said above, Firefox does not offer this functionality, and you can work around it by monitoring events on the entire document. To be sure that there is no a better trick, I’ve just checked jQuery UI, and it appears they use the same approach. So for instance if you wanted to capture mouse movements when mouse is down in jQuery, you would do: ``` $("#someElement"). mousedown(function() { $(document).mousemove(captureMouseMove) }). mouseup(function() { $(document).unbind("mousemove", captureMouseMove) }); function captureMouseMove(event) { // ... } ```
Capture mouse in Firefox
[ "", "javascript", "html", "" ]
I am bit confused about the difference between the usage of std::remove algorithm. Specifically I am not able to understand what is being removed when I use this algorithm. I wrote a small test code like this: ``` std::vector<int> a; a.push_back(1); a.push_back(2); std::remove(a.begin(), a.end(), 1); int s = a.size(); std::vector<int>::iterator iter = a.begin(); std::vector<int>::iterator endIter = a.end(); std::cout<<"Using iter...\n"; for(; iter != endIter; ++iter) { std::cout<<*iter<<"\n"; } std::cout<<"Using size...\n"; for(int i = 0; i < a.size(); ++i) { std::cout<<a[i]<<"\n"; } ``` The output was 2,2 in both the cases. However, if I use erase with the remove something like this: ``` a.erase(std::remove(a.begin(), a.end(), 1), a.end()); ``` I get the output as 2. So my questions are: (1). Is there any use of std::remove other than using it with erase function. (2). Even after doing std::remove, why a.size() returns 2 and not 1? I read the item in Scott Meyer's Effective STL book about the erase-remove idiom. But am still having this confusion.
`remove()` doesn't actually delete elements from the container -- it only shunts non-deleted elements forwards on top of deleted elements. The key is to realise that `remove()` is designed to work on not just a container but on *any arbitrary forward iterator pair*: that means it *can't* actually delete the elements, because an arbitrary iterator pair doesn't necessarily have the ability to delete elements. For example, pointers to the beginning and end of a regular C array are forward iterators and as such can be used with `remove()`: ``` int foo[100]; ... remove(foo, foo + 100, 42); // Remove all elements equal to 42 ``` Here it's obvious that `remove()` cannot resize the array!
**What does std::remove do?** Here's pseudo code of `std::remove`. Take few seconds to see what it's doing and then read the explanation. ``` Iter remove(Iter start, Iter end, T val) { Iter destination = start; //loop through entire list while(start != end) { //skip element(s) to be removed if (*start == val) { start++; } else //retain rest of the elements *destination++ = *start++; } //return the new end of the list return destination; } ``` Notice that remove simply moved up the elements in the sequence, overwriting the values that you wanted to remove. So the values you wanted to remove are indeed gone, but then what's the problem? Let say you had vector with values {1, 2, 3, 4, 5}. After you call remove for val = 3, the vector now has {1, 2, 4, 5, 5}. That is, 4 and 5 got moved up so that 3 is gone from the vector but *the size of vector* hasn't changed. Also, the end of the vector now contains additional left over copy of 5. **What does vector::erase do?** `std::erase` takes start and end of the range you want to get rid off. It does not take *the value* you want to remove, only start and end of the range. Here's pseudo code for how it works: ``` erase(Iter first, Iter last) { //copy remaining elements from last while (last != end()) *first++ = *last++; //truncate vector resize(first - begin()); } ``` So the erase operation actually changes the size of container and frees up the memory. **The remove-erase idiom** The combination of `std::remove` and `std::erase` allows you to remove matching elements from the container so that container would actually get truncated if elements were removed. Here's how to do it: ``` //first do the remove auto removed = std::remove(vec.begin(), vec.end(), val); //now truncate the vector vec.erase(removed, vec.end()); ``` This is known as the remove-erase idiom. Why is it designed like this? The insight is that the operation of finding elements is more generic and independent of underlying container (only dependent on iterators). However operation of erase depends on how container is storing memory (for example, you might have linked list instead of dynamic array). So STL expects containers to do its own erase while providing generic "remove" operation so all containers don't have to implement that code. In my view, the name is very misleading and `std::remove` should have been called `std::find_move`. Note: Above code is strictly pseudocode. The actual STL implementation is more smarter, for example, using `std::move` instead of copy.
Difference between erase and remove
[ "", "c++", "stl", "" ]
I am trying to implement a template function with handles void differently using template specialization. The following code gives me an "Explicit specialization in non-namespace scope" in gcc: ``` template <typename T> static T safeGuiCall(boost::function<T ()> _f) { if (_f.empty()) throw GuiException("Function pointer empty"); { ThreadGuard g; T ret = _f(); return ret; } } // template specialization for functions wit no return value template <> static void safeGuiCall<void>(boost::function<void ()> _f) { if (_f.empty()) throw GuiException("Function pointer empty"); { ThreadGuard g; _f(); } } ``` I have tried moving it out of the class (the class is not templated) and into the namespace but then I get the error "Explicit specialization cannot have a storage class". I have read many discussions about this, but people don't seem to agree how to specialize function templates. Any ideas?
When you specialize a templated method, you must do so outside of the class brackets: ``` template <typename X> struct Test {}; // to simulate type dependency struct X // class declaration: only generic { template <typename T> static void f( Test<T> ); }; // template definition: template <typename T> void X::f( Test<T> ) { std::cout << "generic" << std::endl; } template <> inline void X::f<void>( Test<void> ) { std::cout << "specific" << std::endl; } int main() { Test<int> ti; Test<void> tv; X::f( ti ); // prints 'generic' X::f( tv ); // prints 'specific' } ``` When you take it outside of the class, you must remove the 'static' keyword. Static keyword outside of the class has a specific meaning different from what you probably want. ``` template <typename X> struct Test {}; // to simulate type dependency template <typename T> void f( Test<T> ) { std::cout << "generic" << std::endl; } template <> void f<void>( Test<void> ) { std::cout << "specific" << std::endl; } int main() { Test<int> ti; Test<void> tv; f( ti ); // prints 'generic' f( tv ); // prints 'specific' } ```
You can declare the explicit specialisation in the same way you'd define a member function outside of its class: ``` class A { public: template <typename T> static void foo () {} }; template <> void A::foo<void> () { } ```
template specialization for static member functions; howto?
[ "", "c++", "templates", "boost", "" ]
I have a method that takes either a `StringReader` instance (reading from the clipboard) or a `StreamReader` instance (reading from a file) and, at present, casts either one as a `TextReader` instance. I need it to 'pre-read' some of the source input, then reset the cursor back to the start. I do not necessarily have the original filename. How to I do this? There is mention of the `Seek` method of `System.IO.Stream` but this is not implemented in `TextReader`, although it is in `StreamReader` through the `Basestream` property. However `StringReader` does not have a `BaseStream` property
It depends on the `TextReader`. If it's a `StreamReader`, you can use: ``` sr.BaseStream.Position = 0; sr.DiscardBufferedData(); ``` (Assuming the underlying stream is seekable, of course.) Other implementations of `TextReader` may not *have* a concept of "rewinding", in the same way that `IEnumerable<T>` doesn't. In many ways you can think of `TextReader` as a glorified `IEnumerable<char>`. It has methods to read whole chunks of data at a time, read lines etc, but it's fundamentally a "forward reading" type. EDIT: I don't believe `StringReader` supports any sort of rewinding - you'd be better off recreating the `StringReader` from the original string, if you can. If that's not feasible, you could always create your own `TextReader` class which proxies all the "normal" calls to another `StringReader`, but recreates that proxy instance when it needs to.
If it is a `StreamReader`, and *if* that stream supports seeking, then: ``` reader.BaseStream.Seek(0, SeekOrigin.Begin); reader.DiscardBufferedData(); ``` However, this is not possible on arbitrary `TextReader`s. You could perhaps read all of it as a string, then you can use `StringReader` repeatedly?
How do you reset a C# .NET TextReader cursor back to the start point?
[ "", "c#", ".net", "file", "" ]
I have a template that gets screenscraped from an outside vendor and need to include absolute paths in the navigation so the externally hosted content will properly link back to our site. Right now the page/template is driven by a global menu app written by our back end development staff... so anyone who updates our site goes in and changes the menus and their paths... Right now all of the links are linking to relative paths back to the root. For example ``` <a href="/">Home</a> <a href="/news/">News</a> <a href="/media/">Media</a> <a href="/other/">Other</a> ``` I need a simple way (preferably with jquery) to prepend "<http://www.domain.com>" to each of those links.
``` $('a').attr('href', 'http://www.domain.com'+$(this).attr('href')); ```
Please note that jQuery object $("a").attr("href") is not equal to $("a").get(0).href ? ``` $("a").each(function() { alert(this.href); $(this).attr("href") = this.href; }); ``` In you case, this may not help you , because you want static markup, javascript generate dynamic content. But it seems that you want static markup in that case it has to be emit by server.
How can I use javascript to convert relative href attributes into absolute paths?
[ "", "javascript", "jquery", "html", "url", "" ]
I've read around about `const` and `static readonly` fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my observation is correct: Should these kind of constant values always be `static readonly` for everything that is public? And only use `const` for `internal`/`protected`/`private` values? What do you recommend? Should I maybe even not use `static readonly` fields, but rather use properties maybe?
`public static readonly` fields are a little unusual; `public static` properties (with only a `get`) would be more common (perhaps backed by a `private static readonly` field). `const` values are burned directly into the call-site; this is double edged: * it is useless if the value is fetched at runtime, perhaps from config * if you change the value of a const, you need to rebuild all the clients * but it can be faster, as it avoids a method call... * ...which might sometimes have been inlined by the JIT anyway If the value will **never** change, then const is fine - `Zero` etc make reasonable consts ;p Other than that, `static` properties are more common.
I would use `static readonly` if the *Consumer* is in a different assembly. Having the `const` and the *Consumer* in two different assemblies is a nice way to [shoot yourself in the foot](http://www.stum.de/2009/01/14/const-strings-a-very-convenient-way-to-shoot-yourself-in-the-foot/).
'Static readonly' vs. 'const'
[ "", "c#", "constants", "" ]
I am having some trouble with this regex: ``` <img(.+)src="_image/([0-9]*)/(.+)/> ``` Global and case insensitive flags is on. The problem is that it also grabs Image n (see string below), but I want it only to match the image tags in the string. ``` <p>Image 1:<img width="199" src="_image/12/label" alt=""/> Image 2: <img width="199" src="_image/12/label" alt=""/><img width="199" src="_image/12/label" alt=""/></p> ``` It works if I put a newline before Image n :) Can anyone point out for me what I am doing wrong? Thanks in advance bob
Use a non-greedy regexp: <img .*? src="\_image/(\d+)/(.+?)/.*?>
If I interpret your regex correctly, it looks like you're after the directory name in the first group and the file path in the second group? ``` <IMG.*?SRC="/_image/(\d+?)/([^"]*?)".*?/> ``` Don't forget to use the regex options CaseInsensitive which wraps the regex with (?i:[regex]) In the second group, you're parsing everything that is not the closing ", right now you're looking for all characters, in fact, you don't need to search all characters, you want everything that isn't the closing quote on the string. Also, don't forget to close your SRC string which you're missing, and that the SRC attribute may not be the last in the tag - for instance border, width, height etc. Also, there may be any number of spaces after the closure of the last attribute and the end of tag /> From this regex, your first match group will hold the subdirectory name and the second match group will hold everything after the / of the subdirectory - including nested subdirectories. If you've got nested subdirectories, you may need to expand this slightly: ``` <IMG.*?SRC="/_image/((\d+?)/)+?([^"]*?)".*?/> ``` In this case, each of the leading groups will hold each of the nested directory names, and the last group will hold the file name.
match image tags with regEx
[ "", "javascript", "regex", "replace", "" ]
My application uses log4j for logging and usually I do logging by checking whether a particular level is enabled and then log like the following ``` if(Logger.isApplicationDebugEnabled()){ Logger.logApplicationDebug("something"+values); } ``` Now this if check reduces our branch coverage during jUnit testing. In order to overcome this, my friend suggested getting rid of "if" checks for logging. 1. First one of my friends suggested removing the if check and log directly. The problem with this approach is that it might slow down the application due to formation of strings which would not end up in log files anyway. 2. The second approach I thought of was very similar to SLF4j. Logger.debug("Number {0}, with date {1,date}",1234, new Date()); This felt very attractive and simple.(This solution internally uses MessageFormat.format(str, object[]) method. But I am concerned about the performance this might have. Also note that 'Logger' is my internal utility class and in each of its log methods, there is a check of Log enabling. What do you guys suggest? I went through velocity templates but it requires map of parameters. Is there any lightweight solution which just substitutes values based on param index location or is this solution okay?
I can strongly recommend the slf4j facade for log4j which allows you to use this syntax log.info("Hello {} from {}", "World", "me") which only does the string expansion after it has been decided that the event should actually should be logged so you don't have to specify the ifEnabled wrapper. Then use log4j as the backend for slf4j. In addition this has measured to be *much* faster than the MessageFormatter.
Ok, I'll ask the obvious question: why not just enable debug logging--or all levels really--while running your unit tests? This has the advantage of increasing code coverage tests AND testing for problems in your logging (which is far from out of the realm of possibility). The checks on if logging is enabled are there for a reason: it can be expensive (inside big loops) to not only construct the final log string but the individual parameters themselves might be expensive to construct. Using MessageFormat or java.util.Formatter or whatever won't get rid of the second problem. I'd really encourage you to keep the check.
Logging complexity and concern about MessageFormat performance
[ "", "java", "performance", "logging", "" ]
This code streams large files to our users: ``` // Open the file. iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } ``` Every once and a while we recieve this exception: ``` The remote host closed the connection. The error code is 0x80072746 ``` Here is the full stack trace: ``` Stack Trace: at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status, Byte[] header, Int32 keepConnected, Int32 totalBodySize, Int32 numBodyFragments, IntPtr[] bodyFragments, Int32[] bodyFragmentLengths, Int32 doneWithSession, Int32 finalStatus, Boolean& async) at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal) at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush) at System.Web.HttpResponse.Flush(Boolean finalFlush) at System.Web.HttpResponse.Flush() at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size) at System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count) at BIS.DocumentBus.Controls.DocumentViewer.StreamFile(String filepath) ``` We have never had evidence that users are having trouble downloading our files and plan to simply ignore this exception. Any idea what the source of this problem is? Is it safe to ignore?
That exception means that the client downloading the file broke the connection before the file had finished downloading. i.e. The client navigated to another page, or just closed the browser. I might try moving the `if (Response.IsClientConnected)` line after your `iStream.Read`. Even if you did that, I think there still might be a chance to receive this error if the connection is broken while the `OutputStream.Write` method is still working.
There are a few different possible causes of this. I can think of three: One is filling the buffer with close to 2GB of data, but this shouldn't be the case here, since you are flushing regularly. Another is indeed that described in the answer you previously accepted. It's very hard to reproduce, so I wouldn't assume it was necessarily wrong. Another possible case, and the one I would bet on, is that the executionTimeout is exceeded, which would cause a ThreadAbortException at first, but this could in turn cause the failure of Flush() which would turn into the exception noted
"The remote host closed the connection" in Response.OutputStream.Write
[ "", "c#", "asp.net", "streaming", "" ]
I am having a oracle table consisting of 6 columns,out of which one is date column. The date field has null entries in some rows...no other field is null.. Can I delete the rows having date field as null? or should I update some value in the date field for those rows...? Please provide me the correct way to do both these operations? thanks....
If you need to retain the other values in the row you can provide a default value for the date in a query with; ``` SELECT NVL(dateCol, to_date('31/01/2009','dd/MM/yyyy')) FROM dataTable ``` To update the null values in the table use; ``` UPDATE dataTable SET dateCol = to_date('31/01/2009','dd/MM/yyyy') WHERE dateCol IS NULL ``` To remove the null rows; ``` DELETE FROM dataTable WHERE dateCol IS NULL ```
delete from table\_name where date\_field is null;
oracle9i queries
[ "", "sql", "oracle", "" ]
I receive a DataTable from excel file and data in the first Column looks like this: `11129` `DBNull.Value` `29299` `29020` `DBNull.Value` `29020` I'm using LINQ to select distict and it works if there are no DBNull.Value values as below. ``` albumIds = dt.AsEnumerable().Select(p => (int)p.Field<double>("F1")).Distinct().ToArray(); ``` But if `DBNull.Value` present which represent empty excel cells I get conversion errors. How do I filter out those `DBNull.Value` from my result set? Thank you
As hinted at in Jeremy's answer, If you've a reference to [System.Data.DataSetExtensions.dll](http://msdn.microsoft.com/en-us/library/bb360891.aspx), you'll get some handy extension methods for working with DataSets and DataTables using LINQ. Specifically, you can use the Field`<int?>`() method to convert an integer column that might contain DBNull into a column of nullable ints... ``` albumIds = dt.AsEnumerable().Select(row => row.Field<int?>("F1")) .Where(val => val.HasValue) .Select(val => val.Value) .Distinct() .ToArray(); ```
Can you try this: ``` dt.AsEnumerable().Where(p => p.IsNull("F1") == false) .Select(p => p.Field<int>("F1")).Distinct().ToArray(); ``` I can't really check this as I don't have this DB setup
Filer DataTable to exclude DBNull.Value
[ "", "c#", "asp.net", "linq", "datatable", "" ]
I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be able to see each line of output from the wrapped program as soon as it is output. I figured that I'd just execute the program using `subprocess.Popen`, use `stdout=PIPE`, then read each line as it came in and act on it accordingly. However, when I ran the following code, the output appeared to be buffered somewhere, causing it to appear in two chunks, lines 1 through 332, then 333 through 439 (the last line of output) ``` from subprocess import Popen, PIPE, STDOUT p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE, stderr = STDOUT, shell = True) for line in p.stdout: print line.replace('\n', '') ``` After looking at the documentation on subprocess a little, I discovered the `bufsize` parameter to `Popen`, so I tried setting bufsize to 1 (buffer each line) and 0 (no buffer), but neither value seemed to change the way the lines were being delivered. At this point I was starting to grasp for straws, so I wrote the following output loop: ``` while True: try: print p.stdout.next().replace('\n', '') except StopIteration: break ``` but got the same result. Is it possible to get 'realtime' program output of a program executed using subprocess? Is there some other option in Python that is forward-compatible (not `exec*`)?
I tried this, and for some reason while the code ``` for line in p.stdout: ... ``` buffers aggressively, the variant ``` while True: line = p.stdout.readline() if not line: break ... ``` does not. Apparently this is a known bug: <http://bugs.python.org/issue3907> (The issue is now "Closed" as of Aug 29, 2018)
By setting the buffer size to 1, you essentially force the process to not buffer the output. ``` p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1) for line in iter(p.stdout.readline, b''): print line, p.stdout.close() p.wait() ```
Getting realtime output using subprocess
[ "", "python", "subprocess", "" ]
``` <?php $i = 0; while(conditionals...) { if($i == 0) print "<p>Show this once</p>"; print "<p>display everytime</p>"; $i++; } ?> ``` Would this only show "Show this once" the first time and only that time, and show the "display everytime" as long as the while loop goes thru?
Yes, indeed. You can also combine the if and the increment, so you won't forget to increment: ``` if (!$i++) echo "Show once."; ```
Rather than incrementing it every time the loop runs and wasting useless resource, what you can do is, if the value is 0 for the first time, then print the statement and make the value of the variable as non-zero. Just like a flag. Condition, you are not changing the value of the variable in between the loop somewhere. Something like this: ``` <?php $i = 0; while(conditionals...) { if($i == 0){ print "<p>Show this once</p>"; $i=1; } print "<p>display everytime</p>"; } ?> ```
Display text once within while loop on the first loop
[ "", "php", "while-loop", "" ]
I'm writing a class that needs to take in an object, record it's current state, update the object, and pass it to another class. The only problem is that you can only inherit from one class and I need that to inherit a class in my project. I'm interested in System.IO.Stream because I can if needed, move this class to it's own thread without most if not all of sockets and other methods of IPC. The main problem is, is there an interface for System.IO.Stream? If not, is there a way to get the functionality I want without sacrificing the project-critical data I depend on? (I'm sorry if I sound a little discoherent, I'm not really sure how to word this question.)
It sounds like `IEnumerable<T>` is a better fit - streams are good for passing *bytes* around, but iterators are good for representing more general streams of objects. You'd want something that read from a stream (e.g. a socket) and created objects, probably with C# iterator blocks (yield statements etc). Then you can use processing functions, filters etc on the `IEnumerable<T>`, and blow it back into a socket (or other byte stream) later on. To answer the question - no, `Stream` doesn't have an interface, but it's not clear how relevant that is to the threading part of your question. Is it that you're interested in async IO?
Why do you want an interface for Stream? implementing the interface won't give you any functionality from the class, it'll simply let other classes know that you provide that functionality. if your REALL REALLY need to have multiple inheritance (two base classes so that you can get the functionality from both), you *could* have your base class, the one you definately need, be a subclass of Stream itself. ``` public class MyObject : Base Object { } public class BaseObject : Stream { } ``` etc..? mroe background / context might help.
Is there an interface for System.IO.Stream?
[ "", "c#", "mono", "" ]
This is a more direct question stemming from an earlier [more general question i had earlier](https://stackoverflow.com/questions/828356/allowing-a-user-to-create-a-custom-query-of-a-table/) now that I've spend more time looking into ADO.NET I want to take an ADO.NET DataTable and perform the equivalent of a SQL SELECT query with aggregate functions (such as SUM) on some columns, and GROUP BY set for the remaining columns. I then want to take the result and display it in a DataGrid. I understand that I can create a DataView of a DataTable that contains filter criteria and aggregate functions. But the [MSDN page on Expressions](http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx) say that *"If you use a single table to create an aggregate, there would be no group-by functionality. Instead, all rows would display the same value in the column."* How do I get GROUP BY type functionality out of ADO.NET without writing my Table to a separate database and running a query there? Is there some way to do it by creating or using a second table?
You can use the grouping ability of LINQ to accomplish this. Also, you can bind a DataGrid to a LINQ query, but the data will be read only. A web search for LINQ grouping should get you where you're going.
Here's how to do it using .NET 3.x and above (LINQ): <http://codecorner.galanter.net/2009/12/17/grouping-ado-net-datatable-using-linq/> And this is how to do it using .NET 2.0 and below (standard ADP.NET) <http://codecorner.galanter.net/2009/04/20/group-by-and-aggregates-in-net-datatable/>
Aggregate functions in ADO.NET with GROUP BY functionality
[ "", "c#", "ado.net", "group-by", "dataview", "aggregate-functions", "" ]
I have three modules as: `one.py`: ``` def abc(): print "Heeeeeeeeeeeiiiiiioooooooooo" ``` `two.py`: ``` import one def defg(): one.abc() ``` `three.py`: ``` import os from time import sleep import two two.defg() sleep(20) directory = os.listdir('.') for filename in directory: if filename[-3:] == 'pyc': print '- ' + filename os.remove(filename) ``` I have three doubts. When I run `three.py` for the first time `one.pyc` and `two.pyc` will be created. I can see it since I gave 20 sec delay. After executing the statement `os.remove(filename)`, they get removed. Until here its fine. Again without closing the IDLE as well as the script, I ran `three.py`. This time no `.pyc` file was created. Why is this so? If I close IDLE as well as the script, `.pyc` will be created as before. 1. Why the compiled code is not getting created again and again? 2. Also, if I make a change in `one.py` it will not be shown if I run without closing the shells. I need a solution for this also. 3. Third doubt is if the compiled code is getting deleted first time itself, then how the second run gives the same result without `.pyc`?
The `.pyc` is not getting created again because there is a reference to your imported module in code. When it is re-run, this reference is used. This is why the `.pyc` is not generated again, and also why the extra changes you make are not getting run. You can either remove all references and call a garbage collect, or use the built in `reload()` function on the modules. e.g.: ``` reload(three) ```
I think that IDLE is caching the bytecode within its own Python process, so it doesn't need to regenerate the it each time the file is run.
Strange behavior after deleting *.pyc and rerunning .py script
[ "", "python", "caching", "" ]
I'm trying to learn dependency injection and have come across a problem, when unit testing the application. I'm writing a console application and the container is created and initialized in Main(), it's available as a `get-property` in `Program.Container`, so anywhere in my application I can call `Program.Container.Resolve<..>()`. I have a ServiceValidator class like this: ``` public class ServiceValidator { private readonly IConfiguration _configuration; private readonly IService _service; public ServiceValidator(IConfiguration configuration, IService service) { _configuration = configuration; _service = service; } ``` In another class I use ``` ServiceValidator serviceValidator = Program.Container.Resolve<ServiceValidator>(); serviceValidator.VerifyVersion(); ``` It's the call to `Program.Container.Resolve` that causes me problems in the unit test, as it hasn't been setup. Is that a bad practice, to call resolve on the container? I could create the ServiceValidator instance in `Main()` and pass the object around, but that seems stupid as it would cause lots of parameters for the objects that are just passed around to the next method. So I guess it's acceptable to call Resolve within a class, but then the container must be configured for the unit test. How should I do that, should I move the container to another place than the Program class? What would you recommend? If it matters, I'm using Unity and C# Thanks :-)
> Is that a bad practice, to call resolve on the container? I could create the ServiceValidator instance in Main() and pass the object around, but that seems stupid as it would cause lots of parameters for the objects that are just passed around to the next method. When you use dependency injection all the way, then you won't need to pass lots of parameters to objects. The constructor of each object should have as parameters only those dependencies which it itself uses directly - it won't know about the transitive dependencies of its direct dependencies. So if you have a class X which requires a ServiceValidator, then class X will have a constructor parameter of type ServiceValidator. Then if some class Y uses class X, then class Y will have a constructor parameter of type X. Notice that Y *knows nothing* about ServiceValidator, so you don't need to pass the ServiceValidator from one class to another - the only place where it is used is when constructing X, and that is often done by a DI framework or in only one place in a hand-written factory. Some links for more information: * <http://martinfowler.com/articles/injection.html> * <http://www.youtube.com/watch?v=RlfLCWKxHJ0> - your question about passing objects around is answered starting 19:20 "Myth about DI"
I usually allow calls to resolve dependencies from the container in places like main although I still try to keep them to a minimum. What I then do is configure the container in an initialization method of a test class. I have it initialized with fake implementations for any test class which needs to call the container. Test classes which don't call anything requiring the container be initialized are then able to ignore it and not use the fakes. I usually use mocks in those instances. I also use the [Microsoft Service Locator](http://msdn.microsoft.com/en-us/library/cc707905.aspx) so that the dependency that I am taking is on something from the .NET Framework instead of on a specific container. This allows me to down the road use anything I want even a home brewed container.
Dependency Injection resolve and unit testing
[ "", "c#", ".net", "unit-testing", "dependency-injection", "ioc-container", "" ]
My program is crashing every time I try to store a COM pointer into a struct, and then later try to use the original pointer. I don't have debug access to tell exactly what's wrong. ``` pRend->cp = cpRT; ID2D1SolidColorBrush *scBrush; ERF(cpRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::CornflowerBlue), &scBrush)); ``` It crashes on CreateSolidColorBrush. However, if I comment out pRend->cp = cpRT, it doesn't. By the way, pRend->cp and cpRT are of type ID2D1HwndRenderTarget \*.
As it turns out, I managed to stop the crashing by allocating pRend with malloc. This is not a problem because I will call free when I don't need it anymore. I'm interested in why calling malloc fixes this though. I'm used to just doing `Datatype * var;` and then just using `var`. Is that bad?
Instead of assigning directly QI and then store i.e., ``` pRend->cp = cpRT; ``` should be replaced with ``` cpRT->QueryInterface(&pRend->cp); ```
Storing a COM pointer in a struct
[ "", "c++", "com", "struct", "pointers", "" ]
Every time I interact with dll's like the user32.dll I need constants like MF\_REMOVE. Is there a overview for all that constants or a c# library that constants all these constants?
You'll find all the constants in the C headers of the win32 API. The low-tech way of getting this information is to simply run a text search in the headers folder of visual studio or the platform SDK. This will usually be something like : > C:\Program Files\Microsoft > SDKs\Windows\v6.0A\Include\
This online tool [MagnumDb](http://www.magnumdb.com/) as "Magic Number Database" (disclaimer: I wrote it) is a totally free seach engine that contains 99% of Windows SDK constants (around 380000 integers, enums, guids, interface ids, clsids, etc.). You can query it by name or by value, using wildcards, etc., for example: <http://www.magnumdb.com/search?q=MF_REMOVE> will get you this (name, type, value, hex value, SDK header file location): ``` MF_REMOVE Int32 4096 0x00001000 %ProgramFiles(x86)%\Windows Kits\10\Include\10.0.16299.0\um\winuser.rh(1213,0) ```
Where can I find a list of windows API constants
[ "", "c#", "winapi", "dll", "constants", "" ]
I need to implement ellipsis (`"..."`) in the middle of a text within a resizable element. [Here](http://i40.tinypic.com/29yqslf.jpg) is what it might look like. So, ``` "Lorem ipsum dolor sit amet. Ut ornare dignissim ligula sed commodo." ``` becomes ``` "Lorem ipsum dolor sit amet ... commodo." ``` When the element is stretched out to the width of the text, I want the ellipsis to disappear. How can this be done?
In the HTML, put the full value in a custom data-\* attribute like ``` <span data-original="your string here"></span> ``` Then assign `load` and `resize` event listeners to a JavaScript function which will read the original data attribute and place it in the `innerHTML` of your span tag. Here is an example of the ellipsis function: ``` function start_and_end(str) { if (str.length > 35) { return str.substr(0, 20) + '...' + str.substr(str.length-10, str.length); } return str; } ``` Adjust the values, or if possible, make them dynamic, if necessary for different objects. If you have users from different browsers, you can steal a reference width from a text by the same font and size elsewhere in your dom. Then interpolate to an appropriate amount of characters to use. A tip is also to have an abbr-tag on the ... or who message to make the user be able to get a tooltip with the full string. ``` <abbr title="simple tool tip">something</abbr> ```
I'd like to propose mine example of solving this problem. The main idea is to split text in two even parts (or first is bigger, if the length is odd) one of which has ellipsis in the end and another aligned right with `text-overflow: clip`. So all you need to do with js, if you want to make it automatic/universal - is to split string and set attributes. It has some disadvantages, though. 1. No nice wrapping by words, or even letters (`text-overflow: ''` works only in FF at the moment) 2. If the split happens between words - space should be in the first part. Otherwise, it will be collapsed. 3. End of the string should not have any exclamation marks, due to `direction: rtl` - they will be moved to the left of the string. I think, it is possible to fix this with putting right part of the word in the tag and exclamation mark in the `::after` pseudo-element. But I haven't yet made it properly working. But, with all of these, it looks really cool to me, especially when you dragging the border of the browser, which you can do on the jsfiddle page easily: <https://jsfiddle.net/extempl/93ymy3oL/>. Or just run the snippet with fixed max-width below. Gif under the spoiler: > [![Gif](https://i.stack.imgur.com/usfEA.gif)](https://i.stack.imgur.com/usfEA.gif) ``` body { max-width: 400px; } span::before, span::after { display: inline-block; max-width: 50%; overflow: hidden; white-space: pre; } span::before { content: attr(data-content-start); text-overflow: ellipsis; } span::after { content: attr(data-content-end); text-overflow: ''; direction: rtl; } ``` ``` <span data-content-start="Look deep into nature, and then you " data-content-end= "will understand everything better"></span> <br> <span data-content-start="https://www.google.com.ua/images/branding/g" data-content-end= "ooglelogo/2x/googlelogo_color_272x92dp.png"></span> ```
Ellipsis in the middle of a text (Mac style)
[ "", "javascript", "jquery", "css", "truncation", "" ]
If I have these two classes: ``` class A {} class B : A {} ``` and I make a List<A> but I want to add a List<B> to it by calling List<A>.AddRange(List<B>) but the compiler refuses: ``` Argument '1': cannot convert from 'System.Collections.Generic.List<A>' to 'System.Collections.Generic.IEnumerable<B> ``` which I completely understand because IEnumerable<B> does not inherit from IEnumerable<A>, its generic type has the inheritance. My solution is to enumerate through List<B> and individually add items because List<A>.Add(A item) will work with B items: ``` foreach(B item in listOfBItems) { listOfAItems.Add(item); } ``` However, that's rather non-expressive because what I want is just AddRange. I could use ``` List<B>.ConvertAll<A>(delegate(B item) {return (A)item;}); ``` but that's unnecessarily convoluted and a misnomer because I'm not converting, I'm casting . **Question**: If I were to write my own List-like collection what method would I add to it that would allow me to copy a collection of B's into a collection of A's as a one-liner akin to List<A>.AddRange(List<B>) **and** retain maximum type-safety. (And by maximum I mean that the argument is both a collection and type inhertance checking.)
Indeed, generic types are not variant right now. In C# 4.0, IEnumerable`<B`> will be convertible to IEnumerable`<A`> *if B is convertible to A via a reference conversion*. For some details on the design of this feature, see: <http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx>
Can't you just do: ``` listOfAItems.AddRange(listOfBItems.Cast<A>()); ```
Adding a collection of a subclass with AddRange
[ "", "c#", ".net-3.5", "inheritance", "iteration", "" ]
I just recently set up my Vim environment from Textmate, after becoming addicted to its modal input. However, syntax highlighting seems to be not so beautiful in Vim. I code in C++ and since the function call and class names can't be highlighted, the code is more difficult to read. I played with color scheme for a bit, but couldn't find any field that corresponded to "class name" or "function name". In the picture below, notice how `DroughtLayer::` and `*.size()` is not highlighted on the right in MacVim. [![Picture comparison between Textmate(left) and Vim(right)](https://i.stack.imgur.com/1cHzr.png)](https://i.stack.imgur.com/1cHzr.png) (source: [ivzhao.com](http://ivzhao.com/temp/vimHL.png)) Any ideas how to solve this? It really annoys me as I am so much a visual-sensitive guy.
Interestingly, the syntax highlighters in VIM don't support applying a syntax to identifiers or function names - at least not the syntax highlighters for C and C++. So, even if you do: ``` :hi Function guifg=red ``` or ``` :hi Identifier guifg=red ``` it doesn't give these a color. I just seems to be not much more than keywords and constants for these languages. Here, someone has started extending the cpp syntax file to support method names. It's a start I guess. <http://vim.wikia.com/wiki/Highlighting_of_method_names_in_the_definition>
I had this very same problem when I started using vim. The solution is simple, you just have to edit the c syntax file used by vim, here's how to do it: When you start editing a C or C++ file, vim reads the default c syntax file located in ``` $VIMRUNTIME/syntax/c.vim ``` (Where $VIMRUNTIME is where you have vim installed. You can find out it's default value by opening vim and using the command ":echo $VIMRUNTIME"). You can simply overwrite that file, or you can create your custom C syntax file (which will be loaded by vim instead of the default one) in this location: ``` $HOME/.vim/syntax/c.vim (for UNIX) $HOME/vimfiles/syntax/c.vim (for PC or OS/2) ``` (I have never used a Mac so I don't know which one will work for you. You can find out more in the vim help, ":help vimfiles") Now the fun part. Copy the default "$VIMRUNTIME/syntax/c.vim" file to your vimfiles directory ("$HOME/.vim/syntax/c.vim" for UNIX), and edit it by adding these lines: > ``` > " Highlight Class and Function names > syn match cCustomParen "(" contains=cParen,cCppParen > syn match cCustomFunc "\w\+\s*(" contains=cCustomParen > syn match cCustomScope "::" > syn match cCustomClass "\w\+\s*::" contains=cCustomScope > > hi def link cCustomFunc Function > hi def link cCustomClass Function > ``` That's it! Now functions and class names will be highlighted with the color defined in the "Function" highlight (":hi Function"). If you want to customize colors, you can change the last two lines above to something like this: ``` hi def cCustomFunc gui=bold guifg=yellowgreen hi def cCustomClass gui=reverse guifg=#00FF00 ``` or you can leave the C syntax file alone and define colors in your vimrc file (":help vimrc"): ``` hi cCustomFunc gui=bold guifg=yellowgreen hi cCustomClass gui=reverse guifg=#00FF00 ``` (Note the absence of the "def" keyword, go to ":help highlight-default" for details). For the available parameters to the ":hi" command see ":help :highlight". You can find the complete c.vim file for Vim 7.2 on this link (Note: only use this if you have a non-modified Vim, version 7.2): > <http://pastebin.com/f33aeab77> And the obligatory screenshot: > [![enter image description here](https://i.stack.imgur.com/qenES.png)](https://i.stack.imgur.com/qenES.png)
class & function names highlighting in Vim
[ "", "c++", "vim", "syntax-highlighting", "textmate", "vim-syntax-highlighting", "" ]
I have created an IEnumerable list of racing drivers using LINQ from a string array as such below: ``` string[] driverNames = { "Lewis Hamilton", "Heikki Kovalainen", "Felipe Massa", "Kimi Raikkonen", "Robert Kubica", "Nick Heidfeld", "Fernando Alonso", "Nelson Piquet Jr", "Jarno Trulli", "Timo Glock", "Sebastien Bourdais", "Sebastien Buemi", "Mark Webber", "Sebastian Vettel", "Nico Rosberg", "Kazuki Nakajima", "Adrian Sutil", "Giancarlo Fisichella", "Jenson Button", "Rubens Barrichello" }; IEnumerable<string> result = from driver in driverNames orderby driver select driver; ``` I am just keeping it simple for now. I then bind it to a ASP.NET GridView like so below: ``` GV_CurrentF1Drivers.DataSource = result; GV_CurrentF1Drivers.DataBind(); ``` This works fine. Now I want to take the same output (result) and bind it to a repeater but no matter what I try I can not get the repeater to work and I think I am missing some key understanding of LINQ and how it works with ASP.NET. Below is the full aspx page to show where I have got to so far. Please can somebody (gently if possible) guide me back on to the path? ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Example1.aspx.cs" Inherits="Example1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div style="float: left;"> <asp:GridView ID="GV_CurrentF1Drivers" runat="server" /> </div> <div style="float: left;"> <asp:Repeater ID="R_CurrentF1Drivers" runat="server"> <ItemTemplate> <%# Eval("driver") %></ItemTemplate> </asp:Repeater> </div> </form> </body> </html> ``` I use the following code to bind the result to the Repeater: ``` R_CurrentF1Drivers.DataSource = result; R_CurrentF1Drivers.DataBind(); ``` I get the following error when I try to run the page with the Repeater in: **Exception Details:** System.Web.HttpException: DataBinding: 'System.String' does not contain a property with the name 'driver'.
You're getting back an enumerable of strings with no name. If you want to use the property name driver you can make an anonymous type and say: ``` var result = from driver in driverNames orderby driver select new { Driver = driver }; ``` then do the databinding. I believe you can also `Eval(".")` to evaluate the object itself and not a property. Also as multiple people have said below you can use `<%# Container.DataItem %>`.
Change `<%# Eval("driver") %>` to ``` <%# Container.DataItem %> ```
I am trying to learn how to bind an IEnumerable LINQ collection to a repeater
[ "", "c#", "asp.net", "linq", "" ]
How do I convert hh:mm:ss to hh:mm in SQL Server? ``` select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog where Date between '2009-05-04 00:00:00' and '2009-05-06 14:58' and [user] in(select USERNAME from scr_CustomerAuthorities ) group by Page,Date order by [VisitingCount] asc ```
In general, the set of timestamps is not [**well-ordered**](http://en.wikipedia.org/wiki/Well_ordered_set), this means you cannot get a "last" timestamp whose time part up to minutes is `2009-05-06 14:58`. In `SQL Server`, which keeps the time part of a datetime as a number of `1/300` second fractions after midnight, this "last" timestamp would be `2009-05-06 14:58:59.997`, but this is not guaranteed to be compatible with future releases of with other `TIMESTAMP` storage methods. That means you'll need to split your `BETWEEN` condition into two conditions, one of which being `strict less` than the next minute: ``` select Count(Page) as VisitingCount,Page,CONVERT(VARCHAR(8),Date, 108) from scr_SecuristLog where Date >= '2009-05-04 00:00:00' AND Date < DATEADD(minute, 1, '2009-05-06 14:58') and [user] in(select USERNAME from scr_CustomerAuthorities ) group by Page,Date order by [VisitingCount] asc ``` This solution will efficiently use indexes on `Date`
`CONVERT(VARCHAR(5),Date, 108)`-- Gets only `HH:mm`
How do I convert hh:mm:ss to hh:mm in SQL Server?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I need to write a extended version of the StringUtils.commaDelimitedListToStringArray function which gets an additional parameter: the escape char. so calling my: ``` commaDelimitedListToStringArray("test,test\\,test\\,test,test", "\\") ``` should return: ``` ["test", "test,test,test", "test"] ``` My current attempt is to use String.split() to split the String using regular expressions: ``` String[] array = str.split("[^\\\\],"); ``` But the returned array is: ``` ["tes", "test\,test\,tes", "test"] ``` Any ideas?
The regular expression ``` [^\\], ``` means "match a character which is not a backslash followed by a comma" - this is why patterns such as `t,` are matching, because `t` is a character which is not a backslash. I think you need to use some sort of [negative lookbehind](http://www.regular-expressions.info/lookaround.html), to capture a `,` which is not preceded by a `\` without capturing the preceding character, something like ``` (?<!\\), ``` (BTW, note that I have purposefully not doubly-escaped the backslashes to make this more readable)
Try: ``` String array[] = str.split("(?<!\\\\),"); ``` Basically this is saying split on a comma, except where that comma is preceded by two backslashes. This is called a [negative lookbehind zero-width assertion](http://www.regular-expressions.info/lookaround.html).
How to split a comma separated String while ignoring escaped commas?
[ "", "java", "regex", "csv", "" ]
Answer is not $array[0]; My array is setup as follows ``` $array = array(); $array[7] = 37; $array[19] = 98; $array[42] = 22; $array[68] = 14; ``` I'm sorting the array and trying to get the highest possible match out after the sorting. So in this case $array[19] = 98; I only need the value 98 back and it will *always* be in the first position of the array. I can't reference using $array[0] as the 0 key doesn't exist. Speed constraints mean I can't loop through the array to find the highest match. There also has to be a better solution than ``` foreach ( $array as $value ) { echo $value; break; } ```
``` $keys = array_keys($array); echo $array[$keys[0]]; ``` Or you could use the [current()](https://www.php.net/manual/en/function.current.php) function: ``` reset($array); $value = current($array); ```
You want the first key in the array, if I understood your question correctly: ``` $firstValue = reset($array); $firstKey = key($array); ```
Referencing for element in a PHP array
[ "", "php", "arrays", "" ]
Are **enum** types faster/more efficient than **string** types when used as dictionary keys? ``` IDictionary<string,object> or IDictionary<enum,object> ``` As a matter of fact, which data type is most suitable as a dictionary key and why? Consider the following: *NOTE: Only 5 properties for simplicity* ``` struct MyKeys { public string Incomplete = "IN"; public string Submitted = "SU"; public string Processing="PR"; public string Completed = "CO"; public string Closed = "CL"; } ``` and ``` enum MyKeys { Incomplete, Submitted, Processing, Completed, Closed } ``` Which of the above will be better if used as keys in a dictionary!
Certainly the `enum` version is better (when both are applicable and make sense, of course). Not just for performance *(it can be better or worse, see Rashack's very good comment)* as it's checked compile time and results in cleaner code. You can circumvent the comparer issue by using `Dictionary<int, object>` and casting `enum` keys to `int`s or specifying a custom comparer.
I think you should start by focusing on correctness. This is far more important than the minimal difference between the minor performance differences that may occur within your program. In this case I would focus on the proper representation of your types (enum appears to be best). Then later on profile your application and if there is a issue, then and only then should you fix it. Making code faster later in the process is typically a straight forward process. Take the link that skolima provided. If you had chosen enum, it would have been a roughly 10 minute fix to remove a **potential** performance problem in your application. I want to stress the word potential here. This was definitely a problem for NHibernate but as to whether or not it would be a problem for your program would be solely determined by the uses. On the other hand, making code more correct later in the process tends to be more difficult. In a large enough problem you'll find that people start taking dependencies on the side effects of the previous bad behavior. This can make correcting code without breaking other components challenging.
Which is faster/more efficient: Dictionary<string,object> or Dictionary<enum,object>?
[ "", "c#", "string", "dictionary", "enums", "" ]
I'm about to start work on my first C++ project. I've done lots of C# and VB (VB6 and VB.NET), plus Java and a few other things over the past 10 years or so, just never had a requirement for C++ until now. I plan to use Visual Studio 2008, but I'm interested to find out from experienced C++ programmers whether Visual Studio is a good IDE for a C++ newbie. Will VS in any way make it harder for me to learn to program C++ correctly? Will VS encourage any bad habits? Are there any pitfalls I should look out for?
First off, VS 2008 is quite powerful and probably one of the best IDEs for C++ programming (at least with a supporting plugin such as [Visual Assist X](http://www.wholetomato.com/)). Beware, however, that C++ is a hard language to get right for the compilers and that the default warning level is quite lenient to boot. So it *will* tolerate bad/wrong code quite often. It is always advisable to check the code on other compilers as well – at the very least in `g++` with high warning level in strict mode. Also setting the warning level higher in Visual Studio is encouraged.
Visual Studio is an excellent IDE for C++. If you know it from C#, it will be comfortably familiar.
New to C++: should I use Visual Studio?
[ "", "c++", "ide", "" ]
I am filling items to my ComboBox from a XML file using a DataTable. Currently I have it set so that one column is ComboBox's displaymember and another is it's value member. However this may not always work for me, since I have to set the selectedItem parameter, and value member may not be unique. I don't know if there is a duplicate of the value member in the table or not, so my idea was that I would put entire DataRow as the value member of the ComboBox and then use ComboBox.SelectedITem = (DataRow)some\_data\_row; for selecting, and it would always select the right ComboBox object. How would I accomplish this? IS there a better way of doing this? I'm open to suggestions, however it is very important that I can get to both, display member and value member. Thank you for your help! **EDIT**: Maybe I wasn't clear enough before, however while I am asking if this is the best approach here, I am also asking *how* to do this. If I don't set the valuemember parameter, the SelectedItem is of DataRowView type... Please note, that I want to use the selectedValue parameter to select items from ComboBox, and if I try to do that without explicitly setting the value member an exception is thrown.
First of all thank you Adam Robinson, I'm sure your answer was correct, but it just wasn't what I wanted to hear. I solved my problem in a different way and I think it may be useful to someone else, so I am posting it here. What I did was I created a new class, in my case I named it ListObject, which had a property DataRow (as you will see later it works for other types too, I just used this since this is what I actually wanted as my Item value property). It also overrides methods: * String ToString() * bool Equals(object obj) * int GetHashCode() --is not needed in my case, however Visual Studio warns you it should be overridden. The idea was that I could fill ComboBox.Items collections with objects of my own class, display a custom string (if I had not worked it out like this, my next question on Stack overflow would probably be about customizing DisplayMembers when reading items from a DataRow) and compare only one class's item (in my case DataRow). So here is the code and it works great (at least for what I wanted to do with it). ``` public class ListObject { public DataRow element; public String DisplayObject = null; public ListObject(DataRow dr) { element = dr; } public ListObject(DataRow dr, String dspObject) { element = dr; DisplayObject = dspObject; } public override String ToString() { if (DisplayObject == null) throw new Exception("DisplayObject property was not set."); return element[DisplayObject].ToString(); } public override bool Equals(object obj) { if (obj.GetType() == typeof(ListObject)) return Equals(((ListObject)obj).element, this.element); else return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } ``` In my case it works great since I can just fill the ComboBox's with a foreach statement: ``` dtUsers.ReadXml(Program.Settings.xmlInputUsers); foreach(DataRow dr in dtUsers.Rows) { cmbUser.Items.Add(new ListObject(dr, "Name")); } ``` And when I get the DataRow I want selected I just do this: ``` cmbUser.SelectedItem = new ListObject(dlg.SelectedDataRow); ``` Where I don't have to worry about the DisplayMember etc, because only DataRow's will be compared, and your display parameters will still be set from when you filled ComboBox.Items collection. Also since toString method is overridden you can really customize your output. Creating this class was only possible because of msdn article on *ComboBox.SelectedItem Property* in which it was noted, that SelectedItem property works using the IndexOf method. This method uses the Equals method to determine equality.
If you bind a `ListBox` to a `DataTable`, you're actually binding it to a `DataView` that represents that `DataTable` (`DataTable` implements `IListSource`, and that returns a `DataView`). You can't directly set `SelectedItem` to a `DataRow` instance, you have to set it to a `DataRowView` instance. Unfortunately there's no easy way to obtain a `DataRowView` from a `DataRow`. You would do better to just do all of your interactions through a `DataRowView`. This will allow you to set `SelectedItem` explicitly. You cannot use the `SelectedValue` property, you must use `SelectedItem` for this.
Setting DataRow as ComboBox's value member
[ "", "c#", "combobox", "datatable", "" ]
I have just created a .properties file in Java and got it to work. The problem is where/how to store it. I'm currently developing a "Dynamic Web project" in Eclipse, and have stored the properties file under build/classes/myfile.properties, and I'm using this code to load it: ``` properties.load(this.getClass().getResourceAsStream("/myfile.properties")); ``` But won't this folder get truncated when building the project, or not included when exporting as a WAR file? How can I add this file to the build path, so it will be added to /build/classes on every export (in eclipse)?
If you add your .properties file into the source folder, it will get copied into the classes folder at build time. I usually create a separate "Source Folder" in my projects to hold .properties files and other non-Java source files.
See my question on [copying property files using an ant task](https://stackoverflow.com/questions/775279). Eclipse will do this automatically, as @highlycaffeinated has suggested, but you have to make sure your list-of-files is up-to-date (refresh files on your project before you debug/run/deploy). I use ant for more formal control over this.
Java export .properties file to build folder?
[ "", "java", "" ]
I'm trying to render a colored cube after rendering other cubes that have textures. I have multiple "Drawer" objects that conform to the Drawer interface, and I pass each a reference to the GL object to the *draw( final GL gl )* method of each individual implementing class. However, no matter what I do, I seem unable to render a colored cube. Code sample: ``` gl.glDisable(GL.GL_TEXTURE_2D); gl.glColor3f( 1f, 0f, 0f ); gl.glBegin(GL.GL_QUADS); // Front Face Point3f point = player.getPosition(); gl.glNormal3f(0.0f, 0.0f, 1.0f); //gl.glTexCoord2f(0.0f, 0.0f); gl.glVertex3f(-point.x - 1.0f, -1.0f, -point.z + 1.0f); //gl.glTexCoord2f(1.0f, 0.0f); gl.glVertex3f(-point.x + 1.0f, -1.0f, -point.z + 1.0f); //continue rendering rest of cube. ... gl.glEnd(); gl.glEnable(GL.GL_TEXTURE_2D); ``` I've also tried throwing the glColor3f calls before each vertex call, but that still gives me a white cube. What's up?
There are a few things you need to make sure you do. First off: ``` gl.glEnable(gl.GL_COLOR_MATERIAL); ``` This will let you apply colors to your vertices. (Do this before your calls to glColor3f.) If this still does not resolve the problem, ensure that you are using blending properly (if you're using blending at all.) For most applications, you'll probably want to use ``` gl.glEnable(gl.GL_BLEND); gl.glBlendFunc(gl.GL_SRC_ALPHA,gl.GL_ONE_MINUS_SRC_ALPHA); ``` If neither of these things solve your problem, you might have to give us some more information about what you're doing/setting up prior to this section of your code.
If lighting is enabled, color comes from the material, not the glColor vertex colors. If your draw function that you mentioned is setting a material for the textured objects (and a white material under the texture would be common) then the rest of the cubes would be white. Using GL\_COLOR\_MATERIAL sets up OpenGL to take the glColor commands and update the material instead of just the vertex color, so that should work. So, simply put, if you have lighting enabled, try GL\_COLOR\_MATERIAL.
OpenGL - Unable to render colors other than white after texture mapping
[ "", "java", "opengl", "jogl", "" ]
How can I group by Time? I tried this, but it gives the error "Invalid column name 'Time'.": ``` select Count(Page) as VisitingCount, CONVERT(VARCHAR(5), Date, 108) as [Time] from scr_SecuristLog where Date between '2009-05-04 00:00:00' and '2009-05-06 14:58' and [user] in (select USERNAME from scr_CustomerAuthorities) group by [Time] order by [VisitingCount] asc ```
[Time] is a column alias. Try ``` SELECT COUNT(Page) AS VisitingCount , CONVERT(VARCHAR(5),Date, 108) AS [Time] FROM scr_SecuristLog WHERE Date BETWEEN '2009-05-04 00:00:00' AND '2009-05-06 14:58' AND [user] IN ( SELECT USERNAME FROM scr_CustomerAuthorities ) GROUP BY CONVERT(VARCHAR(5),Date, 108) ORDER BY [VisitingCount] ASC ```
Try ``` GROUP BY CONVERT(VARCHAR(5),Date, 108) ``` Always make sure you group by everything in your select clause that does not have an aggregate function around it.
How can I group by my columns in SQL?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
We have a C#/.NET 2.0 WinForm with an ActiveX ShockwaveFlashObject control on it. The program loops through a schedule of content and displays it over and over on the control, fullscreen, like this: ``` axFlash.BringToFront(); axFlash.Movie = scheduleItem.FilePath; axFlash.Show(); axFlash.Play(); ``` This works great, but after a couple of days running, the form on which the Flash ActiveX control resides will throw an exception like this: ``` System.Runtime.InteropServices.SEHException: External component has thrown an exception. at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Control.DefWndProc(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.AxHost.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ``` Looking at the taskmanager, I see that our program has allocated virtually all of the available memory on the machine. (~500MB) * Are ActiveX (COM) components unmanaged by Garbage Collection? * Is there some known memory leak in Flash9.ocx or Flash10.ocx? * Any ideas how I can get an external component (Flash ActiveX in this case) to release resources back without restarting the program? Could periodically re-creating the ShockwaveFlashObject with a "new" fix things? * Maybe restarting the program periodically is the only good option?
ActiveX components typically are written in unmanaged code, and therefore would not be cleaned up by the CLR garbage collector. You need to ensure you release any references to the ActiveX control. I think this would only create an issue though if you are recreating the ActiveX control a lot. You can use perfmon to measure memory usage by the CLR and memory usage overall. You can use this to narrow down who is leaking the memory. (the difference would be due to unmanaged code, like the activex control) If you do isolate it to the ActiveX or flash control, trying stubbing out those objects with a fake object that doesn't consume memory. This should let you verify it is the source of the leak.
If the code in your C# application is simplistic I would recommend just writing it in AIR. This way you aren't dealing with ActiveX and any bugs that Flash's OCX may have.
ActiveX Flash component in C# .NET 2.0 Application causes memory leak?
[ "", "c#", ".net", "flash", "com", "activex", "" ]
I have Hidden field like ``` <%= Html.Hidden("ID", 1) %> ``` and in javascript i want a value of that field by ``` var ID = document.getElementsByName("ID").value; ``` I can't access it! is there any other way?
Not sure of the context but shouldn't you be using [getElementById](http://www.w3schools.com/jsref/met_doc_getelementbyid.asp) ??
Try this : ``` <input type="hidden" id="ID" /> ``` for javascript to access it : ``` var ID = document.getElementById("ID").value; ``` other way with JQuery : ``` var ID = $('#ID').val(); ```
Can Hidden element be accessed by javascript getElementByName?
[ "", "javascript", "asp.net-mvc", "" ]
I've looked into COM servers and Windows services but I'm not sure what best suits my purposes or how to do it. What I want is something that can be started and run for an indefinite amount of time which holds an object so that other processes or applications obtain references to that object (or make requests to the server) to modify or query its state. The server is essentially an application which processes commands to a device over a serial port and maintains an internal state of the device. I have the device communication and persistence functionality written in C# right now and it can be created and run on a per-process basis but obviously I want it to instantiate once and run independently of other processes. COM tutorials I've read have only confused me since I wasn't entirely sure if that is what I wanted and I was hoping there'd be more of a .Net way to do this. Any help would be immensely appreciated!
I would build a Windows Communication Foundation (WCF) service for this and expose it with one of the many bindings that is available. You can expose it via HTTP/SOAP, HTTP/REST, TCP/Binary, MSMQ, etc. all from the same service. If you have Windows 2008, you can activate it via Windows Activation Service (WAS). If you have some other Windows OS, you should write a Windows Service that you can register with the Service Control Manager (SCM). There are a lot of options here but I would definitely lean toward using WCF to create your service. There's so much "plumbing" that WCF takes care of for you. No need to reinvent all of that. Hope this helps.
this seems like a natural fit for a windows service. i should say that i'm not a .net programmer, but i understand you can create services with .net. as long as you know you can manipulate the serial port with .net you should be good to go. -don
creating long-lived server for other applications on windows
[ "", "c#", ".net", "com", "com+", "" ]
I'm trying to secure a WCF service using windows accounts. The service should run on many systems with different languages. How can i set a PrincipalPermission that has language independent role names? I found ugly workarounds like this one. ``` [PrincipalPermission(SecurityAction.Demand, Role = "Builtin\\Administrators")] // English [PrincipalPermission(SecurityAction.Demand, Role = "Vordefiniert\\Administratoren")] // German public string HelloWorld() { return "Hello"; } ``` I don't think this is a good solution, is there any way to make this language independent? Is there a way to use the account SID instead of a string?
One more try: Have a look at <http://msdn.microsoft.com/en-us/library/system.security.principal.windowsbuiltinrole.aspx> .... and go to the sample . There you can use the BuiltIn enumeration members to get the correctly spelled group name (via the API)... then it should be language neutral. HTH, Thomas
You could roll your own permission attribute which handles the translation: ``` [Serializable, AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false), ComVisible(true)] public sealed class AdministratorPrincipalPermissionAttribute : CodeAccessSecurityAttribute { public AdministratorPrincipalPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { var identifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); var role = identifier.Translate(typeof(NTAccount)).Value; return new PrincipalPermission(null, role); } } ``` Please note that this would require some extra deployment effort (gac, caspol etc.).
How to set a multilanguage PrincipalPermission role name?
[ "", "c#", "security", "permissions", "multilingual", "" ]
ECMAScript 6 introduced [the `let` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let). I've heard that it's described as a local variable, but I'm still not quite sure how it behaves differently than the `var` keyword. What are the differences? When should `let` be used instead of `var`?
# Scoping rules The main difference is scoping rules. Variables declared by `var` keyword are scoped to the immediate function body (hence the function scope) while `let` variables are scoped to the immediate *enclosing* block denoted by `{ }` (hence the block scope). ``` function run() { var foo = "Foo"; let bar = "Bar"; console.log(foo, bar); // Foo Bar { var moo = "Mooo" let baz = "Bazz"; console.log(moo, baz); // Mooo Bazz } console.log(moo); // Mooo console.log(baz); // ReferenceError } run(); ``` The reason why `let` keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript. Take a look at this example from [another Stack Overflow question](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example): ``` var funcs = []; // let's create 3 functions for (var i = 0; i < 3; i++) { // and store them in funcs funcs[i] = function() { // each should log its value. console.log("My value: " + i); }; } for (var j = 0; j < 3; j++) { // and now let's run each one to see funcs[j](); } ``` `My value: 3` was output to console each time `funcs[j]();` was invoked since anonymous functions were bound to the same variable. People had to create immediately invoked functions to capture correct values from the loops but that was also hairy. # Hoisting Variables declared with `var` keyword are [hoisted and *initialized*](https://dev.to/godcrampy/the-secret-of-hoisting-in-javascript-egi) which means they are accessible in their enclosing scope even before they are declared, however their value is `undefined` before the declaration statement is reached: ``` function checkHoisting() { console.log(foo); // undefined var foo = "Foo"; console.log(foo); // Foo } checkHoisting(); ``` `let` variables are [hoisted but *not initialized*](https://stackoverflow.com/questions/31219420/are-variables-declared-with-let-or-const-hoisted) until their definition is evaluated. Accessing them before the initialization results in a `ReferenceError`. The variable is said to be in [the temporal dead zone](https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone) from the start of the block until the declaration statement is processed. ``` function checkHoisting() { console.log(foo); // ReferenceError let foo = "Foo"; console.log(foo); // Foo } checkHoisting(); ``` # Creating global object property At the top level, `let`, unlike `var`, does not create a property on the global object: ``` var foo = "Foo"; // globally scoped let bar = "Bar"; // globally scoped but not part of the global object console.log(window.foo); // Foo console.log(window.bar); // undefined ``` # Redeclaration In strict mode, `var` will let you re-declare the same variable in the same scope while `let` raises a SyntaxError. ``` 'use strict'; var foo = "foo1"; var foo = "foo2"; // No problem, 'foo1' is replaced with 'foo2'. let bar = "bar1"; let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared ```
`let` can also be used to avoid problems with closures. It binds fresh value rather than keeping an old reference as shown in examples below. ``` for(var i=1; i<6; i++) { $("#div" + i).click(function () { console.log(i); }); } ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Clicking on each number will log to console:</p> <div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="div4">4</div> <div id="div5">5</div> ``` Code above demonstrates a classic JavaScript closure problem. Reference to the `i` variable is being stored in the click handler closure, rather than the actual value of `i`. Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click. A general workaround is to wrap this in an anonymous function and pass `i` as an argument. Such issues can also be avoided now by using `let` instead `var` as shown in the code below. (Tested in Chrome and Firefox 50) ``` for(let i=1; i<6; i++) { $("#div" + i).click(function () { console.log(i); }); } ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Clicking on each number will log to console:</p> <div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="div4">4</div> <div id="div5">5</div> ```
What is the difference between "let" and "var"?
[ "", "javascript", "scope", "ecmascript-6", "var", "let", "" ]
I've arrived at the point where I realise that I must start versioning my database schemata and changes. I consequently read the existing posts on SO about that topic but I'm not sure how to proceed. I'm basically a one man company and not long ago I didn't even use version control for my code. I'm on a windows environment, using Aptana (IDE) and SVN (with Tortoise). I work on PHP/mysql projects. What's a efficient and sufficient (no overkill) way to version my database schemata? I do have a freelancer or two in some projects but I don't expect a lot of branching and merging going on. So basically I would like to keep track of concurrent schemata to my code revisions. [edit] **Momentary solution**: for the moment I decided I will just make a schema dump plus one with the necessary initial data whenever I'm going to commit a tag (stable version). That seems to be just enough for me at the current stage.[/edit] [edit2]plus I'm now also using a third file called increments.sql where I put all the changes with dates, etc. to make it easy to trace the change history in one file. from time to time I integrate the changes into the two other files and empty the increments.sql[/edit]
I think this question deserves a modern answer so I'm going to give it myself. When I wrote the question in 2009 I don't think [Phinx](https://phinx.org/) already existed and most definitely Laravel didn't. Today, the answer to this question is very clear: Write incremental DB migration scripts, each with an `up` and a `down` method and run all these scripts or a delta of them when installing or updating your app. And obviously add the migration scripts to your VCS. As mentioned in the beginning, there are excellent tools today in the PHP world which help you manage your migrations easily. Laravel has DB migrations built-in including the respective shell commands. Everyone else has a similarly powerful framework agnostic solution with Phinx. Both Artisan migrations (Laravel) and Phinx work the same. For every change in the DB, create a new migration, use plain SQL or the built-in query builder to write the up and down methods and run `artisan migrate` resp. `phinx migrate` in the console.
Simple way for a small company: dump your database to SQL and add it to your repository. Then every time you change something, add the changes in the dump file. You can then use diff to see changes between versions, not to mention have comments explaining your changes. This will also make you virtually immune to MySQL upgrades. The one downside I've seen to this is that you have to remember to manually add the SQL to your dumpfile. You can train yourself to always remember, but be careful if you work with others. Missing an update could be a pain later on. This could be mitigated by creating some elaborate script to do it for you when submitting to subversion but it's a bit much for a one man show. **Edit:** In the year that's gone by since this answer, I've had to implement a versioning scheme for MySQL for a small team. Manually adding each change was seen as a cumbersome solution, much like it was mentioned in the comments, so we went with dumping the database and adding that file to version control. What we found was that test data was ending up in the dump and was making it quite difficult to figure out what had changed. This could be solved by dumping the schema only, but this was impossible for our projects since our applications depended on certain data in the database to function. Eventually we returned to manually adding changes to the database dump. Not only was this the simplest solution, but it also solved certain issues that some versions of MySQL have with exporting/importing. Normally we would have to dump the development database, remove any test data, log entries, etc, remove/change certain names where applicable and only then be able to create the production database. By manually adding changes we could control exactly what would end up in production, a little at a time, so that in the end everything was ready and moving to the production environment was as painless as possible.
Starting with versioning mysql schemata without overkill. Good solutions?
[ "", "php", "mysql", "svn", "version-control", "database-versioning", "" ]
In PL/SQL Developer v7.1.x, is there way way to ignore large data types in queries or the "Query Data" feature. For example: If you right click on table `FOO`, and select "Query Data" this will execute a `SELECT * FROM FOO`. If that table contains `BLOB` data the query will take a while to complete and temporarily lock up the application. This is especially problematic when querying remote databases (for obvious reasons). I would like a way to tell PL/SQL Developer not to retrieve large data by default. I know there is a way to limit the ResultSet size but this doesn't do what I am looking for. I could just select each column I wanted ignoring certain ones but then I couldn't use the "Query Data" feature. Thanks.
No, the Query Data feature does one thing and one thing only - queries all the data. What you might find useful is that you can drag the name of a table or view from the Browser into a SQL Window, choose "Select" from the menu that pops up, and it will generate a SELECT statement on the table with all the column names included - but does not execute the query straight away. You can then edit it however you like (e.g. comment out the LOB columns) before you run it.
I know that `Toad` has something like that built in, but I'm not aware of a PL/SQL Developer option that disables BLOBS. The option you are left with, for now, is to simply select all the columns individually and truncate the blob. ie: `select foo, bar, trunc(baz,100) from foo where ...`
PL/SQL Developer - ignore/limit large data in queries
[ "", "sql", "plsql", "" ]
I'm currently using the following code in my cms to check if visitor is logged in as admin so that he can edit the current page: ``` if($_SESSION['admin']=="1") { echo "<a href="foobar/?update">edit</a>"; } ``` But I'm worried that the code is unsafe. Can't $\_session variables easily be modified by the user? What would be a safer practice?
No, that's a good way to do it. The user can't modify the $\_SESSION global, unless he has access to your server. Remember to **stay away from client-side cookies**. To make it even more safe, a good way is to store the IP-adress and check that it stays the same between every request.
The code is OK, you're just showing a link. Just make sure that your UPDATE script is protected as well.
Bad handling of PHP sessions variables?
[ "", "php", "security", "session", "" ]
Let's say I have an abstract parent class called "shape", and that there are multiple subclasses (triangle, square, circle... ). I want to define an abstract method in the parent "shape" class which all subclasses must implement, let's call it "draw". So all shape subclasses must provide the "draw()" method. But, the draw method takes a parameter of type "Stencil", and, not every shape subclass can use just any stencil... So there is one abstract "shape" class, multiple shape subclasses, and multiple stencils. I need a draw method defined in the shape class. A square might use Stencil1 and the circle might use Stencil2. I'm guessing that generics would do the trick, but I'm not sure. Each shape subclass needs to define the draw method with a specific stencil because these classes are used by other classes as well, and the compiler should force all programmers to call the draw methods with the stencil that is supported by that class. We can't define an abstract method like "public abstract void draw(Stencil s)" because then the programmer could pass in any stencil to the square class, whereas the square class only supports "Stencil1" Any ideas? **Update1:** Should add that the shape class doesn't care which stencil is used by the subclass, but since the subclasses are used in other classes too, it's important that the draw method is defined so that only the supported stencil is accepted by the compiler.
``` public abstract class Shape<S extends Stencil> { public abstract void draw( S stencil ); } public class Square extends Shape<Stencil1> { public void draw( Stencil1 stencil ) { stencil.letsdo(); stencil.some(); stencil.drawing(); } } public class Circle extends Shape<Stencil2> { public void draw( Stencil2 stencil ) { stencil.some(); stencil.more(); stencil.drawing(); } } ```
I think you should probably reconsider your initial design. Of course, you *could* get around this by using instanceof, etc. However, this will result in a very confusing API (if that's what you are using it for).
Is it possible to have specialized parameters in overridden methods?
[ "", "java", "abstract-class", "overriding", "" ]
Since the getElementsByTagName() function is new (DOM-1?) I wanted another more reliable method to get a reference to an element based on its tag name/id. **Edit-** Without using a framework, since I need to cut down on size; so 10-20K for a framework is unacceptable. I just need the JS code that can fetch an element
getElementsByTagName is not new. It is supported since IE5, FF1 and Opera 7 according to [w3schools](http://www.w3schools.com/HTMLDOM/dom_obj_document.asp) [edit] Thanks for pointing this out. It was indeed supported since Opera 7.
As mentioned, getElementsByTagName is not new... I think you're going to get about 10 references to [jQuery](http://jquery.com). Returns all the paragraph elements: ``` $('p').length ``` If 19kb is too big, and you just want to do element selection, something like [sizzle](http://sizzlejs.com/) works well, at about 4kb. The only thing I would note is that you're probably going to end up needing something that's in jQuery anyway. <http://sizzlejs.com/> Queries are very similar: ``` Sizzle("li"); ``` 19kb is a really small one-time price to pay for the power of jQuery.
Alternative to getElementsByTagName
[ "", "javascript", "html", "dom", "" ]
What's the difference between the two? Why would you use one over the other?
Found here: <http://aaron-powell.spaces.live.com/blog/cns!91A824220E2BF369!150.entry> **DataContractJsonSerializer** The primary purpose of the DataContractJsonSerializer is to be used with WCF, since one serialization is a big focus of WCF. Also, it is also better equipped to handle complex classes which have only certain properties available for serialization. This class is more strongly typed, has more knowledge about the type(s) it's handling and better error handling for badly-formed JSON. **JavaScriptSerializer** This class on the other hand is much better equipped for quick serialization, it's a more cowboy approach. There's less error checking and less control over what properties which are serialized. Update As the above link is dead, here is another link: [http://kb.cnblogs.com/a/1454030](http://kb.cnblogs.com/a/1454030/).
Personally, I'd look at [Json.NET](http://www.newtonsoft.com/json) - this has the advantage of being .NET 2.0 compatible
System.Web.Script.Serialization.JavaScriptSerializer or System.Runtime.Serialization.Json.DataContractJsonSerializer?
[ "", "c#", ".net", "json", "" ]
I think one commonly known way of adding PHP to an Apache webserver is to configure it like this: ``` ScriptAlias /php5.3 /usr/local/php5.3/bin Action application/php5.3 /php5.3/php-cgi AddType application/php5.3 .php ``` Now I tried to write a similar configuration for Python: ``` ScriptAlias /python /usr/bin Action application/python /python/python AddType application/python .py ``` I have a small test script that looks like this: ``` print "Content-Type: text/html\n\n" print "Test" ``` But something seems to be wrong since the apache error log says the following: ``` Premature end of script headers: python ``` So my first though was that my python response is not right. But there is the Content-Type and also both linebreaks. Also the output of a similar PHP script called with `php-cgi` gives exactly the same output. Also I haven't found a tutorial that shows how to get python working this way. So maybe it is not possible, but then I'm curious why this is the case? Or am I missing something?
" So maybe it is not possible, but then I'm curious why this is the case?" Correct. It's not possible. It was never intended, either. Reason 1 - Python is not PHP. PHP -- as a whole -- expects to be a CGI. Python does not. Reason 2 - Python is not inherently a CGI. It's an interpreter that has (almost) no environmental expectations. Reason 3 - Python was never designed to be a CGI. That's why Python is generally embedded into small wrappers (mod\_python, mod\_wsgi, mod\_fastcgi) which can encapsulate the CGI environment in a form that makes more sense to a running Python program.
You can use *any* type of executable as cgi. Your problem is in your apache config, which looks like you just made it up. Check the apache docs for more details, but you don't need the Action and AddType. ``` ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" ``` Then drop the following into your cgi-bin: ``` #!/usr/bin/python # test.py print "Content-Type: text/html\n\n" print "Test" ``` Make sure it's executable, and see the result at /cgi-bin/test.py
Configure Apache to use Python just like CGI PHP
[ "", "python", "apache", "cgi", "" ]
How do you use a progressbar to show the loading percentage for a page? ...(similar to how they show in flash) Thanks
Impossible(on IE8 & FF3 & Opera without plugin or extension). If you want real loading percentage include HTML + Javascript + Stylesheet + Image. you can only detect how many file loaded to page(only Image & javascript can be detected by this technique).
I would say that if you need a progressbar for a page, that page might need some rethinking. Personally I don't like pages that have progress bars (Like the one in the ASUS Download Area). They are just annoying. My browser already have a progressbar. And I would like my bandwidth to be used to download the page and not graphics that would just tell me that I am still waiting for the page. When it comes to AJAX requests ON a page though, I would just use a spinner thing of some sort. To tell the user that something is going on and that the page is not dead. And again, if the background request takes so long that you would need a progressbar, I would again say that the background request should maybe be rethought.
AJAX progress bar dispaying loading progress percentage for page load
[ "", "c#", "ajax", "asp.net-ajax", "progress-bar", "" ]
**Duplicate:** [Multiple javascript/css files: best practices?](https://stackoverflow.com/questions/490618/multiple-javascript-css-files-best-practices) Hi guys, my application is almost done but the thing is that I've noticed that I'm including a lot of external javascript files and css. I'm using a lot of third party free plugins here and didnt want to touch the code for fear of messing something up. But the result is that I notice that I have now included 8 external css files as well as a whopping 20 external Javascript files :O - I don't recall having seen any major website include more than 2 or 3 css\_ js files combined so I definitely must be doing something wrong here. How do I sort this out - I read somewhere that one large js file is more quicker to load than 2 or 3 files which are even half the accumulated size. Any help would be greatly appreciated
One big file is better than a bunch of small because in this case web browser makes one request to the web server instead of, say, 8 requests. What counts more is not the slight differences in total size, but the total [latency](http://rescomp.stanford.edu/~cheshire/rants/Latency.html) of the requests. Imagine two scenarios: you download one file of 8 kB and 8 files of 1kB each. 1. In the first scenario total time is smth like 80 msec (transfer time) + 50 msec (latency) = 130 msec 2. In the second scenario you have smth like 8x10 msec (transfer time) + 8x50 msec (!) of latency = 480 msec (!) You see the difference. This is by no means a comprehensive example, but you get the idea. So, if possible, merge files together. Compress content to decrease the amount of data to transfer. And use caching to get rid of repetitive requests.
YUI Compressor <http://developer.yahoo.com/yui/compressor/> And a nice tutorial : <http://beardscratchers.com/journal/compressing-css-and-javascript-with-yui-compressor>
Including loads of css files and Javascript file - how do I optimize
[ "", "javascript", "css", "optimization", "pageload", "" ]
I am trying to scrape a webpage when it throws a "potentially dangerous script" error. Everytime I do this, I get a server 500 but I can scrape a normal, operating page. Is there a way I can scrape a webpage when it throws an error? Thanks
Why not use [ASP.NET health monitoring](http://msdn.microsoft.com/en-us/library/ms998306.aspx)? There's a mail provider that will automatically send the error details to you without any manual scraping and you can configure it all with just some config file entries. Easy!
Just a guess, but maybe the error thrown, triggers a server error (500)? That would make sense. You should be still able to get the *output* from the page. Generally though, and I hope you don't mind, I'd have to object to your error handling. First off, you could put the error in a log and use a tool to monitor it for errors. Secondly, if your *script* throws an exception, you could hand it off to a service like [Exceptional](http://getexceptional.com/), which in turn notifies you.
Scrape webpage when it throws an ASP.NET error
[ "", "c#", "asp.net", "" ]
Is there a single-expression way to assign a scalar to all elements of a boost matrix or vector? I'm trying to find a more compact way of representing: ``` boost::numeric::ublas::c_vector<float, N> v; for (size_t i=0; i<N; i++) { v[i] = myScalar; } ``` The following do not work: ``` boost::numeric::ublas::c_vector<float, N> v(myScalar, myScalar, ...and so on..., myScalar); boost::numeric::ublas::c_vector<float, N> v; v = myScalar; ```
Because the vector models a standard random access container you should be able to use the standard STL algorithms. Something like: ``` c_vector<float,N> vec; std::fill_n(vec.begin(),N,0.0f); ``` or ``` std::fill(vec.begin(),vec.end(),0.0f); ``` It probably also is compatible with Boost.Assign but you'd have to check.
I have started using [`boost::assign`](http://www.boost.org/doc/libs/1_38_0/libs/assign/doc/index.html) for cases that I want to statically assign specific values (examples lifted from link above). ``` #include <boost/assign/std/vector.hpp> using namespace boost::assign; // bring 'operator+()' into scope { vector<int> values; values += 1,2,3,4,5,6,7,8,9; } ``` You can also use `boost::assign` for maps. ``` #include <boost/assign/list_inserter.hpp> #include <string> using boost::assign; std::map<std::string, int> months; insert( months ) ( "january", 31 )( "february", 28 ) ( "march", 31 )( "april", 30 ) ( "may", 31 )( "june", 30 ) ( "july", 31 )( "august", 31 ) ( "september", 30 )( "october", 31 ) ( "november", 30 )( "december", 31 ); ``` You can allow do direct assignment with `list_of()` and `map_list_of()` ``` #include <boost/assign/list_of.hpp> // for 'list_of()' #include <list> #include <stack> #include <string> #include <map> using namespace std; using namespace boost::assign; // bring 'list_of()' into scope { const list<int> primes = list_of(2)(3)(5)(7)(11); const stack<string> names = list_of( "Mr. Foo" )( "Mr. Bar") ( "Mrs. FooBar" ).to_adapter(); map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6); // or we can use 'list_of()' by specifying what type // the list consists of next = list_of< pair<int,int> >(6,7)(7,8)(8,9); } ``` There are also functions for `repeat()`, `repeat_fun()`, and `range()` which allows you to add repeating values or ranges of values.
filling a boost vector or matrix
[ "", "c++", "boost", "expression", "ublas", "" ]
In Internet Explorer 7 some properties (mouse coordinates) are treated as physical while others are logical (offset). This essentially required Web developers to be aware of or calculate the zoom state. In IE8 release all properties are logical.
You can get it using: ``` var b = document.body.getBoundingClientRect(); alert((b.right - b.left)/document.body.clientWidth); ``` Thanks a lot [@niclasnorgren](http://twitter.com/niclasnorgren)!
Also, if you need to do check in IE 8, you can use window.screen.deviceXDPI and window.screen.deviceYDPI. The default is 96 dpi, and if you're zoomed, the number will be larger (aka 144 when zoomed 150%)
How to get zoom level in Internet Explorer 7? (javascript)
[ "", "javascript", "internet-explorer-7", "" ]
I'm working on a moderately sized WebForms project. Due to the peculiarities of management here, I have to upload the site to a remote server in order to test (no localhost testing). I'm using the 'Publish' command in Visual Studio 2008. Sometimes, it even works. Most of the time, I inexplicably get a "publish failed" in the bottom left corner, with no further details. The few googled articles/forum posts I read suggested making the target local folder for the publish operation readable/writable for everyone. Doesn't help. Is there are way to get further details as to WHY a publish fails in VS2008, and if not, is there a better way of doing these deployments? I'm spending more time building/pushing to the web server than actually debugging.
It happens to us when there is an error in markup (!). Bad thing is that VS will just swallow the error and just tell you Failed. What I suggest is to run your publish from command line using MSBuild. It's not that straightforward but it works (once you get into it).
It's worth checking the output window. I've just had a publish fail because I had deleted an image outside of VS so VS was complaining that the image couldn't be found, but this information was only displayed in the output window. See this link for more information: <http://ericfickes.com/2009/08/find-out-why-visual-studios-publish-fails/>
Visual Studio 'Publish' command fails
[ "", "c#", "asp.net", "visual-studio", "visual-studio-2008", "publishing", "" ]
Here's my problem (for en-US): `Decimal.Parse("1,2,3,4")` returns 1234, instead of throwing an InvalidFormatException. Most Windows applications (Excel en-US) do not drop the thousand separators and do not consider that value a decimal number. The same issue happens for other languages (although with different characters). Are there any other decimal parsing libraries out there that solve this issue? Thanks!
I ended up having to write the code to verify the currency manually. Personally, for a framework that prides itself for having all the globalization stuff built in, it's amazing .NET doesn't have anything to handle this. My solution is below. It works for all the locales in the framework. It doesn't support Negative numbers, as Orion pointed out below, though. What do you guys think? ``` public static bool TryParseCurrency(string value, out decimal result) { result = 0; const int maxCount = 100; if (String.IsNullOrEmpty(value)) return false; const string decimalNumberPattern = @"^\-?[0-9]{{1,{4}}}(\{0}[0-9]{{{2}}})*(\{0}[0-9]{{{3}}})*(\{1}[0-9]+)*$"; NumberFormatInfo format = CultureInfo.CurrentCulture.NumberFormat; int secondaryGroupSize = format.CurrencyGroupSizes.Length > 1 ? format.CurrencyGroupSizes[1] : format.CurrencyGroupSizes[0]; var r = new Regex(String.Format(decimalNumberPattern , format.CurrencyGroupSeparator==" " ? "s" : format.CurrencyGroupSeparator , format.CurrencyDecimalSeparator , secondaryGroupSize , format.CurrencyGroupSizes[0] , maxCount), RegexOptions.Compiled | RegexOptions.CultureInvariant); return !r.IsMatch(value.Trim()) ? false : Decimal.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out result); } ``` And here's one test to show it working (nUnit): ``` [Test] public void TestCurrencyStrictParsingInAllLocales() { var originalCulture = CultureInfo.CurrentCulture; var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures); const decimal originalNumber = 12345678.98m; foreach(var culture in cultures) { var stringValue = originalNumber.ToCurrencyWithoutSymbolFormat(); decimal resultNumber = 0; Assert.IsTrue(DecimalUtils.TryParseCurrency(stringValue, out resultNumber)); Assert.AreEqual(originalNumber, resultNumber); } System.Threading.Thread.CurrentThread.CurrentCulture = originalCulture; } ```
It's allowing thousands, because the default `NumberStyles` value used by `Decimal.Parse` (`NumberStyles.Number`) includes `NumberStyles.AllowThousands`. If you want to disallow the thousands separators, you can just remove that flag, like this: ``` Decimal.Parse("1,2,3,4", NumberStyles.Number ^ NumberStyles.AllowThousands) ``` (the above code will throw an `InvalidFormatException`, which is what you want, right?)
C# Decimal.Parse issue with commas
[ "", "c#", "parsing", "decimal", "" ]
We've recently enabled [APC](https://www.php.net/manual/en/book.apc.php) on our servers, and occasionally when we publish new code or changes we discover that the source files that were changed start throwing errors that aren't reflected in the code, usually parse errors describing a token that doesn't exist. We have verified this by running `php -l` on the files the error logs say are affected. Usually a republish fixes the problem. We're using PHP 5.2.0 and APC 3.01.9. My question is, has anyone else experienced this problem, or does anyone recognize what our problem is? If so, how did you fix it or how could we fix it? Edit: I should probably add in some details about our publishing process. The content is being pushed to the production servers via rsync from a staging server. We enabled `apc.stat_ctime` because it said this helps things run smoother with rsync. `apc.write_lock` is on by default and we haven't disabled it. Ditto for `apc.file_update_protection`.
Sounds like a part-published file is being read and cached as broken. [apc.file\_update\_protection](http://php.net/manual/en/apc.configuration.php#ini.apc.file-update-protection) is designed to help stop this. in php.ini: `apc.file_update_protection integer` > `apc.file_update_protection` setting > puts a delay on caching brand new > files. The default is 2 seconds which > means that if the modification > timestamp (mtime) on a file shows that > it is less than 2 seconds old when it > is accessed, it will not be cached. > The unfortunate person who accessed > this half-written file will still see > weirdness, but at least it won't > persist. Following the question being edited: One reason I don't see these kinds of problems is that I push a whole new copy of the site (with SVN export). Only after that is fully completed does it become visable to Apache/Mod\_php (see my answer [How to get started deploying PHP applications from a subversion repository?](https://stackoverflow.com/questions/800294/how-to-get-started-deploying-php-applications-from-a-subversion-repository/820639#820639) ) The other thing that may happen of course, is that if you are updating in place, you may be updating files that depend on others that have not yet been uploaded. Rsync can only guarantee atomic updates for individual files, not the entire collection that is being changed/uploaded. Another reason I think to upload the site en-mass, and only then put into use.
It sounds like APC isn't preforming or getting the correct file stat info. You could check it to make sure the APC configuration [apc.stat](http://us.php.net/manual/en/apc.configuration.php#ini.apc.stat) is set correctly. Another thing you could do it force the cache to clear with [apc\_clear\_cache()](http://us.php.net/manual/en/function.apc-clear-cache.php) when you publish new code.
Problems with APC on publish
[ "", "php", "apc", "" ]
What could be a good way to code a search functionality for searching documents in a java web application? Is 'tagged search' a good fit for such kind of search functionality?
Why re-invent the wheel? Check out [Apache Lucene](http://lucene.apache.org/java/docs/). Also, search Stack Overflow for "full text search" and you'll find a lot of other very similar questions. Here's another one, for example: [How do I implement Search Functionality in a website?](https://stackoverflow.com/questions/34314/how-do-i-implement-search-functionality-in-a-website)
As for extracting the text content of Office documents (which you need to do before giving it to Lucene), there is the Apache Tika project, which supports quite a few [file formats](http://lucene.apache.org/tika/formats.html), including Microsoft's.
What is the best approach to implement search for searching documents (PDF, XML, HTML, MS Word)?
[ "", "java", "search", "pdf", "ms-word", "" ]
I have a function isNotEmpty which returns true if the string is not empty and false if the string is empty. I've found out that it is not working if I pass an empty string through it. ``` function isNotEmpty($input) { $strTemp = $input; $strTemp = trim($strTemp); if(strTemp != '') //Also tried this "if(strlen($strTemp) > 0)" { return true; } return false; } ``` The validation of the string using isNotEmpty is done: ``` if(isNotEmpty($userinput['phoneNumber'])) { //validate the phone number } else { echo "Phone number not entered<br/>"; } ``` If the string is empty the else doesn't execute, I don't understand why, can someone please shed some light on this please.
Simple problem actually. Change: ``` if (strTemp != '') ``` to ``` if ($strTemp != '') ``` Arguably you may also want to change it to: ``` if ($strTemp !== '') ``` since `!= ''` will return true if you pass is numeric 0 and a few other cases due to [PHP's automatic type conversion](http://sldn.softlayer.com/01/2009/php-type-conversions-for-comparison/). You **should not** use the built-in [empty()](http://www.php.net/empty) function for this; see comments and the [PHP type comparison tables](https://secure.php.net/manual/en/types.comparisons.php).
I always use a regular expression for checking for an empty string, dating back to CGI/Perl days, and also with Javascript, so why not with PHP as well, e.g. (albeit untested) ``` return preg_match('/\S/', $input); ``` Where `\S` represents any non-whitespace character
Why a function checking if a string is empty always returns true?
[ "", "php", "string", "validation", "" ]
Thank you all for your help. A number of you posted (as I should have expected) answers indicating my whole approach was wrong, or that low-level code should never have to know whether or not it is running in a container. I would tend to agree. However, I'm dealing with a complex legacy application and do not have the option of doing a major refactoring for the current problem. Let me step back and ask the question the motivated my original question. I have a legacy application running under JBoss, and have made some modifications to lower-level code. I have created a unit test for my modification. In order to run the test, I need to connect to a database. The legacy code gets the data source this way: (jndiName is a defined string) ``` Context ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup(jndiName); ``` My problem is that when I run this code under unit test, the Context has no data sources defined. My solution to this was to try to see if I'm running under the application server and, if not, create the test DataSource and return it. If I am running under the app server, then I use the code above. So, my *real* question is: What is the correct way to do this? Is there some approved way the unit test can set up the context to return the appropriate data source so that the code under test doesn't need to be aware of where it's running? --- For Context: MY ORIGINAL QUESTION: I have some Java code that needs to know whether or not it is running under JBoss. Is there a canonical way for code to tell whether it is running in a container? My first approach was developed through experimention and consists of getting the initial context and testing that it can look up certain values. ``` private boolean isRunningUnderJBoss(Context ctx) { boolean runningUnderJBoss = false; try { // The following invokes a naming exception when not running under // JBoss. ctx.getNameInNamespace(); // The URL packages must contain the string "jboss". String urlPackages = (String) ctx.lookup("java.naming.factory.url.pkgs"); if ((urlPackages != null) && (urlPackages.toUpperCase().contains("JBOSS"))) { runningUnderJBoss = true; } } catch (Exception e) { // If we get there, we are not under JBoss runningUnderJBoss = false; } return runningUnderJBoss; } Context ctx = new InitialContext(); if (isRunningUnderJboss(ctx) { ......... ``` Now, this seems to work, but it feels like a hack. What is the "correct" way to do this? Ideally, I'd like a way that would work with a variety of application servers, not just JBoss.
The whole approach feels wrong headed to me. If your app needs to know which container it's running in you're doing something wrong. When I use Spring I can move from Tomcat to WebLogic and back without changing anything. I'm sure that with proper configuration I could do the same trick with JBOSS as well. That's the goal I'd shoot for.
The whole concept is back to front. Lower level code should not be doing this sort of testing. If you need a different implementation pass it down at a relevant point.
How should unit tests set up data sources when not running in an application server?
[ "", "java", "jakarta-ee", "jboss", "containers", "detect", "" ]
Im trying to think how to do this with html elements. ![alt text](https://i.stack.imgur.com/pip4W.png) There is nothing special about the colors, so I don't need to make them images. Do note that the text is right aligned. Also, the color bar goes up to the text from the left. So this could be implemented by having the text float right with background color white, and a div with the background color set right next to it (and then a clear). Or instead of floats, I can do text align-right and get a similar effect. Here is the kicker. I'm using a javascript library (shouldn't matter which one) to create an animation. The animation is the bars shrink to the left, and end up like so: ![alt text](https://i.stack.imgur.com/Fjzol.png) The problem with the float or text-align methods are that too many values have to be changed to transition between the two states. The javascript animation effects tend to want to change a couple predefined values, like width or font-size. In order to transfer from picture 1 to picture 2 using the float or text-align methods, I must remove the floating/text-align then set the width of the bar color, but that doesn't work if I want to keep the javascript overhead minimal for such a simple task. I've tried absolute positioning/widths, but I can't get anything to make the text right aligned AND have the bars meet at the same point on the left. I'm hoping maybe I'm just blind of a simple solution, but as I see it, I need one element that has the text positioned to the right somehow, and an element that takes up as much room possible beside it for the color... AND the element that has the color should be able to take a width, while having the text follow beside it. Thank you.
Here's my attempt. **Note:** to the horror of some anti-table zealots this does use tables. Floats just can't do "take up all available space" like tables can. ``` <html> <head> <style type="text/css"> table { width: 300px; background: #DDD; empty-cells: show; } th { padding-left: 8px; width: 100%; height: 1em; } td { padding-left: 12px; width: auto; } div { white-space: nowrap; } #row1 th { background: red; } #row2 th { background: blue; } #row3 th { background: green; } #row4 th { background: yellow; } #row5 th { background: pink; } #row6 th { background: gray; } </style> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("jquery", "1.3.2"); google.setOnLoadCallback(function() { $(function() { $("th").animate({ width: 0 }, 2000); }); }); </script> </head> <body> <table><tr id="row1"><th></th><td><div>FOO</div></td></tr></table> <table><tr id="row2"><th></th><td><div>BAR</div></td></tr></table> <table><tr id="row3"><th></th><td><div>THESE PRETZELS ARE</div></td></tr></table> <table><tr id="row4"><th></th><td><div>MAKING ME THIRSTY</div></td></tr></table> <table><tr id="row5"><th></th><td><div>BLAH</div></td></tr></table> <table><tr id="row6"><th></th><td><div>BLAH</div></td></tr></table> </body> </html> ``` I thought of a non-tables way of doing it that works pretty well, so here it is: ``` <html> <head> <style type="text/css"> div div { height: 1.3em; } #wrapper { width: 300px; overflow: hidden; } div.text { float: right; white-space: nowrap; clear: both; background: white; padding-left: 12px; text-align: left; } #row1, #row2, #row3, #row4, #row5, #row6 { width: 270px; margin-bottom: 4px; } #row1 { background: red; } #row2 { background: blue; } #row3 { background: green; } #row4 { background: yellow; } #row5 { background: pink; } #row6 { background: gray; } </style> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("jquery", "1.3.2"); google.setOnLoadCallback(function() { $(function() { $("div.text").animate({ width: "90%" }, 2000); }); }); </script> </head> <body> <div id="wrapper"> <div class="text">FOO</div><div id="row1"></div> <div class="text">BAR</div><div id="row2"></div> <div class="text">THESE PRETZELS ARE</div><div id="row3"></div> <div class="text">MAKING ME THIRSTY</div><div id="row4"></div> <div class="text">BLAH</div><div id="row5"></div> <div class="text">BLAH</div><div id="row6"></div> </div> </body> </html> ```
This is tested and it works perfectly (no stupid tables and very simple CSS/jQuery): ``` <style type="text/css"> .crazy_slider { display:block; height:25px; width:500px; clear:both; position:relative; z-index:0; text-decoration:none; } .crazy_slider_text { position:absolute; right:0px; top:0px; height:100%; background-color:white; color:#666; font-size:1em; display:block; text-align:left; z-index:1px; padding-left:10px; } #red { background-color:red; } #blue { background-color:blue; } #green { background-color:green; } #yellow { background-color:yellow; } #pink { background-color:pink; } #grey { background-color:grey; } </style> <script type="text/javascript"> $(function() { $('.crazy_slider').hover( function() { var bar_width = $(this).width(); var $crazy_slider_text = $(this).children('.crazy_slider_text'); if($crazy_slider_text.data('original_width') == null || $crazy_slider_text.data('original_width') == undefined || !$crazy_slider_text.data('original_width')) { var original_width = $crazy_slider_text.width(); $crazy_slider_text.data('original_width',original_width); } $crazy_slider_text.stop().animate({width:95+'%'},500); }, function() { var $crazy_slider_text = $(this).children('.crazy_slider_text'); var text_width = $crazy_slider_text.data('original_width'); $crazy_slider_text.stop().animate({width:text_width+"px"},500); } ); }); </script> <a href="#" class="crazy_slider" id="red"><div class="crazy_slider_text">FOO</div></a> <a href="#" class="crazy_slider" id="blue"><div class="crazy_slider_text">BAR</div></a> <a href="#" class="crazy_slider" id="green"><div class="crazy_slider_text">BAZ</div></a> <a href="#" class="crazy_slider" id="yellow"><div class="crazy_slider_text">FOOBAR</div></a> <a href="#" class="crazy_slider" id="pink"><div class="crazy_slider_text">FOOBARBAZ</div></a> <a href="#" class="crazy_slider" id="grey"><div class="crazy_slider_text">BAZAGAIN</div></a> ``` **Edit:** I was assuming you were tying to make some kind of navigation elements with these so I added the mouse interaction logic. In any case, it might be useful, haha? **Second Edit:** I've changed the code to be more efficient and more predictable... if anyone cares. ;)
Width absorbing HTML elements
[ "", "javascript", "html", "css", "" ]
How do I check if a variable is an array in JavaScript? ``` if (variable.constructor == Array) ```
There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen. ``` variable.constructor === Array ``` This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines. If you are having issues with finding out if an objects property is an array, you must first check if the property is there. ``` variable.prop && variable.prop.constructor === Array ``` Some other ways are: ``` Array.isArray(variable) ``` **Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question** This last one is, in my opinion the ugliest, and it is one of the ~~slowest~~ fastest. ~~Running about 1/5 the speed as the first example.~~ This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray> ``` variable instanceof Array ``` This method runs about ~~1/3 the speed~~ as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as `variable instanceof Number` always returns `false`. **Update: `instanceof` now goes 2/3 the speed!** **So yet another update** ``` Object.prototype.toString.call(variable) === '[object Array]'; ``` This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above. Also, I ran some test: <http://jsperf.com/instanceof-array-vs-array-isarray/35> So have some fun and check it out. Note: @EscapeNetscape has created another test as jsperf.com is down. <http://jsben.ch/#/QgYAV> I wanted to make sure the original link stay for whenever jsperf comes back online.
You could also use: ``` if (value instanceof Array) { alert('value is Array!'); } else { alert('Not an array'); } ``` This seems to me a pretty elegant solution, but to each his own. Edit: As of ES5 there is now also: ``` Array.isArray(value); ``` But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).
How do I check if a variable is an array in JavaScript?
[ "", "javascript", "arrays", "list", "variables", "" ]
I know, *I know*, this sounds *soo* easy. But I can't seem to find the correct answer on the Internet. One of the solution I found was to use `is_dir`. ``` if(is_dir($dir)) echo 'directory exists'; else echo 'drectory not exist'; ``` But this is ***wrong***-- All this function does is to check whether the `$dir` is a directory, it doesn't check whether the directory exists, or not. In other words if I put: ``` $rootDir = "C:\\Documents and Settings\\test\\My Documents\\Image Directory\\Me Dog\\"; ``` then the function will return a true, even though you can find no such directory on your web server. Any ideas?
Should work correctly. From `is_dir()` documentation: > Returns TRUE if the filename **exists > and is a directory**, FALSE > otherwise. Well, anyway if it doesn't try this: ``` if(file_exists($dir) && is_dir($dir)) ``` BTW. results of these functions are cached in stat cache. Use [clearstatcache()](http://www.php.net/manual/en/function.clearstatcache.php) to clean that cache.
You'll probably want to use [opendir()](http://www.php.net/function.opendir) after is\_dir() agrees that the path (could) be a directory. If the resource returned by opendir() is valid, you know you have a directory, and already have a handle to read it. Just be sure to call closedir(), either way, if a valid handle is returned. Edit: This answer assumes that you'll be opening the directory either way. If you just need to ensure a path is sane / valid, file\_exists() is much cheaper.
Check whether a directory exists in PHP
[ "", "php", "file-io", "" ]
After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles. url encoding is very restrictive. See <http://www.blooberry.com/indexdot/html/topics/urlencoding.htm> So, for example how do folks deal with for title slugs for things like "Una lágrima cayó en la arena" One can come up with a reasonable table for indo european languages, ie. things that can be encoded via ISO-8859-1. For example, a conversion table would translate 'á' => 'a', so the slug would be "una-lagrima-cayo-en-la-arena" However, I'm using unicode (in particular using UTF-8 encoding), so no guaranties about what sort code points I'm going to get (I have to prepare for things that can't be ISO-8859-1 encoded. I a nushell. How do deal with this? Should I come up with a conversion table for chars in the ISO\_8859-1 range (<255) and drop everything else? **EDIT**: To give a bit more context, a priori, I don't really expect to slugify data in non indo european languages, but I'd like to have a plan if I encounter such data. A conversion table for the extended ASCII would be nice. Any pointers? Also, since people are asking, I'm using python, running on Google App Engine
Nearly-complete transliteration table (for latin, greek and cyrillic character sets) can be found in [slughifi library](http://trac.django-fr.org/browser/site/trunk/project/links/slughifi.py?rev=47). It is geared towards Django, but can be easily modified to fit general needs (I use it with Werkzeug-based app on AppEngine).
I simply use utf-8 for URL paths. As long as the domain is non-IDN FF3, IE works fine with this. Google reads and displays them correctly. The [IRI RFC](http://www.ietf.org/rfc/rfc3987) allows Unicode. Just make sure you parse the incoming urls correctly.
rules for slugs and unicode
[ "", "python", "google-app-engine", "url", "unicode", "friendly-url", "" ]
Take a look at this example function: ``` RuntimeConfiguration* conf_rt_conf() { RuntimeConfiguration *conf; conf = new RuntimeConfiguration(); conf->arch_path="./archive"; conf->err_log="./err_log"; conf->fail_log="./fail_log"; conf->msg_log="./msg_log"; conf->save="html, htm, php"; conf->ignore="jpg, gif"; conf->cookies=""; return conf; } ``` Everything here works fine, but when I run something like this: ``` DatabaseInput** conf_db_input() { DatabaseInput **db_input; db_input=(DatabaseInput **)malloc(NUMB_SITES*sizeof(DatabaseInput *)); for (int i=0;i<NUMB_SITES;i++) db_input[0]= new DatabaseInput(); db_input[0]->full_name="ABCNews"; db_input[0]->alias="abcn"; db_input[0]->prefix="/eng"; db_input[1]->full_name="Rzeczpospolita"; db_input[1]->alias="rp"; db_input[1]->prefix="/pol"; return db_input; } ``` I get segmentation fault on first assignment. It probably has something to do with the fixed memory block allocated for this struct. How do I get it to work properly?
Maybe this: ``` DatabaseInput *db_input[]; db_input = new DatabaseInput*[NUMB_SITES]; // Creates an array of pointers for (int i=0; i<NUMB_SITES; i++) db_input[i]= new DatabaseInput(); ``` could work? (I didn't test it) Note, to free the memory used, you should do something like: ``` for (int i=0; i<NUMB_SITES; i++) delete db_input[i]; delete[] db_input; ```
I'd change ``` for (int i=0;i<NUMB_SITES;i++) db_input[0]= new DatabaseInput(); ``` to this for a start: ``` for (int i=0;i<NUMB_SITES;i++) db_input[i]= new DatabaseInput(); ```
Segmentation fault on string assignment in C++
[ "", "c++", "segmentation-fault", "" ]
For instance can ``` SELECT foo FROM bar WHERE foo BETWEEN 5 AND 10 ``` select 5 and 10 or they are excluded from the range?
The BETWEEN operator is inclusive. From Books Online: > BETWEEN returns TRUE if the value of > test\_expression is greater than or > equal to the value of begin\_expression > and less than or equal to the value of > end\_expression. **DateTime Caveat** NB: With DateTimes you have to be careful; if only a date is given the value is taken as of midnight on that day; to avoid missing times within your end date, or repeating the capture of the following day's data at midnight in multiple ranges, your end date should be 3 milliseconds before midnight on of day following your to date. 3 milliseconds because any less than this and the value will be rounded up to midnight the next day. e.g. to get all values within June 2016 you'd need to run: `where myDateTime between '20160601' and DATEADD(millisecond, -3, '20160701')` i.e. `where myDateTime between '20160601 00:00:00.000' and '20160630 23:59:59.997'` ## datetime2 and datetimeoffset Subtracting 3 ms from a date will leave you vulnerable to missing rows from the 3 ms window. The correct solution is also the simplest one: ``` where myDateTime >= '20160601' AND myDateTime < '20160701' ```
Yes, but be careful when using between for dates. ``` BETWEEN '20090101' AND '20090131' ``` is really interpreted as 12am, or ``` BETWEEN '20090101 00:00:00' AND '20090131 00:00:00' ``` so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use: ``` myDate >= '20090101 00:00:00' AND myDate < '20090201 00:00:00' --CORRECT! ``` or ``` BETWEEN '20090101 00:00:00' AND '20090131 23:59:59' --WRONG! (see update!) ``` **UPDATE**: It is entirely possible to have records created within that last second of the day, with a datetime as late as `20090101 23:59:59.997`!! For this reason, the `BETWEEN (firstday) AND (lastday 23:59:59)` approach is not recommended. Use the `myDate >= (firstday) AND myDate < (Lastday+1)` approach instead. Good [article on this issue here](http://www.kebabshopblues.co.uk/2009/08/30/one-second-to-midnight-datetimes-in-sql-server-2005/).
Does MS SQL Server's "between" include the range boundaries?
[ "", "sql", "sql-server", "between", "" ]
I am working on an "online reminder system" project (ASP.NET 2.0 (C#) / SQL Server 2005) As this is a reminder service which will send the mail to users on a particular dates. But the problem is users are not from a specific countries, they are from all over the world and from different time zones. Now When I am registering I am asking for users time zone in the same way as windows asks our time zone at the time of installation. But I am not getting the if the user selected (+5.30) or something timezone then how to handle this time zone in my asp.net application. How to work according to timezone. And please suggest if there is any better way to handle timezones in this application ?? Thanks
First thing is to make sure which time zone your data is in. I would recommend making sure that any DateTime that you store, is stored in UTC time (use the `DateTime.ToUniversalTime()` to get hold of it). When you are to store a reminder for a user, you will need the current UTC time, add or remove the user's time zone difference, and convert that new time back to UTC; this is what you want to store in the DB. Then, when you want to check for reminders to send, you simply need to look in the database for reminders to send out now, according to UTC time; essentially get all reminders that have a time stamp that is before `DateTime.Now.ToUniversalTime()`. **Update** with some implementation specifics: You can get a list of time zones from the `TimeZoneInfo.GetSystemTimeZones()` method; you can use those to show a list of time zones for the user. If you store the `Id` property from the selected time zone, you can create a TimeZoneInfo class instance from it, and calculate the UTC time for a given local date/time value: ``` TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("<the time zone id>"); // May 7, 08:04:00 DateTime userDateTime = new DateTime(2009, 5, 7, 8, 4, 0); DateTime utcDateTime = userDateTime.Subtract(tzi.BaseUtcOffset); ```
I would recommend to always **use UTC (GMT) time on the server side** (in code-behind, database, etc), and convert time from UTC to **local time for display purposes** only. This means that all time manipulations - including saving time in database, performing calculations, etc - should be be done using UTC. The problem is: how does your code-behind know what is the time zone of the client browser? Say the user enters some date/time value (such as *12/30/2009 14:30*) in the form and submits it to the server. Assuming that the user submitted local time, how does the server know how to convert this value to UTC? The application can ask the user to specify the time zone (and save it in a persistent cookie or database), but it requires and extra effort from the user, and your app would need to implement the logic and screens for this. It would be nicer if the app could **determine client's time zone automatically**. I have addressed this issue with the help of JavaScript's [getTimezoneOffset](http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp) function, which is the only API that can tell the server about the time difference between local time on the client and GMT. Since this is a client-side API, I did the following: on the server side check for a custom session cookie holding the time offset value, and if it's not available, reload the page (only during GET, and not POST, calls) with some JavaScript logic added to generate the time offset and save it in the cookie. From the client-side this is almost transparent (once during session I reload a page on GET). Once I have the offset in the cookie, I apply it to the time management functions depending on direction of time conversion (UTC to local time, or local time to UTC). This may sound a bit complicated, and it is, but after I wrote helper functions, integrating this feature in the site was a matter of making a **single call** in Page\_Load (of pages that needed time conversion), and using time conversion routines when sending and retrieving time values to and from the browser. Here is an example of how it can be used: ``` using My.Utilities.Web; ... // Derive the form class from BaseForm instead of Page. public class WebForm1: BaseForm { ... private void Page_Load(object sender, System.EventArgs e) { // If we only want to load the page to generate the time // zone offset cookie, we do not need to do anything else. if (InitializeLocalTime()) return; // Assume that txtStartDate is a TextBox control. if (!IsPostback) { // To display a date-time value, convert it from GMT (UTC) // to local time. DateTime startDate = GetStartDateFromDB(...); txtStartDate.Text = FormatLocalDate(startDate); ... } else { // To save a date-time value, convert it from local // time to GMT (UTC). DateTime tempDate = DateTime.Parse(txtStartDate.Text); DateTime startDate = ConvertLocalTimeToUtc(tempDate); SaveStartDateInDB(startDate, ...); ... } } ... } ``` If you need more specifics, check out the [It’s About Time: Localizing Time in ASP.NET Applications](http://alekdavis.blogspot.com/2007/05/my-articles.html) article (sorry, but I do not have a direct link to the article on the publisher's site, since asp.netPRO restricts access to paid subscribers only; there are links to PDF copies, though). I wish I could post the sample from the article, but I don't want to violate the copyright; however, here is a [project to build a helper library](http://www.box.net/shared/dk9vtrx31b) that has **all necessary functionality and documentation** (just ignore the stuff you do not need). UPDATE: The article has been posted online with sample project by the new publisher [here](http://devproconnections.com/aspnet/it-s-about-time).
How to work with time zones in ASP.NET?
[ "", "c#", "asp.net", "timezone", "reminders", "" ]
I have a function in C# 2.0 called Foo(), that returns a value of the type boolean. I am instantiating an object in the function that I am not destroying before returning the boolean value. I want to know whether is it necessary to destroy the objects created before returning the value? thanks.
No it isn't. If you Foo method creates *value types*, they are located on the stack and thus cleaned-up as the stack is unwound. If you create *reference types*, your reference to these instances will go out of scope as the method exits and the instances will therefore be up for garbage collection.
no. unless the object in question implements IDisposable, in that case wrap it in a using(){} statement
Returning from a function without destroying objects
[ "", "c#", "garbage-collection", "" ]
Does anyone know where I can find an implimentation that wraps a `std::map` and makes it thread safe? When I say thread safe I mean that it offers only serial access to the map, one thread at a time. Optimally, this map should use only the standard-library and / or boost constructs.
Does not meet the criteria that you have specified, but you could have a look at the [TBB](http://www.threadingbuildingblocks.org/) containers. There is so called `concurrent_hash_map` which allows multiple threads to access concurrently the data in the map. There are some details, but everything is nicely documented and can give you an idea of the "concurrent container". Depending on your needs this might be totally inappropriate...
The boost shared\_mutex would provide the best multiple reader/single writer approach to wrapping a standard map given your constraints. I don't know of any "pre-built" implementations that marry these two since the task is generally trivial.
C++ Thread-Safe Map
[ "", "c++", "dictionary", "collections", "thread-safety", "stdmap", "" ]
How can I validate if the user has selected a file to upload? Edit: bumped
Check it's `value` property: In jQuery (since your tag mentions it): ``` $('#fileInput').val() ``` Or in vanilla JavaScript: ``` document.getElementById('myFileInput').value ```
My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not. Try this: ``` <input type="file" name="fileUpload" onchange="validate_fileupload(this.value);"> function validate_fileupload(fileName) { var allowed_extensions = new Array("jpg","png","gif"); var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename. for(var i = 0; i <= allowed_extensions.length; i++) { if(allowed_extensions[i]==file_extension) { return true; // valid file extension } } return false; } ```
How to validate a file upload field using Javascript/jquery
[ "", "javascript", "jquery", "" ]
Why does this not work in ff/chrome? ``` javascript: document.execCommand('SaveAs','true','http://www.google.com'); ``` (used as a bookmarklet)
execCommand is not completely standardized across browsers. Indeed, execCommand('SaveAs', ...) only seems to be supported on IE. The recommended way to force a save-as would be to use a content-disposition: attachment header, as described in <http://www.jtricks.com/bits/content_disposition.html> Since this is part of the HTTP header, you can use it on any file type. If you're using apache, you can add headers using the .htaccess file, as described [here](http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html). For example: ``` <FilesMatch "\.pdf$"> <IfModule mod_headers.c> Header set Content-Disposition "attachment" # for older browsers Header set Content-Type "application/octet-stream" </IfModule> </FilesMatch> ```
It is possible to do this in Firefox via [data URIs](https://developer.mozilla.org/en-US/docs/data_URIs) (see also [Download data url file](https://stackoverflow.com/questions/3916191/download-data-url-file) ) and optionally via the download attribute. See <http://html5-demos.appspot.com/static/a.download.html> for an HTML5 shim demo. [How to force save as dialog box in firefox besides changing headers?](https://stackoverflow.com/questions/833068/how-to-force-save-as-dialog-box-in-firefox-besides-changing-headers) also covers this topic. You can also test it by the following Firefox-tested demo. ``` <!DOCTYPE html> <body> <script> var a = document.createElement('a'); //alert(a.download === ''); // If true, this seems to indicate support a.setAttribute('download', 'testme.png'); a.href = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAwElEQVQ4jWNgGPRgv7Y2z0lj45STpqbHT5iaxhCt8biBgcJJU9PZJ01MPp80MfkPxZOJN8DEpAFJ4/+TJib/T5mY7CdK8wkTkwJ0zVA8naDmk0ZGPjg0/z9hbGyDV/MZY2ORkyYm77FpPmVispwSp6/e7+DAQtj5pqabsdi8myjNUANmY7H99jEjIxWiDDhuauqCxYDD+7W1eYgy4IyxMetJE5PpyH4/ZWqqTZRmGIAm3fsk2YwOjhkZqZCtmVQAAIOlmIi0XoodAAAAAElFTkSuQmCC'; a.innerHTML = 'testing'; a.style.display = 'none'; document.body.appendChild(a); a.click(); </script> ``` The following also works for URLs as well as JavaScript-initiated loads without the download attribute (though this approach does not allow a file name, it does allow a preview in a new tab): ``` <script> var myText = 'Hello world!', myHTML = '<b>'+myText+'</b>'; function openFile (textToEncode, contentType, newWindow) { // For window.btoa (base64) polyfills, see // https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills var encodedText = window.btoa(textToEncode); var dataURL = 'data:' + contentType + ';base64,' + encodedText; if (newWindow) { // Not useful for application/octet-stream type window.open(dataURL); // To open in a new tab/window } else { window.location = dataURL; // To change the current page } } </script> <h1>Hello world files:</h1> <p>Octet stream type to prompts download dialog in Firefox, but with no default file type or path:</p> <a href="data:application/octet-stream;base64,SGVsbG8sIFdvcmxkIQ%3D%3D"> (text example)</a> <a href="data:application/octet-stream;base64,PGI+SGVsbG8gd29ybGQhPC9iPg=="> (HTML example)</a> <button onclick="openFile(myHTML, 'application/octet-stream');"> (HTML example, from JavaScript)</button> <p>Quickly viewable (and manually savable) in browser but no dialog presented:</p> <a href="data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D">(plain text, same window)</a> <a href="data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D" target="new-tab"> (plain text--in new tab)</a> <a href="data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E">(HTML, same window)</a> <button onclick="openFile(myText, 'text/plain');"> (text example, from JavaScript)</button> <button onclick="openFile(myText, 'text/plain', true);"> (text example, from JavaScript; open in new window)</button> <button onclick="openFile(myHTML, 'text/html', true);"> (HTML example, from JavaScript; open in new window)</button> ```
Does execCommand SaveAs work in Firefox?
[ "", "javascript", "firefox", "google-chrome", "bookmarklet", "" ]
What are the situations and their associated benefits of using Generics over Inheritance and vice-versa, and how should they be best combined? Thanks for the answer guys. I'm going to try to state the motivation for this question as best I can: I have a class as shown below: ``` class InformationReturn<T> where T : Info { InformationReturn(Employee employee, List<T>) { ... } } ``` Now suppose I have a repository that takes an InformationReturn argument, that has to strore different fields in a DB depending on the type of Info object T is. Is it better to create different repositories each for the type T is; one repository that uses reflection to determine the type; or is there a better way using inheritance capabilities over/with generics? **Note**: other client code must operate differently based on the type of T as well.
They're really different ideas altogether. Generics allow you to declare common "specific" functionality (at the risk of sounding oxymoronic) in a general way. A `List<int>` doesn't function any differently from a `List<string>`, aside from the type of data that is held inside. While inheritance could be used to do the same thing, I could create a `List` class, then an `IntList` and a `StringList` class that inherit from it. I could easily make these two classes function entirely differently, or have one offer functionality not available in the other one. **Edit** After reviewing the edit to the question, the answer sortof is "it depends." You can make arguments for both sides--and, indeed, LINQ to SQL and the Entity Framework are both a combination of both reflective inspection using generics, and strongly-typed entity classes and other repository classes. You can certainly take the approach that you're looking at, just know that, in general, a problem that can be solved either with reflection or with something else is LIKELY going to be faster when solved by the "something else." It comes down to how much of a tradeoff you want among performance, maintainability, readability, and reliability.
You should use generics when you want only the same functionality applied to various types (Add, Remove, Count) and it will be **implemented the same way**. Inheritance is when you need the same functionality (GetResponse) but want it to be **implemented different ways**.
When is it Appropriate to use Generics Versus Inheritance?
[ "", "c#", ".net", "vb.net", "generics", "inheritance", "" ]
I am creating a bookmarklet button that, when the user clicks on this button in his browser, will scrape the current page and get some values from this page, such as price, item name and item image. These fields will be variable, means that the logic of getting these values will be different for each domain "amazon, ebay" for example. My questions are: * Should i use javascript to scrape these data then send to the server? * Or just send to my server side the URL then use .net code to scrape values? * What is the best way? and why its better? advantages, disadvantages? Look at this video and you will understand what i want to do exactly <http://www.vimeo.com/1626505>
If you want to pull information from another site for use in *your* site (written in ASP.NET, for example) then you'll typically do this on the server side so that you have rich language for processing the results (e.g. C#). You'll do this via a WebRequest object in .NET. The primary use of client side processing is to use Javascript to pull information to display on your site. An example would be the scripts provided by the Weather Channel to show a little weather box on your site or for very simple actions such as adding a page to favorites. **UPDATE**: Amr writes that he is attempting to recreate the functionality of some popular screen scraping software which would require some quite sophisticated processing. Amr, I'd consider creating an application that uses the IE browser object to display web pages - it is quite simple. You could then just pull the InnerHTML (I think, it has been a few years since I implemented an IE-object-based program) to retrieve the contents of the page and do your magic. You could, of course, use a WebRequest object (just handing it the URL used in the browser object) but that wouldn't be very efficient as it would download the page a second time. Is this what you are after?
If you want to use only JavaScript to do this, you are liable to have a fairly large bookmarklet unless you know the exact layout of every site it will be used on (and even then it will be big). A common way I have seen this done is to use a web service on your own server that your bookmarklet (which uses JavaScript) redirects to along with some parameters, like the URL of the page you are viewing. Your server would then scrape the page and do the work of parsing the HTML for the things you are interested in. A good example is the ["Import to Mendeley"](http://www.mendeley.com/import/) bookmarklet, which passes the URL of the page you are visiting to its server where it then extracts information about scientific papers listed on the page and imports them into your collection.
How to Scrape websites, client side or server side?
[ "", ".net", "asp.net", "javascript", "" ]
I've created composite indexes (*indices* for you mathematical folk) on tables before with an assumption of how they worked. I was just curious if my assumption is correct or not. I assume that when you list the order of columns for the index, you are also specifying how the indexes will be grouped. For instance, if you have columns `a`, `b`, and `c`, and you specify the index in that same order `a ASC`, `b ASC`, and `c ASC` then the resultant index will essentially be many indexes for each "group" in `a`. Is this correct? If not, what will the resultant index actually look like?
Composite indexes work just like regular indexes, except they have multi-values keys. If you define an index on the fields (a,b,c) , the records are sorted first on a, then b, then c. Example: ``` | A | B | C | ------------- | 1 | 2 | 3 | | 1 | 4 | 2 | | 1 | 4 | 4 | | 2 | 3 | 5 | | 2 | 4 | 4 | | 2 | 4 | 5 | ```
Composite index is like a plain alphabet index in a dictionary, but covering two or more letters, like this: ``` AA - page 1 AB - page 12 ``` etc. Table rows are ordered first by the first column in the index, then by the second one etc. It's usable when you search by both columns OR by first column. If your index is like this: ``` AA - page 1 AB - page 12 … AZ - page 245 BA - page 246 … ``` you can use it for searching on `2` letters ( `= 2` columns in a table), or like a plain index on one letter: ``` A - page 1 B - page 246 … ``` Note that in case of a dictionary, the pages themself are alphabetically ordered. That's an example of a `CLUSTERED` index. In a plain, non-`CLUSTERED` index, the references to pages are ordered, like in a history book: ``` Gaul, Alesia: pages 12, 56, 78 Gaul, Augustodonum Aeduorum: page 145 … Gaul, Vellaunodunum: page 24 Egypt, Alexandria: pages 56, 194, 213, 234, 267 ``` Composite indexes may also be used when you `ORDER BY` two or more columns. In this case a `DESC` clause may come handy. See this article in my blog about using `DESC` clause in a composite index: * [**Descending indexes**](http://explainextended.com/2009/04/27/descending-indexes/)
How do composite indexes work?
[ "", "sql", "indexing", "composite", "" ]
I am trying to write an application that uses java.net.Socket. I have also written an app in Java using GWT to display the contents from an ArrayList. However, I now need to populate that ArrayList via a socket connection. Apparently Google Web Toolkit does not support socket connections. Can anyone please give me a workaround for this? Any examples or links to examples will be much appreciated. Regards
GWT is designed to be hooked up to a back end server, and this is where you would make any socket connections that you require. GWT is front-end technology, and because it is compiled to javascript cannot do things like make socket connections. You can use whatever technology you want on the back end, and hook it into your java: - Java back end (talk to it via RPC calls) - Ruby/PHP back end (talk to it via JSON or XML) - etc
You have basically two options: * Use HTTP Connections from your client code (GWT RPC, some other framework, or handrolled). Then you can make your Socket connections from the server * Put together a Java applet (or possibly a Flash client) on the client to do this, and then write your own GWT components to communicate with the applet Browsers do not support direct socket connections from Javascript, so it isn't possible to support java.net.socket directly in GWT client code.
gwt socket connections
[ "", "java", "sockets", "gwt", "" ]
I have an application that works without any problem in a spanish server. When i uploaded the application into the online server (an english windows), im getting exceptions (of type "input string is not a valid Datetime/Int32") with Convert.ToDateTime and Convert.ToInt32. Are any web.config line that could help me in this matter? I tried adding a globalization element with the Spanish culture, but didnt worked. Could you give me a hand? Thanks in advance. Josema.
You need: ``` System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-ES"); DateTime myDateTime = Convert.ToDateTime(string, culture); ```
Are you specifying a [CultureInfo](http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx) argument, as an `IFormatProvider` in your [`String.Format()`](http://msdn.microsoft.com/en-us/library/1ksz8yb7.aspx) calls?
Problem with Convert.ToDateTime in asp.net
[ "", "c#", "asp.net", "formatting", "web-config", "culture", "" ]
Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python? What are the language constructs that exist in Python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does Python lack such constructs? I have so far understood the `lambda` thing; it is only one-line, but maybe it comes close. What about "decorators" and `yield` in this context? I am also using old Python versions in some projects. Which constructs were introduced in which Python version (2.5, 2.6, etc.) or are planned in future versions? Can you link interesting articles on the subject that explain this stuff for Python and also comparing to other languages and could be interesting for someone who wants to extend basic Python knowledge?
Functions are the first-class members in Python: ``` def add(x, y): return x + y a = add # Bind b = a(34, 1) # Call ``` So you can pass functions around all you want. You can do the same with any callable object in Python.
`lambda` is the closest equivalent to a Ruby block, and the restriction to one line [is intentional](http://www.artima.com/weblogs/viewpost.jsp?thread=147358). It is typically argued that multiline anonymous functions (blocks, in Ruby) are *usually* less readable than defining the function somewhere with a name and passing that, as illustrated in [SilentGhost's answer](https://stackoverflow.com/questions/767519/blocks-of-code-in-python/767529#767529).
Blocks of code in Python
[ "", "python", "ruby", "lambda", "" ]
Can anyone tell me what is going wrong with this code? I tried to submit a form with JavaScript, but an error ".submit is not a function" shown. See below for more details of the code: ``` <form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data"> <input onclick="submitAction()" id="submit_value" type="button" name="submit_value" value=""> </form> <script type="text/javascript"> function submitAction() { document.frmProduct.submit(); } </script> ``` I also tried this: ``` <script type="text/javascript"> function submitAction() { document.forms["frmProduct"].submit(); } </script> ``` Both show me the same error :(
> submit is not a function means that you named your submit button or some other element `submit`. Rename the button to `btnSubmit` and your call will magically work. When you name the button submit, you override the `submit()` function on the form.
Make sure that there is no another form with the same name and make sure that there is no `name="submit"` or `id="submit"` in the form.
"Submit is not a function" error in JavaScript
[ "", "javascript", "html", "dom", "submit", "" ]
can any body tell me how to conver const char\* to char\*? ``` get_error_from_header(void *ptr, size_t size, size_t nmemb, void *data) { ErrorMsg *error = (ErrorMsg *)data; char* err = strstr((const char *)ptr,"550"); //error cannot convert const char** to char* if(err) { strncpy(error->data,(char*)ptr,LENGTH_ERROR_MESSAGE-1); error->data[LENGTH_ERROR_MESSAGE-1] = '\0'; error->ret = true; } return size*nmemb; } ```
You don't appear to use `err` in the rest of that function, so why bother creating it? ``` if (NULL != strstr((const char *)ptr, "550")) { ``` If you do need it, will you really need to modify whatever it points to? If not, then declare it as `const` also: ``` const char* err = strstr((const char *)ptr, "550"); ``` Finally, as casts are such nasty things, it is best to use a specific modern-style cast for the operation you want to perform. In this case: ``` if (NULL != strstr(reinterpret_cast<const char *>(ptr), "550")) { ```
There are a few things I don't understand here. I see that this is tagged for [C++/CLI](http://en.wikipedia.org/wiki/C%2B%2B/CLI), but what I describe below should be the same as [Standard C++](http://en.wikipedia.org/wiki/C%2B%2B). ### Doesn't compile The code you give doesn't compile; `get_error_from_header` does not specify a return type. In my experiments I made the return type `size_t`. ### Signature of C++ `strstr()` The signature for `strstr()` in the standard C library is: ``` char * strstr(const char *s1, const char *s2); ``` but the signature for `strstr()` in the [C++ library](http://www.cplusplus.com/reference/clibrary/cstring/strstr/), depending on the overload, is one of: ``` const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 ); ``` I would choose the first overload, because you don't want to modify the string, you only want to read it. Therefore you can change your code to: ``` const char* err = strstr((const char *)ptr, "550"); if (err != NULL) { ... } ``` Also, I'm assuming your comment reporting the error: ``` //error cannot convert const char** to char* ``` is a typo: there's no `const char**` to be seen. ### Assignment to `err` unnecessary As is pointed out in a previous answer, the use of `err` to store the result of `strstr` is unnecessary if all it's used for is checking `NULL`. Therefore you could use: ``` if (strstr((const char *)ptr, "550") != NULL) { ... } ``` ### Use of `reinterpret_cast<>` encouraged As is pointed out in another answer you should be using `reinterpret_cast<>` instead of C-style casts: ``` if (strstr(reinterpret_cast<const char *>(ptr), "550") != NULL) { ... } ``` ### Use of `const_cast<>` to strip `const` Given the example in the question, I don't see where this is necessary, but if you had a variable that you need to strip of `const`-ness, you should use the `const_cast<>` operator. As in: ``` const char * p1; char * p2; p2 = const_cast<char *>(p1); ``` As is pointed out in a comment, the reason to use `const_cast<>` operator is so that the author's intention is clear, and also to make it easy to search for the use of `const_cast<>`; usually stripping const is the source of bugs or a design flaw.
How to convert const char* to char*
[ "", "c++", "string", "const-correctness", "" ]
I'm learning php pdo; my environment is : NetBeans 6.5.1, XAMPP 1.7.0 and I have this code, which it seems to connect. * If I change dbname to a non existent one, it raises exception "db not exists" * If I change user, it raises "login incorrect") but when I call $cn->query, it raises: > An unhandled Win32 exception occurred in apache.exe What am I doing wrong? ``` $hostname = 'localhost'; $username = 'crb'; $password = 'letmein'; try { $cn = new PDO("mysql:host=$hostname;dbname=bitacora", $username, $password); echo 'Connected to database<br />'; $sql = "SELECT * FROM usuario WHERE login = '".$login."' AND clave = '".$clave."'"; // Error here foreach ($cn->query($sql) as $row) { print $row['login'] .' - '. $row['clave'] . '<br />'; } } catch (PDOException $e) { echo $e->getMessage(); } catch (Exception $e) { echo $e->getMessage(); } ```
This is a bug in XAMPP 1.7.0. Upgrade to [1.7.1](http://www.apachefriends.org/en/xampp-windows.html) or follow [these instructions](http://www.apachefriends.org/f/viewtopic.php?f=16&t=32617) to fix your 1.7.0 installation.
Is $cn valid? Check the return value. What you've described so far doesn't convince me that you're connected.
php pdo ¿What am I doing wrong?
[ "", "php", "pdo", "xampp", "" ]
I was reading this morning the book [The Pragmatic Programmer](http://www.pragprog.com/the-pragmatic-programmer) Chapter 3 on Basic Tools every programmer should have and they mentioned Code Generation Tools. They mentioned one Perl script for C++ programs which helped automate the process of implementing the get/set() member functions for private data members. Does anyone know about such a script and where to find it? I've been unable to come up with the right google keywords to find it.
Although it doesn't directly answer your question, you may find that generated code is actually unnecessary for managing properties in C++. The following template code will allow you to declare and use properties conveniently: ``` // Declare your class containing a few properties class my_class { public: property<int> x; property<string> y; ... }; ... my_class obj; cout << obj.x(); // Get obj.y("Hello, world!"); // Set ``` Here is the code: ``` // Utility template to choose the 2nd type if the 1st is void template <typename T, typename U> struct replace_void { typedef T type; }; template <typename T> struct replace_void<void, T> { typedef T type; }; // Getter/setter template template <typename T, typename D = void> class property { typedef typename replace_void<D, property>::type derived_type; derived_type& derived() { return static_cast<derived_type&>(*this); } public: property() {} // May be safer to omit the default ctor explicit property(T const& v) : _v(v) {} property(property const& p) : _v(p._v) {} property& operator=(property const& p) { _v = p._v; return *this; } T operator()() const { return _v; } // Getter void operator()(T const& v) { derived().check(v); _v = v; } // Setter protected: // Default no-op check (derive to override) void check(T const& v) const { (void)v; //avoid unused variable warning} private: T _v; }; ``` `check()` is a function that tests whether the value being assigned is valid. You can override it in a subclass: ``` class nonnegative_int : public property<int, nonnegative_int> { public: // Have to redeclare all relevant ctors unfortunately :( nonnegative_int(int v) : property<int, nonnegative_int>(v) {} void check(int const& v) const { if (v < 0) { throw "Yikes! A negative integer!"; } } }; ``` There you have it -- all of the advantages of externally-generated getter/setter functions, with none of the mess! :) You could choose to have `check()` return a `bool` indicating validity instead of throwing an exception. And you could in principle add a similar method, `access()`, for catching read references to the property. **EDIT:** As Mr. Fooz notes in the comments, the class author can later change the implementation without modifying the logical structure of the class (e.g. by replacing the `property<int> x` member with a pair of `x()` methods), although binary compatibility is lost so users will need to recompile their client code whenever such a change is made. *This ability to painlessly incorporate future changes is actually the main reason people use getter/setter functions instead of public members in the first place.* **Performance note:** Because we are using the [CRTP](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern) to achieve "compile-time polymorphism", there is no virtual-call overhead for providing your own `check()` in a subclass, and you need not declare it `virtual`.
As most C++ private members should not be accesible via Get/Set style functions, this seems like a bad idea. For a simple example of why this is so, consider the C++ std::string class. Its private members probably look something like this (exact implementation not important): ``` private: int last, len; char * data; ``` Do you believe it makes any sense to provide get/set members for those?
Is there a Perl script to implement C++ Class get/set member functions?
[ "", "c++", "perl", "code-generation", "" ]
I have a table with data such as this: ``` <table> <tr onclick="window.location='download.php?id=1'"> <td>Program 1<br/>Short Description 1 (<a onclick="$.popup.show('Install Instructions', 'Instructions pulled from DB here')">Instructions</a>)</td> <td>Added by user and date/time here<td> <td>Filesize here<td> <td><a href="edit.php?id=1">Edit</a> - <a href="delete.php?id=1">Delete</a><td> </tr> (repeat TRs for more programs pulled from DB) </table> ``` The problem I'm having is that when you click the (Instructions) link, it should popup a window with the instructions. It does do it, but it also fires the TR's onclick. So I get the popup for a split second then it goes to download.php. Is there someway I can prevent it from firing the TR's onclick? Preferably using jquery, but I don't mind a plain javascript solutions either.
Basically, you need to stop [propagation of events](http://www.quirksmode.org/js/events_order.html), using event.cancelBubble (for IE) or event.stopPropagation() (for everyone else). The [solution given from quirksmode](http://www.quirksmode.org/js/events_order.html#link9) (which I've used before) is to do something like this: ``` <script type="text/javascript"> var instructions = function(e) { // Get the correct event in a cross-browser manner, then stop bubbling/propagation. if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); // Do what you want now $.popup.show('Install Instructions', 'Instructions pulled from DB here'); } </script> ``` Then your script would call it: ``` <td>Program 1<br/>Short Description 1 (<a onclick="instructions(event)">Instructions</a>)</td> ``` (Of course, you could put this all inline, but that's a bloody mess.) You may also find [this question](https://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute) illuminating.
stopPropogation is the one you want. <http://docs.jquery.com/Events/jQuery.Event#event.stopPropagation.28.29>
jquery, prevent onclick=window.location on parent element
[ "", "javascript", "jquery", "onclick", "" ]
Does the DateTime struct takes care of this? Does any other class/struct? UPDATE : I now have read that leapseconds are only announced 6 months in advance, since the rotation of the earth is not that predictable... Since there's no possibility to implement that in future dates, I can imagine they just omitted them?
I think the answer to both your questions is No. Reference: <http://silverlight.net/forums/t/12114.aspx>
As far as I know, .NET's DateTime struct does NOT automatically handle leap seconds. I don't think you can even set seconds higher than 59 in .NET's DateTime. However, in Java, you are allowed to set seconds to be 0 - 61, because the ISO standard for it allows for 2 leap seconds per year. **EDIT**: I Tried it for kicks: Trying `Dim dt As New DateTime(2008, 12, 2, 12, 34, 61)` in .NET throws this message (61 being the number of seconds): > "Hour, Minute, and Second parameters > describe an un-representable > DateTime."
Are leapseconds taken in account in dotNet (or C#)?
[ "", "c#", ".net", "datetime", "time", "" ]
I don't totally understand how all this works, but I'm getting this error: Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 261858 bytes) in /Users/andrew/Sites/myApp/library/Zend/Mail/Transport/Smtp.php on line 213 I'm running this code locally on my Mac running MAMP. Not sure if that has anything to do with it. This is my code, basically: ``` $config = array('ssl' => 'tls', 'port' => 587, 'auth' => 'login', 'username' => 'username', 'password' => 'password'); $smtpConnection = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config); foreach ($subscribers as $subscriber) { $message = new Zend_Mail('utf-8'); $message->setFrom('my@mailinglist.com', 'Mailing List') ->addTo($subscriber->email) ->setSubject($subject) ->setBodyText($body); $attachment = $message->createAttachment(file_get_contents($filepath)); $attachment->type = 'application/pdf'; $attachment->filename = $filename; $message->send($smtpConnection); } ``` However, the more subscribers there are, the higher this number ends up getting, and this fix will only help for so long: ``` ini_set("memory_limit","12M"); ``` I need to figure out how to send an email with an attachment to a couple hundred people. Here's something else I've come up with but it seems a little hacky to only set the bcc and not the to address: ``` $message = new Zend_Mail('utf-8'); $message->setFrom('my@mailinglist.com', 'Mailing list') ->setSubject($subject) ->setBodyText($body); $attachment = $message->createAttachment(file_get_contents($filepath)); $attachment->type = 'application/pdf'; $attachment->filename = $filename; foreach ($subscribers as $subscriber) { $message->addBcc($subscriber->email); } $message->send($smtpConnection); ``` However, even doing this, I need to specify the "memory\_limit". Can you please point me in the right direction with this? Is there something I'm not doing?
I'm guessing your pdf is about 250Kbytes? You're reading it into memory once per email you send out. Don't. Read it once. :) It might also be an encoding-thing in the Zend framework. * Call file\_get\_contents() *once* before your loop * Set the memory limit much higher as long as your server can handle it (I'd say along the lines of 32-128 Mbytes) * unset() your variables - should force php to GC it (in theory) * You could reuse the $message object (ugly hack, but could save bytes if Zend does some sort of file-encoding and it uses lots of memory) I'd also make a cron-job for sending the emails, and making sure that each email (or a reference to it) is stored in the database along with a status. This way you won't send duplicate mails if you hit another memory limit, or bug.
There's no need to create a new attachment with each message. Just create it once and then attach it each time you send. ``` $config = array('ssl' => 'tls', 'port' => 587, 'auth' => 'login', 'username' => 'username', 'password' => 'password'); $smtpConnection = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config); $attachment = new Zend_Mime_Part(file_get_contents($filepath)); $attachment->type = 'application/pdf'; $attachment->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $attachment->filename = $filename; foreach ($subscribers as $subscriber) { $message = new Zend_Mail('utf-8'); $message->setFrom('my@mailinglist.com', 'Mailing List') ->addTo($subscriber->email) ->setSubject($subject) ->setBodyText($body); $message->addAttachment($attachment); $message->send($smtpConnection); } ```
Zend Framework: Fatal error when trying to use Zend Mail Transport to send multiple emails with attachments
[ "", "php", "email", "zend-framework", "smtp", "attachment", "" ]