Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In my project I need to write small WYSIWYG editor (just let users make text bold/italic/underline and maybe some more). So I wouldn't like to use monsters like tinymce or fckeditor. My question is what HTML elements and javascript functions do I need to know for it? An HTML element in which I can edit and format text is a very interesting thing in this question.
If you want to roll your own, look at [Midas](http://www.mozilla.org/editor/midas-spec.html). It's available in FF3+, IE, Safari, Opera, Chrome. Basically, you use contentEditable and execCommand to turn the browser into an RTE.
``` document.getElementById('edit').contentDocument.designMode = "on"; ``` Have a look at <http://www.mozilla.org/editor/ie2midas.html>
How does one go about writing a simple WYSIWYG editor in JavaScript?
[ "", "javascript", "html", "editor", "wysiwyg", "" ]
Is there a way I can modify the URL of the current page without reloading the page? I would like to access the portion **before** the # hash if possible. I only need to change the portion **after** the domain, so it's not like I'm violating cross-domain policies. ``` window.location.href = "www.mysite.com/page2.php"; // this reloads ```
This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+! See this question's answer for more information: *[Updating address bar with new URL without hash or reloading the page](https://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-page)* Example: ``` function processAjaxData(response, urlPath){ document.getElementById("content").innerHTML = response.html; document.title = response.pageTitle; window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath); } ``` You can then use `window.onpopstate` or `window.addEventListener` to detect the back/forward button navigation: ``` window.addEventListener("popstate", (e) => { if(e.state){ document.getElementById("content").innerHTML = e.state.html; document.title = e.state.pageTitle; } }); ``` --- For a more in-depth look at manipulating browser history, see [this MDN article](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history).
HTML5 introduced the [`history.pushState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) and [`history.replaceState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState) methods, which allow you to add and modify history entries, respectively. ``` window.history.pushState('page2', 'Title', '/page2.php'); ``` Read more about this from [here](https://developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API)
How do I modify the URL without reloading the page?
[ "", "javascript", "html", "url", "url-rewriting", "friendly-url", "" ]
We are currently transferring our websites from Windows 2003 (32-bit) to Windows 2008 (64-bit) and have hit a problem. One of our website use the payment gateway HSBC CPI which requires a DLL to be registered(regsvr32.exe), this DLL is then used inside a classic asp website. The problem is the DLL is a 32-bit DLL and so it will not register with the the Windows 2008 operating system. Is there a way we can wrap this 32 bit dll in a c#.net project so that it's methods are exposed and can be registerd with the OS? Any help would be very much appreciated.
You can register the DLL with regsvr32.exe from the C:\Windows\SysWOW64 folder. However since you can't mix 64/32bit code you'd have to create a C# service running in x86 (see the project properties, platform target) that you can then use from your x64 web app via WCF. An easier option would be to ask HSBC for a x64 dll.
If you want to register the 32-bit COM dll created using VC++ or Visual Basic 6.0 then you have to follow the steps below without making any changes in the code. It also does not require any compilation to be done and also you do not have to run the IIS in WOW Mode. I have faced this issue few years back and I resolved this issue and it works fine for me. Scenario: Let me assume that you have a 3rd party 32-bit COM DLL provided by a vendor. The DLL works fine on 32bit Operating system and the moment you move to a x64 environment it does not work even though you have tried to register it through regsv32. Also let me assume that the name of the DLL is "ASXUpload.DLL". I will use this name in the solution which I am providing below. Solution Please follow the steps below: 1. First of all if you have already registered the DLL in x64 Operating System the unregister the DLL. To do that just type the following in the run command "regsvr32 /u " something like "regsvr32 /u C:\MyDLL\ASXUpload.DLL". If you have already unregistered the DLL from the x64 OS then no need to run this step. 2. Also make sure that you have not kept your DLL inside the Windows folder which is normally C:\Windows. For this example I have kept the DLL in the following folder C:\MyDLL. 3. Now we need to add the COM+ Components using Component Services of Microsoft. To start Component Services, go to Control Panel / Administrative Tools/ Component Services. Once inside component Services, drill down into Computers, then My Computer, then COM+ Applications. Then Right-click on COM+ Applications and choose "New" -> "Application". 4. At "Welcome to the COM Application Install Wizard" screen, click “Next >”. 5. Click on “Create an Empty Application” button. 6. Enter the name. Since my DLL name is ASXUpload.dll so I have typed in the name as “ASXUpload”. When asked "Library or Server", select “Server”. 7. Click “Next >” button and then choose “This User”. 8. Enter the User or click Browse to select the user. Clicking Browse is safer, to ensure that the correct domain and spelling are used. Enter the password and confirm the password. Warning, be sure to include the domain/username if required. Click on “Finish”. (Note: We recommend "This User", otherwise, someone must be logged onto the server in order for DLL to run.). In my case I have chosen the domain administrator account. You can also add a Service Account. If you are not sure please consult with your system administrator. 9. Now “Add Application Roles” screen will appear. Do not add anything just click on the “Next >” button. 10. Now “Add Users to Role” screen appear. Do not add anything just click on the “Next >” button. 11. Now you will see that under Component Services -> Computers -> My Computer -> COM+ Application -> you will see the newly added application. In this example the application name would be "ASXUpload". Now drill down the newly added application “ASXUpload” by clicking the “+” icon and you will see “Components”. 12. Now right-click on “Components” and then choose “New Component”. At "Welcome to the COM Application Install Wizard" screen, click “Next >”. 13. Click on “Install new component(s)” and now select the DLL which you want to register. In the case it would be “C:\MyDLL\ASXUpload.DLL”. 14. Once you select the DLL you will see that it will show you the components found. Click on the “Next >” button to proceed and finally hit the “Finish” button to complete. 15. Now is the tricky part. Right click on the application you have added which you will find under Component Services -> Computers -> My Computer -> COM+ Application. In my case the application name is “ASXUpload”. After you right click on the Application select “Properties”. The application properties window will open up. Click on the “Security” tab. In the Security tab make sure that under “Authorization” section the checkbox “Enforce access checks for this application” is unchecked. Under “Security Level” section select the radio button “Perform access checks only at the process level. Security property will not be included on the object context. COM+ security call context will not be available.” Make sure that option “Apply restriction policy” is unchecked. Set “Impersonate Level” to “Anonymous” 16. If you want to access the DLL from web Application then make sure that you add the IUSR and IWAM account. To do this go to COM+ Application -> Application Name (In this case it will be ASXUpload) -> Roles -> CreateOwner -> Users. Right click on the Users and add the IUSR and IWAM account used by Internet Information Server. 17. Also set the NTFS permission on the folder where you kept the DLL. In this case I have kept the DLL inside the folder C:\MyDLL. Now right click on the folder “MyDLL” and go to the security tab and then add the IUSR and IWAM account. This is all you need to do and you should be able to consume the DLL. I have used this technique twice in two different organizations I have worked in the past on the Production Environment and it works without any issues. First I tried this in the year 2005 and then I used it again in 2008. Let me know if you are facing any issues.
wrap 32 bit dll for 64 bit operating system to work with regsvr32.exe
[ "", "c#", "asp-classic", "dllregistration", "" ]
I came across the following expression in someone else's code. I think it's terrible code for a number of reasons (not least because it fails to take into account bool.TrueString and bool.FalseString), but am curious as to how the compiler will evaluate it. ``` private bool GetBoolValue(string value) { return value != null ? value.ToUpper() == "ON" ? true : false : false; } ``` **Edit** Incidentally, aren't the expressions evaluated from the inside-outwards? In this case, what's the point of checking for value != null after the call to value.ToUpper() which will throw a null reference exception? I think the following is a correct (deliberately) verbose version (I'd never leave it like this :D ): ``` if (value != null) { if (value.ToUpper() == "ON") { return true; } else // this else is actually pointless { return false; } } else { return false; } ``` Which can be shortened to: ``` return value != null && value.ToUpper == "ON"; ``` Is this a correct re-writing of the expression?
It looks like the method is indended to handle a value that comes from a `checkbox` HTML element. If no value is specified for the checkbox, it uses the value `"on"` by default. If the checkbox is not checked there is no value at all from it in the form data, so reading the key from `Request.Form` gives a null reference. In this context the method is correct, althought it's quite horrible due to the use of the `if-condition-then-true-else-false` anti-pattern. Also it should have been given a name that is more fitting for it's specific use, like `GetCheckboxValue`. Your rewrite of the method is correct and sound. As the value is not culture dependant, converting the value to uppercase should not use the current culture. So a rewrite that is even slightly better than the one that you proposed would be: ``` return value != null && value.ToUpperInvariant == "ON"; ``` (The culture independent methods are also a bit faster than the ones using a specific culture, so there is no reason not to use them.) > Incidentally, aren't the expressions > evaluated from the inside-outwards? If it was method calls so that all expressions were actually evaluated, they would, as the inner call has to be made to evaluate the parameters for the outer call. However, the second and third operands of the conditional expression is only evaluated if they are used, so the expressions are evaluated from the outside and inwards. The outermost condition is evaluated first to decide which of the operands it will evaluate.
You are correct, both in your rewriting and in your assertion that this attempt at conciseness is bad because it leads to confusion.
Correct evaluation of expression
[ "", "c#", "expression", "" ]
I have a number of servers running [PHP 5.2.6 (non-thread-safe build)](http://museum.php.net/php5/php-5.2.6-nts-Win32.zip) on Windows 2003/IIS6 utilising FastCGI. I'm having some issues connecting to MS SQL 2000/2005 (MySQL connectivity is working fine, ASP/ASP.NET scripts can connect to MS SQL successfully as well). [One solution](http://www.userscape.com/helpdesk/index.php?pg=kb.page&id=13) suggests copying the SQL Client Tools `ntwdblib.dll` file to the PHP extensions folder or installing all of the SQL Client Tools on the web server (which I'm reluctant to do). Another solution suggested is to use the [Microsoft SQL Server 2005 Driver for PHP](http://blogs.msdn.com/sqlphp/archive/2008/07/28/microsoft-sql-server-2005-driver-for-php-v1-0-has-released.aspx). This looks fine for writing greenfield apps but for applications such as phpBBS or WordPress this doesn't appear to work. For example, the following script: ``` <?php $host = "mssqlhost"; $user = "phpbb2"; $password = "phpbb2"; $connect_sql_server = mssql_connect($host, $user, $password); ?> ``` Fails with: > PHP Warning: mssql\_connect() > [function.mssql-connect]: Unable to > connect to server: mssqlhost in > E:\AppsDev.NET\_UK\_Minds\phpSqlNC\www\test.php > on line 6 The goal is to allow PHP scripts to connect to both SQL 2000 and SQL 2005 which are running on different servers. I should also add that upgrading to a later version of PHP isn't an option at this time. What is the correct way to configure PHP on Windows 2003/IIS6 to connect to SQL 2000/2005?
After trying various 'solutions' it turns out that the problem was solved simply by replacing the `ntwdblib.dll` file in the PHP executables folder. There is no need to install any of: *SQL Native Client*, *SQL Client Tools* or *Microsoft SQL Server 2005 Driver for PHP*, as many dead ends have suggested. All that needs done is to ensure that `ntwdblib.dll` version 2000.80.2039.0 is dropped into the `c:\php` folder (or wherever you've installed/uncompressed PHP to) and then reset IIS. The PHP docs [suggest](https://www.php.net/manual/en/mssql.requirements.php) copying `ntwdblib.dll` to %SYSTEMROOT%\System32 which doesn't work and they also suggest that this will only support named pipes which is also wrong. I haven't tried to see if a later version of `ntwdblib.dll` works or not, but 2000.80.2039.0 works for me.
Not really an answer, but more helpful information... The version of ntwdblib.dll (2000.2.8.0) that comes with latest php 5.2.X works great with Apache and MSSQL (2008). I have a copy of the DLL from the 2000.80.X.X versions and it is newer than what comes with PHP. I don't know if this makes it better. The "mssql\_" functions are not included in the [official msft php mssql](http://blogs.msdn.com/sqlphp/) driver. They have changed them to a different naming convention. ("sqlsrv\_") That link you posted is version 1.0 but they are already on version 1.1. The "mssql\_" functions require that the ntwdblib.dll be present.
What is the correct PHP configuration to connect to MS SQL 2000/2005?
[ "", "php", "sql-server", "windows", "iis-6", "" ]
I wanted to see what happened if you change the reference of an object exclusively locked by Monitor.Enter(). As expected a SynchronizationLockException was thrown. But I was surprised to see several threads getting past the Monitor before the exception was thrown. Here's what the code below is doing. 1. create and start 100 threads 2. make all the thread wait until a ManualResetEvent is set. 3. set the ManualResetEvent - Kinda like waving the green flag at a Indy race. 4. set a exclusive lock (Monitor.Enter(x)) on x 5. change x's reference. At this point I expected some sort of exception to be thrown, but that doesn't happen until Monitor.Exit(x). What's really odd is that 10 - 20 threads seem to be able to get past the lock before the exception is raised. How does that happen? Doesn't seem like it should. Of course changing the reference of the exclusively locked object is a no-no. I would never do it in real code, but still I was surprised to see the other threads getting past the monitor. Your thoughts? ``` using System; using System.Threading; namespace ThreadingPlayground { class Program { private int _value; object x = new object(); ManualResetEvent _event = new ManualResetEvent(false); static void Main() { Program p = new Program(); p.StartThreads(); Console.ReadLine(); } private void StartThreads() { for(int i = 0;i<100;i++) { Thread t = new Thread(IncrementValue); t.Start(); } _event.Set(); } private void IncrementValue() { WaitHandle.WaitAll(new WaitHandle[] {_event}); Monitor.Enter(x); // Change the reference of the exclusively locked object. This // allows other threads to enter, should this be possible? x = Thread.CurrentThread.ManagedThreadId.ToString(); Console.WriteLine(++_value); // throws a SynchronizationLockException // but not until 10 - 20 more lines are written Monitor.Exit(x); } } } ``` [![Console Output, looks like some threads got past the monitor??](https://i.stack.imgur.com/ilFwL.jpg)](https://i.stack.imgur.com/ilFwL.jpg)
What you're seeing is expected behavior. There is nothing special about the actual variable used to pass a reference into `Monitor.Enter()`. Changing the reference should not prevent other threads from acquiring an exclusive lock, as the variable has a new value, and that reference is not locked anywhere. Your issue comes with the `Exit`, because the thread calling `Exit` does not have an exclusive lock on the reference being passed in. Another thread may well have a lock on it, but the thread you're executing in does not. This, as you know, is why it's always best to do your locking with a variable whose reference will never change. If your resource's variable might change, use a new reference. Is this clear enough?
'x' is a reference to an object; it is not the object itself. When you do ``` x = Thread.CurrentThread.ManagedThreadId.ToString(); ``` You have thrown away the locked object that x previously referred to, and made x refer to some other object. Now when you do ``` Monitor.Exit(x); ``` You get the exception because this object is not in fact locked - the object that you locked is now garbage to be collected by the garbage collector.
Strange Behavior When Changing Exclusively Locked Object - Monitor.Enter(x)
[ "", "c#", "multithreading", "monitor", "" ]
Can someone recommend an up to date library for data Sanitization in PHP ? I am looking for a library that proposes a set of functions for data sanitization. Email validation/sanitization (remove those %0A, \r...), strip htlm (stripslashes(htmlentities), remove script, SQL injection … any form of exploit related to data submitted by users. [CakePHP](http://api.cakephp.org/file/libs/sanitize.php) sanitization class (not the "framework") looks nice.. ?
Check out [PHP Filter](http://www.phpro.org/tutorials/Filtering-Data-with-PHP.html)
[Zend Filter](http://framework.zend.com/manual/en/zend.filter.html), [Zend Filter Input](http://framework.zend.com/manual/en/zend.filter.input.html) and [Zend\_Validate](http://framework.zend.com/manual/en/zend.validate.html)
Data Sanitization in PHP
[ "", "php", "sanitization", "" ]
Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless: I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine. The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this. Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?
There is a built-in `error` token in yacc. You would normally do something like: line: goodline | badline ; badline : error '\n' /\* Error-handling action, if needed \*/ goodline : equation '\n' ; Any line that doesn't match `equation` will be handled by `badline`. You might want to use `yyerrok` in the error handling action to ensure error processing is reset for the next line.
Define a token (end of input), and make your lexer output it at the end of the input. So before, if you had these tokens: ``` '1' 'PLUS' '1' ``` You'll now have: ``` '1' 'PLUS' '1' 'END_OF_INPUT' ``` Now, you can define your top-level rule in your parser. Instead of (for example): ``` Equation ::= EXPRESSION ``` You'll have ``` Equation ::= EXPRESSION END_OF_INPUT ``` Obviously you'll have to rewrite these in PLY syntax, but this should get you most of the way.
Tokenizing left over data with lex/yacc
[ "", "python", "yacc", "lex", "ply", "" ]
I'm looking for a place to hook some code to programmatically create, size and position a JPanel after the application has finished loading. I'm just starting with Java. I'm using NetBeans 6.5.1 with jdk1.6.0\_13. I've used the new project wizard to create a basic Java/Swing desktop application. This is a SingleFrameApplication that uses a FrameView with a central main JPanel where all the UI elements are placed. I first tried my code in the FrameView constructor but when I try to arrange my JPanel based on the bounding rectangle of one of the design time controls I added to the UI, that control has not yet finished being positioned and sized so I'm getting all zeros for the coordinates. I've verified my code works as expected by calling it from a click event after the application has loaded so my problem is finding a way to know when everything is finished being sized and arranged. I also tried the componentShown event from the main JPanel but I later read that is only fired if setVisible is explicitly called which apparently doesn't happen during normal application startup. Can anyone provide some pointers? Thanks. **Update:** In addition to what I mention in my answer below, I also read about the Application.ready() method. This would also be a point in time of interest for knowing when the UI part of an application is finished doing everything it needs to do. Communicating to my view from the application seemed a bit messy though.
The solution I went with was actually a combination of the answers from Charles Marin and JRL (I upvoted both of your answers for credit, thanks). I had my FrameView class implement WindowListener. ``` ... public class MyView extends FrameView implements WindowListener ... ``` and in my FrameView constructor I added a listener to the application's main frame. ``` ... getFrame().addWindowListener((WindowListener) this); ... ``` Then in my implementation of windowActivated I could call the code I had to arrange and size a control on the main JPanel based on the location and size of other controls. ``` public void windowActivated(WindowEvent e) { // The application should now be finished doing its startup stuff. // Position and size a control based on other UI controls here } ```
I *think* you want WindowActivated. Have a look at [this part of the tutorial](http://java.sun.com/docs/books/tutorial/uiswing/events/windowlistener.html).
What Java Swing event can be used to know when application has finished starting?
[ "", "java", "swing", "" ]
So I would consider myself a .Net and ASP.NET pro but I am a bit new to Windows Mobile (I am targeting .net 3.5 CF and Windows Mobile 6). I am creating a data driven application that will have 3-4 tables. I have created a form for each table that allows the user to search through the table. Each form inheretes from the Main form so that they each have the same Menu. My question is how do I make sure that only one Window is open. I want to allow the user to go to the menu and choose a table which will open a new form. What I don't want is for the user to open say each form and then when they are done to have to close 3 or 4 windows. Is this possible? If so how do I do it? On a side note is there a better way to do this. I don't want all my logic on one form. So I don't just want to hide and show and panels.
I keep something I call an application hub that everything goes though. So each menu click will call the applciation hub, and each form will reference it. Then, when switching form, the application hub needs to keep track of the current form, close it, then load the requested form. This isn't much code to write, and performs well. Or...performance wise, keep the application hub idea, and keep the dialogs open. It will perform better that way, rather than having to reload the forms all the time. Then on shut down, the application hub can check which forms are open (it should have a reference to each running form) and close them for the user.
Instead of having multiple Forms (inherited form mainForm) you could put the table stuff on UserControls and have total control about their Creation/Destruction/Visibility much easier. Use an Interface or a BaseUserControl to implement common functionality.
Windows Mobile- only keeping one form open. Best design question
[ "", "c#", ".net", "windows-mobile", "compact-framework", "" ]
I am running a tomcat server and am attempting to update code on that server. To do this I need to shut down the server reliably in a Windows environment. To the best of my knowledge, the tomcat shutdown.bat script can have issues with runaway threads, and I need this to work even if I accidentally create a thread that will keep the .bat script from working. The approach I have been attempting is to run a NET STOP command with the service name - however I have multiple tomcats running on one machine in some instances (which means multiple services). Is there a way to get the name of the service that is related to the tomcat that is running my code? Are there any other good solutions to my problem that I should look into? I have many clients and so would prefer a solution that does not involve installing additional software or hard-coding the name of the service.
Just found that the services are listed in the windows registry with keys like "HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services\" and the service name. The Image Path contains the full path name of the executable. If I scan through the registry I can match the tomcat home url to the path of the executable and get the service name from the key. Then I can just run a net stop on that.
if youre after the name of the service from within the Vm running the tomcat, you may want to look into the ManagementBean stuff, the following post on sun goes into some details; [Sun forums](http://forums.sun.com/thread.jspa?threadID=570865) Whatever you do is going to be quite hacky, since its all OS dependant! I would definately advise sticking to the Tomcat control & deployment services, you dont even need to kill the Tomcat process, you should be able to reploy your webapp using the tomcat hot deploy facility - either from the control panel, or from the ant libraries provided with tomcat.
Killing a windows session from a Java program
[ "", "java", "tomcat", "windows-services", "" ]
I am looking for a way to create a program in *unmanaged* c++ that waits until a file is unlocked (as in it is no longer in use) and than does something. I have had no luck locating how to do this, any help would be appreciated! UPDATE: I may have answered my own question, see below and tell me what you think.. UPDATE: All that really matters is that the file is writable, it doesn't matter if it is still in use.
Here is one possible solution to my problem, does anyone see a problem with this? ``` #include <iostream> #include <fstream> #include <windows.h> using namespace std; void main(int argc, char ** argv) { if (argc < 2 || argc > 2) { return; } ofstream myfile; myfile.open(argv[1], ios_base::app); while (!myfile.is_open()) { Sleep(100); myfile.open(argv[1], ios_base::app); } myfile.close(); // file should now be unlocked.. } ``` Thanks again! UPDATE: Changed the code to be more complete.
Something like this will wait without wasting cpu cycles. ``` HANDLE h = FindFirstChangeNotification("C:\Path to folder holding file", FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE); while(true) { if (CheckLockFile("C:\Path to file")) { // Do something break; } WaitForSingleObject(h, APPROPRIATE_TIMEOUT_VALUE); FindNextChangeNotification(h); } bool CheckLockFile(char* FilePath) { HANDLE fh = CreateFile(FilePath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0,NULL); if (fh == INVALID_HANDLE_VALUE) { return false; } CloseHandle(fh); return true; } ``` This assumes the application with the lock on the file has it open for writing.
How do I monitor the lock on a file to see when it is released? [C++]
[ "", "c++", "winapi", "file", "" ]
What is the difference between a template class and a class template?
This is a common point of confusion for many (including the Generic Programming page on Wikipedia, some C++ tutorials, and other answers on this page). As far as C++ is concerned, **there is no such thing as a "template class," there is only a "class template."** The way to read that phrase is "a template for a class," as opposed to a "function template," which is "a template for a function." **Again: classes do not define templates, templates define classes** (and functions). For example, this is a *template*, specifically a *class template*, but *it is **not** a class*: ``` template<typename T> class MyClassTemplate { ... }; ``` The declaration `MyClassTemplate<int>` **is a class,** or pedantically, a class based on a template. *There are no special properties of a class based on a template vs. a class not based on a template.* The special properties are *of the template itself*. The phrase "template class" means nothing, because the word "template" has no meaning as an adjective when applied to the noun "class" as far as C++ is concerned. It implies the existence of a *class* that **is** (or defines) a *template*, which is not a concept that exists in C++. I understand the common confusion, as it is probably based on the fact that the words appear in the order "template class" in the actual language, which is a whole other story.
Bjarne Stroustrup, the creator of C++, says in his book *The C++ Programming Language 4th edition*, 23.2.1 Defining a Template: > There are people who make semantic distinctions between the terms *class template* and *template class*. I don't; that would be too subtle: please consider those terms interchangeable. Similarly, I consider *function template* interchangeable with *template function*.
What is the difference between a template class and a class template?
[ "", "c++", "templates", "terminology", "" ]
I'm onto [problem 245](http://projecteuler.net/index.php?section=problems&id=245) now but have hit some problems. I've done some work on it already but don't feel I've made any real steps towards solving it. Here's what I've got so far: We need to find n=ab with a and b positive integers. We can also assume gcd(a, b) = 1 without loss of generality and thus phi(n) = phi(ab) = phi(a)phi(b). We are trying to solve: ![\frac{n-\phi(n)}{n-1}=\frac1k](https://chart.apis.google.com/chart?cht=tx&chl=%5Cfrac%7Bn-%5Cphi%28n%29%7D%7Bn-1%7D%3D%5Cfrac1k) ![\frac{n-1}{n-\phi(n)}=k](https://chart.apis.google.com/chart?cht=tx&chl=%5Cfrac%7Bn-1%7D%7Bn-%5Cphi%28n%29%7D%3Dk) Hence: ![n\equiv1\ (\text{mod }n-\phi(n))](https://chart.apis.google.com/chart?cht=tx&chl=n%5Cequiv1%5C%20%28%5Ctext%7Bmod%20%7Dn-%5Cphi%28n%29%29) At this point I figured it would be a good idea to actually see how these numbers were distributed. I hacked together a brute-force program that I used to find all (composite) solutions up to 104: ``` 15, 85, 255, 259, 391, 589, 1111, 3193, 4171, 4369, 12361, 17473, 21845, 25429, 28243, 47989, 52537, 65535, 65641, 68377, 83767, 91759 ``` Importantly it looks like there [won't be too many](http://www08.wolframalpha.com/input/?i=15%2C+85%2C+255%2C+259%2C+391%2C+589%2C+1111%2C+3193%2C+4171%2C+4369%2C+12361%2C+17473%2C+21845%2C+25429%2C+28243%2C+47989%2C+52537%2C+65535%2C+65641%2C+68377%2C+83767%2C+91759) less than the 1011 limit the problem asks. The most interesting/ useful bit I discovered was that k was quite small even for the large values of n. In fact the largest k was only 138. (Additionally, it seems k is always even.) Considering this, I would guess it is possible to consider every value of k and find what value(s) n can be with that value of k. Returning to the original equation, note that it can be rewritten as: ![\frac{\phi(n)-1}{n-1}=\frac{k-1}k](https://chart.apis.google.com/chart?cht=tx&chl=%5Cfrac%7B%5Cphi%28n%29-1%7D%7Bn-1%7D%3D%5Cfrac%7Bk-1%7Dk) Since we know k: ![k\cdot\phi(n)\equiv k\ (\text{mod }n-1)](https://chart.apis.google.com/chart?cht=tx&chl=k%5Ccdot%5Cphi%28n%29%5Cequiv%20k%5C%20%28%5Ctext%7Bmod%20%7Dn-1%29) And that's about as far as I have got; I'm still pursuing some of my routes but I wonder if I'm missing the point! With a brute force approach I have found the sum up to 108 which is 5699973227 (only 237 solutions for n). I'm pretty much out of ideas; can anyone give away some hints? --- **Update**: A lot of work has been done by many people and together we've been able to prove several things. Here's a list: n is always odd and k is always even. k <= 105.5. n must be squarefree. I have found every solution for when n=pq (2 prime factors) with p>q. I used the fact that for 2 primes q = k+factor(k^2-k+1) and p = k+[k^2-k+1]/factor(k^2-k+1). We also know for 2 primes k < q < 2k. For n with 2 of more prime factors, all of n's primes are greater than k.
Multiply primes. What I did, is first check every 2-prime product; store the ones that are successes. Then using the stored products, check those with more primes (every 3-prime product shown in your brute force has a 2-prime subset that works). Use these stored products, and try again with 4 primes, 5 primes etc. The only downside is that you need a good sieve or list of primes. Here is a list of the ones for N<=(10^7): **2 primes** 15,85,259,391,589,1111,3193,4171,4369,12361,17473,25429,28243,47989,52537,65641, 68377,83767,91759,100777,120019,144097,186367,268321,286357,291919,316171,327937 ,346063,353029,360301,404797,406867,524851,531721,558013,563767,633727,705667,73 8607,910489,970141,1013539,1080769,1093987,1184233,1185421,1223869,1233823,12618 07,1264693,1455889,1487371,1529641,1574383,1612381,1617379,1657531,1793689,20163 79,2095087,2130871,2214031,2299459,2500681,2553709,2609689,2617963,2763697,30475 21,3146677,3397651,3514603,3539017,3820909,3961219,4078927,4186993,4197901,44997 07,4552411,4935883,4975687,5103841,5299351,5729257,5829877,5864581,6017299,62364 01,6802531,6856609,8759011,9059233,9203377,9301603,9305311,9526747,9536899,95832 79,9782347,9900217 **3 primes** 255,21845,335923,3817309 **4 primes** 65535 **5 primes** 83623935
Project Euler isn't fond of discussing problems on public forums like StackOverflow. All tasks are made to be done solo, if you encounter problems you may ask help for a specific mathematical or programming concept, but you can't just decide to ask how to solve the problem at hand - takes away the point of project Euler. Point is to learn and come up with solutions yourself, and learn new concepts.
Project Euler Problem 245
[ "", "python", "algorithm", "math", "" ]
I'm new to Java, but have some OOP experience with ActionScript 3, so I'm trying to migrate relying on stuff I know. In ActionScript 3 you can create getters and setters using the get and set keywords, meaning you create a method in the class and access data through a property of an instance of that class. I might sound complicated, but it's not. Here's an example: ``` class Dummy{ private var _name:String; public function Dummy(name:String=null){ this._name = name; } //getter public function get name():String{ return _name; } //setter public function set name(value:String):void{ //do some validation if necessary _name = value; } } ``` And I would access `name` in an object as: ``` var dummy:Dummy = new Dummy("fred"); trace(dummy.name);//prints: fred dummy.name = "lolo";//setter trace(dummy.name);//getter ``` How would I do that in Java? Just having some public fields is out of the question. I've noticed that there is this convention of using get and set in front of methods, which I'm OK with. For example, ``` class Dummy{ String _name; public void Dummy(){} public void Dummy(String name){ _name = name; } public String getName(){ return _name; } public void setName(String name){ _name = name; } } ``` Is there an equivalent of ActionScript 3 getter/setters in Java, as in accessing a private field as a field from an instance of the class, but having a method for implementing that internally in the class?
Nope. AS3 getters and setters are an ECMAScript thing. In Java, you're stuck with the getVal() and setVal() style functions--there isn't any syntactic sugar to make things easy for you. I think Eclipse can help auto-generating those types of things though...
Your Java code is fine, except that you would, want to make `_name` **private**. There are no **get** and **set** keywords in Java as in your AS3 example. Sorry, it doesn't get better than what you're doing already. Corrected code: ``` class Dummy { private String _name; public void Dummy() {} public void Dummy(String name) { setName(name); } public String getName() { return _name; } public void setName(String value) { _name = value; } } ```
Getters/setters in Java
[ "", "java", "actionscript-3", "setter", "getter", "accessor", "" ]
Which method is preferred for adding a row to a table? var tr = tbl.insertRow(-1); or var tr = document.createElement('tr'); tbl.appendChild(tr); ?
`insertRow` would be the much better. It is [supported](http://www.quirksmode.org/dom/w3c_html.html) by grade A browsers and it's less verbose and a cleaner API.
I see good arguments for insertRow, but I find one disadvantage: insertRow can only create a new empty row, whereas appendChild takes an existing row object. With appendChild, you can move rows around in a table, move a row from one table to another, or take a row out of a table and later put it back in (very handy for paged tables). To do the same with insertRow (and insertCell), you would have to package up the contents, create new rows and cells, and then add the old contents to the new cells. Clumsy, and seemingly less efficient. Is there a more graceful way to do this? A variant of insertRow that takes an existing row object would be nice.
insertRow vs. appendChild
[ "", "javascript", "dom", "dhtml", "" ]
All I need this for is strcpy(). I want to see whether the first three bytes of a buffer(byte array) are "JMX" as string. This is what I did so far: ``` char * ddj; strcpy( ddj, buffer ); //buffer is BYTE[] if ( strcmp( "JMX", ddj ) == 0 ) //check first three chars are "JMX" { buffer += 20; //increase the index with 20 size -= 20; //int } ``` I get exception at strcmp() line. What is the problem? *I wish I was writing this in C# :(*
Tho things go wrong here: 1. `ddj` does not point to any actual memory. Hence the copy will have undefined behavior 2. The copying is not necessary in the first place. This is what you can do: ``` if(strncmp("JMX", buffer, 3) == 0) { buffer += 20; size -= 20; } ``` This uses [strncmp](http://linux.die.net/man/3/strncmp) instead of [strcmp](http://linux.die.net/man/3/strcmp), thus ensuring that no more than three bytes are compared. If `buffer` can contain less than three bytes, you should do something like: ``` if(buf_len >= 3 && strncmp("JMX", buffer, 3) == 0) { buffer += 20; size -= 20; } ```
You're not allocating any memory for `ddj`. Since it's a local variable, it's allocated on the stack. Local variables are not initialized to 0/false/NULL by default, so the value of `ddj` immediately after it's declared is undefined -- it will have the value of whatever is left in memory at that particular location on the stack. Any attempt to dereference it (that is, to read or write the memory at which it's pointing) will have undefined behavior. In your case, it's crashing because it's pointing to an invalid address. To fix the problem, you need to allocate storage for `ddj`. You can either allocate static storage on the stack, or dynamic storage on the heap. To allocate static storage, do: ``` // Allocate 64 bytes for ddj. It will automatically be deallocated when the function // returns. Be careful of buffer overflows! char ddj[64]; ``` To allocate dynamic storage: ``` // Allocate 64 bytes for ddj. It will NOT be automatically deallocated -- you must // explicitly deallocate it yourself at some point in the future when you're done // with it. Be careful of buffer overflows! char *ddj = new char[64]; ... delete [] ddj; // Deallocate it ``` Instead of managing storage yourself, it would be a better idea to use `std::string`, which automatically deals with memory management. Finally, since all you're doing is comparing the first three characters of the string, there's no need to jump through hoop to copy the string and compare it. Just use [`strncmp()`](http://linux.die.net/man/3/strncmp): ``` if(strncmp(buffer, "JMX", 3) == 0) { ... } ```
How to copy a byte[] into a char*?
[ "", "c++", "c", "" ]
I've got 2 questions about organising Unit tests. 1. Do I have to put test to the same package as tested class, or can I organise tests in different packages? For example if I have **validity** and **other** tests, is it correct to split them into different packages, even if they are for same class? 2. What about mock and stub classes? Shall I separate them from packages containing only tests, or put them together?
The way we do our JUnit test cases is to put them in the same package, but in a different root directory. Since we use Maven, we just use the standard locations making the structure similar to the following. ``` src/main/java/com/foo/Bar.java src/test/java/com/foo/BarTest.java ``` Obviously there's more to the structure, but this lets us build the tests separately from the mainline code, but still access protected classes and the like. With respect to different types of tests, this is very subjective. When we started our testing effort (which unfortunately started after development), I tried to keep things pretty isolated. Unfortunately, it quickly became a nightmare when we got to the 500+ test case point. I've since tried to do more consolidation. This led to reduced amounts of code to maintain. As I said, though, it's very subjective. As far as test-only code, we keep it in a separate `com.foo.test` package that resides only in the `src/test/java` tree.
I too tend to put my tests in the same package but under a different root directory. This allows me to test package-private classes or access packing-private classes while testing something else in the package. They are kept in a separate directory tree to allow excluding them from the deployed result (in particular to ensure that test code didn't accidentally get into production code). What matters most, however, is what works for your situation. In terms of how many test classes per production class, the theory I've seen is that you write one test class per fixture, that is per setup structure. In many cases that is the same (or close enough) to one test class per production class, but I have sometimes written more test classes (in particular equality tests tend to be separated) for a give production class, and occasionally one test class of for a group of (related) production classes (say, for testing the Strategy pattern). Mostly, I don't worry too much about the theory, but rework the tests as needed to keep duplication to an absolute minimum.
Where should I put my JUnit tests?
[ "", "java", "unit-testing", "junit", "" ]
I've just used it for the first time - consider: ``` IGameObject void Update() IDrawableGameObject : IGameObject void Draw() ``` I had a level class which used DrawableGameObjects - I switched this to be IDrawableGameObject's instead to reduce coupling and aid in TDD. However I of course lose the ability to call Update(..) without casting - to get around this I used inheritance. I've never used interface based inheritance before - nor have I really found the need except in this case. I didn't really want to cast each time in my update method as it is called up to 60 times a second, on the other hand a foreach(..) could have worked that used IGameObject's. Any advice? **Edit** I should add - my fake's I created afterwards for unit testing then implement IDrawableGameObject - these classes now have many methods instead of just a handful for each interface. I know interfaces must be only a handful of members large, but does inheritance break this rule? Thanks
> I know interfaces must be only a > handful of members large They need to contain exactly as many members as are necessary to express the concept - no more, no less. There are some quite scary interfaces in the BCL (although maybe you could argue some are oversized). I'd say this definitely looks like an acceptable use of interface inheritance. As an aside... if there is implementation logic that only depends on the interface members, consider using extension methods so that the implementing classes don't need to repeat it... for example: ``` // just a silly example that only uses members of the target type public static void DrawComplete(this IDrawableGameObject obj, Canvas canvas) { obj.Draw(canvas); foreach(var child in obj.Children.OfType<IDrawableGameObject>()) { child.DrawComplete(canvas); } } ``` then all callers get the `DrawComplete` method without all the implementations having to repeat it.
Interface based inheritance is really no different than normal inheritance in terms of "should you do it". It still expresses an "is a" relationship between two types. So in this case if IDrawableGameObject is indeed an IGameObject as it appears to be, the inheritance makes sense.
Interface inheritance - a good thing?
[ "", "c#", "inheritance", "interface", "language-agnostic", "" ]
I'm trying to build a generic grid view in an ASP.NET MVC application. Let me explain with some code: ``` public interface ITrustGrid<T> { IPagedList<T> Elements { get; set; } IList<IColumn<T>> Columns { get; set; } IList<string> Headers { get; } } ``` This is an interface of a class that allows me to set columns and expressions in my controller. I pass implementations to a partial view like this: ``` <% Html.RenderPartial("SimpleTrustGridViewer", ViewData["employeeGrid"] as TrustGrid<EmployeeInfoDTO>); %> ``` The problem is that I can't figure out how to make the partial view that renders the grid generic. In other words, I want to turn this: ``` <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<EmployeeInfoDTO>>" %> ``` into something like this: ``` <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<T>>" %> ``` => How can I make my partial view generic in the most simple way? **EDIT:** I solved this by using a TrustGridBuilder that has a public TrustGrid GetTrustGrid() method which returns a non-generic TrustGrid. The TrustGrid contains strings instead of linq stuff. So I execute the linq in the GetTrustGrid() method and put the strings in a TrustGrid object. Thanks for everybody to help me on the right track.
It's not possible to do it like that. The reason is the `.aspx` will generate a class that you don't have much control on it and you can't add a generic parameter to it. I guess the most straightforward way is to pass it as `object`.
You could make all your model types that you would pass into this partial inherit from a base class/interface that establishes the basic behavior that would be used by this partial view and accept any object of that class/interface type, or just have the view accept any type of object and then use reflection to base your partial view behavior off of. EXAMPLE: ``` public interface IDisplayModel { string DisplayText{get;set;} string ImageUrl{get;set;} string AltText{get;set;} } public interface ITrustGrid<T> where T : IDisplayModel { IPagedList<T> Elements { get; set; } IList<IColumn<T>> Columns { get; set; } IList<string> Headers { get; } } <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ITrustGrid<IDisplayModel>>" %> ``` Naturally, your `IDisplayModel` would vary based on your desired behavior. This would then allow you to pass in anything to this partial that implements this base interface to establish general behavior.
Generic partial view: how to set a generic class as model?
[ "", "c#", "asp.net-mvc", "generics", "" ]
How do I remove an element of an array and shift the remaining elements down. So, if I have an array, ``` array[]={1,2,3,4,5} ``` and want to delete 3 and shift the rest so I have, ``` array[]={1,2,4,5} ``` How would I go about this in the least amount of code?
You just need to overwrite what you're deleting with the next value in the array, propagate that change, and then keep in mind where the new end is: ``` int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // delete 3 (index 2) for (int i = 2; i < 8; ++i) array[i] = array[i + 1]; // copy next element left ``` Now your array is `{1, 2, 4, 5, 6, 7, 8, 9, 9}`. You cannot delete the extra `9` since this is a statically-sized array, you just have to ignore it. This can be done with `std::copy`: ``` std::copy(array + 3, // copy everything starting here array + 9, // and ending here, not including it, array + 2) // to this destination ``` In C++11, use can use `std::move` (the algorithm overload, not the utility overload) instead. More generally, use `std::remove` to remove elements matching a value: ``` // remove *all* 3's, return new ending (remaining elements unspecified) auto arrayEnd = std::remove(std::begin(array), std::end(array), 3); ``` Even more generally, there is `std::remove_if`. Note that the use of `std::vector<int>` may be more appropriate here, as its a "true" dynamically-allocated resizing array. (In the sense that asking for its `size()` reflects removed elements.)
You can use [`memmove()`](http://linux.die.net/man/3/memmove), but you have to keep track of the array size yourself: ``` size_t array_size = 5; int array[5] = {1, 2, 3, 4, 5}; // delete element at index 2 memmove(array + 2, array + 3, (array_size - 2 - 1) * sizeof(int)); array_size--; ``` In C++, though, it would be better to use a `std::vector`: ``` std::vector<int> array; // initialize array... // delete element at index 2 array.erase(array.begin() + 2); ```
Remove an array element and shift the remaining ones
[ "", "c++", "arrays", "" ]
I am trying to extract all the `<input >` tags out of a `<form>` tag. I have created a regexp which can identify the entire `<form>` tag and all the code up to the ending `</form>` but I cannot figure out how to match all the `<input[^>]+>` within that. EDIT: The data is a string. I cannot use DOM functions because it's not part of the document. if I insert it into a hidden tag, it changes the layout of the page because the string contains an entire HTML page including links to external stylesheets.
Regexes are fundamentally bad at parsing HTML (see [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](https://stackoverflow.com/questions/701166) for why). What you need is an HTML parser. See [Can you provide an example of parsing HTML with your favorite parser?](https://stackoverflow.com/questions/773340) for examples using a variety of parsers.
Why can't you just use the DOM? ``` var inputFields = document.getElementById('form_id').getElementsByTagName('input'); for (var i = 0, l = inputFields.length; i < l; i++) { // Do something with inputFields[i] ... } ``` If you must use regex: ``` var formHTML = document.getElementById('form_id').innerHTML; var inputs = formHTML.match(/<input.+?\/?>/g); ``` Note, the above regular expression is not reliable and will not work in ALL situations, hence why you should use the DOM! :)
Regexp to pull input tags out of form
[ "", "javascript", "regex", "" ]
How do I get an extJS combo field to clear its 'value' when the display text is blank or doesn't match a list value, i.e. custom text not in the data store? I'm sure there must be something I'm missing, because such a simple feature can't make an otherwise impressive combo useless.
<http://extjs.com/forum/showthread.php?t=68403>
You can force to the list using forceSelection, also you might need to put an event on to capture the text value change and invalidate it if it's not in the store, perhaps the valid event I'm not sure.
Clear extJS combo value when text is cleared or doesn't match
[ "", "javascript", "extjs", "" ]
I have a `std::vector<int>`, and I want to delete the `n`th element. How do I do that? Example: ``` std::vector<int> vec; vec.push_back(6); vec.push_back(-17); vec.push_back(12); vec.erase(???); ```
To delete a single element, you could do: ``` std::vector<int> vec; vec.push_back(6); vec.push_back(-17); vec.push_back(12); // Deletes the second element (vec[1]) vec.erase(std::next(vec.begin())); ``` Or, to delete more than one element at once: ``` // Deletes the second through third elements (vec[1], vec[2]) vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3)); ```
The `erase` method on `std::vector` is overloaded, so it's probably clearer to call ``` vec.erase(vec.begin() + index); ``` when you only want to erase a single element.
How do I erase an element from std::vector<> by index?
[ "", "c++", "stl", "stdvector", "erase", "" ]
I was listening to a podcast recently (may have been SO - can't remember) when the interviewee said that one of the reasons Java was so successful and popular was the tooling. Having use of great FOSS editors such as Eclipse, NetBeans. Metrics tools such as Cobertura, Find Bugs, Build tools such as Maven and ANT.. I'd have to agree I've done a fair bit of .NET and the tools are OKish. The problem seems to be that there isn't the depth in tooling that there is in Java. The FOSS stuff seems pretty limited. My question: Are there any modern languages with a better community and tooling for getting the job done?
Don't forget Perl's [CPAN](http://www.cpan.org) with a wealth of first-class code like e.g. [profilers](http://search.cpan.org/~timb/Devel-NYTProf-2.09/lib/Devel/NYTProf.pm), [ide's](http://search.cpan.org/~szabgab/Padre-0.34/lib/Padre.pm) and [modern Object Oriented Systems](http://search.cpan.org/~drolsky/Moose-0.77/lib/Moose.pm). C.
sure, there's emacs and vi! seriously, great as some Java tools are, many of their features are meaningless for other languages/environments.
Best language tooling
[ "", "java", "" ]
I'm an accomplished user of SQL; I'm confident creating schema and optimizing queries in ANSI-SQL, for Sybase, MS SQL Server, MySQL, or postgresql. I understand joins, subqueries, indexes, etc., so I don't need to recapitulate any of that that isn't different under Oracle. I'll be taking a job that'll require using Oracle. Point me to **online** resources designed not as an "Intro to SQL for Oracle" but ones that explain "PL/SQL for people who already understand SQL". I'm especially interested in the following: a concise guide to PL/SQL extensions, and optimizing Oracle queries.
[Oracle® Database PL/SQL User's Guide and Reference (10g)](http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/toc.htm) Really, what more could you want? If you are new to Oracle, I'd also suggest you spend a bit of time learning its transaction model, as it is subtly different to SQL Server, which could bite you. [Here](http://www.oracle.com/technology/oramag/oracle/05-nov/o65asktom.html) is a good article on it. The other poster who suggested reading Kyte is spot on.
You should be aware that PL/SQL is a more-or-less complete programming language. Crazy people like me create applications where most of the work is done in PL/SQL packages on the server.
Introduce me to Oracle PL/SQL extensions
[ "", "sql", "oracle", "plsql", "" ]
OK, maybe I'm dumb/blind, but in the docs it says "rebuild and restart the server." But I don't see a button to do this anywhere. Or from any contextual menu. And I can't find anything in their docs explaining how to do it. If I just try to start the app again, it gets angry because I already have App Engine running on the needed port. Only solution I've found is to restart Eclipse... any other ideas? A screenshot of a button would help if possible. :)
In eclipse, there is a view that contains your Console. If you click on that, you will see the STDOUT and STDERR output of your running application. In the upper right, there should be a red box that will terminate the currently running program. ![alt t3xt](https://i.stack.imgur.com/NsRpq.png)
I have a different and possibly more productive solution for you. Like with most web development environments you probably want to change your source code and have Google Appengine server reload the new code for you. You need some version of the traditional "touch" unix command (if you work on windows you can download a version from [here](http://unxutils.sourceforge.net/)). Then go to you project properties, Builders and add a new build step as a "Program". Under "Location" enter the path to your "touch" command ("D:\bin\UnxUtils\usr\local\wbin\touch.exe" for example - on Posix systems just "touch" should be enough since it's already in your PATH) and in "Arguments" put something like "${project\_loc}/war/WEB-INF/appengine-web.xml". Also go to the "Build Options" tab and check "During auto builds". "touch" will update the timestamp in you appengine-web.xml. When the App Engine server detects changes to you appengine-web.xml it will reload the app automatically. The load process is very fast so it can be done whenever you change any file in your project (which normally triggers the auto-build in Eclipse) - you can tweak the builder to only run when you change certain types of files.
How do I restart the Google App Engine Java Server in Eclipse?
[ "", "java", "eclipse", "google-app-engine", "" ]
I have a problem with a continue statement in my C# Foreach loop. I want it to check if there is a blank cell in the datagridview, and if so, then skip printing the value out and carry on to check the next cell. Help appreciated greatly. Here is the code: ``` foreach (DataGridViewRow row in this.dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (cell.Size.IsEmpty) { continue; } MessageBox.Show(cell.Value.ToString()); } } ```
Well, you're currently checking whether the cell's *size* is zero. In a grid, every cell in a column has the same width and every cell in a row has the same height (typically, anyway). You want to be checking based on the *value* of the cell. For example: ``` if (cell.Value == null || cell.Value.Equals("")) { continue; } ``` Tweak this for any other representations of "empty" values that you're interested in. If there are lots, you might want to write a specific method for this, and call it in the check: ``` if (IsEmptyValue(cell.Value)) { continue; } ```
You don't need to use the continue keyword here, you could just do this: ``` foreach (DataGridViewRow row in this.dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { if (!cell.Size.IsEmpty) MessageBox.Show(cell.Value.ToString()); // note the ! operator } } ``` Also, you're checking whether the *size* of the cell is empty. Is this really what you want to do? What errors are you getting?
C# Foreach Loop - Continue Issue
[ "", "c#", "datagridview", "foreach", "continue", "" ]
I have an ASP.NET page where I am showing products in a Gridview control. When users mouse over a Product name a window should appear and show that Product's picture in it (by getting product id and than find associated image for it.) Is there an AJAX control or something like this??
There are a number of ways that it could be done, but typically I see it as a "tooltip" on the item that has an image tag, that points to an aspx page that returns the image. Or the image directly. Here is an example of my first option ``` <img src="http://www.mysite.com/GenerateProductImage.aspx?productId=1" alt="My Product" /> ``` For this, you would have to create the GenerateProductImage.aspx page, and set the response type to be image, having it only return the image. Here is a [CSS ToolTip](http://www.kollermedia.at/archive/2008/03/24/easy-css-tooltip/) demo that will help you get started with the styling part
You have a few choices. You can use the [jQuery tooltip plugin](http://jquery.bassistance.de/tooltip/demo/) or you can try the [Ajax Control Toolkit HoverMenu](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/HoverMenu/HoverMenu.aspx)
Show pictures on mouseover
[ "", "c#", "asp.net", "" ]
Although this question is related to StructureMap, my *general* question is: > When wiring up components with an IoC > container **in code** (as opposed > to configuring via **xml**) do you > generally need explicit project/build > references to all assemblies? Why the separate assemblies? Because: --- > "Abstract classes residing in a > separate assembly from their concrete > implementations are a great way to > achieve such separation." -**Framework > Design Guidelines p.91** --- Example: Let's say I have *PersonBase.dll* and *Bob.dll* *Bob* inherits from the abstract class *PersonBase*. They're both in the *Person* namespace. **But in different assemblies**. I'm programming to *PersonBase*, not *Bob*. Back in my main code, I need a person. StructureMap can scan assemblies. Great, I'll ask StructureMap for one! Now, in my main code, I am of course referring only to *PersonBase*, not to *Bob*. I actually don't want my code to know *anything* about *Bob*. No project references, no nuthin. That's the whole point. So I want to say: ``` //Reference: PersonBase.dll (only) using Person; ... //this is as much as we'll ever be specific about Bob: Scan( x=> { x.Assembly("Bob.dll"); } //Ok, I should now have something that's a PersonBase (Bob). But no ? ObjectFactory.GetAllInstances<PersonBase>().Count == 0 ``` No luck. What does work is being explicit that I want Bob: ``` //Reference: PersonBase.dll and Bob.dll using Person; ... Scan( x => {x.Assembly("Bob.dll"); } //If I'm explicit, it works. But Bob's just a PersonBase, what gives? ObjectFactory.GetAllInstances<Bob>().Count == 1 //there he is! ``` But now I've had to reference *Bob.dll* in my project which is exactly what I didn't want. I can avoid this situation using Spring + Xml configuration. But then I'm back to Spring + Xml configuration ... ! > Am I missing something with using > StructureMap, or as a general > principle, do (fluent) IoC > configurations need explict references > to all assemblies? Possibly related question: [[StructureMap and scanning assemblies](https://stackoverflow.com/questions/508399/structuremap-and-scanning-assemblies)](https://stackoverflow.com/questions/508399/structuremap-and-scanning-assemblies)
I finally got this sorted out. It looks like this: [IoC Uml http://img396.imageshack.us/img396/1343/iocuml.jpg](http://img396.imageshack.us/img396/1343/iocuml.jpg) with the assemblies * Core.exe* PersonBase.dll (referenced **compile time** by Core.exe)* Bob.dll (**loaded up run time** via StructureMap Scan)* Betty.dll (**loaded up run time** via StructureMap Scan) To get it with StructureMap, I needed a custom "ITypeScanner" to support scanning for assemblies: ``` public class MyScanner : ITypeScanner { public void Process(Type type, PluginGraph graph) { if(type.BaseType == null) return; if(type.BaseType.Equals(typeof(PersonBase))) { graph.Configure(x => x.ForRequestedType<PersonBase>() .TheDefault.Is.OfConcreteType(type)); } } } ``` So my main code looks like: ``` ObjectFactory.Configure(x => x.Scan ( scan => { scan.AssembliesFromPath(Environment.CurrentDirectory /*, filter=>filter.You.Could.Filter.Here*/); //scan.WithDefaultConventions(); //doesn't do it scan.With<MyScanner>(); } )); ObjectFactory.GetAllInstances<PersonBase>() .ToList() .ForEach(p => { Console.WriteLine(p.FirstName); } ); ```
You can do xml configuration with StructureMap as well. You can even mix them if you want. There are also StructureMap Attributes you could put in your Bob class to tell StructureMap how to load the assembly. DefaultConstructor is one I end up using from time to time.
IoC, Dll References, and Assembly Scanning
[ "", "c#", "inversion-of-control", "structuremap", "" ]
Given these two queries: ``` Select t1.id, t2.companyName from table1 t1 INNER JOIN table2 t2 on t2.id = t1.fkId WHERE t2.aField <> 'C' ``` OR: ``` Select t1.id, t2.companyName from table1 t1 INNER JOIN table2 t2 on t2.id = t1.fkId and t2.aField <> 'C' ``` Is there a demonstrable difference between the two? Seems to me that the clause "t2.aField <> 'C'" will run on every row in t2 that meets the join criteria regardless. Am I incorrect? **Update:** I did an "Include Actual Execution Plan" in SQL Server. The two queries were identical.
I prefer to use the Join criteria for explaining how the tables are joined together. So I would place the additional clause in the where section. I hope (although I have no stats), that SQL Server would be clever enough to find the optimal query plan regardless of the syntax you use. HOWEVER, if you have indexes which also have id, and aField in them, I would suggest placing them together in the inner join criteria. It would be interesting to see the query plan's in these 2 (or 3) scenarios, and see what happens. Nice question.
There is a difference. You should do an EXPLAIN PLAN for both of the selects and see it in detail. As for a simplier explanation: The WHERE clause gets executed only after the joining of the two tables, so it executes for each row returned from the join and not nececerally every one from table2. Performance wise its best to eliminate unwanted results early on so there should be less rows for joins, where clauses or other operations to deal with later on. In the second example, there are 2 columns that have to be same for the rows to be joined together so it usually will give different results than the first one.
is it better to put more logic in your ON clause or should it only have the minimum necessary?
[ "", "sql", "sql-server", "" ]
In my Swing application, I want the ability to switch between decorated and undecorated without recreating the entire frame. However, the API doesn't let me call `setUndecorated()` after the frame is made visible. Even if i call `setVisible(false)`, `isDisplayable()` still returns true. The API says the only way to make a frame not-displayable is to re-create it. However, I don't want to recreate the frame just to switch off some title bars. I am making a full-screenable application that can be switched between fullscreen and windowed modes; It should be able to switch while maintaining the state, etc. How do I do this after a frame is visible?.
You can't. That's been my experience when I tried to achieve the same. However if you have your entire UI in one panel which is in your frame, you can create a new frame and add that panel to the frame. Not so much work. Something like this: ``` // to start with JPanel myUI = createUIPanel(); JFrame frame = new JFrame(); frame.add(myUI); // .. and later ... JFrame newFrame = new JFrame(); newFrame.setUndecorated(); newFrame.add(myUI); ``` In Swing a panel (and indeed any instance of a component) can only be in one frame at a time, so when you add it to a new frame, it immediately ceases to be in the old frame.
Have you tried calling `Frame.dispose()` and then changing it? Haven't tried it myself, but it might work. If not, then what you can do is have the frame an inconsequential part of the class, with only the most minimal hooks to the highest level panel or panels necessarily, and just move those to the new frame. All the children will follow.
How to call setUndecorated() after a frame is made visible?
[ "", "java", "swing", "fullscreen", "" ]
Well I am using the following code to take any old image into a 160x120 thumbnail, the problem is if there is overflow the background is always black. I've been snooping around the PHP docs but none of these functions seem to have any kind of color parameters. Any ideas or pointers would be great! ``` $original = 'original_image.jpg'; $thumbnail = 'output_thumbnail.jpg'; list($width,$height) = getimagesize($original); $width_ratio = 160 / $width; if ($height * $width_ratio <= 120) { $adjusted_width = 160; $adjusted_height = $height * $width_ratio; } else { $height_ratio = 120 / $height; $adjusted_width = $width * $height_ratio; $adjusted_height = 120; } $image_p = imagecreatetruecolor(160,120); $image = imagecreatefromjpeg($original); imagecopyresampled($image_p,$image,ceil((160 - $adjusted_width) / 2),ceil((120 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height); imagejpeg($image_p,$thumbnail,100); ``` Also if you're unclear what I mean, take [this image](http://www.andrew-g-johnson.com/thumb.jpg) and consider that it was originally just red text on a white background
The [imagecreatetruecolor function](http://www.php.net/imagecreatetruecolor) creates a black canvas. Use the imagefill function to paint it white...
Add this before you copy the original into the new: ``` $white = ImageColorAllocate($image_p, 255, 255, 255); ImageFillToBorder($image_p, 0, 0, $white, $white); ``` EDIT: Actually, I didn't know about imagefill . . . ``` $white = imagecolorallocate($image_p, 255, 255, 255); imagefill($image_p, 0, 0, $white); ```
Why do all my auto-generated thumbnails with GD in PHP have black backgrounds?
[ "", "php", "gd", "thumbnails", "" ]
I’m aware of the tutorial at boost.org addressing this: [Boost.org Signals Tutorial](http://www.boost.org/doc/libs/1_38_0/doc/html/signals/tutorial.html), but the examples are not complete and somewhat over simplified. The examples there don’t show the include files and some sections of the code are a little vague. **Here is what I need:** ClassA raises multiple events/signals ClassB subscribes to those events (Multiple classes may subscribe) In my project I have a lower-level message handler class that raises events to a business class that does some processing of those messages and notifies the UI (wxFrames). I need to know how these all might get wired up (what order, who calls who, etc).
The code below is a minimal working example of what you requested. `ClassA` emits two signals; `SigA` sends (and accepts) no parameters, `SigB` sends an `int`. `ClassB` has two functions which will output to `cout` when each function is called. In the example there is one instance of `ClassA` (`a`) and two of `ClassB` (`b` and `b2`). `main` is used to connect and fire the signals. It's worth noting that `ClassA` and `ClassB` know nothing of each other (ie they're not *compile-time bound*). ``` #include <boost/signal.hpp> #include <boost/bind.hpp> #include <iostream> using namespace boost; using namespace std; struct ClassA { signal<void ()> SigA; signal<void (int)> SigB; }; struct ClassB { void PrintFoo() { cout << "Foo" << endl; } void PrintInt(int i) { cout << "Bar: " << i << endl; } }; int main() { ClassA a; ClassB b, b2; a.SigA.connect(bind(&ClassB::PrintFoo, &b)); a.SigB.connect(bind(&ClassB::PrintInt, &b, _1)); a.SigB.connect(bind(&ClassB::PrintInt, &b2, _1)); a.SigA(); a.SigB(4); } ``` The output: ``` Foo Bar: 4 Bar: 4 ``` For brevity I've taken some shortcuts that you wouldn't normally use in production code (in particular access control is lax and you'd normally 'hide' your signal registration behind a function like in KeithB's example). It seems that most of the difficulty in `boost::signal` is in getting used to using `boost::bind`. It *is* a bit mind-bending at first! For a trickier example you could also use `bind` to hook up `ClassA::SigA` with `ClassB::PrintInt` even though `SigA` does *not* emit an `int`: ``` a.SigA.connect(bind(&ClassB::PrintInt, &b, 10)); ```
Here is an example from our codebase. Its been simplified, so I don't guarentee that it will compile, but it should be close. Sublocation is your class A, and Slot1 is your class B. We have a number of slots like this, each one which subscribes to a different subset of signals. The advantages to using this scheme are that Sublocation doesn't know anything about any of the slots, and the slots don't need to be part of any inheritance hierarchy, and only need implement functionality for the slots that they care about. We use this to add custom functionality into our system with a very simple interface. Sublocation.h ``` class Sublocation { public: typedef boost::signal<void (Time, Time)> ContactSignal; typedef boost::signal<void ()> EndOfSimSignal; void endOfSim(); void addPerson(Time t, Interactor::Ptr i); Connection addSignalContact(const ContactSignal::slot_type& slot) const; Connection addSignalEndOfSim(const EndOfSimSignal::slot_type& slot) const; private: mutable ContactSignal fSigContact; mutable EndOfSimSignal fSigEndOfSim; }; ``` Sublocation.C ``` void Sublocation::endOfSim() { fSigEndOfSim(); } Sublocation::Connection Sublocation::addSignalContact(const ContactSignal::slot_type& slot) const { return fSigContact.connect(slot); } Sublocation::Connection Sublocation::addSignalEndOfSim(const EndOfSimSignal::slot_type& slot) const { return fSigEndOfSim.connect(slot); } Sublocation::Sublocation() { Slot1* slot1 = new Slot1(*this); Slot2* slot2 = new Slot2(*this); } void Sublocation::addPerson(Time t, Interactor::Ptr i) { // compute t1 fSigOnContact(t, t1); // ... } ``` Slot1.h ``` class Slot1 { public: Slot1(const Sublocation& subloc); void onContact(Time t1, Time t2); void onEndOfSim(); private: const Sublocation& fSubloc; }; ``` Slot1.C ``` Slot1::Slot1(const Sublocation& subloc) : fSubloc(subloc) { subloc.addSignalContact(boost::bind(&Slot1::onContact, this, _1, _2)); subloc.addSignalEndSim(boost::bind(&Slot1::onEndSim, this)); } void Slot1::onEndOfSim() { // ... } void Slot1::onContact(Time lastUpdate, Time t) { // ... } ```
Complete example using Boost::Signals for C++ Eventing
[ "", "c++", "boost-signals", "" ]
If a Thread creates a daemon Thread, can I rely on the fact that when the parent exits the run method, the son will also terminate?
No - threads are independent. There's no sense of one thread "owning" another and forcing termination. If you're *really* asking whether when all the non-daemon threads in the application have died, you can rely on the process dying: yes, you can. But that's *all* you can rely on. In particular, if there are two non-daemon threads, each of which has created a daemon thread, and *one* of the non-daemon threads terminates, then the remaining three threads will continue running.
I believe daemon threads are tied to the JVM and not the creating thread.
Are Java daemon threads automatically killed when their parent exits?
[ "", "java", "multithreading", "" ]
I am considering parsing simple math equations by compiling from source at runtime. I have heard that there are security considerations that I should be aware of before using this approach, but I can’t find any info on this. Thanks C# .net 2.0, winforms
If the C# "equations" can be saved and exchanged between users, then there is certainly a security risk. A user could put malicious code in the equation, and have it do bad things on the machines of other users. Or a user could simply be tricked into entering a malicious "equation" (think of the old [alt+F4 prank](http://everything2.com/title/Alt%2520F4) here). Fortunately you can [safely host untrusted code](http://msdn.microsoft.com/en-us/magazine/cc163701.aspx) in a .NET sandbox. The general idea is that you create a separate AppDomain (with the [AppDomain.CreateDomain](http://msdn.microsoft.com/en-us/library/ms130766.aspx) method) that has only minimal permissions, and then load and run the user code there. Loading dynamically generated assemblies into a separate AppDomain is a good idea anyway, because it allows you to [unload](http://msdn.microsoft.com/en-us/library/system.appdomain.unload.aspx) them again.
The problem with this approach is that a user could enter *any* code they wanted (unless you sanitize it). They could put in code to erase all your files. If this is running on a server, **do not** do this. Also, even on a desktop, running a compiler just to evaluate an equation is really slow. Make a grammar for your equations with a tool like [ANTLR](http://www.antlr.org/), and embed the parser into your program.
Using Compile Assembly From Source to evaluate math equations in C#
[ "", "c#", ".net", "math", "parsing", "equation", "" ]
I'm parsing a binary file format. It encodes an integer using four bytes in a way that will naturally fit within c#'s uint type. What is the most C#/idiomatic way to implement this function: ``` uint ReadUint(byte[] buffer); ``` Assume the buffer contains 4 elements. A complete answer might consider some of the common byte orderings caused by little/big endian assumptions in the file, and document the one(s) it chooses to parse.
The most basic (but a little dangerous re endianness) is: ``` return BitConverter.ToUInt32(buffer, 0); ``` Other than than, bit-shifting is fine (as per your own reply) - or you can use Jon's [EndianBitConverter in MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/), which handles the translations. (edit) The little-endian bit-shifting version I use in protobuf-net is pretty-much identical to your version - I just read them in ascending order and use bitwise (not numeric) addition: ``` return ((uint)buffer[0]) | (((uint)buffer[1]) << 8) | (((uint)buffer[2]) << 16) | (((uint)buffer[3]) << 24); ```
I would normally use the BitConverter class for this. In your case the [BitConverter.ToUInt32()](http://msdn.microsoft.com/en-us/library/system.bitconverter.touint32.aspx) method.
What is the idiomatic c# for unpacking an integer from a byte array?
[ "", "c#", "parsing", "" ]
I'm using Logging (`import logging`) to log messages. Within 1 single module, I am logging messages at the debug level `my_logger.debug('msg')`; Some of these debug messages come from `function_a()` and others from `function_b()`; I'd like to be able to enable/disable logging based on whether they come from a or from b; I'm guessing that I have to use Logging's filtering mechanism. Can someone show me how the code below would need to be instrumented to do what I want? ``` import logging logger = logging.getLogger( "module_name" ) def function_a( ... ): logger.debug( "a message" ) def function_b( ... ): logger.debug( "another message" ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) #don't want function_a()'s noise -> .... #somehow filter-out function_a's logging function_a() #don't want function_b()'s noise -> .... #somehow filter-out function_b's logging function_b() ``` If I scaled this simple example to more modules and more funcs per module, I'd be concerned about lots of loggers; Can I keep it down to 1 logger per module? Note that the log messages are "structured", i.e. if the function(s) logging it are doing some parsing work, they all contain a prefix `logger.debug("parsing: xxx")` - can I somehow with a single line just shut-off all "parsing" messages (regardless of the module/function emitting the message?)
Just implement a subclass of `logging.Filter`: <http://docs.python.org/library/logging.html#filter-objects>. It will have one method, `filter(record)`, that examines the log record and returns True to log it or False to discard it. Then you can install the filter on either a `Logger` or a `Handler` by calling its `addFilter(filter)` method. Example: ``` class NoParsingFilter(logging.Filter): def filter(self, record): return not record.getMessage().startswith('parsing') logger.addFilter(NoParsingFilter()) ``` Or something like that, anyway.
Do not use global. It's an accident waiting to happen. You can give your loggers any "."-separated names that are meaningful to you. You can control them as a hierarchy. If you have loggers named `a.b.c` and `a.b.d`, you can check the logging level for `a.b` and alter both loggers. You can have any number of loggers -- they're inexpensive. The most common design pattern is one logger per module. See [Naming Python loggers](https://stackoverflow.com/questions/401277/naming-python-loggers) Do this. ``` import logging logger= logging.getLogger( "module_name" ) logger_a = logger.getLogger( "module_name.function_a" ) logger_b = logger.getLogger( "module_name.function_b" ) def function_a( ... ): logger_a.debug( "a message" ) def function_b( ... ): logger_b.debug( "another message" ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) logger_a.setLevel( logging.DEBUG ) logger_b.setLevel( logging.WARN ) ... etc ... ```
logging with filters
[ "", "python", "logging", "python-logging", "" ]
say i have a nvarchar field in my database that looks like this ``` 1, "abc abccc dabc" 2, "abccc dabc" 3, "abccc abc dabc" ``` i need a select LINQ query that would match the word "abc" with boundaries not part of a string in this case only row 1 and 3 would match
``` from row in table.AsEnumerable() where row.Foo.Split(new char[] {' ', '\t'}, StringSplitOptions.None) .Contains("abc") select row ``` It's important to include the call to `AsEnumerable`, which means the query is executed on the client-side, else (I'm pretty sure) the `Where` clause won't get converted into SQL succesfully.
Maybe a regular expression like this (nb - not compiled or tested): ``` var matches = from a in yourCollection where Regex.Match(a.field, ".*\sabc\s.*") select a; ```
linq match word with boundaries
[ "", "sql", "linq", "" ]
I am writing a C# application that uses a long "hard-coded" string. For maintainability reasons I have decided to put this string in an external text file and load it. Is this a good idea? The extra I/O does not seem big in this case. I realize that I also have an option to embed this file as a .resx resource. Is this a better idea? The file will never need to be localized.
If you intend to allow users/administrators to change the string, I agree with the other answers, and I'd suggest putting it in settings. If you don't want it to be editable after deployment and it will only be modified by you and your developers, then I would put it in an embedded resource (note, this is not the same as a .resx file). You would read it at runtime like this: ``` Assembly assembly = Assembly.GetExecutingAssembly(); Stream stream = assembly.GetManifestResourceStream(“MyAssemblyNamespace.MyTextFile.txt”); StreamReader reader = new StreamReader(stream); string theText = streamReader.ReadToEnd(); ``` **Update:** This is solution that is easy to maintain. The .txt file will just be another file in your solution explorer in Visual Studio and you can edit it just like any other file, keep it under source control like any other file, etc. To turn it into an embedded resource by changing the Build Action in the properties window to "Embedded Resource". The end result is that your file(s) get embedded in your DLL so that you only have 1 DLL to distribute instead of a DLL and a folder of files that have to move around together. **Update 2:** Regarding "production debugging", this is a very static solution, and so you won't be able to change the contents of the text file at runtime because the file is baked into the DLL at compile time. For reading the contents of the file, you can use tools like [reflector](http://www.red-gate.com/products/reflector/) to view the embedded resources of a DLL. You could also write a simple command line tool that dumps all the embedded .txt files from a DLL into individual files for you to look at. For memory usage, there isn't a solution more efficient than "I load it from a file into memory only exactly when it is needed". You have to decide whether the improved maintainability and deployment is worth the cost of a little extra memory when your DLL is loaded into memory for your specific situation. That said, you haven't said how large these files are. If they are really huge (megabytes+), I would probably *not* use this solution and would go with loose files on the hard drive. If they are generally pretty small (hundreds of kilobytes), I wouldn't worry about the extra memory unless you are in some kind of embedded device situation where RAM is really tight.
Why not make it an appSetting in your web/app.config file? ``` <appSettings> <add key="MyLongString" value="This is a really long string value that I don't want hardcoded" /> </appSettings> ``` Then, in code: ``` using System.Configuration; //To ease your typing pains var myReallyLongString = ConfigurationManager.AppSettings["MyLongString"]; ```
Use external file or resource?
[ "", "c#", ".net", "resources", "embedded-resource", "" ]
I made a function which displays date on the webpage,, and i uploaded the same onto some server... But when i changed the date of my system, i noticed that the date is dependent on client machine.. Is it not possible to get the date from actual time server and embed that code into my program.. Hope i am able to explain my doubt.. Please give some solution to this with small sample code..that would be helpful.. Thanks a lot..
If you have written it in javascript, well...that always executes on the client side. If you are calculating date through javascript, its too late, that code is gone. To solve this, you would have to make your js function receive data through parameters, and that data should be calculated on the server side. You could do something like. ``` <%@ page import ="java.util.Date" %><%--Imports date --%> <% Date date = new Date(); String strdate = date.toString();//could be formatted using SimpleDateFormat. %> <!--must be inside a form --> <input type="text" value="javascript:showDate('<%=strdate%>');"/> <!--must be inside a table--> <td>javascript:showDate(<%=strdate%>);</td> ``` Or more elegantly, get server date in your java class, and write it to request: ``` //formattedDate is defined above, in the format you like the most. Could be a //java.util.date or a String request.setDate("date",formattedDate); ``` And then, in your jsp, using for example, JSTL ``` <c:out value="${formattedDate}"/> ``` Or, ``` <% //this java code is run on the server side. String strdate = (String)request.getAttribute("date"); %> <%=strdate%><!-- prints strdate to jsp. Could put it in a table, form, etc --> ``` ***EDIT***: In response to your comment, you should: ``` <%--Imports java packages --%> <%@ page import ="java.util.Date" %> <%@ page import ="java.text.SimpleDateFormat"%> <%-- Java code --%> <% Date date = new Date(); Calendar calendar = Calendar.getInstance(TIME_ZONE).setTime(date); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy"); String strdate = sdf.format(calendar.getTime()); %> <html> <body> <!-- Does not need to use javascript. All work is done on the server side.--> <table> <tr> <td><%=strdate%></td> </tr> </table> </body> </html> ``` I have no idea what your time zone is, but I'm sure you do. Calendar.getInstance() takes an instance of TimeZone as a parameter. That should do it Take a look: <http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html> <http://java.sun.com/javase/6/docs/api/java/util/Calendar.html> [Interesting link about JSP](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/)
Initialize the function with date from the server `var d = new Date(<%= new SimpleDateFormat("yyyy, M-1, dd").format(new Date()) %>);`
HTML/JSP Doubt, Print date on webpage
[ "", "java", "html", "datetime", "jsp", "" ]
I'm not a C++ programmer and have difficulty understanding the explanations given on websites. I don't understand containers or iterators and don't have plans to learn C++ in the near future. So in layman's terms: What is the STL and what can it do for me? How does it compare to something like the Python Standard library or glibc?
To understand the STL, you're going to have to understand some aspects of C++ at least. I'll try my best to explain it. The structure is deceptively simple. Where the library shines is in how use of it can simplify many complex tasks. I'm going to stick to some very simple examples though, both because anything else will likely confuse someone who doesn't know C++, and because I don't want to write a novel. ;) First, some history. The STL (Standard Template Library) was developed separately, and then submitted to the C++ standard committee for consideration, giving them the option of adopting it into the language. But it was not developed as part of the C++ standard, and for this reason, it is designed in a style that is very different from the rest of the C++ standard library. If I remember my ancient history, it also took the standard committee a good while to understand the STL and grow used to it. When they initially saw it, they were not too keen on it, but after a while, realized just how powerful and well-designed it was. So it was adopted into the language. This all happened back in the late 1990's, as the language was approaching ISO standardization. At its core, the STL provides the most fundamental functionality you expect of a standard library: The ability to store sequences of data, and the ability to process these sequences. Every other language has a Collections/Containers part of its standard library, containing implementations of dynamic arrays (known as arraylists in Java, List in C#, and vectors in C++), linked lists, dictionaries and other common data structures. They also typically provide some mechanims for traversing these structures. (Enumerators or iterators, for example) The STL provides the same functionality in C++, but does it in a unusually elegant way, and with some interesting abstractions. The STL is cleanly split into three separate components: * The containers (As described above, every language has these. Arrays, ArrayList, Dictionary, Set, LinkedList and so on. Any data structure that can store a collection of objects is a container in C++) * The algorithms (Every language also has these in *some* form. Algorithms are functions for processing sequences of elements.) For now, assume that a sequence is a container. That's a bit of a simplification, but we'll get to that. Algorithms serve a wide range of purposes, from a `for_each()` function that allows you to apply a function to every element in a sequence, or the related `transform()` which applies a function to every element, and stores the result into a separate sequence (very much like the map operation in functional languages), or accumulate (similar to fold in functional languages), but also sorting or searching functions, and functions that allow you to copy entire sequences. * And finally, the glue that binds containers and algorithms together: Iterators. As I said above, sequences (which are what the algorithms work on) are not quite the same as containers. The elements in a container certainly constitute a sequence, but the first five elements in a container are also a sequence. Or every other element in a container is a sequence. Data read directly from a file stream can be treated as a sequence as well. Even data that is generated on the fly (say, the fibonacci sequence) can be treated as a sequence of values. Sequences do not have to map to a container, or even to data that exist in memory, although that's the most common use. Note that these is no overlap between these three areas. A container stores (and owns) data, and produces iterators. Iterators allow you to inspect, modify and traverse the data. And algorithms operate on iterator ranges Conceptually speaking, an iterator has two functions. It points to some data, and it can be moved around in the sequence (depending on the iterator type, different move operations may be available. Almost all iterators can move to the next element. Some can also move to the previous, and some can jump arbitrary distances backward and forward). If you're familiar with C, this is going to sound a lot like pointers, and that's no coincidence. Iterators are modeled as a generalization of pointers, and in fact, pointers are also valid iterators. All the STL algorithms work on pointers as well as "real" iterators. What this means is that any sequence of data can be represented by a pair of iterators: The first iterator points to the first element in the sequence, and the second points *one past* the end of the sequence. That allows a fairly simple syntax for traversing sequences in a loop: ``` std::vector<int> container; for (iter it = container.begin(); it != container.end(); ++it) { // perform some operations on the iterator (it) or the element it points to (*it) ++(*it); // increment the value the iterator points to } ``` Or we can apply an algorithm to the sequence: ``` std::sort(container.begin(), container.end()); ``` Note that the sort function does not know or care that it is working on a vector. It is passed two iterators, and these could be of any type. They can be plain pointers into an array, linked list iterators or any other valid iterator type. We can generalize the sorting function a bit by supplying our own comparer function (any function that takes two values and returns true if the first is strictly less than the other) ``` // sort in descending order, by passing in a custom comparer which uses greater than instead of less than bool greater(int lhs, int rhs) { return lhs > rhs; } std::sort(container.begin(), container.end(), greater); ``` Of course, we could sort only the first five elements of the vector as well: ``` std::sort(container.begin(), container.begin()+5); ``` The begin() and end() functions are just convenience functions to get iterators from a container. We don't have to use them directly. Another nice trick is that streams too can be generalized into iterators. So let's read all the integers from a file, and copy them to an array (arrays are plain C types, of course, so they're not proper containers and don't have iterators. But pointers work fine) ``` int arr[1024]; std::ifstream file("something.txt"); // (note, this assumes <= 1024 integers are read) std::copy(std::istream_iterator<int>(file) // create an iterator pointing to the current position in the file stream , std::istream_iterator<int>() // and our "end" iterator. When we reach the end of the stream, testing the two iterators for equality will yield true, and so the operation will halt , arr); ``` The unique thing about the STL is how flexible and extensible it is. It interoperates cleanly with C code (pointers are legal iterators), it can be simply and easily extended (you can write your own iterator types if you like. Most of the algorithms take custom predicates of comparers, like the one I showed above, and you can define your own containers. That is, each of the three pillars of the STL can be overridden or extended, so STL could be said to be more of a design strategy than anything. You can write STL code even though you're using your own containers, iterators and algorithms. And because each of these three pillars are cleanly separated from the others, they can be swapped out much more easily than in most other languages where these three responsibilities are mixed up and shared by the same classes. An algorithm does not *know* which, if any, container the sequence it's operating on are stored in. It only knows that the iterators it has been passed can be dereferenced to get access to the data itself. A container does not have to support all the standard algorithms. It simply has to be able to produce a pair of iterators, and then all the functionality comes for free. Compare this to, say, Java, where every collection class has to implement its own search, its own sort, its own everything. In C++, we only need one implementation of find(). It takes two iterators and the value to look for, and it traverses the sequence looking for the value. And so, it works on any container type, even the ones I define myself. Another remarkable feature of the STL is that there is literally zero performance loss in using it. C++ templates are all substituted at compile-time, yielding code that can be optimized just as aggressively as if you had hand-coded everything in C. The above sort function would lose some performance because I pass a function pointer to it as my custom comparer, which typically can not be inlined, but that can be fixed if we define it as such: ``` struct greater { bool operator()(int lhs, int rhs) { return lhs > rhs; } }; std::sort(container.begin(), container.end(), greater()); ``` Now we no longer pass a function pointer, but an object. And member functions (such as operator()) *can* be inlined. So this sort function is going to be just as efficient as anything you could hand-code in C. And again, it doesn't even have to add any complexity to the sort function. In fact, sort has precisely two overloads. One that takes a comparer function, and one that doesn't. The sort function doesn't need to know whether it is passed a function pointer or an object. As long as the syntax "X(a, b)" is valid, where X is the value it was passed as comparer, and a, b the elements to compare, the same implementation of the sort function will work. And because my `greater` object overloaded the operator(), that syntax is valid both for this object and for the function pointer we passed earlier. STL code gets a lot of functionality for free by exploiting tricks like this. The same implementation of a function works with very different argument types because of the way C++ templates work.
The STL is the Standard Template Library. It is a subset of the C++ standard library. The STL provides generic implementations of useful algorithms and containers. The containers provide any easy method of storing data in the program and then finding, sorting and performing other computations on that data.
What is the STL?
[ "", "c++", "stl", "" ]
I'm confused by the following code: ``` import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class GenericsTest<T extends List> { public void foo() { T var = (T) new LinkedList(); } public static void main(String[] args) { GenericsTest<ArrayList> gt1 = new GenericsTest<ArrayList>(); gt1.foo(); System.out.println("Done"); } } ``` The runtime type of `T` appears to be `java.util.List`, regardless of what Type parameter I passed in to the constructor. So why is the compiler requiring casting to `T` when assigning var? Shouldn't it know at compile time that `LinkedList` is assignable to List? I understand the code is bogus, and I understand why it worked at runtime even though it looks like it shouldn't. The part that is confusing to me is why is the compiler requiring me to type (T) when doing the assignment? Yet it compiles perfectly well without the bogus cast. Presumably, the compiler understands erasure. It seems like the compiler should be able to compile the code without the cast as well.
In a comment the poster asks, > However, presumably the compiler knows > that so why does it need to have the > cast to (T). Is there any possible way > the cast could ever fail? *This* cast will not fail. But the compiler is warning that *this* code sets a time bomb ticking to blow up *somewhere else* with a `ClassCastException`. In the example, there's no reason to use generics, since none of the API uses the type variable `T`. Look at a more realistic application of generics. ``` public class GenericsTest<T extends List> { 3 public T foo() { 4 T var = (T) new LinkedList(); 5 return var; 6 } 8 public static void main(String... argv) { 9 GenericsTest<ArrayList> gt1 = new GenericsTest<ArrayList>(); 10 gt1.foo(); 11 System.out.println("Test one okay"); 12 ArrayList<?> list = gt1.foo(); 13 System.out.println("Test two okay"); 14 } } ``` A `ClassCastException` is thrown at line 12. `ClassCastException`, without a cast? The calling code is perfectly correct. The invalid cast, the bug, is at line 4, in the invoked method. But the exception is raised at some time and place far distant. The purpose of Java generics is to assure that code is type-safe. If *all* of the code was compiled without "unchecked" warnings, the guarantee is that there will be no `ClassCastException` raised at runtime. However, if a library you depend on was written incorrectly, as was this example, the promise is broken.
`LinkedList` is assignable to `List`, but it may not be assignable to `T`. In some ways your test code *shouldn't* work - it only works because the cast is effectively removed by the compiler as being useless at execution time (due to type erasure). It's useful at compilation time, because it's required you (the developer) to promise the compiler that you're doing something valid which it can't check. As it happens, what you're doing *isn't* valid, but the compiler has no way of knowing that, and there's no way of checking it at execution time without more information. You can provide that information though: ``` import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class GenericsTest<T extends List> { Class<T> clazz; public GenericsTest(Class<T> clazz) { this.clazz = clazz; } public void foo() { T var = clazz.cast(new LinkedList()); } public static void main(String[] args) { GenericsTest<ArrayList> gt1 = new GenericsTest<ArrayList>(ArrayList.class); gt1.foo(); System.out.println("Done"); } } ``` This will now fail with an appropriate exception - the type information is still available at execution time, and we're using it to perform the cast in a safe way. Note that if you compile with suitable warnings, the compiler will tell you that your original code wasn't really checking anything anyway. For more about this and many other topics, look at the pretty comprehensive [Java Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html).
Confused by Java generics requiring a cast
[ "", "java", "generics", "casting", "" ]
Sorry for a long question and not a very descriptive title, but my problem is very difficult to explain briefly. I have three database tables: ``` TABLE A: AID PK STATUS VARCHAR TABLE B: BID PK AID FK CID FK TABLE C: CID PK CREATIONTIME DATE ``` For each STATUS = 'OK' row in table A I want to find the corresponding row in C which has the latest creation time. First I can to fetch all rows from table A where STATUS = 'OK'. Next I can to fetch all corresponding rows from table B. But how to continue from there? For example: ``` select AID, CID from B where AID in (select AID from A where STATUS = 'OK') ``` could return something like: ``` AID, CID 1 1 2 2 2 3 3 4 4 5 4 6 ``` Let's say that CID 2 has later creation time than CID 3 and CID 6 is newer than CID 5. This means that the correct result would be rows 1, 2, 4 and 6 in table C. Is there a way to express this with a query? EDIT: Sorry that I wasn't specific enough. What I want to get is the CIDs from table C. EDIT: I counted returned rows with the different solutions. Results were very interesting - and diversified: HAINSTECH: 298 473 rows JMUCCHIELLO: 298 473 rows RUSS CAM: 290 121 rows CHRIS: 344 093 rows TYRANNOSAURS: 290 119 rows I have not yet had the time to analyse returned rows in depth, but I'd really appreciate views on which of the queries are "broken" and why.
Something like this, if I've understood you correctly ``` SELECT MAX(CREATIONTIME), A.AID FROM A INNER JOIN B ON A.AID = B.AID INNER JOIN C ON B.CID = C.CID WHERE A.STATUS = 'OK' GROUP BY A.AID ``` **EDIT:** I have now checked the following in SQL Server (I would epxect the same outcome in Oracle) and it returns the `CID` for the `C` record with the Maximum `CREATIONTIME` where the `STATUS` for the related record in `A` id `'OK'`. ``` SELECT C.CID FROM C C INNER JOIN B B ON C.CID = B.CID INNER JOIN ( SELECT MAX(C.CREATIONTIME) CREATIONTIME, A.AID FROM A A INNER JOIN B B ON A.AID = B.AID INNER JOIN C C ON B.CID = C.CID WHERE A.STATUS = 'OK' GROUP BY A.AID ) ABC ON B.AID = ABC.AID AND C.CREATIONTIME = ABC.CREATIONTIME ``` Demonstrated with the following ***T-SQL*** ``` DECLARE @A TABLE(AID INT IDENTITY(1,1), STATUS VARCHAR(10)) DECLARE @B TABLE(BID INT IDENTITY(1,1), AID INT, CID INT) DECLARE @C TABLE(CID INT IDENTITY(1,1), CREATIONTIME DATETIME) INSERT INTO @A VALUES ('OK') INSERT INTO @A VALUES ('OK') INSERT INTO @A VALUES ('NOT OK') INSERT INTO @A VALUES ('OK') INSERT INTO @A VALUES ('NOT OK') INSERT INTO @C VALUES ('10 MAR 2008') INSERT INTO @C VALUES ('13 MAR 2008') INSERT INTO @C VALUES ('15 MAR 2008') INSERT INTO @C VALUES ('17 MAR 2008') INSERT INTO @C VALUES ('21 MAR 2008') INSERT INTO @B VALUES (1,1) INSERT INTO @B VALUES (1,2) INSERT INTO @B VALUES (1,3) INSERT INTO @B VALUES (2,2) INSERT INTO @B VALUES (2,3) INSERT INTO @B VALUES (2,4) INSERT INTO @B VALUES (3,3) INSERT INTO @B VALUES (3,4) INSERT INTO @B VALUES (3,5) INSERT INTO @B VALUES (4,5) INSERT INTO @B VALUES (4,1) INSERT INTO @B VALUES (4,2) SELECT C.CID FROM @C C INNER JOIN @B B ON C.CID = B.CID INNER JOIN ( SELECT MAX(C.CREATIONTIME) CREATIONTIME, A.AID FROM @A A INNER JOIN @B B ON A.AID = B.AID INNER JOIN @C C ON B.CID = C.CID WHERE A.STATUS = 'OK' GROUP BY A.AID ) ABC ON B.AID = ABC.AID AND C.CREATIONTIME = ABC.CREATIONTIME ``` Results in the following ``` CID ----------- 3 4 5 ``` **EDIT 2:** In response to your comment about each of the statements giving different results, I have ran some of the different answers here through SQL Server 2005 using my test data above (I appreciate you are using Oracle). Here are the results ``` --Expected results for CIDs would be --CID ----------- --3 --4 --5 --As indicated in the comments next to the insert statements DECLARE @A TABLE(AID INT IDENTITY(1,1), STATUS VARCHAR(10)) DECLARE @B TABLE(BID INT IDENTITY(1,1), AID INT, CID INT) DECLARE @C TABLE(CID INT IDENTITY(1,1), CREATIONTIME DATETIME) INSERT INTO @A VALUES ('OK') -- AID 1 INSERT INTO @A VALUES ('OK') -- AID 2 INSERT INTO @A VALUES ('NOT OK') INSERT INTO @A VALUES ('OK') -- AID 4 INSERT INTO @A VALUES ('NOT OK') INSERT INTO @C VALUES ('10 MAR 2008') INSERT INTO @C VALUES ('13 MAR 2008') INSERT INTO @C VALUES ('15 MAR 2008') INSERT INTO @C VALUES ('17 MAR 2008') INSERT INTO @C VALUES ('21 MAR 2008') INSERT INTO @B VALUES (1,1) INSERT INTO @B VALUES (1,2) INSERT INTO @B VALUES (1,3) -- Will be CID 3 For AID 1 INSERT INTO @B VALUES (2,2) INSERT INTO @B VALUES (2,3) INSERT INTO @B VALUES (2,4) -- Will be CID 4 For AID 2 INSERT INTO @B VALUES (3,3) INSERT INTO @B VALUES (3,4) INSERT INTO @B VALUES (3,5) INSERT INTO @B VALUES (4,5) -- Will be CID 5 FOR AID 4 INSERT INTO @B VALUES (4,1) INSERT INTO @B VALUES (4,2) -- Russ Cam SELECT C.CID, ABC.CREATIONTIME FROM @C C INNER JOIN @B B ON C.CID = B.CID INNER JOIN ( SELECT MAX(C.CREATIONTIME) CREATIONTIME, A.AID FROM @A A INNER JOIN @B B ON A.AID = B.AID INNER JOIN @C C ON B.CID = C.CID WHERE A.STATUS = 'OK' GROUP BY A.AID ) ABC ON B.AID = ABC.AID AND C.CREATIONTIME = ABC.CREATIONTIME -- Tyrannosaurs select A.AID, max(AggC.CREATIONTIME) from @A A, @B B, ( select C.CID, max(C.CREATIONTIME) CREATIONTIME from @C C group by CID ) AggC where A.AID = B.AID and B.CID = AggC.CID and A.Status = 'OK' group by A.AID -- jmucchiello SELECT c.cid, max(c.creationtime) FROM @B b, @C c WHERE b.cid = c.cid AND b.aid IN (SELECT a.aid FROM @A a WHERE status = 'OK') GROUP BY c.cid -- hainstech SELECT agg.aid, agg.cid FROM ( SELECT a.aid ,c.cid ,max(c.creationtime) as maxcCreationTime FROM @C c INNER JOIN @B b ON b.cid = c.cid INNER JOIN @A a on a.aid = b.aid WHERE a.status = 'OK' GROUP BY a.aid, c.cid ) as agg --chris SELECT A.AID, C.CID, C.CREATIONTIME FROM @A A, @B B, @C C WHERE A.STATUS = 'OK' AND A.AID = B.AID AND B.CID = C.CID AND C.CREATIONTIME = (SELECT MAX(C2.CREATIONTIME) FROM @C C2, @B B2 WHERE B2.AID = A.AID AND C2.CID = B2.CID); ``` the results are as follows ``` --Russ Cam - Correct CIDs (I have added in the CREATIONTIME for reference) CID CREATIONTIME ----------- ----------------------- 3 2008-03-15 00:00:00.000 4 2008-03-17 00:00:00.000 5 2008-03-21 00:00:00.000 --Tyrannosaurs - No CIDs in the resultset AID ----------- ----------------------- 1 2008-03-15 00:00:00.000 2 2008-03-17 00:00:00.000 4 2008-03-21 00:00:00.000 --jmucchiello - Incorrect CIDs in the resultset cid ----------- ----------------------- 1 2008-03-10 00:00:00.000 2 2008-03-13 00:00:00.000 3 2008-03-15 00:00:00.000 4 2008-03-17 00:00:00.000 5 2008-03-21 00:00:00.000 --hainstech - Too many CIDs in the resultset, which CID has the MAX(CREATIONTIME) for each AID? aid cid ----------- ----------- 1 1 1 2 1 3 2 2 2 3 2 4 4 1 4 2 4 5 --chris - Correct CIDs, it is the same SQL as mine AID CID CREATIONTIME ----------- ----------- ----------------------- 1 3 2008-03-15 00:00:00.000 2 4 2008-03-17 00:00:00.000 4 5 2008-03-21 00:00:00.000 ``` I would recommend running each of the given answers against a smaller number of records, so that you can ascertain whether the resultset returned is the expected one.
EDIT: My previous answer was nonsense. This is now a complete rewrite This is actually a problem which has bugged me throughout my SQL life. The solution I'm going to give you is messy as hell but it works and I'd appreciate anyone either saying "yes this is messy as hell but it's the only way to do it" or say "no, do this...". I think the unease comes from joining two dates. The way it happens here it's not an issue as they will be an exact match (they have exactly the same root data) but it still feels wrong... Anyway, breaking this down, you need to do this in two stages. 1) The first is to return a results set [AID], [earliest CreationTime] giving you the earliest creationtime for each AID. 2) You can then use latestCreationTime to pull the CID you want. So for part (1), I'd personally create a view to do it just to keep things neat. It allows you to test this part and get it working before you merge it with the other stuff. ``` create view LatestCreationTimes as select b.AID, max(c.CreationTime) LatestCreationTime from TableB b, TableC c where b.CID = c.CID group by b.AID ``` Note, we've not taken into account the status at this point. You then need to join that to TableA (to get the status) and TableB and TableC (to get the CID). You need to do all the obvious links (AID, CID) and also join the LatestCreationTime column in the view to the CreationTime column in TableC. Don't also forget to join the view on AID otherwise where two records have been created at the same time for different A records you'll get issues. ``` select A.AID, C.CID from TableA a, TableB b, TableC c, LatestCreationTimes lct where a.AID = b.AID and b.CID = c.CID and a.AID = lct.AID and c.CreationTime = lct.LatestCreationTime and a.STATUS = 'OK' ``` I'm certain that works - I've tested it, tweaked data, retested it and it behaves. At least it does what I believe it's meant to do. It doesn't however deal with the possibility of two identical CreationTimes in table C for the same record. I'm guessing that this shouldn't happen however unless you've written sometime that absolutely constrains it it needs to be accounted for. To do this I need to make an assumption about which one you'd prefer. In this case I'm going to say that if there are two CIDs which match, you'd rather have the higher one (it's most likely more up to date). ``` select A.AID, max(C.CID) CID from TableA a, TableB b, TableC c, LatestCreationTimes lct where a.AID = b.AID and b.CID = c.CID and c.CreationTime = lct.LatestCreationTime and a.STATUS = 'OK' group by A.AID ``` And that, I believe should work for you. If you want it as one query rather than with the view then: ``` select A.AID, max(C.CID) CID from TableA a, TableB b, TableC c, (select b.AID, max(c.CreationTime) LatestCreationTime from TableB b, TableC c where b.CID = c.CID group by b.AID) lct where a.AID = b.AID and b.CID = c.CID and c.CreationTime = lct.LatestCreationTime and a.STATUS = 'OK' group by A.AID ``` (I've just embedded the view in the query, otherwise the principal is exactly the same).
SQL SELECT: combining and grouping data between three tables using subqueries
[ "", "sql", "oracle", "select", "subquery", "" ]
In IE, I can just call `element.click()` from JavaScript - how do I accomplish the same task in Firefox? Ideally I'd like to have some JavaScript that would work equally well cross-browser, but if necessary I'll have different per-browser JavaScript for this.
The [`document.createEvent` documentation](https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent) says that "**The *createEvent* method is deprecated. Use [event constructors](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) instead.**" So you should use this method instead: ``` var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); ``` and fire it on an element like this: ``` element.dispatchEvent(clickEvent); ``` as shown [here](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events).
For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent [described here on MDN](https://developer.mozilla.org/en/DOM/document.createEvent) and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link... ``` var theEvent = document.createEvent("MouseEvent"); theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var element = document.getElementById('link'); element.dispatchEvent(theEvent); while (element) { if (element.tagName == "A" && element.href != "") { if (element.target == "_blank") { window.open(element.href, element.target); } else { document.location = element.href; } element = null; } else { element = element.parentElement; } } ```
How do I programmatically click on an element in JavaScript?
[ "", "javascript", "dom", "firefox", "dom-events", "dhtml", "" ]
I was looking through the Java documentation, and I came across the clear() method of ArrayLists. What's the use of this, as opposed to simply reassigning a new ArrayList object to the variable?
Because there might be multiple references to the one list, it might be preferable and/or more practical to clear it than reassigning all the references. If you empty your array a lot (within, say, a large loop) there's no point creating lots of temporary objects. Sure the garbage collector will eventually clean them up but there's no point being wasteful with resources if you don't have to be. And because clearing the list is less work than creating a new one.
You might have a final field (class variable) `List`: ``` private final List<Thing> things = ... ``` Somewhere in the class you want to clear (remove all) things. Since `things` is final it can't be reassigned. Furthermore, you probably don't want to reassign a new List instance as you already have a perfectly good List instantiated.
Usefulness of ArrayList<E>.clear()?
[ "", "java", "memory-management", "arraylist", "" ]
I need to write, in JavaScript (I am using jQuery), a function that is aware of the number of characters that fit in a line of the browser window. I'm using a monospace font to ease the problem, but it would be better if I generalize it for different fonts. How can I know how many characters would fill a row in the browser? The intention is to count the number of characters that fill a line.
You can create element and append characters to it until you detect wrapping, e.g. by observing changes in `offsetHeight` (you can optimze it using bisection algorithm). This is of course very dependent on browser, system, installed fonts and user's settings so you would have to calculate it for each fragment of text each time page is displayed, resized or when user changes font size (even full-page zoom introduces some off-by-one errors which could cause number of characters change). Therefore it may be an overkill in most situations and when implemented poorly cause more trouble than it solves. There are other solutions, e.g. if you want to ensure that only one line is visible you can use `white-space:nowrap` and `overflow:hidden` and in some browsers `text-overflow:ellipsis` to make text cut nicely. Or if you don't want words cut, use 1-line high container with `overflow:hidden`.
You can get the total width available for the browser with ``` window.innerWidth ``` And then you can get the width of an element with the following method. ``` document.getElementById('elem').clientWidth ```
How can I measure how many characters will fit the width of the document?
[ "", "javascript", "jquery", "string", "" ]
I want reorder table rows using JavaScript . for example take the following dummy table: ``` <table> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr> <tr> <td>A</td> <td>B</td> <td>C</td> <td>D</td> </tr> <tr> <td>A1</td> <td>B1</td> <td>C1</td> <td>D1</td> </tr> </table> ``` I want to do this in JavaScript without using jQuery. I want to show the A1,B1,C1,D1.. row as the first row and then 1,2,3,4 row and then A,B,C,D row. I know that there will be some wait time on the client side but I need to do it in the client side. Is there some generic solution to do this, for any number of rows?
The best way to solve this in Javascript is: Give the Tr.. a unique name. for eg: X\_Y,X\_Z,A\_Y,A\_Z Now add a hidden lable or text Box which gives the sorting order from the server i.e When the page renders I want to sort it All the Tr's that have a ID starting with A should come first and All the Z's should come second. ``` <asp:label id="lblFirstSortOrder" runat="server" style="display:none;">A,X</label> <asp:label id="lblSecondSortOrder" runat="server" style="display:none;">Z,Y</label> ``` When the page renders..the order should be A\_Z,A\_Y,X\_Z,X\_Y Before Rendering this is table that comes from the aspx file: ``` <table> <tr id='Tr_Heading'> <td>A</td> <td>B</td> </tr> <tr id="Tr_X_Y"> <td>GH</td> <td>GH1</td> </tr> <tr id="tr_X_Z"> <td>HU</td> <td>HU1</td> </tr> <tr id="tr_A_Z"> <td>JI</td> <td>JI1</td> </tr> <tr id="tr_A_Y"> <td>JI</td> <td>JI1</td> </tr> ``` Script: ``` function SortAndArrange() { var firstList = document.getElementById('lblFirstSortOrder').value; var secondList = document.getElementById('lblSecondSortOrder').value; var firstTypes = new Array(); firstTypes = firstList.split(','); var secondLists = new Array(); secondLists = secondList.split(','); var refNode = document.getElementById('Tbl_' + firstTypes[0] + "_" + secondTypes[0]); for (var i = 0; i<firstTypes.length; i++) { for (var j = 0; j< secondTypes.length;j++) { var TrName = 'Tbl_'+firstTypes[i]+'_'+secondTypes[j]; var FirstSecondTrs = document.getElementById(TrName); if (FirstSecondTrs) { FirstSecondTrs.parentNode.removeChild(FirstSecondTrs); insertAfter(refNode,FirstSecondTrs); refNode = FirstSecondTrs; } } } } function insertAfter( referenceNode, newNode ) { referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling ); } ``` I hope you guys get the idea.. for me the sorting order will always come from the server and not from the user of the page... Thanks a Lot for all the answers.. Apprecite it. Helped me get to this solution. Thanks, Ben
If I understand correctly, you are asking how to take the last row and make it the first row, pushing down the rest. This should do it: ``` <table id="mytable"> ... </table> <script type="text/javascript"> var tbl = document.getElementById('mytable'); var rows = tbl.getElementsByTagName('tr'); var firstRow = rows[0]; var lastRow = rows[rows.length]; firstRow.parentNode.insertBefore(lastRow.parentNode.removeChild(lastRow), firstRow); </script> ``` Assuming your table does not have nested tables. At which point this would need to be a little smarter. This also assumes you're not using TBODY and THEAD nodes. But I'm sure you can get the idea and enhance it from there.
Rearranging table in JavaScript
[ "", "javascript", "" ]
I've tried looking at similar problems, but could not easily find one that helped my problem. I've created a project in C++ and am working on UNIX to compile, link, and run it. My specific problem is an undefined reference to a method I declare in a separate file. In the file SharedCache.cpp, I have the following method: ``` int SharedCache::replaceLine(ullong address){ int evictPID = -1; int cacheSet = calcCacheSet( address ); //random uniformly-distributed value for cache line float numLines = static_cast<float>(CACHE_LINES_PER_SET); uint cacheLine = static_cast<uint>(uniformDistr( numLines )); if(cache[cacheSet][cacheLine] != NULL){ evictPID = cache[cacheSet][cacheLine]->PID; } uint PID= calcPID(address); uint tag= calcTag(address); cache[cacheSet][cacheLine]->setLine(PID, tag); //mutex method return PID; } ``` The line `uint cacheLine = static_cast<uint>( uniformDistr( numLines ));` makes a call to the function I want to use from another file. The linker error is an undefined reference to this method. uniformDistr( float ); is declared in the header distributions.h and defined in distributions.cpp. In my project options I set the linker flag -distributions and I also compiled the distributions.cpp to make sure a distributions.o file exists to link with. From here, I don't know where to go, because this has not solved the problem.
I've not used KDevelop, however, on the command line you would just add distributions.o as an input file to the linking process. No need for dashes or leaving off the .o extension. Alternatively, can you just add distributions.cpp to your KDevelop project? That way it should get compiled and linked automatically (this is how it works in things like Visual Studio or Eclipse).
Without more precise information on which compiler/linker commands were invoked and the exact error outputs, it is difficult to provide a good answer. However, from your description of what you did, it seems that you are not passing `distributions.o` to the linker. Unlike other languages where the compiler/linker search for object files to link in automatically, C++ linkers require an explicit specification of the objects to link together. Your use of -ldistributions here is incorrect: the -l flag is used to link to a static or dynamic *library* (respectively .a and .so files on Linux), whereas you want to specify another *object file* that the linker should consider. Specifying `-ldistributions` makes the linker look for `distributions.a` or `distributions.so` in the standard library locations. Basically, your linker invocation now looks something like this (probably with many more flags and libraries): ``` gcc -o my_program SharedCache.o -ldistributions ``` To correctly link the distributions code in, you need to make it look something like (again, many flags and libraries probably missing compared to the real thing): ``` gcc -o my_program SharedCache.o distributions.o ``` This should resolve the missing symbols issue and produce a working binary (or at the very least a different error ;-) ). How to do this in KDevelop however I do not know.
linker error: undefined reference c++
[ "", "c++", "reference", "linker", "undefined", "" ]
I'm building a plugin system for my application. I've read that anyone can decomple .class files and therefore I'm forced ot use a Ahead-Of-Time compiler (right?). The problem is that I need to load some plugin classes dynamically. Right now I'm loading all .class files in a folder and invoking a static method (I never create a object) as a plugin system. Can I load those classes when all my source is AOT compled? Should I approach the problem another way? Is Java the right language for me?
Ahead of time compilation is not for blocking people from de-compiling. I think you should use an obfuscator for that purpose. Dynamically loading classes for plugin system should work with both the obfuscators and AOT.
Tahit Akhtar is right. You need an obfuscator. You'll have to configure it not to obfuscate the name of the classes and methods that your program uses dynamically to load and call the plugins. That is, the public SPI of the plugins cannot be obfuscated, but their implementations can.
Java AOT + loading java classes dynamically
[ "", "java", "class", "compilation", "" ]
I'm building a thesaurus using a HashMap to store the synonyms. I'm trying to search through the words based on a regular expression: the method will have to take a string as parameter and return an array of results. Here's my first stab at it: ``` public ArrayList<String> searchDefinition(String regex) { ArrayList<String> results = new ArrayList<String>(); Pattern p = Pattern.compile(regex); Set<String> keys = thesaurus.keySet(); Iterator<String> ite = keys.iterator(); while (ite.hasNext()) { String candidate = ite.next(); Matcher m = p.matcher(candidate); System.out.println("Attempting to match: " + candidate + " to " + regex); if (m.matches()) { System.out.println("it matches"); results.add(candidate); } } if (results.isEmpty()) { return null; } else { return results; } } ``` Now, this does not work as I would expect (or maybe I'm using regular expressions incorrectly). If I have the following keys in the hashmap: ``` cat, car, chopper ``` then by calling `searchDefinition("c")` or `searchDefinition("c*")` I get `null`. 1. How do I make this work as expected? 2. Is there a better data structure than HashMap to keep a `graph` like needed by a thesaurus? (curiosity only, as for this assignment we're asked to use Java Collection Map). 3. Anything else I'm doing innapropriately in the code above? Thanks, Dan EDIT: I've corrected the example. It doesn't work even if I use the correct case.
You need to specify case insensitivity [Pattern.compile](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#compile(java.lang.String,%20int))`( "c",`[Pattern.CASE\_INSENSITIVE](http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#CASE_INSENSITIVE) `)`. To find a word with a `c` in it you need to use [matcher.find()](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#find()). [Matcher.matches()](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#matches()) tries to match the whole string.
But, hmm: (a) Why would you use a HashMap if you intend to always search it sequentially? That's a lot of wasted overhead to process the hash keys and all when you never use them. Surely a simple ArrayList or LinkedList would be a better idea. (b) What does this have to do with a thesaurus? Why would you search a thesaurus using regular expressions? If I want to know synonyms for, say, "cat", I would think that I would search for "cat", not "c.\*". My first thought on how to build a thesaurus would be ... well, I guess the first question I'd ask is, "Is synonym an equivalance relationship?", i.e. if A is a synonym for B, does it follow that B is a synonym for A? And if A is a synonym for B and B is a synonym for C, then is A a synonym for C? Assuming the answers to these questions are "yes", then what we want to build is something that divides all the words in the language into sets of synonyms, so we then can map any word in each set to all the other words in that set. So what you need is a way to take any word, map it to some sort of nexus point, and then go from that nexus point to all of the words that map to it. This would be straightforward on a database: Just create a table with two columns, say "word" and "token", each with its own index. All synonyms map to the same token. The token can be anything as long as its unique for any given set of synonyms, like a sequence number. Then search for the given word, find the associated token, and then get all the words with that token. For example we might create records with (big,1), (large,1), (gigantic,1), (cat,2), (feline,2), etc. Search for "big" and you get 1, then search for 1 and you get "big", "large", and "giant". I don't know any class in the built-in Java collections that does this. The easiest way I can think of is to build two co-ordinated hash tables: One that maps words to tokens, and another that maps tokens to an array of words. So table 1 might have big->1, large->1, gigantic->1, cat->2, feline->2, etc. Then table 2 maps 1->[big,large,gigantic], 2->[cat,feline], etc. You look up in the first table to map a word to a token, and in the second to map that token back to a list of words. It's clumsy because all the data is stored redundantly, maybe there's a better solution but I'm not getting it off the top of my head. (Well, it would be easy if we assume that we're going to sequentially search the entire list of words every time, but performance would suck as the list got big.)
Java: Search in HashMap keys based on regex?
[ "", "java", "regex", "hashmap", "" ]
Is there any way to resize a [jqGrid](http://www.trirand.com/blog/) when the browser window is resized? I have tried the method described [here](http://www.trirand.com/blog/?page_id=18/discussion/browser-resize-how-to-resize-jqgrid/page-1/post-3350/) but that technique does not work in IE7.
As a follow-up: The previous code shown in this post was eventually abandoned because it was unreliable. I am now using the following API function to resize the grid, as recommended by the jqGrid documentation: ``` jQuery("#targetGrid").setGridWidth(width); ``` To do the actual resizing, a function implementing the following logic is bound to the window's resize event: * Calculate the width of the grid using its parent's clientWidth and (if that is not available) its offsetWidth attribute. * Perform a sanity check to make sure width has changed more than x pixels (to work around some application-specific problems) * Finally, use setGridWidth() to change the grid's width Here is example code to handle resizing: ``` jQuery(window).bind('resize', function() { // Get width of parent container var width = jQuery(targetContainer).attr('clientWidth'); if (width == null || width < 1){ // For IE, revert to offsetWidth if necessary width = jQuery(targetContainer).attr('offsetWidth'); } width = width - 2; // Fudge factor to prevent horizontal scrollbars if (width > 0 && // Only resize if new width exceeds a minimal threshold // Fixes IE issue with in-place resizing when mousing-over frame bars Math.abs(width - jQuery(targetGrid).width()) > 5) { jQuery(targetGrid).setGridWidth(width); } }).trigger('resize'); ``` And example markup: ``` <div id="grid_container"> <table id="grid"></table> <div id="grid_pgr"></div> </div> ```
Been using this in production for some time now without any complaints (May take some tweaking to look right on your site.. for instance, subtracting the width of a sidebar, etc) ``` $(window).bind('resize', function() { $("#jqgrid").setGridWidth($(window).width()); }).trigger('resize'); ```
Resize jqGrid when browser is resized?
[ "", "javascript", "jquery", "jqgrid", "grid", "resize", "" ]
I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed. I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work and I'm sure there is a better approach. So far I've tried: * the array.toFile() method but couldn't figure out how to get it to work with nested arrays of strings, it seemed geared towards integer data. * Lists and sets do not have a toFile method built in, so I would have had to parse and encode it manually. * CSV seemed like a good approach but this would also require manually parsing it, and did not allow me to simply append new lines at the end - so any new calls the the CSVWriter would overwrite the file existing data. I'm really trying to avoid using databases (maybe SQLite but it seems a bit overkill) because I'm trying to develop this to have no software prerequisites besides Python.
Must the file be human readable? If not, [shelve](http://docs.python.org/library/shelve.html) is really easy to use.
In addition to `pickle` ([mentioned above](https://stackoverflow.com/questions/875228/simple-data-storing-in-python/875272#875272)), there's [`json`](http://docs.python.org/library/json.html) (built in to 2.6, available via [simplejson](http://pypi.python.org/pypi/simplejson/) before that), and [`marshal`](http://docs.python.org/library/marshal.html#module-marshal). Also, there's a [`reader`](http://docs.python.org/library/csv.html#csv.reader) in the same [`csv` module](http://docs.python.org/library/csv.html) the writer is in. UPDATE: As S. Lott pointed out in a comment, there's also YAML, available via [PyYAML](http://pyyaml.org/), among others.
Simple data storing in Python
[ "", "python", "file-io", "csv", "multidimensional-array", "fileparsing", "" ]
I have a select list which is being populated using the values from a text field. I also have two buttons: an add button which adds the entered value to the select list and a remove button which removes the entered value from the select list. I would like to do the following using jQuery: 1. If the value entered into the text field is **NOT AVAILABLE** in the select list, show the add button and hide the remove button. 2. If the value entered into the text field is **AVAILABLE** in the select list, hide the add button and show the remove button. 3. If the select list is **EMPTY** show the add button and hide the remove button. Here is some code I've come up with: ``` // Remove selected options $('#removeButton').click(function() { //$.map($('#addedchargeamtid :selected'), function(e) { $.map($('#addedchargeamtid option'), function(e) { var exp = $(e).text(); // Would like to have all the Option values in CVS format 0.00,1.99, etc... // If removed this should also remove the value in the array }) $('#removeButton').hide(); return !$('#addedchargeamtid :selected').remove(); }); // Add charge amount $('#addedchargeamtid option:selected').focus(function() { $('#removeButton').show(); }); ``` It shows the remove button when I add the first value, but if I remove the value the button doesn't show back up. UPDATE: Okay I have edited it to this. ``` $('#removeButton').click(function() { $('#addedchargeamtid :selected').remove(); $.map($('#addedchargeamtid option'), function(e) { var exp = $(e).text(); alert(exp); // Need this in CSV format but I think it displays the correct values }) //if($("#addedchargeamtid option").length > 0) { <-- Didn't work if($("#addedchargeamtid").length > 0) { $('#removeButton').show(); } else { $('#removeButton').hide(); } }); ``` still not hiding the button when no value in the SELECT. Tried it with the option as well.
I believe you can check to see if the option length is >0 saying that it has values and if not then it doesn't exist meaning it doesn't have values like so: ``` if($("#addedchargeamtid option").length > 0 ) //if addedchargeamtid is the id of select tag { $('#removeButton').show(); } else { $('#removeButton').hide(); } ```
If I understand the problem correctly, I think you want to change this: ``` // Add charge amount $('#addedchargeamtid option:selected').focus(function() { $('#removeButton').show(); }); ``` to this: ``` // Add charge amount $('#addedchargeamtid option').focus(function() { $('#removeButton').show(); }); ``` so that the event handler gets added to all the select's options, not just the currently selected one when the code executes. And also make sure you're setting up this handler for any newly-created items, as well.
jQuery enable/disable show/hide button w/ SELECT options. Get remaining option values
[ "", "javascript", "jquery", "dhtml", "" ]
I've read [Neal Gafter's](http://gafter.blogspot.com/2006/11/reified-generics-for-java.html) blog on the subject and am still unclear on a number of points. Why is it not possible to create implementations of the Collections API that preserve type information given the current state of Java, the JVM and existing collections API? Couldn't these replace the existing implementations in a future version of Java in a way where backwards compatibility is preserved? As an example: ``` List<T> list = REIList<T>(T.Class); ``` Where REIList is something like this: ``` public REIList<T>() implements List { private Object o; private Class klass; public REIList(Object o) { this.o = o; klass = o.getClass(); } ... the rest of the list implementation ... ``` And the methods use Object o and Class klass to get the type information. Why would preserving generic class information require language changes rather than just a JVM implementation change? What am I not understanding?
The whole point is that reified generics have support in the compiler for preserving type information, whereas type erased generics don't. AFAIK, the whole point of having type erasure in the first place was to enable backwards compatibility (e.g. lower versioned JVMs could still understand generic classes). You can explicitly add the type information in the implementation, as you have above, but that requires additional code every time the list is used, and is pretty messy in my opinion. Also, in this case, you still don't have runtime type checking for all of the list methods unless you add the checks yourself, however reified generics will ensure the runtime types.
Contrary to beliefs of majority of Java developers, it is possible to keep compile-time type information and retrieve this information at runtime, despite in a very restricted way. In other words: **Java does provide reified generics in a very restricted way**. ## Regarding type erasure Notice that, at compile-time, the compiler has full type information available but this information is intentionally dropped *in general* when the binary code is generated, in a process known as *type erasure*. This is done this way due to compatibility issues: The intention of language designers was providing full source code compatibility and full binary code compatibility between versions of the platform. If it was implemented differently, you would have to recompile your legacy applications when you migrate to newer versions of the platform. The way it was done, all method signatures are preserved (source code compatibility) and you don't need to recompile anything (binary compatibility). ## Regarding reified generics in Java If you need to keep compile-time type information, you need to employ anonymous classes. The point is: in the very special case of anonymous classes, it is possible to retrieve full compile-time type information at runtime which, in other words means: reified generics. I've written an article about this subject: <http://rgomes-info.blogspot.co.uk/2013/12/using-typetokens-to-retrieve-generic.html> In the article, I describe how our users reacted to the technique. In a nutshell, this is an obscure subject and the technique (or the pattern, if you prefer) looks extraneous to majority of Java developers. ## Sample code The article I've mentioned above has links to source code which exercises the idea.
What are Reified Generics? How do they solve Type Erasure problems and why can't they be added without major changes?
[ "", "java", "generics", "collections", "jvm", "reification", "" ]
For example: ``` declare @bitHaveRows bit select @bitHaveRows = count(*) from table where (predicate) ``` Are there any functions I can call on this line: ``` select @bitHaveRows = count(*) ``` to assign this bit a value of 0 if there are no rows, or 1 if there are one or more rows?
According to the [conversion chart](http://msdn.microsoft.com/en-us/library/ms187928.aspx), there's an implicit conversion from int to bit. But if for some reason that doesn't work: ``` CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END ```
``` declare @bRowsExist SELECT @bRowsExist = CAST(count(*) as bit) FROM yourtable ``` ...not sure if it's a better query than the other suggestions
SQL -- Assigning a bit variable in select statement
[ "", "sql", "" ]
If I run the following SQL query ``` SELECT * FROM A LEFT JOIN B ON A.foo=B.foo WHERE A.date = "Yesterday" ``` Does the `WHERE` statement get evaluated before or after the `JOIN`? If after, what would be a better way to write this statement so that returns only rows in `A` from `"Yesterday"` are joined to `B`?
It depends on the database. On SQL Server, run: `SET SHOWPLAN_ALL ON` then run the query, you will get an idea of what happens when it runs.
Your idea of "evaluation" is not correct as SQL is a declarative language. BTW you can see the query execution plan. In MySQL prefix your query with keyword `describe` to see the execution plan.
SQL order of operations
[ "", "sql", "join", "optimization", "where-clause", "sql-execution-plan", "" ]
I need to call a library function that sometimes won't terminate within a given time, unfortunately. Is there a way to call the function but abort it if it doesn't terminate within `n` seconds? I cannot modify the function, so I cannot put the abort condition into it directly. I have to **add a timeout to the function externally**. Is it maybe a possible solution to start it as a (boost) thread, which I can then terminate after a certain time? Would something like that work? I actually believe the function is *not* thread-safe, but that wouldn't matter if I run it as the *only* single thread, right? Are there other (better) solutions?
You could spawn a `boost::thread` to call the API: ``` boost::thread api_caller(::api_function, arg1, arg2); if (api_caller.timed_join(boost::posix_time::milliseconds(500))) { // API call returned within 500ms } else { // API call timed out } ``` Boost doesn't allow you to kill the worker thread, though. In this example, it's just orphaned. You'll have to be careful about what that API call does, because it may never release resources it's acquired.
I think the only safe way to accomplish this would be to spawn a separate *sandbox* process that calls the library function as a proxy to your application. You'll need to implement some type of IPC between your application and the proxy. Implementing a timeout on reading the IPC reply is then fairly trivial. If the read fails due to timeout, you can then safely terminate the proxy without risking the health of your application.
C++: How to implement a timeout for an arbitrary function call?
[ "", "c++", "function", "timeout", "abort", "" ]
Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it without writing any elisp? EDIT: Trey, I want to keep pabbrev working in python mode not turn it off. So lets say there are 2 indent levels, either none, or 1 level normally if it hit tab 3 times the first would put the point at 4 spaces in (or whatever indent is set to), the second back to 0 spaces, and the third back to 4 spaces. With pabbrev mode on one indent puts the mark 4 spaces, the second brings up a buffer for autocomplete. This should not happen if there is no letters to the left of my point. Does that make any more sense?
In light of the clarified requirements, you need something along the lines of this. I'm pretty sure you can't get away w/out writing some elisp. What's nice (IMO) is that this should work for all modes, not just python mode. ``` (defadvice pabbrev-expand-maybe (around pabbrev-expand-maybe-when-not-after-whitespace activate) "prevent expansion when only whitespace between point and beginning of line" (if (save-match-data (save-excursion (let ((p (point))) (string-match "^\\s-*$" (buffer-substring-no-properties (progn (beginning-of-line) (point)) p))))) (let ((last-command (if (eq last-command this-command) (pabbrev-get-previous-binding) last-command)) (this-command (pabbrev-get-previous-binding))) (pabbrev-call-previous-tab-binding)) ad-do-it)) ```
How is this for a late response? This should work out of the box now, thanks to a patch from Trey. Binding tab in the way that pabbrev.el is somewhat naughty, but what are you to do if you want rapid expansion.
Emacs Pabbrev and Python
[ "", "python", "emacs", "pabbrev", "" ]
What if you don't want to start a separate project for grails but instead sneak it into an existing webapp? I have to build an admin interface/crud for some new entities and thought it would be a perfect way to learn grails.
I'm trying to make one application with a Grails app and a Spring app. I've tried to sneak the Grails App into the Spring one, but this is "impossible". It's easier to sneak the Spring app into the Grails app. Grails knows what Spring is, but Spring has no idea of what Grails is. In [this](http://www.ibm.com/developerworks/java/library/j-grails07158/index.html?S_TACT=105AGX02&S_CMP=EDU) article you can find useful information about how to use your hibernate mapping files or annotations in Grails, so you don't have to remap everything. Also you can use all your java clases (put them into src/java). You can put the beans defined in the ApplicationContext.xml in conf/spring/resources.xml. You can leave them in ApplicationContext, but I've had some problems. I don't have ended the job (almost) and it looks good.
It would be hard to "sneak it in" unless the existing app has the correct dir structure that maps exactly to how grails likes it - after all, convention over config is where the power of grails comes from. You can try doing the admin interface as a "seperate" app to the original/existing spring app, and map the existing database to the grails domain objects. though i m not sure how you would run them side by side easily without more information on the existing app. It is possible definitely though.
Integrating grails into an existing spring application?
[ "", "java", "spring", "grails", "" ]
**This was resolved. The statement was in another part of the stored procedure.** The stored procedure I'm writing won't allow me to do this: ``` declare @dtTopDate datetime select top 1 @dtTopDate = date_build from database..table where database..table.parent = @Parent and database..table.child = @Child order by date_build desc ``` Gives me this error: > Column "database..table.date\_build" is > invalid in the ORDER BY clause because > it is not contained in either an > aggregate function or the GROUP BY > clause. What am I doing wrong? [Edit] There is no group by statement here. SQL2005. Here is some more context: ``` if @Notify = 0 begin declare @dtTopDate datetime select top 1 @dtTopDate = date_build from database..table where database..table.parent = @Parent and database..table.child = @Child order by date_build desc insert into database2..table (parent, child, notification_date, change_date) values (@Parent, @Child, @dtTopDate, getdate()) return end ```
The problem was in another part of the stored procedure. I was using a count(\*) elsewhere and it required a group by. Thanks for the help.
This works for me, but I'm not sure if this is what you are trying to do b/c your example has some errors. ``` use Test go CREATE TABLE [dbo].[MyTable] ( [MyTableId] [uniqueidentifier] NOT NULL, [MyDate] [datetime] NOT NULL, CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED([MyTableId] ASC,[MyDate] ASC) ) GO CREATE PROCEDURE ProcTopDate ( @MyDate datetime OUT ) AS BEGIN SET NOCOUNT ON; SELECT TOP 1 @MyDate = [MyDate] FROM [Test].[dbo].[MyTable] order by MyDate END GO insert into MyTable(MyTableId, MyDate) values(newid(), getdate()) go declare @MyDate datetime exec ProcTopDate @MyDate OUT print @MyDate ```
SQL -- Selecting Top 1 with Order by?
[ "", "sql", "" ]
I have a lightweight online shopping site based on JSP and XML, and I'm wondering what the particular weaknesses of this system are as opposed to, say, PHP and MySQL? I know JSP can use Java APIs, but I feel PHP has a more "natural" relationship with HTML and also has the benefits of being dynamically typed, and is far more widespread and in-demand. Is there a reason for this?
I would say the main disadvantages of the XML solution over a database one would be: 1. search speed 2. update speed 3. scalability 4. concurrency (thanks Jonathan)
Lightweight is relative. Go for the database solution. You never know when your "lightweight" site becomes "mission-critical"
Benefits of databases as opposed to XML in a lightweight shopping site?
[ "", "php", "xml", "database", "jsp", "" ]
Right now I am using std::pair to represent a 2d point in c++. However, I am getting annoyed with having to write ``` typedef std::pair<double, double> Point; Point difference = Point(p2.first - p1.first, p2.second - p1.second); ``` instead of being able to overload operator+ and operator-. So, my question is, to make my Point class, should I * Publicly derive from std::pair and add my own member functions? This is nice because all my code can stay the same. I am not going to be doing anything like `std::pair<double, double>* p = new Point;` so I don't have to worry about things like virtual destructors. * Roll my own Point class, which is annoying since I am duplicating std::pair's functionality, however I am "doing it the pure way". * Make template specializations of operator+ and operator- for std::pair, which admittedly I don't remember if they go in source or header files. I guess it's up for debate, I'd really like to do #1 but I don't know if it's a bad idea since I've heard that inheriting from STL is a no-no.
You could roll your own Point class, but use std::pair internally to store the data. This prevents the inheritance from STL issue, but still uses std::pair's functionality.
Better than rolling your own: grab an existing free Vector/Point library. One recommendation: the one attached to [Essential Math for Games Programmers](http://www.essentialmath.com/). You can use whatever library you find as a starting point, then optimize / specialize / tweak from there.
Making a Point class in c++
[ "", "c++", "inheritance", "operator-overloading", "" ]
Using Watin, I'm trying to handle a confirm dialog box and tell watin to press "OK". This is reasoanbly well documented on the internet - you use a `ConfirmDialogHandler` and the `UseDialogOnce` method.. Except it isn't working for me. I get the following error: `WatiN.Core.Exceptions.WatiNException: Dialog not available within 5 seconds` I'm using the watin 2.0 beta atm, but I was previously using an earlier version of 1.X which had the same issue. Tested on a colleagues machine running 64 bit Vista, I'm running 64 bit Windows 7. The code looks like this: ``` using (IE ie = new IE("http://localhost/TestApp/TestConfirmPage.asp")) { var approveConfirmDialog = new ConfirmDialogHandler(); using (new UseDialogOnce(ie.DialogWatcher, approveConfirmDialog)) { ie.Button(Find.ByName("btn")).ClickNoWait(); approveConfirmDialog.WaitUntilExists(5); approveConfirmDialog.OKButton.Click(); } ie.WaitForComplete(); } ``` The ASP page is very simple, it consists of a button that forces a confirm, like this: ``` <input type="button" name="btn" id="btn" value="Click me" onclick="ConfirmApp()" /> ``` And `ConfirmApp` has been stripped down for testing so that now all it contains is: ``` bOK = confirm("You clicked a popup. Did you mean to?"); return bOK; ```
The code looks fine to me, and I think it should work. The only think I did differently it was to put Wait for Complete inside using Dialog block. Don't know why but before I did that I also have some issues, sometimes it works sometimes it doesn't. And I don't use time limitation at Wait until exists. But you probably already tried that one. For example: ``` using (new UseDialogOnce(ie.DialogWatcher, approveConfirmDialog)) { ie.Button(Find.ByName("btn")).ClickNoWait(); approveConfirmDialog.WaitUntilExists(); approveConfirmDialog.OKButton.Click(); ie.WaitForComplete(); } ```
I had the same problem and tried many things but just overlooked one part i was calling .Click() and then just changed it to .ClickNoWait() and things sorted. Hope this helps
Watin - Handling Confirm Dialogs with ConfirmDialogHandler
[ "", "c#", "asp.net", "watin", "" ]
I want to create a file in the current directory (where the executable is running). My code: ``` LPTSTR NPath = NULL; DWORD a = GetCurrentDirectory(MAX_PATH,NPath); HANDLE hNewFile = CreateFile(NPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); ``` I get exception at `GetCurrentDirectory()`. Why am I getting an exception?
I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. [Accelerated C++](http://www.acceleratedcpp.com/) by Koenig and Moo is excellent. To get the executable path use [GetModuleFileName](http://msdn.microsoft.com/en-us/library/ms683197%28VS.85%29.aspx): ``` TCHAR buffer[MAX_PATH] = { 0 }; GetModuleFileName( NULL, buffer, MAX_PATH ); ``` Here's a C++ function that gets the directory without the file name: ``` #include <windows.h> #include <string> #include <iostream> std::wstring ExePath() { TCHAR buffer[MAX_PATH] = { 0 }; GetModuleFileName( NULL, buffer, MAX_PATH ); std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/"); return std::wstring(buffer).substr(0, pos); } int main() { std::cout << "my directory is " << ExePath() << "\n"; } ```
The question is not clear whether the current working directory is wanted or the path of the directory containing the executable. Most answers seem to answer the latter. But for the former, and for the second part of the question of creating the file, the C++17 standard now incorporates the `filesystem` library which simplifies this a lot: ``` #include <filesystem> #include <iostream> std::filesystem::path cwd = std::filesystem::current_path() / "filename.txt"; std::ofstream file(cwd.string()); file.close(); ``` This fetches the current working directory, adds the filename to the path and creates an empty file. Note that the path object takes care of os dependent path handling, so `cwd.string()` returns an os dependent path string. Neato.
How to get Current Directory?
[ "", "c++", "windows", "" ]
In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just ``` check_status() ``` I would like to see something like: ``` Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... ok Time to ion canon charge is 9m 21s Booster rocket in AFTERBURNER state Range check is optimal Rocket fuel is 10h 19m 40s to depletion Beer served is type WICKSE LAGER, chill optimal Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO Virtual ... on ``` However, I would also like it to pass the output as a list if I call it in the context of a variable assignment: ``` not_robot_stat = check_status() print not_robot_stat >>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'} ``` So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?
**New Solution** This is a new that solution detects when the result of the function is used for assignment by examining its own bytecode. There is no bytecode writing done, and it should even be compatible with future versions of Python because it uses the opcode module for definitions. ``` import inspect, dis, opcode def check_status(): try: frame = inspect.currentframe().f_back next_opcode = opcode.opname[ord(frame.f_code.co_code[frame.f_lasti+3])] if next_opcode == "POP_TOP": # or next_opcode == "RETURN_VALUE": # include the above line in the if statement if you consider "return check_status()" to be assignment print "I was not assigned" print "Pretty printer status check 0.02v" print "NOTE: This is so totally not written for giant robots" return finally: del frame # do normal routine info = {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} return info # no assignment def test1(): check_status() # assignment def test2(): a = check_status() # could be assignment (check above for options) def test3(): return check_status() # assignment def test4(): a = [] a.append(check_status()) return a ``` **Solution 1** This is the old solution that detects whenever you are calling the function while debugging under python -i or PDB. ``` import inspect def check_status(): frame = inspect.currentframe() try: if frame.f_back.f_code.co_name == "<module>" and frame.f_back.f_code.co_filename == "<stdin>": print "Pretty printer status check 0.02v" print "NOTE: This is so totally not written for giant robots" finally: del frame # do regular stuff return {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} def test(): check_status() >>> check_status() Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} >>> a=check_status() Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots >>> a {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5} test() >>> ```
> However, I would also like it to pass the output as a list You mean "return the output as a dictionary" - be careful ;-) One thing you could do is use the ability of the Python interpreter to automatically convert to a string the result of any expression. To do this, create a custom subclass of `dict` that, when asked to convert itself to a string, performs whatever pretty formatting you want. For instance, ``` class PrettyDict(dict): def __str__(self): return '''Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... %s Time to ion canon charge is %dm %ds Booster rocket in %s state (other stuff) ''' % (self.conf_op and 'ok' or 'OMGPANIC!!!', self.t_canoncharge / 60, self.t_canoncharge % 60, BOOSTER_STATES[self.booster_charge], ... ) ``` Of course you could probably come up with a prettier way to write the code, but the basic idea is that the `__str__` method creates the pretty-printed string that represents the state of the object and returns it. Then, if you return a `PrettyDict` from your `check_status()` function, when you type ``` >>> check_status() ``` you would see ``` Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... ok Time to ion canon charge is 9m 21s Booster rocket in AFTERBURNER state Range check is optimal Rocket fuel is 10h 19m 40s to depletion Beer served is type WICKSE LAGER, chill optimal Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO Virtual ... on ``` The only catch is that ``` >>> not_robot_stat = check_status() >>> print not_robot_stat ``` would give you the same thing, because the same conversion to string takes place as part of the `print` function. But for using this in some real application, I doubt that that would matter. If you really wanted to see the return value as a pure dict, you could do ``` >>> print repr(not_robot_stat) ``` instead, and it should show you ``` {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'} ``` The point is that, as other posters have said, there is no way for a function in Python to know what's going to be done with it's return value (*EDIT*: okay, maybe there would be some weird bytecode-hacking way, but don't do that) - but you can work around it in the cases that matter.
Is there a way to check whether function output is assigned to a variable in Python?
[ "", "python", "functional-programming", "bytecode", "" ]
I'm asking this question as someone who works for a company with a 70% to 75% VB.NET developer community. I would say 80% of those developers do not know what an OOD pattern is. I'm wondering if this is the best thing for the health of my company's development efforts? I'm looking at the tag counts on: <https://stackoverflow.com/tags> There are currently: 12175 .NET questions 18630 C# questions 2067 VB.NET questions Checking Amazon, it seems like there are: 51 C# Wrox books 21 VB.NET Wrox books On CodePlex there are: 979 Projects tagged C# 136 Projects tagged VB.NET There is definitely less materials to learn from if you wanted to be a VB.NET developer. What would be a company's advantage to standardizing on VB.NET and hiring VB.NET developers? How does Microsoft answer this question? Is the only two arguments: 1. We had these VB6 programmers and lets make them comfortable 2. XML Literals If you work for a company that has completely standardized on VB.NET, can you post an answer explaining the pragmatic or technical reasons why they made that choice? **UPDATE:** More stats - O'Reilly Radar [State of the Computer Book Market 2008, part 4 -- The Languages](http://radar.oreilly.com/2009/02/state-of-the-computer-book-mar-22.html)
I'm sure most of the time the reason companies go forward with VB.NET is exactly as you mentioned - large amounts of VB6 in the organization, both in terms of codebase and developers. Keep in mind that ASP websites and VB6 applications can be migrated to VB.NET with little to no pain. VB6 to C# is a different story. That being said, having worked at companies that have used VB.NET, there's really very little difference in how you do things and developers who *are* curious get used to reading examples, books, etc. in C#. It's not like it's terrifically hard to translate C# code to VB.NET, especially if you're not copy-pasting.
We're not standardized on VB.Net, and I often have to go back and forth between VB.Net adn C#. I'm unusual, in that I come from a C/C++ background, know C#, but actually prefer VB.Net (I severely dislike vb6/vbscript). I say all this because it's important to remember the VB6 is NOT VB.Net. It's a whole new language and IMO does deserve to stand up next to C#. I *really hated* vb6, but I fell in love with VB.Net almost instantly. However, VB.Net did inherit some things from VB6, and not just a syntax style. I'm talking reputation, and that's not entirely deserved. But I'm also talking about the developer base that helped create that reputation. That seems to be part of what you're experiencing. With that in mind, it looks like you're judging the language based primarily on popularity. Not that there's anything wrong with this. There's plenty to be said for the ability to more-easily find samples and community support. But let's at least call it what it is. And if that's your measure, there's certainly *enough* support out there for VB.Net to make it viable, and it's not hard to take advantage of the C# samples. Also, we're still on .Net 2.0 where I work. For 2.0, I definitely prefer VB.Net. I like the syntax better and I like the way it does a few other things over C#. But I play around with Visual Studio 2008 at home. On 2008 I really prefer the C# lambda expression syntax. Regarding your two arguments: * For #1, [that may not be such a good idea](https://stackoverflow.com/questions/507291/should-we-select-vb-net-or-c-when-upgrading-our-legacy-apps/507309#507309), though I suspect it's the primary reason for many shops. * For #2, I've *never* used Xml literals. They looks nice, but just haven't been that practical. --- Something I wanted to add: it seems like some of the recent C# features are actually intended to make C# work more like VB. Static classes fill the conceptual space of a vb module. The `var` keyword makes variable declaration look more VB's dim. The upcoming dynamic keyword will allow vb-style late binding. Even properties, which is something you could say was "added" to c# for 1.0, are something that vb has had since before .Net.
Are VB.NET Developers Less Curious? Standardizing on VB.NET
[ "", "c#", ".net", "vb.net", "" ]
Is there a function in c# that takes two 32 bit integers (int) and returns a single 64 bit one (long)? Sounds like there should be a simple way to do this, but I couldn't find a solution.
Try the following ``` public long MakeLong(int left, int right) { //implicit conversion of left to a long long res = left; //shift the bits creating an empty space on the right // ex: 0x0000CFFF becomes 0xCFFF0000 res = (res << 32); //combine the bits on the right with the previous value // ex: 0xCFFF0000 | 0x0000ABCD becomes 0xCFFFABCD res = res | (long)(uint)right; //uint first to prevent loss of signed bit //return the combined result return res; } ```
Just for clarity... While the accepted answer does appear to work correctly. All of the one liners presented do not appear to produce accurate results. **Here is a one liner that does work:** ``` long correct = (long)left << 32 | (long)(uint)right; ``` **Here is some code so you can test it for yourself:** ``` long original = 1979205471486323557L; int left = (int)(original >> 32); int right = (int)(original & 0xffffffffL); long correct = (long)left << 32 | (long)(uint)right; long incorrect1 = (long)(((long)left << 32) | (long)right); long incorrect2 = ((Int64)left << 32 | right); long incorrect3 = (long)(left * uint.MaxValue) + right; long incorrect4 = (long)(left * 0x100000000) + right; Console.WriteLine(original == correct); Console.WriteLine(original == incorrect1); Console.WriteLine(original == incorrect2); Console.WriteLine(original == incorrect3); Console.WriteLine(original == incorrect4); ```
C# - Making one Int64 from two Int32s
[ "", "c#", "" ]
How to send HTML content in email using Python? I can send simple texts.
From [Python v2.7.14 documentation - 18.1.11. email: Examples](https://docs.python.org/2/library/email-examples.html#id5): > Here’s an example of how to create an HTML message with an alternative plain text version: ``` #! /usr/bin/python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "my@email.com" you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('localhost') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(me, you, msg.as_string()) s.quit() ```
Here is a [Gmail](http://en.wikipedia.org/wiki/Gmail) implementation of the accepted answer: ``` import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "my@email.com" you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login('userName', 'password') mail.sendmail(me, you, msg.as_string()) mail.quit() ```
Send HTML emails with Python
[ "", "python", "html", "email", "html-email", "" ]
Is there any way that I can use C# to load and then "render" an ascx control? Essentially I am trying to replace inline ASP with a C# function which will return the same HTML. This would then let me set it as a webmethod so that I can update that section of the page with jQuery, using the same code that generated the original html. I really need some way of doing this, and this seems like a logical route.
You need to create a page in which you render the control: ``` public static string RenderUserControl(string path) { Page pageHolder = new Page(); Control viewControl = pageHolder.LoadControl(path); pageHolder.Controls.Add(viewControl); using(StringWriter output = new StringWriter()) { HttpContext.Current.Server.Execute(pageHolder, output, false); return output.ToString(); } } ``` A user control on its own will not render. ([This article](http://jamesewelch.com/2008/07/11/how-to-render-a-aspnet-user-control-within-a-web-service-and-return-the-generated-html/) has some related information from which I borrowed some code).
Keltex's answer was the only that worked for me since i was working with nested user-controls. Additionally, if you would want to pass parameters to your user control you can do so by: ``` _MyNameSpace_MyUserControl viewcontrol = (_MyNameSpace_MyUserControl) pageHolder.LoadControl(path); viewcontrol.MyParam = "My value"; ```
Load ascx component using C# code
[ "", "c#", "asp.net", "ascx", "" ]
I need to write a small console app (patch) that turns off the print spooler service, does a few things, then starts the print spooler service. I'd like to write this in C#. Can someone point me in the right direction? Thanks in advance!
You can probably do that using the ServiceController class : ``` ServiceController controller = new ServiceController("Spooler"); controller.Stop(); ... controller.Start(); ```
``` net start spooler net stop spooler ``` <http://www.tech-recipes.com/rx/864/windows-service-managing-through-command-line/>
How do you programmatically turn off the Windows XP Print Spooler service in C#
[ "", "c#", "windows", "windows-xp", "console-application", "" ]
I have code like this. ``` var key = "anything"; var object = { key: "key attribute" }; ``` I want to know if there is a way to replace that `key` with "anything". like ``` var object = { "anything": "key attribute" }; ```
In ES6, use **[computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names)**. ``` const key = "anything"; const object = { [key]: "key attribute" // ^^^^^ COMPUTED PROPERTY NAME }; ``` Note the square brackets around `key`. You can actually specify any expression in the square brackets, not just a variable.
Yes. You can use: ``` var key = "anything"; var json = { }; json[key] = "key attribute"; ``` Or simply use your second method if you have the values at hand when writing the program.
Is there a way to use variable keys in a JavaScript object literal?
[ "", "javascript", "" ]
I have to get records from my MySQL DB where: ``` sentto = "$username" ``` OR ``` sentto = "everyone" ``` How would I put this in a MySQL query? I tried a few things, but they don't seem to be working: ``` mysql_query("SELECT * FROM pmessages WHERE status='unread' AND sentto='$username' || sentto='everyone'"); mysql_query("SELECT * FROM pmessages WHERE status='unread' AND sentto='$username' AND sentto='everyone'"); ``` I seem to be stumped, if anyone knows how to do this the right way please let me know. This is a new scenario for me. Thank you!
``` SELECT * FROM pmmessages WHERE sentto = '$username' OR sentto = 'everyone' ``` **Edit** Chris, based on your new query of: ``` SELECT * FROM pmessages WHERE status='unread' AND sentto='$username' OR sentto='everyone' ``` You need to modify it so that your AND stands alone (it is conflicting with your OR). Rewrite it to this ``` SELECT * FROM pmessages WHERE status='unread' AND (sentto='$username' OR sentto='everyone' ) ```
Taking the detail from one of your comments into account - use the " `OR` " keyword and parentheses to make sure that the right conditions are combined. ``` SELECT * FROM pmessages WHERE status = 'unread' AND (sentto = ? OR sentto = 'everyone') ``` Your problem was never with the `OR`, though, it was actually the `AND` precedence and lack of parentheses. The very significant detail that you completely omitted from your question was the additional test for "`status = unread`". Note the use of `?` above - you should *really*, *really* use prepared statements whenever combining MySQL and PHP, i.e.: ``` $sql = "..." # as above $sth = $db->prepare($sql); $res = $sth->execute($username); while ($row = $sth->fetchrow()) { ... } ``` (or the `mysqli` equivalent)
MySQL Query Selecting records from a database where a value equals one of two different things
[ "", "php", "mysql", "" ]
[Update]: my initial example doesn't reflect my problem. Updated the sample, hopfully it is better now. Java Generic and overloading don't play well together. ``` public interface Request<E> { E getValue(); } ``` I have a generic parameterized Request interface as above, and I would like write a DataStore class to save the payload request carries. The save logic is different for different payload type. What I really want is something like ``` public interface DataStore { void save(Request<E1> r); void save(Request<E2> r); } ``` But this is of course illegal. If I want to preserve type safety, DataStore must declare different methods for each type I want to handle, e.g ``` public interface DataStore { // here E1 is the actual type I want to handle, not a generic parameter public void saveE1(Request<E1> e); public void saveE2(Request<E2> e); } ``` Or sacrifices type safety ``` public class DataStore { public void save(Request e) { Object value = e.getValue(); if (value instanceof ReqE1Impl) { // do something } else if (value instanceof ReqE2Impl) { // do something else } } } ``` Both ways suck! Is there any better way?
The better way to do this would involve the object knowing how to save itself. If you still want to use a DataStore, you could do something like this: ``` interface YourInterface { void save(); } interface Request<E extends YourInterface> { E getValue(); } class DataStore<E extends YourInterface> { public void save(Request<E> r) { r.getValue().save(); } } ``` You just have to ensure that your objects then each implement that `interface` and viola, you have Generics and polymorphism playing nice with each other. NOTE: The way your (revised) question is written, you are not using polymorphism. You are using overloading. Method overloading is decided at compile time, while method polymorphism is decided at runtime. This is part of why you are running into these difficulties. If you really do not want the above kind of design where the objects do all the work of saving themselves, then perhaps you can do something like this (as a very weak example): ``` interface YourInterface { String serialize(); } interface Request<E extends YourInterface> { E getValue(); } class DataStore<E extends YourInterface> { public void save(Request<E> r) { String value = r.getValue().serialize(); // Now do something with value to save to a datastore } } ``` Above is a weak example, but the main idea is that the objects know how to do the part of serialization that differs between objects, and the DataStore can then do the work that is common to all of your objects. And yes, you are right (with the wrong terminology) -- generics don't play nice with overloading. But they do play nice with polymorphism. Polymorphism is usually a better instrument than overloading anyway.
Perhaps I am misunderstanding the question, but generics seem to solve this ok: ``` public interface Handler<E> { void save (E obj, DataStore<E> store); } public interface DataStore<E> { public void save (E obj); } public class AHandler implements Handler<String> { public void save (String obj, DataStore<String> obj2) { } } public class BHandler implements Handler<Boolean> { public void save (Boolean b1, DataStore<Boolean> obj3) { } } ```
Java Generic Question: Any better way?
[ "", "java", "generics", "" ]
When experiencing networking problems on client machines, I'd like to be able to run a few command lines and email the results of them to myself. I've found Runtime.exec will allow me to execute arbitrary commands, but Collecting the results in a String is more interesting. I realize I could redirect output to a file, and then read from the file, but my spidey sense is telling me there's a more elegant way of doing it. Suggestions?
You need to capture both the std out and std err in the process. You can then write std out to a file/mail or similar. See [this article](https://www.infoworld.com/article/2071275/when-runtime-exec---won-t.html) for more info, and in particular note the `StreamGobbler` mechanism that captures stdout/err in separate threads. This is essential to prevent blocking and is the source of numerous errors if you don't do it properly!
Use [ProcessBuilder](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html). After calling start() you'll get a [Process](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) object from which you can get the stderr and stdout streams. UPDATE: ProcessBuilder gives you more control; You don't have to use it but I find it easier in the long run. Especially the ability to redirect stderr to stdout which means you only have to suck down one stream.
Capturing stdout when calling Runtime.exec
[ "", "java", "shell", "runtime", "" ]
I have some script in my default page that redirects users to language specific versions of my website depending on the language of the browser. I want to add something that redirects those users who do NOT have Javascript enabled. Currently I have the following : ``` <noscript> <META HTTP-EQUIV=REFRESH CONTENT="1; URL=en/index.htm">. </noscript> ``` But I've read this is not too wise as some search engines frown upon it. How do I do this and keep search engines happy?
You can redirect at server side with 301 HTTP status code too. This is the best way to do it for good SEO. The example is in C# but every plattform has his own method to add headers to the response: ``` Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", "/newfolder/newfilelocation"); ``` The reason to use the 301 status code is that the search engine indexes the new page because it was "Moved permanently" instead of the 302 that was "Moved temporarily".
You should use a .htaccess file to detect the browser's language from the headers (using a regular expression) and then redirect them that way. Doing that is completely agnostic of the client-side configuration and search engines will handle it properly. There is a ton of information out there on specifically how to accomplish this.
How best to redirect a webpage without using Javascript?
[ "", "javascript", "html", "http-status-code-301", "http-status-code-302", "" ]
I want to have a way to teach hudson to delete the complete workspace before doing a checkout & build. Is there a plugin which enables that?
Currently, each SCM plugin provides workspace cleanup functionality. Soon, core Hudson will have this capability, and the SCM plugins will migrate the setting to that core feature: [issue 3966](http://issues.hudson-ci.org/browse/HUDSON-3966)
Under Source Code Management, expand the advanced properties and un-check "Use Update" (this option is present for me for CVS, not sure about all other SCM tools). This option controls if Hudson uses an "update" command to simply grab changed files from SCM, or if it checks out a new/clean copy from source control.
How to delete Hudson workspace before build?
[ "", "java", "build", "hudson", "" ]
I have a query that should *always* be returning a single int. I have now logged it returning a string entirely unrelated to what it should be. We've been getting some random FormatExceptions that we've tracked down to several database queries. After some additional logging, I found that, this morning, the query below returned the string "gladiator". Website.PkID is an int column and works most of the time, but some times it fails miserably and returns either an int that's waaaay out there (bigger than any valid WebsiteID) or a random string. This particular query is hit once per session start. It's not using a shared connection, so I'm having trouble understanding how it could get such a mixed-up result. Could there be some kind of corruption in the connection pools? I don't think the problem is isolated to this query. I've seen similar FormatExceptions (because of an unexpected result) coming from LINQ queries as well. We've also spotted some of these errors around the same times: > A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host. Could it be a connection issue? Or maybe we're getting result sets mixed up between the db server and the web server? This has really got me scratching my head. Offending query: ``` public static int GetActiveWebSiteID(string storeID, string statusID) { int retval; string sql = @"SELECT isnull(MAX(PkID),0) FROM WebSite WHERE StoreID = @StoreID AND WebSiteStatusID = @WebSiteStatusID"; SqlConnection conn = new SqlConnection(Settings.ConnString); SqlCommand cmd = new SqlCommand(sql, conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@StoreID", (object)storeID ?? DBNull.Value); cmd.Parameters.AddWithValue("@WebSiteStatusID", (object)statusID ?? DBNull.Value); conn.Open(); using(conn) { var scalar = cmd.ExecuteScalar(); // <-- This value returned here should only ever be an int, but randomly is a string retval = Convert.ToInt32(scalar); } return retval; } ``` The above query has worked fine for years until recently. We now have a bunch of additional LINQ queries in the app (not sure if that makes a difference). We're running .Net 3.5.
After a few months of ignoring this issue, it started to reach a critical mass as traffic gradually increased. We increased logging and found numerous definitive instances where, under heavy load, completely different result sets would get returned to unrelated queries. We watched the queries in Profiler and were able to see that the bad results were always associated with the same spid, and that each bad result was always one query behind the actual sql statement being queried. It was like a result set got missed and whatever result set was next in the spid (from another connection in the same pool) was returned. Crazy. Through trial and error, we eventually tracked down a handful of SqlCommand or LINQ queries whose SqlConnection wasn't closed immediately after use. Instead, through some sloppy programming originating from a misunderstanding of LINQ connections, the DataContext objects were disposed (and connections closed) only at the end of a request rather than immediately. Once we refactored these methods to immediately close the connection with a C# "using" block (freeing up that pool for the next request), we received no more errors. While we still don't know the underlying reason that a connection pool would get so mixed up, we were able to cease all errors of this type. This problem was resolved in conjunction with another similar error I posted, found here: [What Causes "Internal Connection Fatal Errors"?](https://stackoverflow.com/questions/1155263/what-causes-internal-connection-fatal-errors)
I think that you were thinking about `sqlCommand.ExecuteNonQuery` that returns the number of rows affected within an int value... This is the definition of the ExecuteScalar method: ``` public override object ExecuteScalar() Member of System.Data.SqlClient.SqlCommand ``` **Summary:** Executes the query, and **returns the first column of the first row** in the result set returned by the query. Additional columns or rows are ignored. **Returns:** The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. So, I think that the common way of returning that column is as a string representation of the column value.
Why is my SqlCommand returning a string when it should be an int?
[ "", "c#", "sql-server", "linq-to-sql", "ado.net", "" ]
Say, an application properties page with lots of JCheckboxes, JTextfields, JLists and other JComponents. Now, what I need to do is track the changes user makes and save them. What would be the correct way of implementing this?
You don't need to track changes in real times (unless special needs). You can react on the OK button, iterating on the components, getting their value, perhaps comparing with the old one or just saving all the values blindly. And of course abandon everything if the user cancels.
Two approaches you can use: (1) When the user clicks OK on your properties page, pull the current values out of your JComponents and update your settings or whatnot. This is the easiest method as you don't need ActionListeners and if the user backs out you don't have to roll back changes (from your question it's not entirely clear what this dialog/page does, though). (2) For swing objects that implement ActionListener, listen for the ActionEvent and process the changes accordingly. For JTextFields, use a DocumentListener as in the sample code below: ``` import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class Test implements DocumentListener { private JTextField jtf; public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { Test test = new Test(); } }); } public Test() { JFrame jf = new JFrame(); JPanel jp = new JPanel(); jtf = new JTextField(); jtf.getDocument().addDocumentListener(this); jp.setLayout(new BorderLayout()); jp.add(jtf, BorderLayout.CENTER); jf.add(jp); jf.setSize(200, 100); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } public void changedUpdate(DocumentEvent e) { // Do stuff here } public void insertUpdate(DocumentEvent e) { // Do stuff here } public void removeUpdate(DocumentEvent e) { // Do stuff here } } ``` As you might guess from (1), the challenge from (2) comes about if the user backs out and you have to think about how you're going to roll back any changes. It really depends on what you're doing, though.
Tracking changes in a swing GUI
[ "", "java", "swing", "" ]
Does map() iterate through the list like "for" would? Is there a value in using map vs for? If so, right now my code looks like this: ``` for item in items: item.my_func() ``` If it makes sense, I would like to make it map(). Is that possible? What is an example like?
You could use [`map`](http://docs.python.org/3.0/library/functions.html#map) instead of the `for` loop you've shown, but since you do not appear to use the result of `item.my_func()`, this is **not recommended**. `map` should be used if you want to apply a function without side-effects to all elements of a list. In all other situations, use an explicit for-loop. Also, as of Python 3.0 `map` returns an iterator, so in that case `map` will not behave the same (unless you explicitly evaluate all elements returned by the iterator, e.g. by calling [`list`](http://docs.python.org/3.0/library/functions.html#list) on it). --- **Edit**: [kibibu](https://stackoverflow.com/users/81804/kibibu) asks in the comments for a clarification on why `map`'s first argument should not be a function with side effects. I'll give answering that question a shot: `map` is meant to be passed a function `f` [in the mathematical sense](http://en.wikipedia.org/wiki/Function_%28mathematics%29). Under such circumstances it does not matter in which order `f` is applied to the elements of the second argument (as long as they are *returned* in their original order, of course). More importantly, under those circumstances `map(g, map(f, l))` is semantically equivalent to `map(lambda x: g(f(x)), l)`, *regardless of the order in which `f` and `g` are applied to their respective inputs*. E.g., it doesn't matter whether `map` returns an iterator or a full list at once. However, if `f` and/or `g` cause side effects, then this equivalence is only guaranteed if the semantics of `map(g, map(f, l))` are such that at any stage `g` is applied to the first *n* elements returned by `map(f, l)` before `map(f, l)` applies `f` to the \*(n + 1)\*​st element of `l`. (Meaning that `map` must perform the laziest possible iteration---which it does in Python 3, but not in Python 2!) Going one step further: even if we assume the Python 3 implementation of `map`, the semantic equivalence may easily break down if the output of `map(f, l)` is e.g. passed through [`itertools.tee`](http://docs.python.org/3.1/library/itertools.html#itertools.tee) before being supplied to the outer `map` call. The above discussion may seem of a theoretic nature, but as programs become more complex, they become more difficult to reason about and therefore harder to debug. Ensuring that some things are invariant alleviates that problem somewhat, and may in fact prevent a whole class of bugs. Lastly, `map` reminds many people of its truly functional counterpart in various (purely) functional languages. Passing it a "function" with side effects will confuse those people. Therefore, seeing as the alternative (i.e., using an explicit loop) is not harder to implement than a call to `map`, it is highly recommended that one restricts use of `map` to those cases in which the function to be applied does not cause side effects.
You can write this using map like this: ``` map(cls.my_func, items) ``` replacing cls with the class of the items you are iterating over. As mentioned by Stephan202, this is **not recommended** in this case. As a rule, if you want to create a new list by applying some function to each item in the list, use map. This has the implied meaning that the function has no side effect, and thus you could (potentially) run the map in parallel. If you don't want to create a new list, or if the function has side effects, use a for loop. This is the case in your example.
Is there a value in using map() vs for?
[ "", "python", "for-loop", "map-function", "" ]
I am wondering if you can use Linq to SQL using a .mdf file on a machine without a SQL Server instance installed?
Nope, you need to attach the file to some instance of MSSQL. You can do it with MsSQL Express.
You have to attach the database to some instance of Sql server. You'll probably want to do this on the same machine, otherwise you add in network latency (which can be extreme in some cases) when writing to the database.
Do you have to have SQL Server installed on a machine if the connection string using is a path to a .mdf File?
[ "", "sql", "linq", "mdf", "" ]
When I try my program on my win2k8 machine it runs fine but on win 2k3 it gives me this error that error message here's the code that' generating the error ``` WebClient wc = new WebClient(); wc.DownloadFile("ftp://ftp.website.com/sample.zip"); ``` there's the weird part. if i disable the firewall on the server completely. the error goes away. but it still errors if i add the program to the exception list and turn on the firewall. have search the web for days, couldn't find any solution.
You should try using passive mode for FTP. The WebClient class doesn't allow that, but FtpWebRequest does. ``` FtpWebRequest request = WebRequest.Create("ftp://ftp.website.com/sample.zip") as FtpWebRequest; request.UsePassive = true; FtpWebResponse response = request.GetResponse() as FtpWebResponse; Stream ftpStream = response.GetResponse(); int bufferSize = 8192; byte[] buffer = new byte[bufferSize]; using (FileStream fileStream = new FileStream("localfile.zip", FileMode.Create, FileAccess.Write)) { int nBytes; while((nBytes = ftpStream.Read(buffer, 0, bufferSize) > 0) { fileStream.Write(buffer, 0, nBytes); } } ```
Please post the complete exception, including any InnerException: ``` try { WebClient wc = new WebClient(); wc.DownloadFile("ftp://ftp.website.com/sample.zip"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); // Or Debug.Trace, or whatever throw; // As if the catch were not present } ```
The underlying connection was closed: An unexpected error occurred on a receive
[ "", "c#", "windows-server-2008", "windows-server-2003", "webclient", "" ]
I know what I asking might not make a lot of sense for C# experts but I'll explain what I want to do and then you can suggest me how to do it in a better way if you want ok? I have a C# class called DatabaseManager that deals with different MySQL queries (ado.net NET connector, not linq or any kind of ActiveRecord-ish library). I am doing something like ``` categories = db_manager.getCategories(); ``` The list of categories is quite small (10 items) so I'd like to know what's the best way of accessing the retrieved information without a lot of additional code. Right now I'm using a Struct to store the information but I'm sure there's a better way of doing this. Here's my code: ``` public struct Category { public string name; } internal ArrayList getCategories() { ArrayList categories = new ArrayList(); MySqlDataReader reader; Category category_info; try { conn.Open(); reader = category_query.ExecuteReader(); while (reader.Read()) { category_info = new Category(); category_info.name = reader["name"].ToString(); categories.Add(category_info); } reader.Close(); conn.Close(); } catch (MySqlException e) { Console.WriteLine("ERROR " + e.ToString()); } return categories; } ```
Example: ``` public IEnumerable<Category> GetCategories() { using (var connection = new MySqlConnection("CONNECTION STRING")) using (var command = new MySqlCommand("SELECT name FROM categories", connection)) { connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { yield return new Category { name = reader.GetString(0) }; } } } } ``` Remarks: 1. Let ADO.NET connection pooling do the right work for you (avoid storing connections in static fields, etc...) 2. Always make sure to properly dispose unmanaged resources (using "using" in C#) 3. Always return the lowest interface in the hierarchy from your public methods (in this case IEnumerable<Category>). 4. Leave the callers handle exceptions and logging. These are crosscutting concerns and should not be mixed with your DB access code.
The first thing I would do is to replace you use of ArrayList with List that will provide compile-time type checkig for your use of the category list (so you will not have to type cast it when using it in your code).
Storing reader information in C#
[ "", "c#", ".net", "mysql", "database", "" ]
I have started having problems with my VPS in the way that it would faill to serve the pages on all the websites. It just showed a blank page, or offered to download the php file ( luckily the code was not in the download file :) ). The server was still running, but this seemed to be a problem with PHP, since i could login into WHM. If i did a apache restart, the sites would work again. After some talks with the server support they told me this is a problem with the APC extension witch they considered to be old and not recommended for production servers. So they removed it for now, to see if the same kind of fails would continue to appear. I haven't read anywhere that APC could have some problems or that its not always recommended to use, quite the contrary ... everywhere people are saying to always use it. The APC extension was installed ssh and is the latest version. **Edit:** They also dont recomend MemCache and say that a more reliable extension would be eAccelerator
Um APC is current tech and almost a must for any performant PHP site. Not only that but it will ship as **standard** in PHP 6 (rather than being an optional module like it is now). I don't know what your issue is/was but it's not APC being outdated or old tech.
I run several servers myself and the only time I have ever had trouble with APC was when trying to run it concurrently with Zend Optimizer. They don't work together so if I must use Optimizer (like if some commercial, third-party code requires it) I run eAccelerator instead of APC. Effectively 6 of one, half-dozen of another when it comes to performance but I really doubt APC is the problem here.
APC not recommended for production?
[ "", "php", "apache", "caching", "apc", "" ]
Is this possible? I am creating a single base factory function to drive factories of different types (but have some similarities) and I want to be able to pass arguments as an array to the base factory which then possibly creates an instance of a new object populating the arguments of the constructor of the relevant class via an array. In JavaScript it's possible to use an array to call a function with multiple arguments by using the apply method: ``` namespace.myFunc = function(arg1, arg2) { //do something; } var result = namespace.myFunc("arg1","arg2"); //this is the same as above: var r = [ "arg1","arg2" ]; var result = myFunc.apply(namespace, r); ``` It doesn't seem as if there's anyway to create an instance of an object using apply though, is there? Something like (this doesn't work): ``` var instance = new MyClass.apply(namespace, r); ```
Try this: ``` var instance = {}; MyClass.apply( instance, r); ``` All the keyword "new" does is pass in a new object to the constructor which then becomes the this variable inside the constructor function. Depending upon how the constructor was written, you may have to do this: ``` var instance = {}; var returned = MyClass.apply( instance, args); if( returned != null) { instance = returned; } ``` Update: A comment says this doesn't work if there is a prototype. Try this. ``` function newApply(class, args) { function F() { return class.apply(this, args); } F.prototype = class.prototype; return new F(); } newApply( MyClass, args); ```
Note that * ``` new myClass() ``` without any arguments may fail, since the constructor function may rely on the existence of arguments. * ``` myClass.apply(something, args) ``` will fail in many cases, especially if called on native classes like Date or Number. I know that "eval is evil", but in this case you may want to try the following: ``` function newApply(Cls, args) { var argsWrapper = []; for (var i = 0; i < args.length; i++) { argsWrapper.push('args[' + i + ']'); } eval('var inst = new Cls(' + argsWrapper.join(',') + ');' ); return inst; } ``` Simple as that. (It works the same as `Instance.New` in [this blog post](http://webreflection.blogspot.com/2007/05/joking-with-javascript-constructors.html))
How can I construct an object using an array of values for parameters, rather than listing them out, in JavaScript?
[ "", "javascript", "oop", "firefox-addon", "new-operator", "apply", "" ]
I'm working on a project with different assemblies (imagine a printer-module, a imaging-module etc.). In this project, all interfaces are declared inside one Interfaces-assembly (imagine Interfaces.dll with interfaces IPrinterModule, IImagingModule etc.). Since I'm a cowboy-coder ;) I have to ask the SO-community if this really is best practice or how this can be done in a better way?
We have adopted a similar approach. You definitely want to separate the interfaces from their (current) implementation, so it is easy to provide different implementations in future. Martin Fowler has described this as the [Separated Interfaces](http://www.martinfowler.com/eaaCatalog/separatedInterface.html) pattern. If the interfaces have dependencies on each other (does an IPrinter return an IImageXXX?) then you really need them in the same assembly to avoid circular build dependencies.
That sounds good to me - having a separate assembly for interfaces is quite common, especially for systems that do a lot of plugins. Most likely you are using these interfaces to create loosely-coupled bridges between orthogonal components (good for you, by the way). The only way to do this in a truly modular way is to have a separate assembly for those interfaces so that every type that either implements the interface or references it is actually using the same interface type. Really your only other option would be to compile everything in the entire system into one assembly.
Where to declare interfaces?
[ "", "c#", ".net", "" ]
We are about to migrate an intranet web application from using a proprietary forms-based security to Active Directory. The application logs a variety of user actions, and there is a significant amount of data associated with user accounts. Our plan was to migrate all of these UserId columns in various tables: from a foreign key linking the proprietary system, to an Active Directory GUID. Login names are identical between the two systems, so migrating is not an issue. However, we identified one major problem: Our security policy dictates that inactive users must be deleted from Active Directory. An orphaned GUID in our security logs makes the entries pretty meaningless to anyone viewing them. **How can an application maintain the human-readable basics (name, login, etc.) about a GUID that has been deleted from Active Directory?** We have considered the following options. One of these options may end up being the optimal, but we wish to try for better: * Denormalize the log tables and store name/login instead of a GUID (okay for logs, not so much for active data.) * Maintain a "cache" of AD object information where entries are never deleted * Keeping the AD account but deactivating/locking it down
We have decided to use a "cache" table that will store a dictionary of GUIDs that map to friendly user information. This will require a view that abstracts an AD user list, and coalesces in missing entries from the cache.
I wouldn't fully denormalize the log table, but instead store the pertinent AD information alongside the GUID, as Tim said. However, if you will need this AD information in other areas, cache it in your user table. I would recommend against changing your security policy.
Logging AD User Actions (with deleted users)
[ "", "c#", ".net", "logging", "active-directory", "" ]
Is there a way I can know who holds a reference to an object? I see that my object is not finalized by the d'tor after I call GC.Collect.
There is no way to do this effectively in code. The best way to track down leaks of this sort is to use a tool like WinDbg. The SOS extension has several commands which are specifically designed to help track down memory leaks. Rico did a thorough blog entry on the subject: * <http://blogs.msdn.com/ricom/archive/2004/12/10/279612.aspx>
You ought to call [`GC.WaitForPendingFinalizers`](http://msdn.microsoft.com/en-us/library/system.gc.waitforpendingfinalizers.aspx) after `GC.Collect` to allow the garbage collector to clear the freachable queue. Since the GC runs in a different thread it is possible that your application has moved on while the GC is trying to finalize any objects that require finalization. By calling [`GC.WaitForPendingFinalizers`](http://msdn.microsoft.com/en-us/library/system.gc.waitforpendingfinalizers.aspx) you are forcing your current thread to wait until the GC has finished clearing the freachable queue (the queue of items that require finalization) before resuming execution. That being said however, I agree with Joel Coehoorn's comment - the GC works best when you leave it alone.
Is there a way I can know who holds a reference to an object?
[ "", "c#", ".net", "memory-leaks", "garbage-collection", "" ]
What's the best way in C# to set up a utility app that can be run from the command line and produce some output (or write to a file), but that could be run as a Windows service as well to do its job in the background (e.g. monitoring a directory, or whatever). I would like to write the code once and be able to either call it interactively from PowerShell or some other CLI, but at the same time also find a way to install the same EXE file as a Windows service and have it run unattended. Can I do this? And if so: how can I do this?
Yes you can. One way to do it would be to use a command line param, say "/console", to tell the console version apart from the run as a service version: * create a Windows Console App and then * in the Program.cs, more precisely in the Main function you can test for the presence of the "/console" param * if the "/console" is there, start the program normally * if the param is not there, invoke your Service class from a ServiceBase ``` // Class that represents the Service version of your app public class serviceSample : ServiceBase { protected override void OnStart(string[] args) { // Run the service version here // NOTE: If you're task is long running as is with most // services you should be invoking it on Worker Thread // !!! don't take too long in this function !!! base.OnStart(args); } protected override void OnStop() { // stop service code goes here base.OnStop(); } } ``` ... Then in Program.cs: ``` static class Program { // The main entry point for the application. static void Main(string[] args) { ServiceBase[] ServicesToRun; ``` ``` if ((args.Length > 0) && (args[0] == "/console")) { // Run the console version here } else { ServicesToRun = new ServiceBase[] { new serviceSample () }; ServiceBase.Run(ServicesToRun); } } ``` }
The best way to accomplish this from a design standpoint is to implement all your functionality in a library project and build separate wrapper projects around it to execute the way you want (ie a windows service, a command line program, an asp.net web service, a wcf service etc.)
Create a combo command line / Windows service app
[ "", "c#", ".net", "command-line", "windows-services", "" ]
Is there any native compression (for javascript/css files) available in ASP.NET?
In the appendix of [Professional ASP.NET 3.5](https://rads.stackoverflow.com/amzn/click/com/0470187573) Scott Hanselman talks about [Packer for .NET](http://svn.offwhite.net/trac/SmallSharpTools.Packer/wiki). This will integrate with MSBuild and pack javascript files for production deployments etc.
Try Chirpy. It mashes, minifies, and validates your javascript, stylesheet, and dotless files. You can use YUI Compressor or Google Closure Compiler. <http://chirpy.codeplex.com/> Or, for more info, check out: <http://www.weirdlover.com/2010/05/22/visual-studio-add-in-for-dotless-js-and-css-files/>
ASP.NET - script and css compression
[ "", "asp.net", "javascript", "css", "compression", "" ]
Just wondering if the following is considered to be good programming practice or not? I like to keep my individual source files as concise and uncluttered as possible, but I'm wondering what more experienced coders would think of it. I especially like the idea of the Settings.java class to keep all of my "Magic Numbers" in the one place. Has anyone any suggestions as to how I might improve on things? Happy coding :-) ``` class ApplicationLauncher { public static void main(String[] args) { SwingApplication mySwingApplication = new SwingApplication(); } } ////////////// import javax.swing.*; public class SwingApplication extends JFrame { public SwingApplication() { JFrame myJFrame = new JFrame(); myJFrame.setSize(Settings.frameWidth, Settings.frameHeight); myJFrame.setVisible(true); } } ////////////// class Settings { static int frameWidth = 100; static int frameHeight = 200; } ```
There's nothing wrong with having a settings class; however, in your example the settings are rather ambigious in terms of what frame they apply to, neither are they actual settings, but rather default values that strictly belong in the SwingApplication class. Another thing which we don't have much control over is how the constructor call in Swing cascades into the program's message pump loop. To me it has never made sense with a constructor that never returns (unless the frame is closed) and does more than initialize an object.
Having special classes with magic numbers as static members is a good Java practice. As programs grow, multiple settings classes, each with descriptive names, can be used.
Java - Is This Good Programming Practice?
[ "", "java", "coding-style", "constants", "" ]
in SQL Server, if I have an int variable, how can I write a query that returns the values 1 through the int variable's value? So given: ``` declare @cnt int set @cnt = 5 ``` What query would return 1 - 5? Is this possible?
An alternative answer to the others already given, maybe not so practical but it may be faster in certain situations. If you have a known upper bound for the values of @cnt you will encounter (say 1000) you could create a simple one-column table with the first 1000 integers in it, like ``` val --- 1 2 3 4 ... ``` and then whenever you want a set of integers you could get it using ``` select val from integerTable where val <= @cnt ```
You could do a **WHILE** loop in SQL like this: ``` DECLARE @Cnt int, @Val int; SET @Cnt = 5; SET @Val = 0; DECLARE @MyValues TABLE ( val int ); WHILE @Val < @Cnt BEGIN SET @Val = @Val + 1; INSERT @MyValues(val) SELECT @Val; END; SELECT Val FROM @MyValues; ```
SQL query to return 1 through int variable
[ "", "sql", "sql-server", "" ]
I am trying to make a call to a Parent class method from a contained object, but have no luck with the following code. What is the standard way to do it? I have searched around and this seems to work for inherited objects, but not for contained objects. Is it right to call it a Parent class even? Or is it called an Owner class? ``` class Parent{ private: Child mychild; public: void doSomething(); } class Child{ public: void doOtherThing(); } void Child::doOtherThing(){ Parent::doSomething(); } ```
A contained object has no special access to the class that contains it, and in general does not know that it is contained. You need to pass a reference or a pointer to the containing class somehow - for example: ``` class Child{ public: void doOtherThing( Parent & p ); }; void Child::doOtherThing( Parent & p ){ p.doSomething(); } ```
The child has no connection to the parent class at all. You'll have to pass 'this' down to the child (probably in the constructors) to make this work.
C++ how to call a parent class method from contained class?
[ "", "c++", "class", "" ]
I am using Java 6 and am trying to create an `HttpsURLConnection` against a remote server, using a client certificate. The server is using an selfsigned root certificate, and requires that a password-protected client certificate is presented. I've added the server root certificate and the client certificate to a default java keystore which I found in `/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/lib/security/cacerts` (OSX 10.5). The name of the keystore file seems to suggest that the client certificate is not supposed to go in there? Anyway, adding the root certificate to this store solved the infamous `javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed' problem.` However, I'm now stuck on how to use the client certificate. I've tried two approaches and neither gets me anywhere. First, and preferred, try: ``` SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); URL url = new URL("https://somehost.dk:3049"); HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); conn.setSSLSocketFactory(sslsocketfactory); InputStream inputstream = conn.getInputStream(); // The last line fails, and gives: // javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure ``` I've tried skipping the HttpsURLConnection class (not ideal since I want to talk HTTP with the server), and do this instead: ``` SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("somehost.dk", 3049); InputStream inputstream = sslsocket.getInputStream(); // do anything with the inputstream results in: // java.net.SocketTimeoutException: Read timed out ``` I am not even sure that the client certificate is the problem here.
Finally solved it ;). Got a strong hint [here](http://emo.sourceforge.net/cert-login-howto.html) (Gandalfs answer touched a bit on it as well). The missing links was (mostly) the first of the parameters below, and to some extent that I overlooked the difference between keystores and truststores. The self-signed server certificate must be imported into a truststore: > keytool -import -alias gridserver -file gridserver.crt -storepass $PASS -keystore gridserver.keystore These properties need to be set (either on the commandline, or in code): ``` -Djavax.net.ssl.keyStoreType=pkcs12 -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.keyStore=clientcertificate.p12 -Djavax.net.ssl.trustStore=gridserver.keystore -Djavax.net.debug=ssl # very verbose debug -Djavax.net.ssl.keyStorePassword=$PASS -Djavax.net.ssl.trustStorePassword=$PASS ``` Working example code: ``` SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); URL url = new URL("https://gridserver:3049/cgi-bin/ls.py"); HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); conn.setSSLSocketFactory(sslsocketfactory); InputStream inputstream = conn.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String string = null; while ((string = bufferedreader.readLine()) != null) { System.out.println("Received " + string); } ```
While not recommended, you can also disable SSL cert validation altogether, using the following code that came from [The Java Developers Almanac](https://web.archive.org/web/20061217061841/http://www.exampledepot.com/egs/javax.net.ssl/TrustAll.html): > ``` > import javax.net.ssl.*; import java.security.SecureRandom; import > java.security.cert.X509Certificate; > > public class SSLTool { > > public static void disableCertificateValidation() { > // Create a trust manager that does not validate certificate chains > TrustManager[] trustAllCerts = new TrustManager[] { > new X509TrustManager() { > public X509Certificate[] getAcceptedIssuers() { > return new X509Certificate[0]; > } > public void checkClientTrusted(X509Certificate[] certs, String authType) {} > public void checkServerTrusted(X509Certificate[] certs, String authType) {} > }}; > > // Ignore differences between given hostname and certificate hostname > HostnameVerifier hv = new HostnameVerifier() { > public boolean verify(String hostname, SSLSession session) { return true; } > }; > > // Install the all-trusting trust manager > try { > SSLContext sc = SSLContext.getInstance("SSL"); > sc.init(null, trustAllCerts, new SecureRandom()); > HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); > HttpsURLConnection.setDefaultHostnameVerifier(hv); > } catch (Exception e) {} } } > ```
Java client certificates over HTTPS/SSL
[ "", "java", "ssl", "jsse", "sslhandshakeexception", "" ]
I wish an easy way to communicate mathematical equations with gmail. There's a [javascript](http://www1.chapman.edu/~jipsen/mathml/asciimath.html) script called AsciiMath, which should translate Tex-like equations into standard mathML. I thought that it would be nice to use this script with GM. I thought that before sending the email, this script would convert all the TeX-like equations in your email to MathML. Thus the reader which is using FF (or IE with MathPlayer installed) would be able to easily read those equations. Ideally, I wish to somehow keep the original TeX-like equations in a plain-text message, so that it would be readable by plain text email clients, such as `mutt`. Obviously the weakest link here is the client software, which most likely doesn't support MathML. Still if my correspondent is using Firefox and some kind of webmail (which is pretty reasonable) - it should work. My question is, is it possible? Did anyone do that? Do you see any technical problems with this approach (gmail filtering the MathML, client not parsing it correctly etc.)? Any smarter ideas?
[GmailTeX](http://alexeev.org/gmailtex.html) does exactly what you want. It is pure javascript so it works in Firefox, Chrome, Opera.
What about using [texify](http://texify.com) and converting it just to a html image or a link to that image? This would save some work with parsing and converting the tex math code and wold work fine even with simple mail clients.
Greasemonkey script for inserting math in gmail
[ "", "javascript", "email", "latex", "gmail", "mathml", "" ]
Because I've made `.cpp` files and then transferred them into `.h` files, the only difference I can find is that you can't `#include` `.cpp` files. Is there any difference that I am missing?
The C++ build system (compiler) knows no difference, so it's all one of conventions. The convention is that `.h` files are declarations, and `.cpp` files are definitions. That's why `.h` files are `#include`d -- we include the declarations.
`.h` files, or header files, are used to list the publicly accessible instance variables and methods in the class declaration. `.cpp` files, or implementation files, are used to actually implement those methods and use those instance variables. The reason they are separate is because `.h` files aren't compiled into binary code while `.cpp` files are. Take a library, for example. Say you are the author and you don't want it to be open source. So you distribute the compiled binary library and the header files to your customers. That allows them to easily see all the information about your library's classes they can use without being able to see how you implemented those methods. They are more for the people using your code rather than the compiler. As was said before: it's the convention.
What is the difference between a .cpp file and a .h file?
[ "", "c++", "header", "" ]
I have a project that uses two third party libraries, both of which make use of TCHARs in their header files. Unfortunately one library is complied as multi-byte (call it library a), and the other is compiled as Unicode (call it library b). Now the way I understand it is that TCHAR is replaced by the precompiler with either wchar or char depending on the build options. So when library a was compiled any method that takes a parameter of type TCHAR was set to expect a parameter of type char, and methods in library b are set to expect a parameter of type wchar. Unfortunately my consuming application has to pick a character set too. If I pick Unicode then the header file I have included for library a tells me that the method wants a wchar, because when I compile the TCHARs in the header they are interpreted as wchars. This includes TCHARS defined inside of structures. I have confirmed this behavior in practice, when I allocate and pass a TCHAR buffer I get back garbage because it fills my wchar buffer with multi-byte data. My questions are: Is there a clean way to consume both of these libraries in the same application? Am I maybe doing something wrong with how I'm using these libraries?
Assuming you're not using too many class/function in either one of these libraries, I would wrap one of the library completely. Let's say if you decided to use mbc in your app and wrap library b (unicode), your wrapper header file can use `wchar_t` instead of `TCHAR` so #define will not affect your interface. Inside your wrapper's cpp file where you #include library b's headers, you #define `TCHAR` to match library b. No code other than your wrapper should be allowed to see library b. If you're using more than a few class/function in both of these libraries, maintaining the wrapper code will quickly become a problem of its own.
As [Shing Yip](https://stackoverflow.com/questions/813898/handling-tchars-in-header-files-for-libraries-with-different-character-sets/814034#814034) suggested, better wrap the difference in an API of your own. This makes your source code independent of it. The wrapping API then has to convert characters from your encoding to the library's. On windows, I you have functions called [WideCharToMultiByte](http://msdn.microsoft.com/en-us/library/aa450778.aspx) and the like.
Handling TCHARs in header files for libraries with different character sets
[ "", "c++", "libraries", "tchar", "" ]
I have a web application inside where i need to check whether the user has sufficient permissions / roles/rights to access the page. I had set the users rights in a table with `USER_ID`, `ROLE_ID`. and when a user is logging in to the application, I will be reading the records for this user and the construct a string and assign to a session variable. When the logged in user access each page, I will read the value from session variable and then parse the string and then check whether this user has sufficient rights assigned to it. Now I afraid whether accessing the session variable in every pages load would affect the performance. Is there any alternative way to solve this?
You should see a net gain in performance. It will take some resource to load the session, but that will usually be much less than the resources required to retrieve a record from the database, which can involve creating a connection, authenticating, parsing the query, retrieving a record and sending it over a network. Compared to that, taking a session file off the hard drive is much quicker. It does sound like you're trying to optimize prematurely. You should wait a while then monitor to see where your bottlenecks really are.
no, it won't affect the performance of your site in a noticable way (unless you have hundreds of users per second). but i noticed something: > (...) I will be reading the records for this user and the construct a string and assign to a session variable. When the logged in user access each page, I will read the value from session variable and then parse the string (...) a-ha! see, sessions are nothing but strings that are encoded and parsed on `session_start()` (normally, `serialize()` and `unserialize()` are used for this). you don't need to manually encode the data you're going to store in the session, it's done for you (and definitley faster than any custom method, because these features are implemented in the core).
Accessing Session variable and performance
[ "", "php", "performance", "session", "" ]
Are boolean expressions in SQL WHERE clauses [short-circuit evaluated](http://en.wikipedia.org/wiki/Short-circuit_evaluation)? For example: ``` SELECT * FROM Table t WHERE @key IS NULL OR (@key IS NOT NULL AND @key = t.Key) ``` If `@key IS NULL` evaluates to `true`, is `@key IS NOT NULL AND @key = t.Key` evaluated? If no, why not? If yes, is it guaranteed? Is it part of ANSI SQL or is it database specific? If database specific, SQLServer? Oracle? MySQL?
ANSI SQL Draft 2003 5WD-01-Framework-2003-09.pdf > 6.3.3.3 Rule evaluation order > > [...] > > Where the precedence is not determined by the Formats or by > parentheses, effective evaluation of expressions is generally > performed from left to right. However, it is > **implementation-dependent** whether expressions are actually evaluated left to right, particularly when operands or operators might > cause conditions to be raised **or if the results of the expressions > can be determined without completely evaluating all parts of the > expression.**
From the above, short circuiting is not really available. If you need it, I suggest a Case statement: ``` Where Case when Expr1 then Expr2 else Expr3 end = desiredResult ``` `Expr1`is always evaluated, but only one of `Expr2` and `Expr3` will be evaluated per row.
Is the SQL WHERE clause short-circuit evaluated?
[ "", "sql", "short-circuiting", "" ]
I have two queries, as following: ``` SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10; SELECT FOUND_ROWS(); ``` I want to execute both these queries in a single attempt. ``` $result = mysql_query($query); ``` But then tell me how I will handle each tables set separately. Actually in ASP.NET we uses dataset which handles two queries as ``` ds.Tables[0]; ds.Tables[1]; .. etc ``` How can I do the same using PHP/MYSQL?
**Update:** Apparently possible by passing a flag to `mysql_connect()`. See [Executing multiple SQL queries in one statement with PHP](https://stackoverflow.com/questions/13980803/executing-multiple-sql-queries-in-one-statement-with-php/13982705#13982705) Nevertheless, any current reader should avoid using the `mysql_`-class of functions and prefer PDO. You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it. For the record, it can be done using mysqli and the [mysqli\_multi\_query](https://www.php.net/manual/en/mysqli.multi-query.php)-function.
As others have answered, the mysqli API can execute multi-queries with the msyqli\_multi\_query() function. For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries: ``` $stmt = $dbh->prepare(" select sql_calc_found_rows * from foo limit 1 ; select found_rows()"); $stmt->execute(); do { while ($row = $stmt->fetch()) { print_r($row); } } while ($stmt->nextRowset()); ``` However, multi-query is pretty widely considered a **bad idea** for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the [classic "Little Bobby Tables" XKCD cartoon](http://xkcd.com/327/). When using an API that restrict you to single-query, that can't happen.
How to execute two mysql queries as one in PHP/MYSQL?
[ "", "php", "mysql", "loops", "" ]