Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am currently porting a project with a few hundred code files and dependencies onto several third-party libraries to Mac Os. I've finally gotten to the point where the program compiles without warnings or errors, but it does not seem to execute my own main function. Instead it seems to execute some other main function which seems to belong to a third party. This function writes some diagnostic-looking data to the console and exits afterwards: ``` (gdb) continue Current language: auto; currently c++ // // This is an automatically generated file. // Do not edit. // const unsigned short expTable[] = { 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, ... 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, }; Debugger stopped. Program exited with status value:0. ``` I can't use the debugger to find out where this main function resides because, while the stack trace seems valid, gdb doesn't show me the correct line number and file name for each stack entry (See [this unsolved question](https://stackoverflow.com/questions/594782/gcc-debugger-stack-trace-displays-wrong-file-name-and-line-number) for details). The search took several minutes to complete, but did not return any results. My project is using SDL among other libraries, but I am award of SDL\_Main() and the underlying problems and have built my project on top of a perfectly fine working SDL project template. So I am quite sure that my own main function is valid. Do you have any idea what might be going wrong? I'm currently out of ideas on how to find and remove the rogue main function. Thanks, Adrian **EDIT:** As I just found out, I made a mistake while searching file files with the string "This is an automatically generated". I just found several dozen files with the same string, all belonging to FreeImage, one of the third party libraries I am using. So, the problem seems to be related to FreeImage, but I am not still not sure how to proceed since I have compiled Freeimage as a library with the enclosed MacOs makefile and included only the library. I will try to rebuild a newer version of FreeImage and see it if that fixed my problem.
Could it be an initializer for a static object that fails before your main() is called?
Do you have several main in the binary? Try using `nm` on it. *(it shouldn't be possible as `ld` won't link with duplicates, but go into the dynamical libs and look for `_main` there)* ``` nm a.out | grep -5 _main ``` This should give 5 lines before and after any `_main` found in the binary `a.out` If you have several, see the surrounding symbols for hints which parts they are in... Next step can be to do the same on each dynamic lib that is used. To get a list of the used dynamic libraries use `otool` ``` otool -L a.out ```
How do I find my program's main(...) function?
[ "", "c++", "unix", "gcc", "gdb", "" ]
While implementing a [flash-based uploader](http://swfupload.org/), we were faced with an issue: [Flash doesn't provide the correct cookies](http://swfupload.org/forum/generaldiscussion/383). We need our PHP Session ID to be passed via a POST variable. We have come up with and implemented a functional solution, checking for a POST PHPSESSID. **Is POSTing the Session ID as secure as sending it in a cookie?** Possible reason for: Because both are in the http header, and equally possible for a client to forge. Possible reason against: Because it's easier to forge a POST variable than a Cookie.
It is as secure — forging the POST is equally as easy as the cookie. These are both done by simply setting flags in cURL. That being said, I think you've got a good solution as well.
If you are able to obtain the session ID from active content in order to POST it, this presumably means that your session cookie is not marked [HttpOnly](http://www.owasp.org/index.php/HTTPOnly), which one of our hosts claims is otherwise [a good idea for defending against cross-site scripting attacks](http://www.codinghorror.com/blog/archives/001167.html). Consider instead a JavaScript-based or even refresh-based uploader monitor, which should integrate well enough with everything else that the cookie can be HttpOnly. On the other hand, if your site does not accept third-party content, cross-site scripting attacks may not be of any concern; in that case, the POST is fine.
Is POST as secure as a Cookie?
[ "", "php", "security", "session", "cookies", "swfupload", "" ]
What is the best practical way of learning index tuning while writing tsql queries? I have VS2008 SQL Express. Could someone please provide me examples, etc? I have already found online articles and they are great in theory, but I still fail to see index tuning in real life action. Are there small easy to create examples out there?
To tune indexes, you tend to need large tables with lots of data, so small simple examples aren't easy to come by. My experience is with the SQL 2000 tools. Query Analyser, showing the Execution Plan and looking at the types of index and joins used. Very hard to describe it here. I can recommend a good book on the subject, particularly Chapter 9. [http://www.amazon.com/Professional-Server-Performance-Tuning-Programmer/dp/0470176393](https://rads.stackoverflow.com/amzn/click/com/0470176393) I would discourage you from using the automated Index Tuning tools until you understand how to do it yourself manually. I think it's important when it recommends adding an index that you have the ability to sanity-check the recommendation and decide for yourself whether it is a good option. Often it will recommend you add a "covering" index with many columns in order to speed up a single query you've asked to be analysed, but this may have adverse effects on your database overall when you look at all queries against that table.
Kimberly Trip (SQL Goddess) is an expert and has talked & written lots on the subject: <http://www.sqlskills.com/BLOGS/KIMBERLY/category/Indexes.aspx>
How can I learn SQL Server index tuning?
[ "", "sql", "sql-server", "t-sql", "indexing", "performance", "" ]
What's the correct regex for a plus character (+) as the first argument (i.e. the string to replace) to Java's `replaceAll` method in the String class? I can't get the syntax right.
You need to escape the `+` for the regular expression, using `\`. However, Java uses a String parameter to construct regular expressions, which uses `\` for its own escape sequences. So you have to escape the `\` itself: ``` "\\+" ```
when in doubt, let java do the work for you: ``` myStr.replaceAll(Pattern.quote("+"), replaceStr); ```
How to replace a plus character using Java's String.replaceAll method
[ "", "java", "regex", "" ]
In a C# winforms app what is the normal way to persist the data on form that is opened by another form? I'd planned on just keeping it all on the form object but when the form is closed it seems the that form object is disposed. meaning I loose all the data. I could wrap the form up in another object which takes all the data off it but that seems like a lot of work. Is there a way to just hide the form when it is closed rather than disposing of it?
On closing a form is not Disposed. Generally this is how the data is managed. ``` Result res; using (MyForm form = new MyForm()) { if(form.ShowDialog()== DialogResult.OK) { // In Myform, after the data collection is done, you can set DialogResult=DialogResult.Ok and close form using form.Close(); res = form.Result; // expose forms data as result. } } UserResult(res); ```
2 possibilities: 1)catch the close event and just hide it. Create functions (to the hidden form) to get the input values using properties. ``` private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { this.Visible = false; e.Cancel = true; } ``` 2)And what Moj tells: if you close the form after you created it, the form object will still be alive and can be accessed I favor 2) + the properties
Persisting form data in Win forms applications
[ "", "c#", "winforms", "" ]
I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month". i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that. Any suggestions?
I'm not entirely sure, but you might look at the Python [DateUtil](http://labix.org/python-dateutil) module.
Neither mxDateTime nor Datejs nor that webservice support "last thursday of the month". The OP wants to know all of the last thursdays of the month for, say, a full year. mxDateTime supports the operations, but the question must be posed in Python code, not as a string. The best I could figure is [parsedatetime](http://code.google.com/p/parsedatetime/), but that doesn't support "last thursday of the month". It does support: ``` >>> c.parseDateText("last thursday of april 2001") (2001, 4, 20, 13, 55, 58, 3, 64, 0) >>> c.parseDateText("last thursday of may 2001") (2001, 5, 20, 13, 56, 3, 3, 64, 0) >>> c.parseDateText("last thursday of may 2010") (2010, 5, 20, 13, 56, 7, 3, 64, 0) >>> ``` (Note that neither DateJS nor that web service support this syntax.) **EDIT**: Umm, okay, but while the year and the month are right, the day isn't. The last thursday of april 2001 was the 27th. I think you're going to have to roll your own solution here. It does not support: ``` >>> c.parseDateText("last thursday of 2010") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "parsedatetime/parsedatetime.py", line 411, in parseDateText mth = self.ptc.MonthOffsets[mth] KeyError >>> ``` So one possibility is text substitution: normalize the string to lowercase, single spaces, etc. then do a string substitution of "the month" for each of the months you're interested in. You'll likely have to tweak any solution you find. For example, in some [old code of Skip Montanaro](http://web.archive.org/web/20050309211440/manatee.mojam.com/~skip/python/dates.py) which he wrote for an online music calendering system: ``` # someone keeps submitting dates with september spelled wrong... 'septmber':9, ``` Or you write your own parser on top of mxDateTime, using all of the above links as references.
Tool/library for calculating intervals like "last thursday of the month"
[ "", "python", "datetime", "date", "" ]
I am looking for a version of the gcc (C++) compiler targeting the ARM uP and WindowsCE operating system. Thus far I have only been able to locate compilers which either target the ARM uP but produce ELF executables (GNUARM etc) or they do target windows CE but have not been updated since 2003. I believe the exact name of the compiler I am looking for is `arm-wince-pe-gcc` as mentioned In the GCC documentation but I have no clue how to get hold of a binary. Any/all help will be greatly appreciated.
I found a binary version of the required compiler here: <http://sourceforge.net/project/showfiles.php?group_id=173455&package_id=198682> choose 0.51.0/cygwin-cegcc-cegcc-0.51.0-1.tar.gz file for download.
I'm using CEGCC from SourceForce: [<http://cegcc.sourceforge.net/>](http://cegcc.sourceforge.net/), and so far it works OK. I've managed to build a Windows API application, zlib and libpng, and everything runs just fine on Windows CE 5.0, and the C code you write is the same one you'd write in Visual Studio. Use the mingw32ce toolchain from there. Build the toolchain yourself, from the latest SVN sources. I use this under Linux, but it should work under Cygwin as well I'm guessing.
Where can I find the binaries for arm-wince-pe-gcc?
[ "", "c++", "windows-ce", "" ]
In the following: ``` <select id="test"> <option value="1">Test One</option> <option value="2">Test Two</option> </select> ``` How can I get the text of the selected option (i.e. "Test One" or "Test Two") using JavaScript `document.getElementsById('test').selectedValue` returns 1 or 2, what property returns the text of the selected option?
``` function getSelectedText(elementId) { var elt = document.getElementById(elementId); if (elt.selectedIndex == -1) return null; return elt.options[elt.selectedIndex].text; } var text = getSelectedText('test'); ```
If you use jQuery then you can write the following code: ``` $("#selectId option:selected").html(); ```
Retrieving the text of the selected <option> in <select> element
[ "", "javascript", "html", "dom", "" ]
I tried overriding `__and__`, but that is for the & operator, not *and* - the one that I want. Can I override *and*?
You cannot override the `and`, `or`, and `not` boolean operators.
No you can't override `and` and `or`. With the behavior that these have in Python (i.e. short-circuiting) they are more like control flow tools than operators and overriding them would be more like overriding `if` than + or -. You *can* influence the truth value of your objects (i.e. whether they evaluate as true or false) by overriding `__nonzero__` (or `__bool__` in Python 3).
Any way to override the and operator in Python?
[ "", "python", "" ]
I have a menu with the following structure (simplified for illustration purposes): ``` Menu Bar |--File | |--Save | |--Exit |--Tools | |--Tool Category 1 | |--Tool Category 2 | |--Tool Category 3 |--Help |--About ``` I want to reconstruct this as follows: ``` Menu Bar |--File | |--Save | |--Exit |--Tool Category 1 |--Tool Category 2 |--Tool Category 3 |--Help |--About ``` However, in Visual Studio 2008 Pro it won't let me drag these menu items other than reorganize them within the particular menu group they are already in. Is there a way for me to move them without completely rebuilding the menu bar? Note that there are actually many more menu items than those that I've shown.
I tried this and it worked: 1. Right click on the menu item you want to move 2. Select "Cut" in the context menu 3. Right click on the menu strip where you want to move it 4. Select "Paste" in the context menu Hope it helps.
You can also go to the Designer Code for the Menu Items. You will find code similar to: ``` this.mnuInfo.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.mniAddNewProject, this.mniAddNewWorkFlow, this.mniDeleteProject } ); ``` Add the menu item into which you want to move your existing menu items and then modify then move the items. ``` this.mnuInfo.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.mniAddNewProject } ); this.newMenuItem.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.mniAddNewWorkFlow, this.mniDeleteProject } ); ``` And that's it. I hope this helps.
Moving a menu in Visual C#
[ "", "c#", "visual-studio", "visual-studio-2008", "" ]
According to a school assignment, only one property of the Document object can be dynamically changed after a Web page is rendered. Is it body or cookie?
You can manipulate the body contents, but can't assign to the body property. It's a readonly property. You can however set or get the cookies associated with the document. Reference: <http://www.w3schools.com/htmldom/dom_obj_document.asp>
The assignment is wrong: all of the following properties have special meaning in the DOM and are writeable: * alinkColor * bgColor * cookie * fgColor * linkColor * title * vlinkColor The list above should work across different browsers. There are others (like `charset` and `defaultCharset` for IE, or [some of these](https://developer.mozilla.org/en/DOM/document#Properties) for Geckos) which don't, and not all of them are [standard](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-1006298752).
Javascript: What Document object property can be dynamically rendered after a Web page is rendered?
[ "", "javascript", "dom", "" ]
I have recently joined a project that is using multiple different projects. A lot of these projects are depending on each other, using JAR files of the other project included in a library, so anytime you change one project, you have to then know which other projest use it and update them too. I would like to make this much easier, and was thinking about merging all this java code into one project in seperate packages. Is it possible to do this and then deploy only some of the packages in a jar. I would like to not deploy only part of it but have been sassked if this is possible. Is there a better way to handle this?
### Approach 1: Using Hudson If you use a continuous integration server like [Hudson](http://hudson-ci.org/), then you can configure upstream/downstream projects (see [Terminology](http://wiki.hudson-ci.org/display/HUDSON/Terminology)). > A project can have one or several downstream projcets. The downstream projects are added to the build queue if the current project is built successfully. It is possible to setup that it should add the downstream project to the call queue even if the current project is unstable (default is off). What this means is, if someone checks in some code into one project, at least you would get early warning if it broke other builds. ### Approach 2: Using Maven If the projects are not too complex, then perhaps you could create a main project, and make these sub-projects child modules of this project. However, mangling a project into a form that Maven likes can be quite tricky.
If you use Eclipse (or any decent IDE) you can just make one project depend on another, and supply that configuration aspect in your SVN, and assume checkouts in your build scripts. Note that if one project depends on a certain version of another project, the Jar file is a far simpler way to manage this. A major refactoring could immediately means lots of work in all the other projects to fix things, whereas you could just drop the new jar in to each project as required and do the migration work then.
Multiple Java projects and refactoring
[ "", "java", "refactoring", "package", "packaging", "" ]
I just posted a question about how to get a delegate to update a textbox on another form. Just when I thought I had the answer using Invoke...this happens. Here is my code: **Main Form Code:** ``` using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using System.Data.OleDb; using System.Collections.Specialized; using System.Text; using System.Threading; delegate void logAdd(string message); namespace LCR_ShepherdStaffupdater_1._0 { public partial class Main : Form { public Main() { InitializeComponent(); } public void add(string message) { this.Log.Items.Add(message); } public void logAdd(string message) { /////////////////////////// COMPILER ERROR BELOW /////////// this.Invoke(new logAdd(add), new object[] { message }); // Compile error occurs here }////////////////////////////// COMPILER ERROR ABOVE /////////// private void exitProgramToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void aboutToolStripMenuItem1_Click(object sender, EventArgs e) { Form aboutBox = new AboutBox1(); aboutBox.ShowDialog(); } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { } private void settingsToolStripMenuItem1_Click(object sender, EventArgs e) { settingsForm.settings.ShowDialog(); } private void synchronize_Click(object sender, EventArgs e) { string message = "Here my message is"; // changed this ErrorLogging.updateLog(message); // changed this } } public class settingsForm { public static Form settings = new Settings(); } } ``` **Logging Class Code:** ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LCR_ShepherdStaffupdater_1._0 { public class Logging { static Main mainClass = new Main(); static logAdd logAddDelegate; public static void updateLog(string message) { logAddDelegate = mainClass.logAdd; logAddDelegate(message); } } } ``` * **Compile Error:** *InvalidOperationException was unhandled - Invoke or BeginInvoke cannot be called on a control until the window handle has been created.* I already tried to create a handle on the Log item...but that didn't work. The problem is I have NO CLUE what I am doing and I have searched Google **extensively** only to find vague answers. Please tell me how to create the handle before I invoke this delegate. While you are at it, give me some ways I can make this code more simple. For example, I dont want two Add functions... I had to do that because there was no way for me to find an item to invoke from the Logging class. Is there a better way to accomplish what I need to do? Thank you!!! **EDIT:** My project is fairly large, but these are the only items causing this specific problem. **Log** is my RichTextBox1 (Log.Items.Add(message)) I renamed it to Log so it is easier to retype. I am calling updateLog(message) from a different form though...let me update that in here (although it makes no difference where I call updateLog(message) from it still gives me this error) You guys are going to have to make things more simpler for me...and provide examples. I don't understand HALF of everything you guys are saying here...I have no clue on how to work with Invoking of methods and Handles. I've researched the crap out of it too... **SECOND EDIT:** I believe I have located the problem, but do not know how to fix it. In my logging class I use this code to create mainClass: **static Main mainClass = new Main();** I am creating a entirely new blueprint replica to Main(), including **Log** (the richtextbox I am trying to update) When I call updateLog(message) I believe I am trying to update the Log (richtextbox) on the second entity of Main() otherwise known as mainClass. Of course, doing so will throw me this exception because I haven't even seen that replica of the current Main I am using. This is what I am shooting for, thanks to one of the people that gave an answer: ``` Main mainClass = Application.OpenForms.OfType<Main>().First(); logAddDelegate = mainClass.logAdd; logAddDelegate(message); ``` I need to create mainClass not with the new() operator because I dont want to create a new blueprint of the form I want to be able to edit the current form. The above code doesn't work though, I can't even find Application. Is that even C# syntax? If I can get the above code to work, I think I can resolve my issue and finally lay this problem to rest after a couple of HOURS of seeking for answers. **FINAL EDIT:** I figured it out thanks to one of the users below. Here is my updated code: **Main Form Code:** ``` using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using System.Data.OleDb; using System.Collections.Specialized; using System.Text; using System.Threading; delegate void logAdd(string message); namespace LCR_ShepherdStaffupdater_1._0 { public partial class Main : Form { private static Main mainFormForLogging; public static Main MainFormForLogging { get { return mainFormForLogging; } } public Main() { InitializeComponent(); if (mainFormForLogging == null) { mainFormForLogging = this; } } public void add(string message) { this.Log.Items.Add(message); } public void logAdd(string message) { this.Log.BeginInvoke(new logAdd(add), new object[] { message }); } private void exitProgramToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void aboutToolStripMenuItem1_Click(object sender, EventArgs e) { Form aboutBox = new AboutBox1(); aboutBox.ShowDialog(); } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { } private void settingsToolStripMenuItem1_Click(object sender, EventArgs e) { settingsForm.settings.ShowDialog(); } private void synchronize_Click(object sender, EventArgs e) { add("test"); Logging.updateLog("testthisone"); //DatabaseHandling.createDataSet(); } } public class settingsForm { public static Form settings = new Settings(); } } ``` **Logging Class Code:** ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LCR_ShepherdStaffupdater_1._0 { public class Logging { static Main mainClass = Main.MainFormForLogging; static logAdd logAddDelegate; public static void updateLog(string message) { logAddDelegate = mainClass.logAdd; logAddDelegate(message); } } } ```
Right, I'm going to start again. In order to understand what is happening, you need to understand how .NET and Windows relate to one another. .NET runs on Windows and wraps many of the native, Win32 concepts like a window, a listview, an editbox (the Win32 name for a standard textbox). This means that you can have a valid .NET instance of a TextBox or a Form, but not have the underlying Windows version of that item (EditBox, or Window) yet. When HandleCreated is true, the Windows version of the item is created. Your issue is occurring because something is leading to the logAdd method being called before the Form's Window has been created. This means somewhere during your startup after the Form instance has been instantiated but before the Window handle has been created, something is trying to call logAdd. If you add a breakpoint to logAdd, you should be able to see what is doing that call. What you will find is that the call is being made on the Main instance you create in your logger class and NOT the Main instance that is actually running. As the logger instance never gets shown, the window handle is not created, and so you get your error. The general way an application runs is to call Application.Run(new Main()) in your startup method, which is usually in the Program class and called Main. You need your logger to point to this instance of main. There are several ways to get the instance of the form, each with its own caveats, but for simplicity you could expose the instance off the Main class itself. For example: ``` public partial class Main : Form { private static Main mainFormForLogging; public static Main MainFormForLogging { get { return mainFormForLogging; } } public Main() { InitializeComponent(); if (mainFormForLogging == null) { mainFormForLogging = this; } } protected void Dispose(bool disposing) { if (disposing) { if (this == mainFormForLogging) { mainFormForLogging = null; } } base.Dispose(disposing); } } ```
I have solved this in the past using the following method: ``` private void invokeOnFormThread(MethodInvoker method) { if (IsHandleCreated) Invoke(new EventHandler(delegate { method(); })); else method(); } ``` Call `invokeOnFormThread` instead of Invoke. It will only use the form's thread if a handle has already been created, otherwise it will use the caller's thread.
C# compile error: "Invoke or BeginInvoke cannot be called on a control until the window handle has been created."
[ "", "c#", "delegates", "invoke", "handle", "runtime-error", "" ]
I am trying to use an ajax 'POST' call through the jquery $.ajax function to send data to a php file. For some reason the callback is a success but the data is not getting to the php file. Here is an example of the code: ``` In JS file: $.ajax({ type: "POST", url: "setData.php", data: "myPOSTvar=myData" success: function(){ alert("Data Saved"); } }); In php file: $var = $_POST['myPOSTvar'] ... ``` $var ends up with a default value instead of the data it is sent. Any ideas? Sorry about the syntax errors...at work right now and don't have my code in front of me...the syntax is all correct in the actual script, just typed to quick when posting here...
Try this and see if you get any info. ``` $.post("setData.php", { myPOSTvar: "myData" }, function(data){ alert("Data saved"); }); ```
I doubt it's a success, the url should be a string : url: `"setData.php"` .
AJAX/JQUERY/PHP issue
[ "", "php", "jquery", "ajax", "" ]
Google maps is an impressive display of what you can do with JavaScript and Ajaxy-goodness. Even my mouse scroll wheel and right-click works to provide specific functionality. In the standard HTML spec, I don't see an `onmouserightclick` event or similar basic JavaScript handling for the mouse wheel. Maybe I am looking in the wrong places. I presume these events are browser and platform-specific (or "sensitive" instead of specific). And am wondering what the basic, plain HTML and JavaScript are needed to exploit these events, in ALL browsers. Naturally, when designing a site these features have to be extra since some people still use the one-button mouse. How to I use events with the mouse wheel and right-click? I'm looking for sample code. **EDIT:** Thanks for the jQuery code guys! The system-developer in me still has questions and doubts though. Mainly I'm concerned about platform-limitations that would seem to apply here. Is there a browser that some of these features don't work in? Does the mouse wheel up and down events also allow for mouse wheel click events? I would just expect there to be some limitation out there and am wondering if it's officially documented. I want to know how it works at a low level. I am glad to see it is easy in jQuery, another reason for me to get into it.
***Mouse Wheel***: ol' no-jquery-or-prototype-library method: [here](http://adomas.org/javascript-mouse-wheel/) Prototype method: [Here](http://www.ogonek.net/mousewheel/demo.html) JQuery method: [Here](http://www.ogonek.net/mousewheel/jquery-demo.html)
If you're using jQuery, it's extremely simple to do things with the right click menu : ``` $(document).bind("contextmenu",function(e){ alert("You right clicked!"); return false; //disable the context menu }); ``` Otherwise, you can use this script, provided by quirskmode: <http://www.quirksmode.org/js/events_properties.html#link6> As for the mouse wheel, this a great script that I've used in the past: <http://adomas.org/javascript-mouse-wheel/>
Special mouse events in a browser: wheel, right-click?
[ "", "javascript", "cross-browser", "sample", "mousewheel", "right-click", "" ]
I'm trying to convince a page that it is the window.top even though it is in an iframe. In FF you can do window.**defineGetter**('top', function() { return window}); in Webkit (Safari/Chrome) you can simply do window.top = window but in IE none of those methods work. Anyone done this before?
Setting window.top doesn't work. Its not allowed in IE. I ended up having to make my own fake window object, fill it with most of the properties of the window object, and then making a fake .top property.
I'd maybe try using the "define getter" notation that John Resig uses in his [article on the topic](http://ejohn.org/blog/javascript-getters-and-setters/): `Window.prototype.__defineGetter__('top',function(){return this;});`
IE Overwrite window.top
[ "", "javascript", "internet-explorer", "dom", "" ]
I'm Jason. I'm having a bit of a problem with the Substance look and feel (<https://substance.dev.java.net/>). My problem is more general. I've already got my GUI written and it works fine, but when I use a Substance Look-and-feel, it requires all GUI initialization to take place in the EDT thread (Event Dispatching Thread or something). Right now I'm using com.sun.java.swing.plaf.windows.WindowsLookAndFeel (not sure if I spelled that right) and it doesn't require anything of this sort. So I put the main initialization into the EDT by calling SwingUtilities.invokeLater(). This made it work. However, the program also spawns several other windows during its execution. Right now I have code like: ``` SomeNewWindow window = new SomeNewWindow(); // ... some bs emitted window.doStuff(); ``` This code works fine because by the time window.doStuff() is called, it's already initialized. But Substance requires me to do something like this: ``` SwingUtilities.invokeLater(new Runnable(){ public void run(){ SomeNewWindow window = new SomeNewWindow(); }}); // ... bs emitted window.doStuff(); ``` Here it sometimes throws a NullPointerException because window is not initialized by the time window.doStuff() is called. I can't put window.doStuff() into the EDT thread because it usually takes several seconds to return and will hang the GUI. I've tried putting Thread.sleep(1000) right after I invoke the EDT thread because it's probably initialized by then. But this seems awkward. I simply need a way for the main thread to 'know' when the SomeNewWindow initialization has returned so it can continue on without having to worry about a NullPointerException. Thanks in advance.
You could switch from invokeLater to invokeAndWait, which will wait until the window is created. It's a bit cheesy, but not as bad as putting in a sleep.
Is there a reason why you can't just move the doStuff() call into the invokeLater callback? ``` SwingUtilities.invokeLater(new Runnable(){ public void run(){ SomeNewWindow window = new SomeNewWindow(); window.doStuff(); } }); ``` If the above is impossible, I'd go with `invokeAndWait()` instead of `invokeLater()`, as Paul Tomblin already suggested.
Java: GUIs must be initialized in the EDT thread?
[ "", "java", "multithreading", "user-interface", "swing", "look-and-feel", "" ]
I'm trying to render images with verdana text using PHP imagettftext function. However, all east asian characters are not being rendered correctly. I tried using other fonts like tahoma and Lucida Grande, but neither works. Arial Unicode, however, works perfectly. The problem is that I don't want to use Arial as my font. Is there any way I could render using a font like Verdana? (not a unicode and/or font expert; so explanation of the problem would be helpful)
None of Verdana, Tahoma or Lucida Grande contain Chinese/Japanese/Korean characters so they will never be able to render them “correctly”. No font contains glyphs for *every* Unicode code point, so whichever you pick you're going to end up with missing glyphs at some point. There *is* a font that is like Verdana and contains some CJK characters — specifically Japanese kanji. Maybe that's enough to cover what you're trying to do? It's called Meiryo and comes with Windows Vista/7. You can also get it [here](http://www.microsoft.com/downloads/details.aspx?FamilyID=f7d758d2-46ff-4c55-92f2-69ae834ac928&displaylang=en). However it is a TrueType Collection (.ttc) file, which I'm not sure if PHP/GD can handle directly; many East Asian fonts come as .ttc files, because they typically contain both proportional and monospace fonts based on the same glyph shapes. If PHP can't cope with .ttc, you might need to convert the Meiryo-proportional font out of it into a separate .ttf file, using either a font editor, or the simple ‘breakttc.exe’ command-line tool from the TrueType SDK (ttsdk.zip, mysteriously vanished from microsoft.com, but easily locatable using Google).
IIRC your truetype font must have unicode characters within it. You can see how many characters a certain font has in the Character Map tool in windows.
East Asian Characters rendered as squares with PHP imagettftext()
[ "", "php", "unicode", "fonts", "" ]
It is said that Blitz++ provides *near-Fortran performance*. Does Fortran actually tend to be faster than regular C++ for equivalent tasks? What about other HL languages of exceptional runtime performance? I've heard of a few languages suprassing C++ for certain tasks... Objective Caml, Java, D... I guess GC can make much code *faster*, because it removes the need for excessive copying around the stack? (assuming the code is *not* written for performance) I am asking out of curiosity -- I always assumed C++ is pretty much unbeatable barring expert ASM coding.
Fortran is faster and almost always better than C++ for purely numerical code. There are many reasons why Fortran is faster. It is the oldest compiled language (a lot of knowledge in optimizing compilers). It is still THE language for numerical computations, so many compiler vendors make a living of selling optimized compilers. There are also other, more technical reasons. Fortran (well, at least Fortran77) does not have pointers, and thus, does not have the aliasing problems, which plague the C/C++ languages in that domain. Many high performance libraries are still coded in Fortran, with a long (> 30 years) history. Neither C or C++ have any good array constructs (C is too low level, C++ has as many array libraries as compilers on the planet, which are all incompatible with each other, thus preventing a pool of well tested, fast code).
Whether fortran is faster than c++ is a matter of discussion. Some say yes, some say no; I won't go into that. It depends on the compiler, the architecture you're running it on, the implementation of the algorithm ... etc. Where fortran *does have* a big advantage over C is the time it takes you to implement those algorithms. And that makes it extremely well suited for any kind of numerical computing. I'll state just a few obvious advantages over C: * 1-based array indexing (tremendously helpful when implementing larger models, and you don't have to think about it, but just *FORmula TRANslate* * has a power operator (`**`) (*God, whose idea was that a power function will do ? Instead of an operator?!*) * it has, I'd say the best support for multidimensional arrays of all the languages in the current market (and it doesn't seem that's gonna change so soon) - `A(1,2)` just like in math * not to mention avoiding the loops - A=B\*C multiplies the arrays (almost like matlab syntax with *compiled speed*) * it has parallelism features built *into the language* (check the new standard on this one) * very easily connectible with languages like C, python, so you can make your heavy duty calculations in fortran, while .. whatever ... in the language of your choice, if you feel so inclined * completely backward compatible (since whole F77 is a subset of F90) so you have whole century of coding at your disposal * *very very portable* (this might not work for some compiler extensions, but in general it works like a charm) * problem oriented solving community (since fortran users are usually not cs, but math, phy, engineers ... people with no programming, but rather problem solving experience whose knowledge about *your* problem can be very helpful) Can't think of anything else off the top of my head right now, so this will have to do.
Languages faster than C++
[ "", "c++", "programming-languages", "performance", "" ]
I need to create a bunch of timer as local variable to do something like: ``` void Foo() { Timer t = new Timer(myTimerCallback,null,1000,Timeout.Infinite); } ``` Unfortunately, some of them are collected by GC before them invoke myTimerCallback after 1 second. Since I have so many Timers, it's impossible to store them in private static member. And it's also hard to find a place to put GC.Keeplive(t). How can I make each timer to do their thing before dying?
You can store them in a collection to keep a reference and in the event method remove the reference from the collection. I think you need to use the state parameter to identify the timer in the collection (pass a reference to the timer or a key in the collection as state parameter in the "new timer" statement). Please note that the callback functions are executed on other threads, so you will/may have multiple callback functions running simultaneously. Use locking to ensure that adding/removing references is done safely.
Your best bet is to store them in a member variable and then dispose of them when you no longer need them.
How to prevent my Timer from GC collecting before its callback excuted?
[ "", "c#", "" ]
I'm looking for a good JavaScript equivalent of the C/PHP `printf()` or for C#/Java programmers, `String.Format()` (`IFormatProvider` for .NET). My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good. I realize Microsoft's [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) library provides a version of `String.Format()`, but we don't want the entire overhead of that framework.
## Current JavaScript From ES6 on you could use template strings: ``` let soMany = 10; console.log(`This is ${soMany} times easier!`); // "This is 10 times easier!" ``` See Kim's [answer](https://stackoverflow.com/a/32202320/2430448) below for details. --- ## Older answer Try [sprintf() for JavaScript](https://github.com/alexei/sprintf.js). --- If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously. Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this: ``` "{0}{1}".format("{1}", "{0}") ``` Normally you would expect the output to be `{1}{0}` but the actual output is `{1}{1}`. So do a simultaneous replacement instead like in [fearphage’s suggestion](https://stackoverflow.com/questions/610406/javascript-printf-string-format/4673436#4673436).
Building on the previously suggested solutions: ``` // First, checks if it isn't implemented yet. if (!String.prototype.format) { String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; } ``` `"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")` outputs > ASP is dead, but ASP.NET is alive! ASP {2} --- If you prefer not to modify `String`'s prototype: ``` if (!String.format) { String.format = function(format) { var args = Array.prototype.slice.call(arguments, 1); return format.replace(/{(\d+)}/g, function(match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; } ``` Gives you the much more familiar: `String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');` with the same result: > ASP is dead, but ASP.NET is alive! ASP {2}
JavaScript equivalent to printf/String.Format
[ "", "javascript", "printf", "string.format", "" ]
I try to put an event on document loading but not works... I'd put an alert box, but never seen it... ``` document.addEventListener ("load",initEventHandlers,false); function initEventHandlers () { document.getElementbyId ('croixzoom').addEventListener ('click',fermezoom,false); alert ("Hello, i\'m a eventHAndlers") } function fermezoom (){ document.getElementbyId ('zoom').style.visibility = 'hidden'; document.getElementbyId ('fondzoom').style.visibility = 'hidden'; } ``` Thanks for you help
The document does not have an onload / load event, try attaching it to 'window': ``` window.addEventListener ("load",initEventHandlers,false); ```
What about: ``` window.onload = initEventHandlers; ``` This will work for you.
Event 'load' doesn't work on JavaScript
[ "", "javascript", "events", "" ]
Which is more widely supported: `window.onload` or `document.onload`?
## When do they fire? [`window.onload`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload) * By default, it is fired when the entire page loads, **including** its content (images, CSS, scripts, etc.). In some browsers it now takes over the role of `document.onload` and fires when the DOM is ready as well. `document.onload` * It is called when the DOM is ready which can be **prior** to images and other external content is loaded. ## How well are they supported? `window.onload` appears to be the most widely supported. In fact, some of the most modern browsers have in a sense replaced `document.onload` with `window.onload`. Browser support issues are most likely the reason why many people are starting to use libraries such as [jQuery](http://jquery.com/) to handle the checking for the document being ready, like so: ``` $(document).ready(function() { /* code here */ }); $(function() { /* code here */ }); ``` --- For the purpose of history. `window.onload` vs `body.onload`: > A similar question was asked on codingforums a while > back regarding the usage of `window.onload` over `body.onload`. The > result seemed to be that you should use `window.onload` because it is > good to separate your structure from the action.
The general idea is that **window.onload fires** when the document's window is **ready for presentation** and **document.onload fires** when the **DOM tree** (built from the markup code within the document) is **completed**. Ideally, subscribing to [DOM-tree events](http://en.wikipedia.org/wiki/DOM_events), allows offscreen-manipulations through Javascript, incurring **almost no CPU load**. Contrarily, **`window.onload`** can **take a while to fire**, when multiple external resources have yet to be requested, parsed and loaded. **►Test scenario:** To observe the difference and **how your browser** of choice **implements** the aforementioned **event handlers**, simply insert the following code within your document's - `<body>`- tag. ``` <script language="javascript"> window.tdiff = []; fred = function(a,b){return a-b;}; window.document.onload = function(e){ console.log("document.onload", e, Date.now() ,window.tdiff, (window.tdiff[0] = Date.now()) && window.tdiff.reduce(fred) ); } window.onload = function(e){ console.log("window.onload", e, Date.now() ,window.tdiff, (window.tdiff[1] = Date.now()) && window.tdiff.reduce(fred) ); } </script> ``` **►Result:** Here is the resulting behavior, observable for Chrome v20 (and probably most current browsers). * No `document.onload` event. * `onload` fires twice when declared inside the `<body>`, once when declared inside the `<head>` (where the event then acts as `document.onload` ). * counting and acting dependent on the state of the counter allows to emulate both event behaviors. * Alternatively declare the `window.onload` event handler within the confines of the HTML-`<head>` element. **►Example Project:** The code above is taken from [this project's](https://github.com/lsauer/KeyBoarder/tree/gh-pages) codebase (`index.html` and `keyboarder.js`). --- For a list of [event handlers of the window object](https://developer.mozilla.org/en-US/docs/DOM/window#Event_handlers), please refer to the MDN documentation.
window.onload vs document.onload
[ "", "javascript", "event-handling", "dom-events", "" ]
I'm sure you all know the behaviour I mean - code such as: ``` Thread thread = new Thread(); int activeCount = thread.activeCount(); ``` provokes a compiler warning. Why isn't it an error? **EDIT:** To be clear: question has nothing to do with Threads. I realise Thread examples are often given when discussing this because of the potential to really mess things up with them. But really the problem is that such usage is *always* nonsense and you can't (competently) write such a call and mean it. Any example of this type of method call would be barmy. Here's another: ``` String hello = "hello"; String number123AsString = hello.valueOf(123); ``` Which makes it look as if each String instance comes with a "String valueOf(int i)" method.
Basically I believe the Java designers made a mistake when they designed the language, and it's too late to fix it due to the compatibility issues involved. Yes, it can lead to very misleading code. Yes, you should avoid it. Yes, you should make sure your IDE is configured to treat it as an error, IMO. Should you ever design a language yourself, bear it in mind as an example of the kind of thing to avoid :) Just to respond to DJClayworth's point, here's what's allowed in C#: ``` public class Foo { public static void Bar() { } } public class Abc { public void Test() { // Static methods in the same class and base classes // (and outer classes) are available, with no // qualification Def(); // Static methods in other classes are available via // the class name Foo.Bar(); Abc abc = new Abc(); // This would *not* be legal. It being legal has no benefit, // and just allows misleading code // abc.Def(); } public static void Def() { } } ``` Why do I think it's misleading? Because if I look at code `someVariable.SomeMethod()` I expect it to *use the value of `someVariable`*. If `SomeMethod()` is a static method, that expectation is invalid; the code is tricking me. How can that possibly be a *good* thing? Bizarrely enough, Java won't let you use a potentially uninitialized variable to call a static method, despite the fact that the only information it's going to use is the declared type of the variable. It's an inconsistent and unhelpful mess. Why allow it? EDIT: This edit is a response to Clayton's answer, which claims it allows inheritance for static methods. It doesn't. Static methods just aren't polymorphic. Here's a short but complete program to demonstrate that: ``` class Base { static void foo() { System.out.println("Base.foo()"); } } class Derived extends Base { static void foo() { System.out.println("Derived.foo()"); } } public class Test { public static void main(String[] args) { Base b = new Derived(); b.foo(); // Prints "Base.foo()" b = null; b.foo(); // Still prints "Base.foo()" } } ``` As you can see, the execution-time value of `b` is completely ignored.
Why should it be an error? The instance has access to all the static methods. The static methods can't change the state of the instance (trying to *is* a compile error). The problem with the well-known example that you give is very specific to *threads*, not static method calls. It looks as though you're getting the `activeCount()` for the thread referred to by `thread`, but you're really getting the count for the calling thread. This is a logical error that you as a programmer are making. Issuing a warning is the appropriate thing for the compiler to do in this case. It's up to you to heed the warning and fix your code. EDIT: I realize that the syntax of the language is what's *allowing* you to write misleading code, but remember that the compiler and its warnings are part of the language too. The language allows you to do something that the compiler considers dubious, but it gives you the warning to make sure you're aware that it could cause problems.
Why isn't calling a static method by way of an instance an error for the Java compiler?
[ "", "java", "static", "methods", "" ]
Are there any performance drawbacks in SQL to joining a table on a char (or varchar) value, as opposed to say joining on an integer value?
There are performance *considerations* related to the size of the join column. An integer is 4 bytes wide - so any char value larger than 4 bytes requires more disk I/O, cache space, etc. Obviously, a char(5) wouldn't affect much, but a char(4000) would be extraordinarily wasteful. Double the char sizes if you use unicode types. Usually this question comes up in the context of natural vs surrogate keys. In that argument, the size of the datatype is not the only factor - as you can often avoid a join with a natural (char) key. Of course, neither one is likely to be the bottleneck in your application - so design with impunity (at least in this area).
Joining on a char or var char will normally have an overhead as opposed to joining on an int. There are two factors I'm aware of when comparing chars: - collation has to be taken account of - char fields have more data to be compared\* \*(each character is represented by 8 bits, a 10 char value is thus 80 bits long, compared to 32 bits for an int) \*(this is 16 bits per character if using NCHAR or NVARCHAR)
joins on ints vs joins on chars (or varchars)
[ "", "sql", "join", "" ]
I there a method to allow me to use an array as an object? I have the following code in my main class ``` function __construct() { require 'config.php'; $this->config = new PHPSO_Config(); } ``` where the PHPSO\_Config class looks something like this ``` class PHPSO_Config { /** * The administrators email address */ var $adminEmail = 'user@domain.tld'; //I'm using this email to test } ``` so can I accomplish the same thing and be able to access the config vars as an object without creating a second class?
You can cast an array to an object using ``` $myObject = (object) $myarray; ``` thus the following should work (untested): ``` function __construct() { require 'config.php'; $this->config = (object) array("username" => "root"); } ``` then $class->config->username should work.
You could use [PHP5 overloading](http://uk.php.net/manual/en/language.oop5.overloading.php) to make it seem that your class has the properties provided by the config class, e.g. something like this: ``` class MyClass { private $config; function __construct() { require 'config.php'; $this->config = new PHPSO_Config(); } public function __get($name) { if (property_exists($this->config, $name)) { return $this->config->$name; } return null; } ``` Then doing something like this: ``` $config=new MyClass; echo $config->adminEmail; ``` Would result in seeing the adminEmail member variable of the internal config class. This is almost a [Strategy Pattern](http://en.wikipedia.org/wiki/Strategy_pattern), where the runtime implementation of a class can be selected at runtime.
Arrays as objects
[ "", "php", "oop", "class", "" ]
I am trying to create a thread in C++ (Win32) to run a simple method. I'm new to C++ threading, but very familiar with threading in C#. Here is some pseudo-code of what I am trying to do: ``` static void MyMethod(int data) { RunStuff(data); } void RunStuff(int data) { //long running operation here } ``` I want to to call *RunStuff* from *MyMethod* without it blocking. What would be the simplest way of running *RunStuff* on a separate thread? **Edit:** I should also mention that I want to keep dependencies to a minimum. (No MFC... etc)
``` #include <boost/thread.hpp> static boost::thread runStuffThread; static void MyMethod(int data) { runStuffThread = boost::thread(boost::bind(RunStuff, data)); } // elsewhere... runStuffThread.join(); //blocks ```
C++11 available with more recent compilers such as Visual Studio 2013 has threads as part of the language along with quite a few other nice bits and pieces such as lambdas. The include file `threads` provides the thread class which is a set of templates. The thread functionality is in the `std::` namespace. Some thread synchronization functions use `std::this_thread` as a namespace (see [Why the std::this\_thread namespace?](https://stackoverflow.com/questions/15032692/why-the-stdthis-thread-namespace) for a bit of explanation). The following console application example using Visual Studio 2013 demonstrates some of the thread functionality of C++11 including the use of a lambda (see [What is a lambda expression in C++11?](https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11)). Notice that the functions used for thread sleep, such as `std::this_thread::sleep_for()`, uses duration from `std::chrono`. ``` // threading.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <chrono> #include <thread> #include <mutex> int funThread(const char *pName, const int nTimes, std::mutex *myMutex) { // loop the specified number of times each time waiting a second. // we are using this mutex, which is shared by the threads to // synchronize and allow only one thread at a time to to output. for (int i = 0; i < nTimes; i++) { myMutex->lock(); std::cout << "thread " << pName << " i = " << i << std::endl; // delay this thread that is running for a second. // the this_thread construct allows us access to several different // functions such as sleep_for() and yield(). we do the sleep // before doing the unlock() to demo how the lock/unlock works. std::this_thread::sleep_for(std::chrono::seconds(1)); myMutex->unlock(); std::this_thread::yield(); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { // create a mutex which we are going to use to synchronize output // between the two threads. std::mutex myMutex; // create and start two threads each with a different name and a // different number of iterations. we provide the mutex we are using // to synchronize the two threads. std::thread myThread1(funThread, "one", 5, &myMutex); std::thread myThread2(funThread, "two", 15, &myMutex); // wait for our two threads to finish. myThread1.join(); myThread2.join(); auto fun = [](int x) {for (int i = 0; i < x; i++) { std::cout << "lambda thread " << i << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } }; // create a thread from the lambda above requesting three iterations. std::thread xThread(fun, 3); xThread.join(); return 0; } ```
Simple C++ Threading
[ "", "c++", "multithreading", "winapi", "" ]
I've started seeing an AccessViolationException being thrown in my application a several different spots. It never occured on my development pc, our test server. It also only manifested itself on 1 of our 2 production servers. Because it only seemed to happen on one of our production servers, I started looking at the installed .net framework versions on the servers. I found that (for some strange reason), the production server that was having problems had 2.0 sp2, 3.0 sp2, and 3.5 sp1, while the other production server and the test server had 2.0 sp1. My app only targets the 2.0 framework, decided to uninstall all the framework versions from the production server and install only 2.0 sp1. So far I have not been able to reproduce the problem. Very interesting. Development pc: compact 2.0 sp2, compact 3.5, 2.0 sp2, 3.0 sp2, 3.5 sp1 Test server: 2.0 sp1 Production server1: 2.0 sp1 Production server2: 2.0 sp2, 3.0 sp2, 3.5 sp1 Now, why I can't reproduce the problem on my development pc which has 2.0 sp2 on it, I can't figure out. I heard rumors that this access violation may happen on some software that utilizes remoting, which mine does, but the access violation never happends when remoting is actually occuring. I'm ok with using only 2.0 sp1 for now, but I'm really interested to know if anyone has had this issue, and if they found a workaround for newer versions of the frameowork. Here's a couple of the exceptions and their stack traces: ``` System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at ICSharpCode.TextEditor.TextArea.HandleKeyPress(Char ch) at ICSharpCode.TextEditor.TextArea.SimulateKeyPress(Char ch) at ICSharpCode.TextEditor.TextArea.OnKeyPress(KeyPressEventArgs e) at System.Windows.Forms.Control.ProcessKeyEventArgs(Message& m) at System.Windows.Forms.Control.ProcessKeyMessage(Message& m) at System.Windows.Forms.Control.WmKeyChar(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Control.DefWndProc(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.TextBoxBase.WndProc(Message& m) at System.Windows.Forms.RichTextBox.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ```
I had the same problem. 2.0 worked fine. after installing up to 3.5 sp1, application gets Access Violation. installed <http://support.microsoft.com/kb/971030> and my problem is solved, even though I am not using LCG.
I had the same problem after upgrading from .NET 4.5 to .NET 4.5.1. What fixed it for me was running this command: `netsh winsock reset`
Attempted to read or write protected memory
[ "", "c#", ".net", "access-violation", "servicepacks", "" ]
I am planning to implement logging into a web application that I am currently working on but I am struggling with some of the details. What is the best way to go about logging a Java web application? Specifically; * Where does the configuration file go in .war package file? * Where do people log to, relative or absolute path flat file, or a database? * Does Log4J logging go directly into the application server log file automatically or is that something you have to set up? In this case I am using Tomcat, but I often use Jrun. * Any other gotchas I should be aware of for web application logging? Currently I am using Log4J but I imagine that the best practices would apply universally to all logging implementations. **EDIT:** One addition to the questions up top. * Where do you initilize the log configuration? In a traditional app, I do this at the entry point; ``` DOMConfigurator.configureAndWatch("log4j.xml"); ``` What would the web application equivalent be?
I place my configuration on the default package: src/ and log to files using the ${catalina.home} system property: ``` log4j.appender.???.file=${catalina.home}/logs/system.log ```
I would recommend you to use [SLF4J](http://www.slf4j.org). This is simple logging facade which supports most of popular logging systems (*Log4j*, *commons-logging*, *Java Logging API* and *Logback*). Using it, **you will able to replace your underline logging system** to any other, by simple CLASSPATH update. The other benefit of *SLF4J* are [parameterized calls](http://www.slf4j.org/faq.html#logging_performance), which reduces ugly logging code. Actually, they recommends to use *SLF4J* with [Logback](http://logback.qos.ch). *Logback* is a successor of *Log4J*. And it was designed by the same author.
Logging Java web applications?
[ "", "java", "web-applications", "logging", "log4j", "" ]
I took a snapshot of the jquery.js file and jquery-ui files that I use and dumped them into a giant .js file with all of the other .js files that I use for my site. When I do just this with no minfication/packing, the files stop working and I get "recursion too deep" errors on the file when I try to load it on my site instead of the usual .js files. All of the errors came from jquery and jquery-ui. Using a simple numbering scheme I made sure that the jquery.js/jquery-ui files were the first listed in the file and in the correct order (the same as includes as individual files.) Two questions: 1) Doesn't the include tags for JavaScript have the same effect as dumping all of the files into one giant file? Is there extra isolation/insulation that JavaScript files get from being in their own script tags or in different files? 2) My goal is to make my site faster by having one huge .js file with all JavaScript I ever use in my site (which is heavy in JQuery) and minify that file. Why is this misguided? What is a better way to do it? NOTE: Google's CDN version of the JQuery files don't work for me, all of the JQuery plugins/themes I use don't work with Google's versions (anyway who says that they can successfully use Google's CDN is lying.) UPDATE: Thanks for the good advice in the answers, all of it helped me learn more about deploying JavaScript files on a production server. I am actually always using the latest SVN branch of the JQuery UI plugins and there were errors in the UI plugins that prevented them from being merged together with my files. I got the latest Theme Rolled plugins that are already minified in one file and that worked around the problem.
Probably your JavaScript files have some syntax errors. Browser can correct them when loading files one by one, but fail when "bad" files combined. You can try to compile your file using Rhino compiler (<http://www.mozilla.org/rhino/>) ``` java -cp build/js.jar org.mozilla.javascript.tools.jsc.Main giant.js ``` Also you can use JSLint validator (<http://www.jslint.com/>), thought likelly it will not be able to handle jQuery. But you still can combine all *your* files and validate them.
I'd recommend using a script manager such as [this one](http://www.gfilter.net/?Post=JSManager.js---Easily-manage-JS-dependancies) to only register the files and plugins you need, and load them on the fly. This keeps your requests to a minimum, and you don't have to load some huge 300k JS file one very page.
Why does dumping all JavaScript files into one giant file change their behavior?
[ "", "javascript", "jquery", "jquery-ui", "" ]
I am trying to query for a list of stored procedure definitions using information\_schema.routines that exist in one database but not in another. ``` SELECT t1.Routine_Definition FROM [server1].MyDatabase.INFORMATION_SCHEMA.Routines t1 LEFT JOIN [server2].MyDatabase.INFORMATION_SCHEMA.Routines t2 ON t1.Routine_Name = t2.Routine_Name WHERE t2.Routine_Name is null ``` This gives me the query definitions in a single line so when I have a comment like this ``` --Some comment SELECT Column FROM Somewhere ``` The SQL gets commented out and I cannot use the definition to create the SP. How to I parse this back with the proper line breaks? or Is there a better way to get these scripts (using code)?
The stored procedure is only displayed on one line in Management Studio. If you run the query with results to text, **or** use the following, you will get the correct line breaks: ``` declare @sql varchar(8000) -- varchar(max) in SQL 2005+ SELECT @sql = t1.Routine_Definition FROM INFORMATION_SCHEMA.Routines t1 print @sql ```
``` DECLARE MY_CURSOR Cursor FOR SELECT t1.Routine_Definition FROM [server1].MyDatabase.INFORMATION_SCHEMA.Routines t1 LEFT JOIN [server2].MyDatabase.INFORMATION_SCHEMA.Routines t2 ON t1.Routine_Name = t2.Routine_Name WHERE t2.Routine_Name is null AND LEN(t1.Routine_Definition) < 4000 Open My_Cursor DECLARE @sql VARCHAR(MAX) FETCH NEXT FROM MY_Cursor INTO @sql While (@@FETCH_STATUS <> -1) BEGIN IF (@@FETCH_STATUS <> -2) Print @sql FETCH NEXT FROM MY_CURSOR INTO @sql END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR GO ``` Here is how I implemented ck's solution... the INFORMATION\_SCHEMA view only returns the first 4000 characters in the definition. (Ideally you wont have SP that are that long)You will want to script those manually or some other way.
MSSQL: How do you script Stored Procedure creation with code?
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "information-schema", "" ]
in C#, is there a way to 1. Get the memory address stored in a reference type variable? 2. Get the memory address of a variable? EDIT: ``` int i; int* pi = &i; ``` * How do you print out the hex value of pi?
For #2, the `&` operator will work in the same fashion as in C. If the variable is not on the stack, you may need to use a `fixed` statement to pin it down while you work so the garbage collector does not move it, though. For #1, reference types are trickier: you'll need to use a `GCHandle`, and the reference type has to be blittable, i.e. have a defined memory layout and be bitwise copyable. In order to access the address as a number, you can cast from pointer type to `IntPtr` (an integer type defined to be the same size as a pointer), and from there to `uint` or `ulong` (depending on the pointer size of the underlying machine). ``` using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] class Blittable { int x; } class Program { public static unsafe void Main() { int i; object o = new Blittable(); int* ptr = &i; IntPtr addr = (IntPtr)ptr; Console.WriteLine(addr.ToString("x")); GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned); addr = h.AddrOfPinnedObject(); Console.WriteLine(addr.ToString("x")); h.Free(); } } ```
Number 1 is not possible at all, you can't have a pointer to a managed object. However, you can use an IntPtr structure to get information about the address of the pointer in the reference: ``` GCHandle handle = GCHandle.Alloc(str, GCHandleType.Pinned); IntPtr pointer = GCHandle.ToIntPtr(handle); string pointerDisplay = pointer.ToString(); handle.Free(); ``` For number 2 you use the & operator: ``` int* p = &myIntVariable; ``` Pointers of course have to be done in a unsafe block, and you have to allow unsafe code in the project settings. If the variable is a local variable in a method, it's allocated on the stack so it's already fixed, but if the variable is a member of an object, you have to pin that object in memory using the `fixed` keyword so that it's not moved by the garbage collector.
C# memory address and variable
[ "", "c#", ".net", "memory-management", "" ]
I need a quick jump start for using Spring and Hibernate together and I was looking for some sample code to modify and extend. Bonus points for Struts2 and Spring Security integration.
There is a [sample project](http://struts.apache.org/2.0.14/docs/struts-2-spring-2-jpa-ajax.html) that includes Spring, Hibernate and Struts2 available from the Struts2 website that appears to have most of what I want. It includes a basic JPA configuration but it does not provide DAO classes. The generic DAO pattern is documented on the Hibernate site [here](http://www.hibernate.org/328.html). This gives a good DAO foundation but the code is using Hibernate directly with no JPA or Spring. The [following post](http://icoloma.blogspot.com/2006/11/jpa-and-spring-fucking-cooltm_26.html) (**warning:** language) gives some information about using Spring with JPA and not the HibernateTemplate class. Put together this information has me well on the way to my skeleton project.
The official docs is your best bet for both [Spring](http://static.springframework.org/spring/docs/2.5.x/reference/index.html) and [Hibernate](http://www.hibernate.org/docs). However, you can look into [When Spring Meets Hibernate](http://www.ibm.com/developerworks/web/library/wa-spring2/) and [Spring and Hibernate with MyEclipse](http://www.myeclipseide.com/documentation/quickstarts/hibernateandspring/) tutorial to get you started. Your best bet, if you are using Netbeans or have no problems in using that, just start a brand new application and follow the [web application wizard and specify Spring and Hibernate](http://www.netbeans.org/kb/trails/web.html) as application framework, and ORM respectively. It will generate a complete skeleton for you to work on. You can even add Struts2 as web framework later, in project->properties->framework. You might want to look into [Struts2 Spring Plugin](http://struts.apache.org/2.x/docs/spring-plugin.html) for the latter. Further, [Spring Security Integration](http://www.acegisecurity.org/guide/springsecurity.html).
What are some good sample applications using Spring and Hibernate?
[ "", "java", "hibernate", "spring", "spring-security", "" ]
I'm having a strange behavior with an operator overloading in C++. I have a class, and I need to check if its contents are greater or equal to a long double. I overloaded the >= operator to make this check, my declaration is as follows: ``` bool MyClass::operator>=(long double value) const; ``` I have to say that I also have a cast-to-long-double operator for my class, that works without exceptions only under certain conditions. Now, when I use this operator, the compiler complains that there's an ambiguous use of operator>= and the alternatives are: * Mine. * The built-in `operator>=(long double, int)`. Now, how do I force the program to use my operator?
**2015 update:** Or, if you want to keep conversion ability using the `(double)obj` syntax instead the `obj.to_double()` syntax, make the conversion function `explicit` by prefixing it with that keyword. You need an explicit cast then for the conversion to trigger. Personally, I prefer the `.to_double` syntax, unless the conversion would be to `bool` because in that case the conversion is used by `if(obj)` even if it is `explicit`, and that is considerably more readable than `if(obj.to_bool())` in my opinion. --- Drop the conversion operator. It will cause troubles all the way. Have a function like ``` to_double() ``` Or similar that returns the double value and call that function explicitly to get a double. For the problem at hand, there is this problem: ``` obj >= 10 ``` Consider that expression. The builtin operator matches the first argument by a user defined conversion sequence for your type using the conversion operator long double(). But your function matches the second argument by a standard conversion sequence from int to long double (integral to floating point conversion). It is always ambiguous when there are conversions for two arguments, but not at least one argument that can be converted better while the remaining arguments are not converted worse for one call. In your case, the builtin one matches the second argument better but the first worse, but your function matches the first argument better but the second worse. It's confusing, so here are some examples (conversions from char to int are called promotions, which are better than conversions from char to something other than int, which is called a conversion): ``` void f(int, int); void f(long, long); f('a', 'a'); ``` Calls the first version. Because all arguments for the first can be converted better. Equally, the following will still call the first: ``` void f(int, long); void f(long, long); f('a', 'a'); ``` Because the first can be converted better, and the second is not converted worse. But the following is *ambiguous*: ``` void f(char, long); void f(int, char); f('a', 'a'); // ambiguous ``` It's more interesting in this case. The first version accepts the first argument by an exact match. The second version accepts the second argument by an exact match. But both versions do not accept their other argument at least equally well. The first version requires a conversion for its second argument, while the second version requires a promotion for its argument. So, even though a promotion is better than a conversion, the call to the second version fails. It's very similar to your case above. Even though a standard conversion sequence (converting from int/float/double to long double) is *better* than a user-defined conversion sequence (converting from MyClass to long double), your operator version is not chosen, because your other parameter (long double) requires a conversion from the argument which is worse than what the builtin operator needs for that argument (perfect match). Overload resolution is a complex matter in C++, so one can impossibly remember all the subtle rules in it. But getting the rough plan is quite possible. I hope it helps you.
By providing an implicit conversion to a `double` you are effectively stating, my class is equivalent to a `double` and for this reason you shouldn't really mind if the built in operator >= for `double`s is used. If you *do* care, then your class really isn't 'equivalent' to a `double` and you should consider not providing an *implicit* conversion to `double`, but instead providing an *explicit* GetAsDouble, or ConvertToDouble member function. The reason that you have an ambiguity at the moment is that for an expression `t >= d` where `t` is an instance of your class and `d` is a double, the compiler always has to provide a conversion of either the left hand side or the right hand side so the expression really is ambiguous. Either `t`'s `operator double` is called and the built-in operator >= for `double`s is used, or d must be promoted to a `long double` and your member operator >= is used. Edit, you've updated your question to suggest that your conversion is to long double and your comparison is against an int. In which case the last paragraph should read: The reason that you have an ambiguity at the moment is that for an expression `t >= d` where `t` is an instance of your class and `d` is an `int`, the compiler always has to provide a conversion of either the left hand side or the right hand side so the expression really is ambiguous. Either `t`'s `operator long double` is called and the built-in operator >= for `long double` and `int` is used, or d must be promoted to a `long double` and your member operator >= is used.
Odd behavior with operator>= overloading
[ "", "c++", "operator-overloading", "overload-resolution", "" ]
I've got a usercontrol that has a <asp:TextBox> with autopostback set to true. When the user types text in and moves off the textbox, asp.net fires a postback event. However, it isn't handled specifically by the textbox, but is instead simply a postback - the page\_load fires and then life goes on. What I need is a way to know that this textbox fired the event. I then want to fire my own custom event so that my main page can subscribe to it and handle the event when the textbox changes. At first I thought I could capture the sender - I was assuming that the sender would be the textbox, but it appears to be the page itself. Anyone have any thoughts?
I think you're missing something, so I want to explain it step by step : your textbox should be something like that : ``` <asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged"></asp:TextBox> ``` and in your codebehind you shhould have an event like that : ``` protected void TextBox1_TextChanged(object sender, EventArgs e) { string str = TextBox1.Text; } ``` **NOTE :** if you want to attach your event in code-behind you can do this by : ``` TextBox1.TextChanged +=new EventHandler(TextBox1_TextChanged); ``` but if you talking about custom controls, you should implement **IPostBackDataHandler** interface to raise events.
Is this i dynamically created usercontrol or textbox? If so you have to recreate that control in the page\_load event and the event should be fired on the textbox as normal.
Determine when Postback occurs because of a textbox being changed
[ "", "c#", "asp.net", "events", "" ]
I need to deliver one and half hour seminar on programming for students at the department of mathematics. I have chosen python as language. 1. What should be content of my presentation ? 2. What are good resources available ? 3. What is necessity of programming for maths students? 4. How will knowledge of programming will help them? Thank you !!! NOTE: I know [here](https://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc) is one post but it doesn't solve my problem.
Do the getting started guide to scipy? <http://www.scipy.org/Getting_Started>
Sage: <http://www.sagemath.org/>
Python for mathematics students?
[ "", "python", "math", "" ]
I am using the following code to play a sound file using the java sound API. ``` Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream); clip.open(inputStream); clip.start(); ``` The method call to the Clip.start() method returns immediately, and the system playbacks the sound file in a background thread. I want my method to pause until the playback has completed. Is there any nice way to do it? EDIT: For everyone interested in my final solution, based on the answer from Uri, I used the code below: ``` private final BlockingQueue<URL> queue = new ArrayBlockingQueue<URL>(1); public void playSoundStream(InputStream stream) { Clip clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem.getAudioInputStream(stream); clip.open(inputStream); clip.start(); LineListener listener = new LineListener() { public void update(LineEvent event) { if (event.getType() != Type.STOP) { return; } try { queue.take(); } catch (InterruptedException e) { //ignore this } } }; clip.addLineListener(listener ); } ```
A sound clip is a type or Line and therefore supports Line listeners. If you use addLineListener, you should get events when play starts and stops; if you're not in a loop, you should get a stop when the clip ends. However, as with any events, there might be a lag before the actual end of playback and the stopping. Making the method wait is slightly trickier. You can either busy-wait on it (not a good idea) or use other synchronization mechanisms. I think there is a pattern (not sure about it) for waiting on a long operation to throw a completion event, but that's a general question you may want to post separately to SO.
I prefer this way in Java 8: ``` CountDownLatch syncLatch = new CountDownLatch(1); try (AudioInputStream stream = AudioSystem.getAudioInputStream(inStream)) { Clip clip = AudioSystem.getClip(); // Listener which allow method return once sound is completed clip.addLineListener(e -> { if (e.getType() == LineEvent.Type.STOP) { syncLatch.countDown(); } }); clip.open(stream); clip.start(); } syncLatch.await(); ```
how can I wait for a java sound clip to finish playing back?
[ "", "java", "javasound", "" ]
We have a query to remove some rows from the table based on an id field (primary key). It is a pretty straightforward query: ``` delete all from OUR_TABLE where ID in (123, 345, ...) ``` The problem is no.of ids can be huge (Eg. 70k), so the query takes a long time. Is there any way to optimize this? (We are using sybase - if that matters).
Consider running this in batches. A loop running 1000 records at a time may be much faster than one query that does everything and in addition will not keep the table locked out to other users for as long at a stretch. If you have cascade delete (and lots of foreign key tables affected) or triggers involved, you may need to run in even smaller batches. You'll have to experiement to see which is the best number for your situation. I've had tables where I had to delete in batches of 100 and others where 50000 worked (fortunate in that case as I was deleting a million records). But in any even I would put my key values that I intend to delete into a temp table and delete from there.
There are two ways to make statements like this one perform: 1. Create a new table and copy all but the rows to delete. Swap the tables afterwards (`alter table name ...`) I suggest to give it a try even when it sounds stupid. Some databases are much faster at copying than at deleting. 2. Partition your tables. Create N tables and use a view to join them into one. Sort the rows into different tables grouped by the delete criterion. The idea is to drop a whole table instead of deleting individual rows.
Improving performance of Sql Delete
[ "", "sql", "database", "sybase", "query-optimization", "database-optimization", "" ]
I'm trying to convert from `System.Windows.Controls.Image` to `byte[]` and I didnt know which method from Image class could help in this scenary, by the way I really dont know what should I do, cause in my LINQ model the field appears as `Binary` type, I have to change this if I want to save it like a `byte[]` type? I found code posted here, but without using WPF: ``` Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight); System.IO.MemoryStream stream = new System.IO.MemoryStream(); newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); PHJProjectPhoto myPhoto = new PHJProjectPhoto { ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[] OrderDate = DateTime.Now, ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text, ProjectId = selectedProjectId }; ```
Real Solution... if want to save jpg images from an System.Windows.Control.Image when your database mapped field on your ORM is Byte[] / byte[] / Bynary ``` public byte[] getJPGFromImageControl(BitmapImage imageC) { MemoryStream memStream = new MemoryStream(); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(imageC)); encoder.Save(memStream); return memStream.ToArray(); } ``` call as : ``` getJPGFromImageControl(firmaUno.Source as BitmapImage) ``` Hopes helps :)
I don't know how your Image is declared, but suppose we have this XAML declaration: ``` <Image x:Name="img"> <Image.Source> <BitmapImage UriSource="test.png" /> </Image.Source> </Image> ``` Then you can convert the contents of test.png to a byte-array like this: ``` var bmp = img.Source as BitmapImage; int height = bmp.PixelHeight; int width = bmp.PixelWidth; int stride = width * ((bmp.Format.BitsPerPixel + 7) / 8); byte[] bits = new byte[height * stride]; bmp.CopyPixels(bits, stride, 0); ```
WPF Image to byte[]
[ "", "c#", "wpf", "image", "arrays", "" ]
I have a date value, which I'm told is 8 bytes, a single "long" (aka int64) value, and converted to hex: ``` 60f347d15798c901 ``` How can I convert this and values like this, using PHP, into a time/date? Converting it to decimal gives me: 96 243 71 209 87 152 201 1 A little more info: the original value is a C# DateTime, and should represent a time/date about 2 or 3 weeks ago.
(Thanks to thomasrutter's post, which gave me the Windows filetime epoch): The given date appears to be a Windows 64-bit little-endian file date-time, 60 f3 47 d1 57 98 c9 01, which is equivalent to the quadword 01c99857d147f360 which as an integer is 128801567297500000 This is "the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC)" After conversion, it gives Thu, 26 February 2009 21:18:49 UTC Sample code: ``` <?php // strip non-hex characters function hexstring($str) { $hex = array( '0'=>'0', '1'=>'1', '2'=>'2', '3'=>'3', '4'=>'4', '5'=>'5', '6'=>'6', '7'=>'7', '8'=>'8', '9'=>'9', 'a'=>'a', 'b'=>'b', 'c'=>'c', 'd'=>'d', 'e'=>'e', 'f'=>'f', 'A'=>'a', 'B'=>'b', 'C'=>'c', 'D'=>'d', 'E'=>'e', 'F'=>'f' ); $t = ''; $len = strlen($str); for ($i=0; $i<$len; ++$i) { $ch = $str[$i]; if (isset($hex[$ch])) $t .= $hex[$ch]; } return $t; } // swap little-endian to big-endian function flip_endian($str) { // make sure #digits is even if ( strlen($str) & 1 ) $str = '0' . $str; $t = ''; for ($i = strlen($str)-2; $i >= 0; $i-=2) $t .= substr($str, $i, 2); return $t; } // convert hex string to BC-int function hex_to_bcint($str) { $hex = array( '0'=>'0', '1'=>'1', '2'=>'2', '3'=>'3', '4'=>'4', '5'=>'5', '6'=>'6', '7'=>'7', '8'=>'8', '9'=>'9', 'a'=>'10', 'b'=>'11', 'c'=>'12', 'd'=>'13', 'e'=>'14', 'f'=>'15', 'A'=>'10', 'B'=>'11', 'C'=>'12', 'D'=>'13', 'E'=>'14', 'F'=>'15' ); $bci = '0'; $len = strlen($str); for ($i=0; $i<$len; ++$i) { $bci = bcmul($bci, '16'); $ch = $str[$i]; if (isset($hex[$ch])) $bci = bcadd($bci, $hex[$ch]); } return $bci; } // WARNING! range clipping // Windows date time has range from 29000 BC to 29000 AD // Unix time only has range from 1901 AD to 2038 AD // WARNING! loss of accuracy // Windows date time has accuracy to 0.0000001s // Unix time only has accuracy to 1.0s function win64_to_unix($bci) { // Unix epoch as a Windows file date-time value $magicnum = '116444735995904000'; $t = bcsub($bci, $magicnum); // Cast to Unix epoch $t = bcdiv($t, '10000000', 0); // Convert from ticks to seconds return $t; } // get input $dtval = isset($_GET["dt"]) ? strval($_GET["dt"]) : "0"; $dtval = hexstring($dtval); // strip non-hex chars // convert to quadword $dtval = substr($dtval, 0, 16); // clip overlength string $dtval = str_pad($dtval, 16, '0'); // pad underlength string $quad = flip_endian($dtval); // convert to int $win64_datetime = hex_to_bcint($quad); // convert to Unix timestamp value $unix_datetime = win64_to_unix($win64_datetime); ?><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Windows datetime test code</title> </head> <form method="get"> <label>Datetime value: <input name="dt" type="text" value="<?php echo $dtval; ?>"/></label> <input type="submit" /> </form> <hr /> Result: Quad: <?php echo $quad; ?><br /> Int: <?php echo $win64_datetime; ?><br /> Unix timestamp: <?php echo $unix_datetime; ?><br /> Date: <?php echo date("D, d F Y H:i:s e", $unix_datetime); ?><br /> <body> </body> </html> ```
I found [another reference](http://www.digital-detective.co.uk/freetools/decode.asp) which might point to some more relevant information. In this case, a Windows date and time as used in the registry. Apparently these are also stored as 64 bit values. This is looking a bit more helpful, as it mentions that ending in C?01 is an indicator of this type of date. Note that this is little endian (ie, most significant bytes on the right) so the bytes are in the wrong byte order for hexdec() without reversing them 2 hex digits at a time (ie, start with right-most 2 hex digits, then next two, etc). And, according to [this source](http://social.microsoft.com/Forums/en-US/vblanguage/thread/9a663255-94c8-426e-8aed-571ab97f4fe1), > A single tick represents one hundred nanoseconds or one ten-millionth of a second. The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents. What might trip you up is that unfortunately PHP cannot handle 64 bit integers. It maxes out at 32 bit. Floats will help, but that doesn't stop hexdec() itself from only coping with ints. So it may be complicated to do this math; you may still need to split it into two, then combine them into a float by casting the more significant value to float and multiplying it by 2^32 also cast as float. *It's possible that PHP built for 64-bit hardware may not have this limitation, but I don't know for sure.*
Help me translate long value, expressed in hex, back in to a date/time
[ "", "php", "datetime", "hex", "long-integer", "" ]
I'm trying to compare two `DataRow`s in a loop. However, the following `if` statement doesn't return `true`: ``` if (dt1.Rows[0]["Name"] == dt2.Rows[b]["Name"]) { // This never executes } ``` However, if I add `.ToString()` to the end of each `DataRow`, the `if` statement returns `true`: ``` if (dt1.Rows[0]["Name"].ToString() == dt2.Rows[b]["Name"].ToString()) { // This now executes } ``` The column "Name" is from the same table/column. So the question is quite simple... What am I doing wrong? Thanks Stephen
As [itsmatt has said](https://stackoverflow.com/questions/614713/datarow-comparison-not-working-as-expected/614725#614725), your first snippet is doing a reference comparison. An alternative to calling `ToString` is to use `Object.Equals`: ``` if (Object.Equals(dt1.Rows[0]["Name"], dt2.Rows[b]["Name"])) { // stuff } ``` The reason for using the static method instead of the instance method is to avoid problems with null references.
Those cells hold objects so you are doing an object comparison, which just does a reference comparison, which is different from a value comparison. It asks the question "Are these two objects really the same object?", essentially are they referring to the same object, hence "reference comparison". When you do the ToString() call, you are then doing string comparison. That is why it works. [Here's a link to MS's discussion of Operator== and comparison.](http://msdn.microsoft.com/en-us/library/ms173147.aspx)
DataRow comparison not working as expected
[ "", "c#", "datarow", "" ]
I have a data structure that I want to access / modify in different ways in different situations. I came up with this: ``` class DataStructure { public: int getType(); private: // underlying data containers }; class WrapperBase { public: void wrap(DataStructure *input) {dataStructure = input;} protected: DataStructure *dataStructure; }; class WrapperOne : public WrapperBase { public: // @Mykola: I know bytes 4-10 in an array of type one specify the date // so this method will format those bytes and return them Data getDate() }; class WrapperTwo : public WrapperBase { public: // @Mykola: There is mostly just a chunk of data in packet type two. So this // method will turn 4 bytes into an int at position index and return that int dataAt(int index); }; ``` One problem I see here is that WrapperBase isn't abstract even though it should be. I could of course add some pure virtual dummy function or an assert(0) in the constructor but that seems too hackish a solution. Or should I get rid of the inheritance entirely since it's only really done for code-reuse? Any other problems with this solution? Or am I on the wrong track entirely? **Edit @ Paul** Why do I want to do this? Well, I get several 1000 arrays of serialized data, which I want to add to a dataset. The first few bytes of each array tell me what sort of data it is, which dictates how I have process it. So then I do something like: ``` // some place in the program dataSet.processData(dataStructure); // in the data set class DataSet::processData(DataStructure *dataStructure) { if(dataStructure->getType() == TYPE_ONE) { WrapperOne wrapperOne; wrapperOne.wrap(dataStructure); processDataTypeOne(wrapperOne); } // repeat the above for other data types } ``` I could of course put all the logic in the `processDataTypeOne` function, and that was what I was doing in the beginning, but operating on the raw data structure turned into an ugly mess of index operations. That's why I'd like to wrap it in an object, which will hide all that.
Make your wrappers to be a data. Create factory that will return either data or different wrappers. Here is what I mean. ``` class DataStructure { public: typedef int DataType; DataStructure( int id ): id_( id ) {} DataStructure( const DataStructure& dataStructure ); virtual ~DataStructure(); virtual void Set( const DataType& data ) { data_ = data; } virtual DataType Get() const { return data_; } int id() const { return id_; } private: DataType data_; int id_; }; class WrapperBase : public DataStructure { public: WrapperBase( DataStructure* dataStructure ): DataStructure( dataStructure->id() ), dataStructure_( dataStructure ) {} virtual void Set( const DataType& data ); virtual DataType Get() const; protected: DataStructure* dataStructure_; }; class WrapperOne : public WrapperBase { public: WrapperOne( DataStructure* dataStructure ); virtual void Set( const DataType& data ); virtual DataType Get() const; }; class WrapperTwo : public WrapperBase { public: WrapperTwo( DataStructure* dataStructure ); virtual void Set( const DataType& data ); virtual DataType Get() const; }; DataStructure* getWrapper( DataStructure* dataStructure ) { switch ( dataStructure->id() ) { case 1: return new WrapperOne( dataStructure ); case 2: return new WrapperTwo( dataStructure ); default: return new DataStructure( *dataStructure ); } } void processData(DataStructure *dataStructure) { std::auto_ptr<DataStructure> wrapper( getWrapper( dataStructure ) ); processDataImpl( wrapper.get() ); } ```
Think about what you want your base class for your data to do. If you are going to save your data or display it to the screen you may want a base class with functions like ToString and ToXML. Let the code evolve. Write out the different DataStructure classes you need. Then find the commonality and move that into the base class.
Wrapping a data structure
[ "", "c++", "inheritance", "data-structures", "oop", "" ]
I'm wondering what the best way is to play back an MP4 video in a Windows Forms application (.NET 2.0) on Vista and XP.
You could [Embed Windows Media Player on a Form](http://msdn.microsoft.com/en-us/library/bb383953.aspx). **UPDATE**: WMP doesn't support MP4 out-of-the-box, but there are [codecs packs](http://www.tech-faq.com/windows-media-player-mp4-codec.shtml) that add such support. It's possible to bundle a codec installation with your setup, but I think WMP is able to fetch and install MP4 codec on its own.
Either embedding media player or look at managed DirectX (although MDX is a bit old now)
How do you playback MP4 video in a Windows Forms App
[ "", "c#", ".net", "winforms", "" ]
I am writing some JUnit tests that verify that an exception of type `MyCustomException` is thrown. However, this exception is wrapped in other exceptions a number of times, e.g. in an InvocationTargetException, which in turn is wrapped in a RuntimeException. What's the best way to determine whether MyCustomException somehow caused the exception that I actually catch? I would like to do something like this (see underlined): ``` try { doSomethingPotentiallyExceptional(); fail("Expected an exception."); } catch (RuntimeException e) { if (!e.wasCausedBy(MyCustomException.class) fail("Expected a different kind of exception."); } ``` I would like to avoid calling `getCause()` a few "layers" deep, and similar ugly work-arounds. Is there a nicer way? Apparently, Spring has [NestedRuntimeException.contains(Class)](http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/core/NestedRuntimeException.html), which does what I want - but I'm not using Spring.
Why would you want to avoid `getCause`. You can, of course, write yourself a method to perform the task, something like: ``` public static boolean isCause( Class<? extends Throwable> expected, Throwable exc ) { return expected.isInstance(exc) || ( exc != null && isCause(expected, exc.getCause()) ); } ```
If you are using [Apache Commons Lang](https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/exception/ExceptionUtils.html#indexOfThrowable%28java.lang.Throwable,%20java.lang.Class%29), then you can use the following: (1) When the cause should be exactly of the specified type ``` if (ExceptionUtils.indexOfThrowable(exception, ExpectedException.class) != -1) { // exception is or has a cause of type ExpectedException.class } ``` (2) When the cause should be either of the specified type or its subclass type ``` if (ExceptionUtils.indexOfType(exception, ExpectedException.class) != -1) { // exception is or has a cause of type ExpectedException.class or its subclass } ```
Best way to check whether a certain exception type was the cause (of a cause, etc ...) in a nested exception?
[ "", "java", "spring", "exception", "nested-exceptions", "" ]
If I understand correctly, the `.bss` section in ELF files is used to allocate space for zero-initialized variables. Our tool chain produces ELF files, hence my question: does the `.bss` section actually have to contain all those zeroes? It seems such an awful waste of spaces that when, say, I allocate a global ten megabyte array, it results in ten megabytes of zeroes in the ELF file. What am I seeing wrong here?
Has been some time since i worked with ELF. But i think i still remember this stuff. No, it does not physically contain those zeros. If you look into an ELF file program header, then you will see each header has two numbers: One is the size in the file. And another is the size as the section has when allocated in virtual memory (`readelf -l ./a.out`): ``` Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align PHDR 0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4 INTERP 0x000114 0x08048114 0x08048114 0x00013 0x00013 R 0x1 [Requesting program interpreter: /lib/ld-linux.so.2] LOAD 0x000000 0x08048000 0x08048000 0x00454 0x00454 R E 0x1000 LOAD 0x000454 0x08049454 0x08049454 0x00104 0x61bac RW 0x1000 DYNAMIC 0x000468 0x08049468 0x08049468 0x000d0 0x000d0 RW 0x4 NOTE 0x000128 0x08048128 0x08048128 0x00020 0x00020 R 0x4 GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4 ``` Headers of type `LOAD` are the one that are copied into virtual memory when the file is loaded for execution. Other headers contain other information, like the shared libraries that are needed. As you see, the `FileSize` and `MemSiz` significantly differ for the header that contains the `bss` section (the second `LOAD` one): ``` 0x00104 (file-size) 0x61bac (mem-size) ``` For this example code: ``` int a[100000]; int main() { } ``` The ELF specification says that the part of a segment that the mem-size is greater than the file-size is just filled out with zeros in virtual memory. The segment to section mapping of the second `LOAD` header is like this: ``` 03 .ctors .dtors .jcr .dynamic .got .got.plt .data .bss ``` So there are some other sections in there too. For C++ constructor/destructors. The same thing for Java. Then it contains a copy of the `.dynamic` section and other stuff useful for dynamic linking (i believe this is the place that contains the needed shared libraries among other stuff). After that the `.data` section that contains initialized globals and local static variables. At the end, the `.bss` section appears, which is filled by zeros at load time because file-size does not cover it. By the way, you can see into which output-section a particular symbol is going to be placed by using the `-M` linker option. For gcc, you use `-Wl,-M` to put the option through to the linker. The above example shows that `a` is allocated within `.bss`. It may help you verify that your uninitialized objects really end up in `.bss` and not somewhere else: ``` .bss 0x08049560 0x61aa0 [many input .o files...] *(COMMON) *fill* 0x08049568 0x18 00 COMMON 0x08049580 0x61a80 /tmp/cc2GT6nS.o 0x08049580 a 0x080ab000 . = ALIGN ((. != 0x0)?0x4:0x1) 0x080ab000 . = ALIGN (0x4) 0x080ab000 . = ALIGN (0x4) 0x080ab000 _end = . ``` GCC keeps uninitialized globals in a COMMON section by default, for compatibility with old compilers, that allow to have globals defined twice in a program without multiple definition errors. Use `-fno-common` to make GCC use the .bss sections for object files (does not make a difference for the final linked executable, because as you see it's going to get into a .bss output section anyway. This is controlled by the *linker script*. Display it with `ld -verbose`). But that shouldn't scare you, it's just an internal detail. See the manpage of gcc.
The `.bss` section in an ELF file is used for static data which is **not initialized** programmatically but guaranteed to be set to zero at runtime. Here's a little example that will explain the difference. ``` int main() { static int bss_test1[100]; static int bss_test2[100] = {0}; return 0; } ``` In this case `bss_test1` is placed into the `.bss` since it is uninitialized. `bss_test2` however is placed into the `.data` segment along with a bunch of zeros. The runtime loader basically allocates the amount of space reserved for the `.bss` and zeroes it out before any userland code begins executing. You can see the difference using `objdump`, `nm`, or similar utilities: ``` moozletoots$ objdump -t a.out | grep bss_test 08049780 l O .bss 00000190 bss_test1.3 080494c0 l O .data 00000190 bss_test2.4 ``` This is usually one of the first *surprises* that embedded developers run into... never initialize statics to zero explicitly. The runtime loader (usually) takes care of that. As soon as you initialize anything explicitly, you are telling the compiler/linker to include the data in the executable image.
Do .bss section zero initialized variables occupy space in elf file?
[ "", "c++", "storage", "elf", "segments", "" ]
How can I automatically replace all C style comments (`/* comment */`) by C++ style comments (`// comment`)? This has to be done automatically in several files. Any solution is okay, as long as it works.
This tool does the job: <https://github.com/cenit/jburkardt/tree/master/recomment> > RECOMMENT is a C++ program which > converts C style comments to C++ style > comments. It also handles all the non-trivial cases mentioned by other people: > This code incorporates suggestions and > coding provided on 28 April 2005 by > Steven Martin of JDS Uniphase, > Melbourne Florida. These suggestions > allow the program to ignore the > internal contents of strings, (which > might otherwise seem to begin or end > comments), to handle lines of code > with trailing comments, and to handle > comments with trailing bits of code.
This is not a trivial problem. ``` int * /* foo /* this is not the beginning of a comment. int * */ var = NULL; ``` What do you want to replace that with? Any real substitution requires sometimes splitting lines. ``` int * // foo // this is not the beginning of a comment. // int * var = NULL; ```
Replace C style comments by C++ style comments
[ "", "c++", "comments", "" ]
given ``` public Class Example { public static void Foo< T>(int ID){} public static void Foo< T,U>(int ID){} } ``` Questions: 1. Is it correct to call this an "overloaded generic method"? 2. How can either method be specified in creation of a MethodInfo object? ``` Type exampleType = Type.GetType("fullyqualifiednameOfExample, namespaceOfExample"); MethodInfo mi = exampleType.GetMethod("Foo", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof(Type), typeof(Type) }, null); ``` argument 4 causes the compiler much displeasure
I can't find a way of using GetMethod that would do what you want. But you can get all the methods and go through the list until you find the method that you want. Remember you need to call MakeGenericMethod before you can actually use it. ``` var allMethods = typeof (Example).GetMethods(BindingFlags.Public | BindingFlags.Static); MethodInfo foundMi = allMethods.FirstOrDefault( mi => mi.Name == "Foo" && mi.GetGenericArguments().Count() == 2); if (foundMi != null) { MethodInfo closedMi = foundMi.MakeGenericMethod(new Type[] {typeof (int), typeof (string)}); Example example= new Example(); closedMi.Invoke(example, new object[] { 5 }); } ```
Here are the answers to your questions along with an example: 1. Yes, although there are two things really to be aware of here with generic methods, type inference and overload method resolution. Type inference occurs at compile time before the compiler tries to resolve overloaded method signatures. The compiler applies type inference logic to all generic methods that share the same name. In the overload resolution step, the compiler includes only those generic methods on which type inference succeeded. [More here...](http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).aspx) 2. Please see the full example Console Application program code below that shows how several variants of the Foo method can be specified in creation of a MethodInfo object and then invoked using an Extension method: Program.cs ``` class Program { static void Main(string[] args) { MethodInfo foo1 = typeof(Example).GetGenericMethod("Foo", new[] { typeof(string) }, new[] { typeof(int) }, typeof(void)); MethodInfo foo2 = typeof(Example).GetGenericMethod("Foo", new[] { typeof(string), typeof(int) }, new[] { typeof(int) }, typeof(void)); MethodInfo foo3 = typeof(Example).GetGenericMethod("Foo", new[] { typeof(string) }, new[] { typeof(string) }, typeof(void)); MethodInfo foo4 = typeof(Example).GetGenericMethod("Foo", new[] { typeof(string), typeof(int) }, new[] { typeof(int), typeof(string) }, typeof(string)); Console.WriteLine(foo1.Invoke(null, new object[] { 1 })); Console.WriteLine(foo2.Invoke(null, new object[] { 1 })); Console.WriteLine(foo3.Invoke(null, new object[] { "s" })); Console.WriteLine(foo4.Invoke(null, new object[] { 1, "s" })); } } ``` Example.cs: ``` public class Example { public static void Foo<T>(int ID) { } public static void Foo<T, U>(int ID) { } public static void Foo<T>(string ID) { } public static string Foo<T, U>(int intID, string ID) { return ID; } } ``` Extensions.cs: ``` public static class Extensions { public static MethodInfo GetGenericMethod(this Type t, string name, Type[] genericArgTypes, Type[] argTypes, Type returnType) { MethodInfo foo1 = (from m in t.GetMethods(BindingFlags.Public | BindingFlags.Static) where m.Name == name && m.GetGenericArguments().Length == genericArgTypes.Length && m.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(argTypes) && m.ReturnType == returnType select m).Single().MakeGenericMethod(genericArgTypes); return foo1; } } ```
referencing desired overloaded generic method
[ "", "c#", "reflection", "generics", "methodinfo", "" ]
I get this error if I click a button that starts the backgroundworker twice. ``` This BackgroundWorker is currently busy and cannot run multiple tasks concurrently ``` How can I avoid this?
Simple: Don't start the BackgroundWorker twice. You can check if it is already running by using the `IsBusy` property, so just change this code: ``` worker.RunWorkerAsync(); ``` to this: ``` if( !worker.IsBusy ) worker.RunWorkerAsync(); else MessageBox.Show("Can't run the worker twice!"); ``` Update: If you do actually need to launch multiple background tasks at the same time, you can simply create multiple BackgroundWorker objects
Create a new BackgroundWorker object for each operation that you want to perform. I.e., rather than: ``` BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); for (int i; i < max; i++) { worker.RunWorkerAsync(i); } ``` Try this: ``` for (int i; i < max; i++) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerAsync(i); } ```
This BackgroundWorker is currently busy and cannot run multiple tasks concurrently
[ "", "c#", "backgroundworker", "" ]
I have implemented validation rules on a textBox in my WinForm and it works well. However it checks the validation only when I tab out of the field. I would like it to check as soon as anything is entered in the box and everytime the content changes. Also I'd like it to check validation as soon as the WinForm opens. I remember doing this fairly recently by setting some events and whatnot, but I can't seem to remember how.
TextChanged event in the future you can find all of the events on the MSDN library, here's the [TextBox class reference](http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox(VS.80).aspx): <http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox(VS.80).aspx>
If you're using databinding, go to the Properties of the textbox. Open (DataBindings) at the top, click on the (Advanced) property, three dots will appear (...) Click on those. The advanced data binding screen appears. For each property of the TextBox that is bound, in your case `Text`, you can set when the databinding, and thus the validation, should "kick in" using the combobox `Data Source Update mode`. If you set it to `OnPropertyChanged`, it will re-evaluate as you type (the default is `OnValidation` which only updates as you tab).
Validate on text change in TextBox
[ "", "c#", ".net", "winforms", "validation", "textbox", "" ]
I'm devolping on **Compact Framework 2.0 SP1** and when I try to use **Math.Sinh** it throws me a *Not Supported Exception* If I can't use this function, is there any other alternative? Thanks!
``` sinh(x) = (e^x - e^-x) / 2 ``` [see wikipedia](http://en.wikipedia.org/wiki/Hyperbolic_trigonometric_function) So you should be able to write your own function !
We use [OpenNETCF](http://www.opennetcf.com/FreeSoftware/tabid/84/Default.aspx) to gain access to a lot of APIs that the Compact Framework just doesn't support. The Math package is just one of the them. Indeed, OpenNETCF does support the Sinh function. ``` OpenNETCF.Math2.Sinh(angle: double) ``` If you do a lot of work with the Compact Framework, the [OpenNETCF Smart Device Framework](http://www.opennetcf.com/Default.aspx?tabid=91) can be very helpful.
c# Compact Framework Not Supported Exception on Math.Sinh
[ "", "c#", "math", "compact-framework", "" ]
I see reference of ant a lot but I don't get exactly what its meant to do? from what i've heard its supposed to compile your projects but can't i just do that by clicking Run->Run in eclipse? Edit : I guess I should rephrase my question. I already know that ant is a 'build automation software', my question is, what exactly is build automation? I thought that you're supposed to test your app, and when it is running you click the 'build' button in eclipse or through command-line java, and it makes a .jar file out of it? So why do you need to 'automate' this process?
> *I already know that ant is a 'build automation software', my question is, what exactly is build automation? I thought that you're supposed to test your app, and when it is running you click the 'build' button in eclipse or through command-line java, and it makes a .jar file out of it? So why do you need to 'automate' this process?* Not all the Java development is done through eclipse and not all the jars may be built from the command line ( or should be built from the command line ) . You may need additionally run test cases, unit tests, and many, many other process. What ant does, is provide a mechanism to automate all this work ( so you don't have to do it every time ) and perhaps you may invoke this ant script each day at 6 p.m. For instance, in some projects, a daily build is needed, the following are the task that may be automated with ant, so they can run without human intervention. * Connect to subversion server. * Download/update with the latest version * Compile the application * Run the test cases * Pack the application ( in jar, war, ear, or whatever ) * Commit this build binaries to subversion. * Install the application in a remote server * Restart the server * Send an email with the summary of the job. Of course for other projects this is overkill, but for some others is very helpful.
[rogeriopvl](https://stackoverflow.com/questions/610732/what-is-ant-used-for-in-java/610738#610738) is absolutely correct, but to answer your "can't I just do that by clicking Run->Run in Eclipse?" question: that's fine for a project that you're working on on your own, and don't need a repeatable, scriptable build in multiple environments. If you're working on an open source project, however, or professional software which needs to be able to build on a build server etc, requiring a particular IDE to be running isn't a good idea.
What is build automation software (for example, Ant)?
[ "", "java", "ant", "build-process", "" ]
I am making a regex expression in which I only want to match wrong tags like: `<p> *some text here, some other tags may be here as well but no ending 'p' tag* </p>` ``` <P>Affectionately Inscribed </P><P>TO </P><P>HENRY BULLAR, </P><P>(of the western circuit)<P>PREFACE</P> ``` In the above same text I want to get the result as `<P>(of the western circuit)<P>` and nothing else should be captured. I'm using this but its not working: ``` <P>[^\(</P>\)]*<P> ``` Please help.
Regex is not always a good choice for xml/html type data. In particular, attributes, case-sensitivity, comments, etc all have a big impact. For xhtml, I'd use `XmlDocument`/`XDocument` and an xpath query. For "non-x" html, I'd look at the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) and the same.
Match group one of: ``` (?:<p>(?:(?!<\/?p>).?)+)(<p>) ``` matches the second `<p>` in: ``` <P>(of the western circuit)<P>PREFACE</P> ``` Note: I'm usually one of those that say: "Don't do HTML with regex, use a parser instead". But I don't think the specific problem can be solved with a parser, which would probably just ignore/transparently deal with the invalid markup.
Regex - I only want to match the start tags in regex
[ "", "c#", ".net", "html", "regex", "tags", "" ]
I'm working on porting a large vb6 application to .NET. The current app is a desktop app that communicates with a set of local access databases. There are about 200 forms in the application and about 100 tables. The screens are mostly complex. Most show master-detail relationships, lots of rows in embedded spreadsheet and dynamically generated editing controls. They will port it to .NET. I'm not sure if they will want it web-based or winforms. To me, it seems that the application is better suited for winforms. Thankfully, the access databases will be replaced with sql server regardless of choice. My reasons for winforms: * Richer UI. * Client caching * Faster development. Winforms is productive for me even though ASP.NET is light years more productive than classic ASP. I would still rather work in winforms. * Can display more data and spend less time concerned with managing state. I plan to breakout the business/data layer into a seperate library. The business objects in the library will be able to be used either by the winforms or web app. I'm thinking that if we port to winforms first and have a clean seperation of UI and business logic, I will be able to reuse the business logic in a web version at a later date. Given the business/data layer is in a seperate library with no UI dependencies. In the end, it's not my decision to make but I would like to hear your experience moving large windows apps to asp.net. What was your experience moving a large desktop app to asp.net? How would you approach a project like this? Would you rather port this app to winforms or asp.net? Why? Thanks! Steve
I would suggest that you do your port in stages to make the transition easier. The first stage would be to port from VB6 desktop to .NET desktop (win forms). Then in the second stage, if still needed, you move all or parts of the .NET desktop to an ASP.NET GUI. The step from VB6 to .NET is in itself quite large for a team to make, regardless of GUI choice. The staged approach would allow your team to get to grips with .NET in an application style more similar to the current app. Your goal to separate business logic into re-usable libraries is therefore important for this staged approach to work. If you take this approach, you have much more flexibility about the GUI type (or types) used. For example you could have all simpler screens provided in an ASP.NET website, with an auxillary WindowsForms app containing more complex screens that users can download as required. Importantly both of these would use the same business logic libraries, they are mostly just different interfaces to the same application. ASP.NET (or web development in general) requires a quite different developer mindset when dealing with state, cross browser, html/css etc. I recently worked on a port/migration of a large Delphi desktop app to .NET. The goal was to go to ASP.NET, however this fell over completely because the existing team had limited web development experience and tried to just re-implement the dektop app using ASP.NET. I'd say that this is a much bigger risk when compared to re-creating screens in Windows Forms, at least the end result will be usable and provide end-users some value. While Ajax and jQuery have made great improvements to the richness of web GUIs, it sounds like your the existing app has some areas such as spreadsheet presentation of data that would be easier to implement efficiently in a desktop app. In summary, the "ideal" is to move the business logic and rules to .NET in such a way that you can then simply "plug-in" a user interface at a later date. This may be much easier said then done, but that is the goal I normally aim for.
One major advantage of porting to a new ASP.Net Web app would be that you will have a lot more opportunities to clean it up. When moving to winforms, there will be a great temptation and pressure to just "port it screen for screen", while if you go to web you will have the opportunity to refactor and improve at a more fundamental level. My company is currently porting a fairly large legacy VB6/Access app to ASP.Net, and with AJAX (and now Silverlight) it's possible to get a really high level of visual quality and complexity in the UI on the web these days. There are obvious advantages from a user access and deployment standpoint as well. As far as how to approach the project, I have had success using an iterative approach -- build out a thin slice (implementing a single feature) to prove out the architecture, then add in features based on priority and complexity.
Moving large vb6 app to web or winforms. You decide!
[ "", "c#", "asp.net", "winforms", "desktop-application", "vb6-migration", "" ]
Are there any general rules when using recursion on how to avoid stackoverflows?
How many times you will be able to recurse will depend on: * The stack size (which is usually 1MB IIRC, but the binary can be hand-edited; I wouldn't recommend doing so) * How much stack each level of the recursion uses (a method with 10 uncaptured `Guid` local variables will be take more stack than a method which doesn't have any local variables, for example) * The JIT you're using - sometimes the JIT *will* use tail recursion, other times it won't. The rules are complicated and I can't remember them. (There's a [blog post by David Broman back from 2007](https://web.archive.org/web/20190110160434/https://blogs.msdn.microsoft.com/davbr/2007/06/20/enter-leave-tailcall-hooks-part-2-tall-tales-of-tail-calls), and [an MSDN page from the same author/date](http://blogs.msdn.com/davbr/pages/tail-call-jit-conditions.aspx), but they may be out of date by now.) How to avoid stack overflows? Don't recurse too far :) If you can't be reasonably sure that your recursion will terminate without going very far (I'd be worried at "more than 10" although that's very safe) then rewrite it to avoid recursion.
It really depends on what recursive algorithm you're using. If it's simple recursion, you can do something like this: ``` public int CalculateSomethingRecursively(int someNumber) { return doSomethingRecursively(someNumber, 0); } private int doSomethingRecursively(int someNumber, int level) { if (level >= MAX_LEVEL || !shouldKeepCalculating(someNumber)) return someNumber; return doSomethingRecursively(someNumber, level + 1); } ``` It's worth noting that this approach is really only useful where the level of recursion can be defined as a logical limit. In the case that this cannot occur (such as a divide and conquer algorithm), you will have to decide how you want to balance simplicity versus performance versus resource limitations. In these cases, you may have to switch between methods once you hit an arbritrary pre-defined limit. An effective means of doing this that I have used in the quicksort algorithm is to do it as a ratio of the total size of the list. In this case, the logical limit is a result of when conditions are no longer optimal.
Using Recursion in C#
[ "", "c#", "recursion", "stack-overflow", "" ]
I have a C#.NET application running on a machine. How do I calculate the checksum of the entire code at runtime? ### Note: I do not want to calculate the checksum of the image in use but the actual code part.
I have never used this, but: Using reflection you can navigate to the [GetILAsByteArray](http://msdn.microsoft.com/en-us/library/system.reflection.methodbody.getilasbytearray.aspx) and do a checksum (per method). But I think it will be a lot easier to use code signing or the Assembly.GetExecutingAssembly and then do a checksum on the .dll or .exe.
I would just use [code signing](http://www.wintellect.com/cs/blogs/jrobbins/archive/2007/12/21/code-signing-it-s-cheaper-and-easier-than-you-thought.aspx), but if you really want to roll your own solution (which may be a bad idea. Code signing is a Good Thing) you could use reflection to look into the IL code and calculate a checksum based on that. That's not a very nice solution, and could cause some weird bugs, so please, save yourself some trouble and use code signing.
How can I calculate the checksum of code at runtime?
[ "", "c#", ".net", "checksum", "" ]
I'm used to having my compiler complain when I do something stupid like a typo on a variable name but JavaScript has a habit of letting this pass. Are there any static analysis tools for JavaScript?
I agree that JSLint is the best place to start. Note that [JavaScript Lint](http://www.javascriptlint.com/) is distinct from [JSLint](http://www.jslint.com/). I’d also suggest checking out [JSure](https://github.com/berke/jsure), which in my limited testing did better than either of them, though with some rough edges in the implementation—the Intel Mac version crashed on startup for me, though the PowerPC version ran fine even on Intel, and the Linux version ran fine as well. (The developer, Berke Durak, said he'd get back to me when this was fixed, but I haven't heard from him.) Don’t expect as much from JavaScript static analysis as you get from a good C checker. As Durak told me, “any non-trivial analysis is very difficult due to Javascript's dynamic nature.” (Another, even more obscure Mac-only bug, this time with JSLint’s Konfabulator widget: Dragging a BBEdit document icon onto the widget moves the document to the trash. The developer, Douglas Crockford, hadn’t tried the widget on a Mac.) 10 August 2009: Today at the [Static Analysis Symposium](http://sas09.cs.ucdavis.edu/), Simon Holm Jensen presented a paper on [TAJS: Type Analyzer for JavaScript](http://www.brics.dk/TAJS/), written with Anders Møller and Peter Thiemann. The paper doesn’t mention the above tools, but Jensen told me he’d looked at some of them and wasn’t impressed. The code for TAJS should be available sometime this summer.
UPDATED ANSWER, 2017: Yes. Use ESLint. <http://eslint.org> --- In addition to [JSLint](http://jslint.org) (already mentioned in [Flash Sheridan's answer](https://stackoverflow.com/a/710837/55478)) and the [Closure compiler](https://developers.google.com/closure/compiler/docs/gettingstarted_app) (previously mentioned in [awhyte's answer](https://stackoverflow.com/a/2220180/55478)) I have have also gotten a lot of benefit from running [JSHint](http://jshint.com/about) and [PHP CodeSniffer](http://pear.php.net/package/PHP_CodeSniffer). As of 2012, all four tools are free open-source and have a large and active developer community behind them. They're each a bit different (and I think, complementary) in the kinds of checks they perform: **JSLint** was designed to be, and still is Douglas Crockford's personal linting tool. It ships with a *great* default ruleset -- Crockford's own, [constantly updated](https://github.com/douglascrockford/JSLint/commits/master/) as he [continues to learn](http://tech.groups.yahoo.com/group/jslint_com/msearch?date=any&DM=------------&DD=----&DY=----&DM2=------------&DD2=----&DY2=----&AM=contains&AT=douglas&SM=contains&ST=&MM=contains&MT=%22try+it+now%22&charset=UTF-8) about JavaScript and its pitfalls. JSLint is [highly opinionated](https://gist.github.com/1745829) and this is generally [seen as a good thing.](http://docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint "jQuery passes JSLint as of version 1.4.3") Thus there's (intentionally) a [limited amount](http://www.jslint.com/lint.html#options) you can do to configure or disable individual rules. But this can make it tough to apply JSLint to legacy code. **JSHint** is very similar to JSLint (in fact it [began life](http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/) as JSLint fork) but it is easier/possible to [configure or disable](http://www.jshint.com/docs/) all of JSLint's checks via command line options or via a [`.jshintrc` file](https://npmjs.org/package/jshint). I particularly like that I can tell JSHint to report *all* of the errors in a file, even if there are hundreds of errors. By contrast, although JSLint does have a `maxerr` configuration option, it will generally bail out relatively early when attempting to process files that contain large numbers of errors. **The Closure compiler** is extremely useful in that, if code *won't* compile with Closure, you can feel very certain said code *is* deeply hosed in some fundamental way. Closure compilation is possibly the closest thing that there is in the JS world to an "interpreter" syntax check like `php -l` or `ruby -c` Closure also [warns you about potential issues](https://developers.google.com/closure/compiler/docs/error-ref) such as missing parameters and undeclared or redefined variables. If you aren't seeing the warnings you expect, try increasing the warning level by invoking Closure with an option of `--warning_level VERBOSE` **PHP CodeSniffer** [can parse JavaScript](https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Tokenizers/JS.php) as well as PHP and CSS. CodeSniffer ships with several different coding standards, (say `phpcs -i` to see them) which include many useful sniffs for JavaScript code including checks against [inline control structures](https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php) and [superfluous whitespace](https://github.com/squizlabs/PHP_CodeSniffer/blob/master/CodeSniffer/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php). Here is a [list of JavaScript sniffs](https://gist.github.com/3375708#file_js_code_sniffs.md) available in PHP CodeSniffer as of version 1.3.6 and here is a [custom ruleset that would allow you to run them all at once.](https://gist.github.com/3375708#file_js_sniffs.xml) Using custom rulesets, it's easy to [pick and choose the rules](http://pear.php.net/manual/en/package.php.php-codesniffer.annotated-ruleset.php) you want to apply. And you can even [write your own sniffs](http://pear.php.net/manual/en/package.php.php-codesniffer.coding-standard-tutorial.php) if you want to enforce a particular "house style" that isn't supported out of the box. Afaik CodeSniffer is the only tool of the four mentioned here that supports customization and creation of new static analysis rules. One caveat though: CodeSniffer is also the slowest-running of any of the tools mentioned.
Are there any JavaScript static analysis tools?
[ "", "javascript", "static-analysis", "" ]
I have this query that works fine. It selects rows into the SY.UserOptions table for the ‘Jeff’ user. However, I created another query that I want to do the same thing, but for every user. So I added SY.Users to the query, which in effect mulplies the 2 tables together. However, it gives me an error that I do not understand. ``` --This works SELECT ‘Jeff’, t.Application, t.Task, tl.Description FROM SY.Tasks t LEFT OUTER JOIN SY.TaskLevels tl ON t.Application = tl.Application And t.Task = tl.Task AND t.DftAccessLevel = tl.AccessLevel -- This does not work SELECT u.[User], t.Application, t.Task, tl.Description FROM SY.Tasks t, SY.Users u LEFT OUTER JOIN SY.TaskLevels tl ON t.Application = tl.Application And t.Task = tl.Task AND t.DftAccessLevel = tl.AccessLevel ``` --Here is the error > Msg 4104, Level 16, State 1, Procedure CreateUserOptions, Line 15 > The multi-part identifier "t.Application" could not be bound. > Msg 4104, Level 16, State 1, Procedure CreateUserOptions, Line 15 > The multi-part identifier "t.Task" could not be bound. > Msg 4104, Level 16, State 1, Procedure CreateUserOptions, Line 15 > The multi-part identifier "t.DftAccessLevel" could not be bound. Can I not multiply tables together like that and include a join?
I think the problem is that in the second query, when you join the SY.Users table and the SY.TaskLevels table, you are referencing the SY.Tasks table - which is not part of the join. Switch the Sy.Users table and the Sy.Tasks table around and your problem should be fixed.
You need a field to join the users table to the Tasks table. ``` SELECT u.[User], t.Application, t.Task, tl.Description FROM SY.Tasks t INNER JOIN SY.Users u --LEFT OUTER if it makes a difference ON t.user = u.User --not sure if these fields are available maybe some type of userId? LEFT OUTER JOIN SY.TaskLevels tl ON t.Application = tl.Application And t.Task = tl.Task AND t.DftAccessLevel = tl.AccessLevel ```
Advanced SQL INSERT
[ "", "sql", "t-sql", "" ]
I'm new to sphinx, and I'm seting it up on a new website. It's working fine, and when i search with the *search* in the console, everything work. Using the PHP api and the searched, gives me the same results as well. But it gives me only ids and weights for the rows found. Is there some way to bring some text fields togheter with the 'matches' hash, for example? If there is no way to do this, does anyone have a good idea about how to retrieve the records from the database (sql) in the sphinx weight sort order (searching all them at the same time)?
You can use a mysql FIELD() function call in your ORDER BY to ensure everything is in the order sphinx specified. ``` $idlist = array(); foreach ( $sphinx_result["matches"] as $id => $idinfo ) { $idlist[] = "$id"; } $ids = implode(", ", $idlist); SELECT * FROM table WHERE id IN ($ids) ORDER BY FIELD(id, $ids) ```
Yeah, sphinx doesn't bring the results. But I found out a simple way to reorder the query using the IN() clause, to bring all together. Quering something ``` SELECT * FROM table WHERE id IN(id_list... ) ``` just indexing the result, with their id in the table: ``` while ($row = mysql_fetch_objects) $result[$row->id] = $row; ``` and having the matching results from sphinx, its very easy to reorder: ``` $ordered_result = array(); foreach ($sphinxs_results['matches'] as $id => $content) $ordered_result[] = $result1[$id]; ``` this shall work, if your $sphinxs\_results are in the correct order. its almost pat's answer, but with less one loop. Can make some diference in big results, I guess.
Whats the best way to retrieve information from Sphinx (in PHP)?
[ "", "php", "mysql", "database", "full-text-search", "sphinx", "" ]
I have a list of lists that looks like this: ``` [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] ``` and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list: ``` {'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, 'Bob': 2} ``` I tried various list comprehensions, but I couldn't get it to work right with the nested lists. I could use a nested loop, like this: ``` names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] names_dict = {} for i, name_sublist in enumerate(names): for name in name_sublist: names_dict[name] = i ``` but I suspect there is a shorter, more elegant way of doing it.
``` names_dict = dict((name,index) for index,lst in enumerate(names) for name in lst) ``` Example: ``` >>> names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] >>> names_dict = dict((name,index) ... for index,lst in enumerate(names) ... for name in lst) >>> names_dict {'Tom': 0, 'Mike': 1, 'Dick': 0, 'Harry': 1, 'Bob': 2, 'John': 1} ```
Same idea as MizardX, but slightly smaller and prettier in Python 3.0 using [dict comprehensions:](http://www.python.org/dev/peps/pep-0274/) ``` >>> names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] >>> names_dict = {name:index for index, lst in enumerate(names) for name in lst} >>> names_dict {'Tom': 0, 'Mike': 1, 'Dick': 0, 'Harry': 1, 'Bob': 2, 'John': 1} ```
Python Golf: what's the most concise way of turning this list of lists into a dictionary:
[ "", "python", "code-golf", "" ]
I have this code on an applet. The applet works ok, but I get a lot of unnecessary duplicate download. In particular, I have noticed that each "getResource" triggers a download of the .JAR file. ``` static { ac = new ImageIcon(MyClass.class.getResource("images/ac.png")).getImage(); dc = new ImageIcon(MyClass.class.getResource("images/dc.png")).getImage(); //...other images } ``` How can this be avoided?
Do you include the applet to a HTML page? If so, try to enable the JAR caching, as is described here: <http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html> If that does not help for some reason :) perhaps expose your resources / images along your applet JAR on a web server and reach them using separate HTTP requests (yes, its ugly and yes, it does not reduce number of needed downloads, but it at least reduces the amount of data that need to be transferred).
Simply removing all instances of URLConnection.setDefaultUseCaches(false) will solve the problem. Please refer for more details. <http://java-junction.blogspot.com/2009/11/applet-jar-caching-not-working.html>
JAR multiple download
[ "", "java", "jar", "applet", "download", "overloading", "" ]
I often find that the headers section of a file gets larger and larger all the time, but it never gets smaller. Throughout the life of a source file, classes may have moved and been refactored and it's very possible that there are quite a few `#include`s that don't need to be there and anymore. Leaving them there only prolong the compile time and adds unnecessary compilation dependencies. Trying to figure out which are still needed can be quite tedious. Is there some kind of tool that can detect superfluous `#include` directives and suggest which ones I can safely remove? Does lint do this maybe?
It's not automatic, but [Doxygen](http://www.doxygen.nl/) will produce dependency diagrams for `#included` files. You will have to go through them visually, but they can be very useful for getting a picture of what is using what.
Google's cppclean (links to: [download](https://github.com/myint/cppclean), [documentation](https://code.google.com/p/cppclean/)) can find several categories of C++ problems, and it can now find superfluous #includes. There's also a Clang-based tool, [include-what-you-use](https://github.com/include-what-you-use/include-what-you-use), that can do this. include-what-you-use can even suggest forward declarations (so you don't have to #include so much) and optionally clean up your #includes for you. Current versions of [Eclipse CDT](http://www.eclipse.org/cdt/) also have this functionality built in: going under the Source menu and clicking Organize Includes will alphabetize your #include's, add any headers that Eclipse thinks you're using without directly including them, and comments out any headers that it doesn't think you need. This feature isn't 100% reliable, however.
Detecting superfluous #includes in C/C++
[ "", "c++", "c", "refactoring", "include", "dependencies", "" ]
Given: ``` Object nestKey; Object nestedKey; Object nestedValue; Map<T,Map<T,T>> nest; Map<T,T> nested; ``` How is a mapping added to nested where: > nest.containsKey(nestKey) == true; ? Or is there an existing library of collections that would be more effective?
You mean something like the following *generic method*? ``` static <U,V,W> W putNestedEntry( Map<U,Map<V,W>> nest, U nestKey, V nestedKey, W nestedValue) { Map<V,W> nested = nest.get(nestKey); if (nested == null) { nested = new HashMap<V,W>(); nest.put(nestKey, nested); } return nested.put(nestedKey, nestedValue); } ```
It is a fairly common idiom to either: * have a map of a map as you suggest * have one map, where your keys combine "main" key and "subkey" (possibly a more efficient use of space, but generally less suitable if you need to *iterate* keys and subkeys)
How to add a inner mapping in a nested collection?
[ "", "java", "collections", "dictionary", "nested", "" ]
I have an interesting problem, and I can't seem to figure out the lambda expression to make this work. I have the following code: ``` List<string[]> list = GetSomeData(); // Returns large number of string[]'s List<string[]> list2 = GetSomeData2(); // similar data, but smaller subset &nbsp; List<string[]> newList = list.FindAll(predicate(string[] line){ return (???); }); ``` I want to return only those records in list in which element 0 of each string[] is equal to one of the element 0's in list2. list contains data like this: ``` "000", "Data", "more data", "etc..." ``` list2 contains data like this: ``` "000", "different data", "even more different data" ``` Fundamentally, i could write this code like this: ``` List<string[]> newList = new List<string[]>(); foreach(var e in list) { foreach(var e2 in list2) { if (e[0] == e2[0]) newList.Add(e); } } return newList; ``` But, i'm trying to use generics and lambda's more, so i'm looking for a nice clean solution. This one is frustrating me though.. maybe a Find inside of a Find? EDIT: Marc's answer below lead me to experiment with a varation that looks like this: ``` var z = list.Where(x => list2.Select(y => y[0]).Contains(x[0])).ToList(); ``` I'm not sure how efficent this is, but it works and is sufficiently succinct. Anyone else have any suggestions?
You could join? I'd use two steps myself, though: ``` var keys = new HashSet<string>(list2.Select(x => x[0])); var data = list.Where(x => keys.Contains(x[0])); ``` If you only have .NET 2.0, then either install [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) and use the above (or similar with a `Dictionary<>` if LINQBridge doesn't include `HashSet<>`), or perhaps use nested `Find`: ``` var data = list.FindAll(arr => list2.Find(arr2 => arr2[0] == arr[0]) != null); ``` note though that the `Find` approach is O(n\*m), where-as the `HashSet<>` approach is O(n+m)...
You could use the Intersect extension method in System.Linq, but you would need to provide an IEqualityComparer to do the work. ``` static void Main(string[] args) { List<string[]> data1 = new List<string[]>(); List<string[]> data2 = new List<string[]>(); var result = data1.Intersect(data2, new Comparer()); } class Comparer : IEqualityComparer<string[]> { #region IEqualityComparer<string[]> Members bool IEqualityComparer<string[]>.Equals(string[] x, string[] y) { return x[0] == y[0]; } int IEqualityComparer<string[]>.GetHashCode(string[] obj) { return obj.GetHashCode(); } #endregion } ```
Using lambda expressions to get a subset where array elements are equal
[ "", "c#", "lambda", "" ]
As I see it, there are two ways to handle mouse events to draw a picture. The first is to detect when the mouse moves and draw a line to where the mouse is, shown [here](http://www.cs.iupui.edu/~aharris/pygame/ch05/paint.py). However, the problem with this is that with a large brush size, many gaps appear between each "line" that is not straight since it is using the line's stroke size to create thick lines. The other way is to draw circles when the mouse moves as is shown [here](http://www.ida.liu.se/~ETE257/timetable/LecturePythonPygame2.html). The problem with this is that gaps appear between each circle if the mouse moves faster than the computer detects mouse input. Here's a screenshot with my issues with both: ![http://imgur.com/32DXN.jpg](https://i.stack.imgur.com/7ILzZ.png) What is the best way to implement a brush like MS Paint's, with a decently-big brush size with no gaps in the stroke of the line or no gaps between each circle?
Why not do both? Draw a circle at each endpoint and a line between the two. **EDIT** rofl, just couldn't stop myself. Actually, you don't want to use `pygame.draw.line` because it cheats. It fills a 1 pixel wide row or column (depending on angle of attack) of pixels. If you do go at a roughly perpendicular angle, 0 deg or 90 deg, this isn't an issue, but at 45's, you'll notice a sort of *string bean* effect. The only solution is to draw a circle at every pixel's distance. Here... ``` import pygame, random screen = pygame.display.set_mode((800,600)) draw_on = False last_pos = (0, 0) color = (255, 128, 0) radius = 10 def roundline(srf, color, start, end, radius=1): dx = end[0]-start[0] dy = end[1]-start[1] distance = max(abs(dx), abs(dy)) for i in range(distance): x = int( start[0]+float(i)/distance*dx) y = int( start[1]+float(i)/distance*dy) pygame.draw.circle(srf, color, (x, y), radius) try: while True: e = pygame.event.wait() if e.type == pygame.QUIT: raise StopIteration if e.type == pygame.MOUSEBUTTONDOWN: color = (random.randrange(256), random.randrange(256), random.randrange(256)) pygame.draw.circle(screen, color, e.pos, radius) draw_on = True if e.type == pygame.MOUSEBUTTONUP: draw_on = False if e.type == pygame.MOUSEMOTION: if draw_on: pygame.draw.circle(screen, color, e.pos, radius) roundline(screen, color, e.pos, last_pos, radius) last_pos = e.pos pygame.display.flip() except StopIteration: pass pygame.quit() ```
Not blitting at each loop step can improve the speed of the drawing (using this code adapted from the previous one allow to remove lag problem on my machine) ``` import pygame, random screen = pygame.display.set_mode((800,600)) draw_on = False last_pos = (0, 0) color = (255, 128, 0) radius = 10 def roundline(srf, color, start, end, radius=1): dx = end[0]-start[0] dy = end[1]-start[1] distance = max(abs(dx), abs(dy)) for i in range(distance): x = int( start[0]+float(i)/distance*dx) y = int( start[1]+float(i)/distance*dy) pygame.display.update(pygame.draw.circle(srf, color, (x, y), radius)) try: while True: e = pygame.event.wait() if e.type == pygame.QUIT: raise StopIteration if e.type == pygame.MOUSEBUTTONDOWN: color = (random.randrange(256), random.randrange(256), random.randrange(256)) pygame.draw.circle(screen, color, e.pos, radius) draw_on = True if e.type == pygame.MOUSEBUTTONUP: draw_on = False if e.type == pygame.MOUSEMOTION: if draw_on: pygame.display.update(pygame.draw.circle(screen, color, e.pos, radius)) roundline(screen, color, e.pos, last_pos, radius) last_pos = e.pos #pygame.display.flip() except StopIteration: pass pygame.quit() ```
How to create MS Paint clone with Python and pygame
[ "", "python", "mouse", "pygame", "draw", "paint", "" ]
I love to organize my code, so ideally I want one class per file or, when I have non-member functions, one function per file. The reasons are: 1. When I read the code I will always know in what file I should find a certain function or class. 2. If it's one class or one non-member function per header file, then I won't include a whole mess when I `include` a header file. 3. If I make a small change in a function then only that function will have to be recompiled. However, splitting everything up into many header and many implementation files can considerately slow down compilation. In my project, most functions access a certain number of templated other library functions. So that code will be compiled over and over, once for each implementation file. Compiling my whole project currently takes 45 minutes or so on one machine. There are about 50 object files, and each one uses the same expensive-to-compile headers. Maybe, is it acceptable to have one class (or non-member function) per *header* file, but putting the implementations of many or all of these functions into *one* implementation file, like in the following example? ``` // foo.h void foo(int n); // bar.h void bar(double d); // foobar.cpp #include <vector> void foo(int n) { std::vector<int> v; ... } void bar(double d) { std::vector<int> w; ... } ``` Again, the advantage would be that I can include just the foo function or just the bar function, and compilation of the whole project will be faster because `foobar.cpp` is *one* file, so the `std::vector<int>` (which is just an example here for some other expensive-to-compile templated construction) has to be compiled in only once, as opposed to twice if I compiled a `foo.cpp` and `bar.cpp` separately. Of course, my reason (3) above is not valid for this scenario: After just changing foo(){...} I have to recompile the whole, potentially big, file `foobar.cpp`. I'm curious what your opinions are!
IMHO, you should combine items into logical groupings and create your files based on that. When I'm writing functions, there are often a half a dozen or so that are tightly related to each other. I tend to put them together in a single header and implementation file. When I write classes, I usually limit myself to one heavyweight class per header and implementation file. I might add in some convenience functions or tiny helper classes. If I find that an implementation file is thousands of lines long, that's usually a sign that there's too much there and I need to break it up.
One function per file could get messy in my opinion. Imagine if POSIX and ANSI C headers were made the same way. ``` #include <strlen.h> #include <strcpy.h> #include <strncpy.h> #include <strchr.h> #include <strstr.h> #include <malloc.h> #include <calloc.h> #include <free.h> #include <printf.h> #include <fprintf.h> #include <vpritnf.h> #include <snprintf.h> ``` One class per file is a good idea though.
Should I put many functions into one file? Or, more or less, one function per file?
[ "", "c++", "build-process", "compilation", "code-organization", "file-organization", "" ]
I have an external JS file that I include in my ASPX page. Whenever I make changes to the JS, I need to close the browser and reopen it to see the changes. I have tried Ctrl F5 to refresh the cached JS copy but that doesn't work in IE. Is there some way to not restart the browser to see the updated changes?
As others suggest, I would switch to Firefox for developing and keep IE only for testing. If you want to keep developing on IE try the [Internet Explorer Developer Toolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359). It offers some of the functionality of Firebug and you will have quick access to options for disabling the cache or clearing the cache for a specific domain, solving your caching problems. ![Cache menu](https://lh5.ggpht.com/_EuP0VgCBcqk/SZ7OqlxsyuI/AAAAAAAACV0/4cVa_syswwQ/s800/capturaIEDevToolbar.png)
I sometimes keep the JavaScript or CSS files open in other tabs and force reload those tabs to get IE to understand "please reload everything, no really, everything."
External JS and browser
[ "", "javascript", "internet-explorer", "caching", "" ]
I'm running Vista 64 box, and attempting to setup Joomla using IIS7 (I like Joomla, I want to have some asp.net components on my web site, so that's why I want to use IIS7 and not Apache). It's my first time installing both PHP and MySQL, so it's very possible that I'm doing something obviously wrong... though I think I tried enough diagnostic steps (described below) that there's nothing obviously wrong *to me*... I installed PHP (32 bit, 5.2.8), and that seems to work OK: I got a `test.php` that displays phpinfo in an IIS7-served web page. I also installed MySQL (32 bit, 5.1.31, downloaded from <http://dev.mysql.com/downloads/mysql/5.1.html#win32> ). That seems to work fine too (I can connect to it using MySQL Administrator). I've setup `php.ini` and what not to turn on the MySQL extension. If I do PHP -m from the command line I see MySQL in the list. However, with phpinfo (either from the command line (PHP -info) or served via IIS (in a `test.php` file)), there is no MySQL section. Because MySQL is not even showing up in the command-line call of PHP, I don't think this has anything to do with IIS -- just an install of MySQL & PHP on vista. I didn't install MySQL 64bit because I have an 32bit install of PHP, and since MySQL 32 bit seems to work fine I assume that's not the issue. It seems there is no official 64bit version of PHP so that's why I installed that (and again, that seems to work fine). I currently have UAC disabled, so that's not the issue. If I put the semi-colon back in front of extension=php\_mysql.dll in my `php.ini` then when running PHP -m, the MySQL module doesn't show up. If I take it out again then it shows up. So I'm at least certain I'm modifying the right `php.ini`. I've copied `libeay32.dll`, `libmysql.dll`, and `php_mysql.dll` to `c:\windows\system32`. I've taken them out and that doesn't seem to make a difference to the output of PHP -m (i.e., MySQL still shows up there if the module is uncommented from `php.ini`). I also tried copying the DLLs `ibeay32.dll`, `libmysql.dll`, and `php_mysql.dll` to `c:\windows\sysWOW64`; that made no difference. It seems like the smallest positive step would be for MySQL to show up when running PHP -info from the command line. Is there any further thing I should try to figure out why MySQL is showing up in PHP -m and not with PHP -info? Or am I off track as using this to gauge whether PHP can talk to MySQL?
I've solved most of it. The answer was to copy `libmysql.dll` to sysWOW64. The other DLLs are not needed, and nothing needs to be copied to system32. I guess this is a result of using php32 on a 64 bit system. I thought that didn't work at first because running PHP -info from the command line still doesn't show MySQL. However, running phpinfo from a PHP file served by IIS does show MySQL. I still don't know why MySQL doesn't show up when running PHP -info from the command line, but I guess I can live with this for now.
If you want to focus on the php development I strongly suggest you don't manually install these things and go download xampp from <http://www.apachefriends.org/en/xampp.html> Basically this is a completely tested and build package which will link the software and give you a full develoment environment. There are other apache/php/mysql bundles out there as well. The thing here is that as soon as you have the apache php working with mysql, you can just configure the IIS connector easily and you won't break the mysql connectivity Also remember to check everything with
Can't get PHP to work with MySQL on Vista 64
[ "", "php", "mysql", "windows-vista", "64-bit", "" ]
I have a listbox with 20 colors. It looks something like this: 1:Red 2:Green 3:Blue 4:Orange 5:Red 6:Yellow 7:Orange 8:Red 9:Green .... It gets the data from an ObjectDataSource which in turn gets it's data from a method which returns a datatable. I want a dropdown which basically has 2 items, Order By # and Order By Color. If the user chooses Order By #, it will Order the ListBox in ascending or descending order. If the user chooses Order By Color, it will Order By Color. How do I go about doing this? Can I sort this using a DataView? Thanks, XaiSoft
You can add the sort expression to your ObjectDataSource as a Select parameter, you can define it like so: ``` <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="SelectMethod" TypeName="MyDataObject"> <asp:Parameter Direction="input" Type="string" Name="sortExpression"> </asp:Parameter> </asp:ObjectDataSource> ``` Then in the "SelectMethod" method where the data is retrieved add a parameter of that name and return a DataView: ``` public DataView SelectMethod(string sortExpression) { DataTable table = GetData(); DataView dv = new DataView(table); dv.Sort = sortExpression; return dv; } ``` Then in the wizard for the ObjectDataSource you can bind that Parameter to the dropdown SelectedValue. Make the value of each of the DropDown items the same as your column names.
(I'm assuming you've already figured out how to bind the ListBox in the first place.) Set the property AutoPostback="true" on your DropdownList. This will cause the SelectedIndexChanged event to fire when the user picks a different value. In there you can rebind your listbox. --- **Edit:** deleted my misunderstanding around the ObjectDataSource - joshperry's answer covers that much better!
How to dynamically Order a listbox with a dropdown?
[ "", "c#", "asp.net", "" ]
How can I exit the JavaScript script much like PHP's `exit` or `die`? I know it's not the best programming practice but I need to.
[JavaScript equivalent for PHP's `die`](https://github.com/kvz/phpjs/blob/master/experimental/misc/die.js). BTW it just calls [`exit()`](https://github.com/kvz/phpjs/blob/master/experimental/misc/exit.js) (thanks splattne): ``` function exit( status ) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brettz9.blogspot.com) // + input by: Paul // + bugfixed by: Hyam Singer (http://www.impact-computing.com/) // + improved by: Philip Peterson // + bugfixed by: Brett Zamir (http://brettz9.blogspot.com) // % note 1: Should be considered expirimental. Please comment on this function. // * example 1: exit(); // * returns 1: null var i; if (typeof status === 'string') { alert(status); } window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false); var handlers = [ 'copy', 'cut', 'paste', 'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll', 'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput', 'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload' ]; function stopPropagation (e) { e.stopPropagation(); // e.preventDefault(); // Stop for the form controls, etc., too? } for (i=0; i < handlers.length; i++) { window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true); } if (window.stop) { window.stop(); } throw ''; } ```
"exit" functions usually quit the program or script along with an error message as paramete. For example die(...) in php ``` die("sorry my fault, didn't mean to but now I am in byte nirvana") ``` The equivalent in JS is to signal an error with the **throw** keyword like this: ``` throw new Error(); ``` You can easily test this: ``` var m = 100; throw ''; var x = 100; x >>>undefined m >>>100 ```
How to terminate the script in JavaScript?
[ "", "javascript", "exit", "die", "" ]
All my college years I have been using `public`, and would like to know the difference between `public`, `private`, and `protected`? Also what does `static` do as opposed to having nothing?
## Access modifiers From [learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers): > [**`public`**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/public) > > The type or member can be accessed by any other code in the same assembly or another assembly that references it. > > [**`private`**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private) > > The type or member can only be accessed by code in the same class or struct. > > [**`protected`**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected) > > The type or member can only be accessed by code in the same class or struct, or in a derived class. > > [**`private protected`**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected) (added in C# 7.2) > > The type or member can only be accessed by code in the same class or struct, or in a derived class from the same assembly, but not from another assembly. > > [**`internal`**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal) > > The type or member can be accessed by any code in the same assembly, but not from another assembly. > > [**`protected internal`**](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected-internal) > > The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly. When **no access modifier** is set, a default access modifier is used. So there is always some form of access modifier even if it's not set. ## [`static` modifier](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static) The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created. A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. However, there is a such thing as a [static constructor](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors). Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this: ``` static class Foo() { static Foo() { Bar = "fubar"; } public static string Bar { get; set; } } ``` Static classes are often used as services, you can use them like so: ``` MyStaticClass.ServiceMethod(...); ```
A graphical overview (summary in a nutshell) ![Visibility](https://i.stack.imgur.com/ExkwO.png) Actually, it's a little bit more complicated than that. Now (as of C# 7.2), there's also private protected, and it matters whether a derived class is in the same assembly or not. So the overview needs to be expanded: [![Visibility expanded](https://i.stack.imgur.com/TNtq3.png)](https://i.stack.imgur.com/TNtq3.png) See also the [C#-dotnet-docs on the subject](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers). Since [static classes](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members) are sealed, they cannot be inherited (except from Object), so the keyword protected is invalid on static classes. For the defaults if you put no access modifier in front, see here: [Default visibility for C# classes and members (fields, methods, etc.)?](https://stackoverflow.com/questions/3763612/default-visibility-for-c-sharp-classes-and-members-fields-methods-etc) Non-nested ``` enum public non-nested classes / structs internal interfaces internal delegates in namespace internal class/struct member(s) private delegates nested in class/struct private ``` Nested: ``` nested enum public nested interface public nested class private nested struct private ``` Also, there is the sealed-keyword, which makes a class not-inheritable. Also, in VB.NET, the keywords are sometimes different, so here a cheat-sheet: [![VB vs. CS equivalents](https://i.stack.imgur.com/o6BZf.png)](https://i.stack.imgur.com/o6BZf.png)
In C#, what is the difference between public, private, protected, and having no access modifier?
[ "", "c#", ".net", "asp.net", "access-modifiers", "" ]
How do I find the home directory of an arbitrary user from within Grails? On Linux it's often /home/user. However, on some OS's, like OpenSolaris for example, the path is /export/home/user.
For UNIX-Like systems you might want to execute "`echo ~username`" using the shell (so use `Runtime.exec()` to run `{"/bin/sh", "-c", "echo ~username"}`).
Normally you use the statement ``` String userHome = System.getProperty( "user.home" ); ``` to get the home directory of the user on any platform. See the method documentation for [getProperty](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperty(java.lang.String)) to see what else you can get. There may be access problems you might want to avoid by using [this](https://stackoverflow.com/questions/277100/accesscontrolexception-when-attempting-to-delete-a-file/277287#277287) workaround (Using a security policy file)
How to find a user's home directory on linux or unix?
[ "", "java", "linux", "unix", "grails", "" ]
I am trying to find a way, if possible, to use IN and LIKE together. What I want to accomplish is putting a subquery that pulls up a list of data into an IN statement. The problem is the list of data contains wildcards. Is there any way to do this? Just something I was curious on. ``` Example of data in the 2 tables Parent table ID Office_Code Employee_Name 1 GG234 Tom 2 GG654 Bill 3 PQ123 Chris Second table ID Code_Wildcard 1 GG% 2 PQ% ``` --- Clarifying note (via third-party) Since I'm seeing several responses which don't seems to address what Ziltoid asks, I thought I try clarifying what I think he means. In SQL, "`WHERE col IN (1,2,3)`" is roughly the equivalent of "`WHERE col = 1 OR col = 2 OR col = 3`". He's looking for something which I'll pseudo-code as ``` WHERE col IN_LIKE ('A%', 'TH%E', '%C') ``` which would be roughly the equivalent of ``` WHERE col LIKE 'A%' OR col LIKE 'TH%E' OR col LIKE '%C' ``` The Regex answers seem to come closest; the rest seem way off the mark.
I'm not sure which database you're using, but with Oracle you could accomplish something equivalent by aliasing your subquery in the FROM clause rather than using it in an IN clause. Using your example: ``` select p.* from (select code_wildcard from second where id = 1) s join parent p on p.office_code like s.code_wildcard ```
In `MySQL`, use `REGEXP`: ``` WHERE field1 REGEXP('(value1)|(value2)|(value3)') ``` Same in `Oracle`: ``` WHERE REGEXP_LIKE(field1, '(value1)|(value2)|(value3)') ```
Is there any way to combine IN with LIKE in an SQL statement?
[ "", "sql", "" ]
I currently use 3 different regular expressions in one preg\_match, using the or sign | to separate them. This works perfectly. However the first and second regex have the same type of output. e.g. [0] Source Text [1] Number Amount [2] Name - however the last one since it uses a different arrangement of source text results in: [0] Source Text [1] Name [2] Number Amount. ``` preg_match('/^Guo (\d+) Cars @(\w+)|^AV (\d+) Cars @(\w+)|^@(\w+) (\d+) [#]?av/i', $source, $output); ``` Since `Name` is able to be numeric I can't do a simple check to see if it is numeric. Is there a way I can either switch the order in the regex or identify which regex it matched too. Speed is of the essence here so I didn't want to use 3 separate preg\_match statements (and more to come).
Three separate regular expressions don't have to be slower. One big statement will mean a lot of backtracing for the regular expression engine. Key in regular expression optimisation is to make the engine fail ASAP. Did you do some benchmarking pulling them appart? In your case you can make use of the [PCRE](http://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions)'s named captures `(?<name>match something here)` and replace with `${name}` instead of `\1`. I'm not 100% certain this works for `preg_replace`. I know `preg_match` correctly stores named captures for certain, though. PCRE needs to be compiled with the `PCRE_DUPNAMES` option for that to be useful in your case (as in RoBorg's) post. I'm not sure if PHP's compiled PCRE DLL file has that option set.
You could use named capture groups: ``` preg_match('/^Guo (?P<number_amount>\d+) Cars @(?P<name>\w+)|^AV (?P<number_amount>\d+) Cars @(?P<name>\w+)|^@(?P<name>\w+) (?P<number_amount>\d+) [#]?av/i', $source, $output); ```
Tricky Question: How to order results from a multiple regexes
[ "", "php", "regex", "" ]
**DUPE** [C# Treeview state expanded](https://stackoverflow.com/questions/516192/c-treeview-state-expanded) See above...
I think that depends upon your treeview. The Telerik treeview does this via viewstate... <http://www.telerik.com/community/forums/aspnet/treeview/how-do-i-maintain-treeview-state-after-postback.aspx> ... and this following post suggests a way of hand-rolling this... <http://blog.binaryocean.com/PermaLink,guid,23808645-43b5-4e2a-afb1-53dc8da35636.aspx> I've not tried either solution, so can't vouch for them, but they look promising.
You can try to enable view state for your tree view control.
How do I save the state of the treeview nodes (expanded/collapsed) between postbacks?
[ "", "c#", "asp.net", "" ]
I have run into an issue in which IE does not open up the Save As/Open dialog box for an Excel document like Firefox does. So I have created a servlet filter that is using '\*.xls' as the url pattern. The issue that I now face (since this is the first filter I have created) is how to get the name of the file that the user wants so that the dialog box gets populated correctly. Currently the filter is invoked when the user selects a link on a given page. Here is what I came up with: The above is what I have doFilter(). ``` String fileName = "fileName.xls"; HttpServletRequest httpRequest = (HttpServletRequest) pRequest; String requestURI = httpRequest.getRequestURI(); if(StringUtils.isNotBlank(requestURI)) { String uri[] = StringUtils.split(requestURI, '/'); fileName = uri[uri.length - 1]; } HttpServletResponse httpResponse = (HttpServletResponse) pResponse; httpResponse.setContentType("application/vnd.ms-excel"); httpResponse.setHeader("Content-disposition", "attachment; filename=\"" + fileName +"\""); ``` web.xml: ``` <filter> <filter-name>ExcelFilter</filter-name> <filter-class>vsg.rp.common.ExcelFilter</filter-class> </filter> <filter-mapping> <filter-name>ExcelFilter</filter-name> <url-pattern>*.xls</url-pattern> </filter-mapping> ``` This all is working on my development box: Windows XP, JBoss, Eclipse, Oracle. But when it runs on the test server—Linux, Apache/JBoss, Oracle—it does not work. It appears that the filter is not even being called, no errors thrown, etc. Any idea as to why this would happen?
You want the content type set appropriately as well as the content disposition header, thus: > response.setContentType("application/vnd.ms-excel"); > response.setHeader("Content-Disposition", > "attachment; filename=\"" + filename + > "\"");
Use the `Content-Disposition` HTTP header and set it to something like: ``` attachment; filename=myworkbook.xls ``` The is a [Microsoft Knowledge Base Article](http://support.microsoft.com/kb/260519) all about this problem. And here is an [example of setting Content-Disposition in Java code](http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index3.html).
Issue opening Excel documents with Internet Explorer
[ "", "java", "internet-explorer", "jsp", "servlet-filters", "" ]
This is a fairly newbie question which should be answerable reasonably quickly... Basically, after the first call to *Printf* in *echo*, the contents of *args* is corrupted. It sounds to me like i'm passing the pointers around incorrectly. But can't figure out why? ``` #define MAX_PRINT_OUTPUT 4096 void Echo(char *args[MAX_COMMAND_ARGUMENTS], int argCount) { for (int i = 1; i < argCount; ++i) { Printf("%s ", args[i]); Printf("\n"); } }; void Printf(const char *output, ...) { va_list args; char formattedOutput[MAX_PRINT_OUTPUT]; va_start(args, output); vsnprintf(formattedOutput, sizeof(formattedOutput), output, args); va_end(args); g_PlatformDevice->Print(formattedOutput); }; void RiseWindows::Print(const char *output) { //Corruption appears to occur as soon as this function is entered #define CONSOLE_OUTPUT_SIZE 32767 char buffer[CONSOLE_OUTPUT_SIZE]; char *pBuffer = buffer; const char *pOutput = output; int i = 0; while (pOutput[i] && ((pBuffer - buffer) < sizeof(buffer) - 1)) { if (pOutput[i] == '\n' && pOutput[i+1] == '\r' ) { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; ++i; } else if (pOutput[i] == '\r') { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; } else if (pOutput[i] == '\n') { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; } else { *pBuffer = pOutput[i]; ++pBuffer; } ++i; } *pBuffer = 0; SendMessage(this->ConsoleWindow.hwndBuffer, EM_LINESCROLL, 0, 0xffff); SendMessage(this->ConsoleWindow.hwndBuffer, EM_SCROLLCARET, 0, 0); SendMessage(this->ConsoleWindow.hwndBuffer, EM_REPLACESEL, 0, (LPARAM)buffer); }; ``` **NOTE** This is not production code, just proof of concept. **EDIT** g\_PlatformDevice is of type RiseWindows, if that wasn't clear... **EDIT** This is on a windows xp platform running under vs2008 **UPDATE** For anyone interested, the problem appears to have been an overflowed call stack, further down the stack then this another large array was being defined. Refactoring this eliminated the memory corruption. So chalked up to stack battering!
You haven't mentioned what environment this code runs under. It could be you are blowing your stack. You are declaring a 32767 byte array on the stack in RiseWindows::Print. On some embedded system environments that I am familiar with that would be bad news. Can you increase your stack size and/or allocate that buffer on the heap just to test that theory? You may want to make that buffer a std::vector instead, or possibly a private member vector to avoid allocating and reallocating it every time you call Print. Along those lines, how big is MAX\_PRINT\_OUTPUT?
Probably not the bug you're asking about, but in your loop you are double incrementing pBuffer in some cases, which could be pushing you over the end of buffer because you only check against length-1 (for null termination).
Why does this code corrupt memory?
[ "", "c++", "memory-corruption", "" ]
I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing `)`] with the code below: > ``` > feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date") > > for item in feed: > print repr(item.title[0:-1]) > ``` I include that because, as you can see, the item.title is a repr() data type, which I don't know much about. A particular `repr(item.title[0:-1])` `print`ed in the interactive window looks like this: > ``` > 'randy travis (Billy Bobs 3/21' > 'Michael Schenker Group (House of Blues Dallas 3/26' > ``` The user selects a band and I hope to, after parsing each `item.title` into 3 variables (one each for band, venue, and date... or possibly an array or I don't know...) select only those related to the band selected. Then they are sent to Google for geocoding, but that's another story. I've seen some examples of `regex` and I'm reading about them, but it seems very complicated. Is it? I thought maybe someone here would have some insight as to exactly how to do this in an intelligent way. Should I use the `re` module? Does it matter that the output is currently is `repr()`s? Is there a better way? I was thinking I'd use a loop like (and this is my pseudoPython, just kind of notes I'm writing): ``` list = bandRaw,venue,date,latLong for item in feed: parse item.title for bandRaw, venue, date if bandRaw == str(band) send venue name + ", Dallas, TX" to google for geocoding return lat,long list = list + return character + bandRaw + "," + venue + "," + date + "," + lat + "," + long else ``` In the end, I need to have the chosen entries in a .csv (comma-delimited) file looking like this: > ``` > band,venue,date,lat,long > randy travis,Billy Bobs,3/21,1234.5678,1234.5678 > Michael Schenker Group,House of Blues Dallas,3/26,4321.8765,4321.8765 > ``` I hope this isn't too much to ask. I'll be looking into it on my own, just thought I should post here to make sure it got answered. So, the question is, how do I best parse each `repr(item.title[0:-1])` in the `feed` into the 3 separate values that I can then concatenate into a .csv file?
Don't let regex scare you off... it's well worth learning. Given the examples above, you might try putting the trailing parenthesis back in, and then using this pattern: ``` import re pat = re.compile('([\w\s]+)\(([\w\s]+)(\d+/\d+)\)') info = pat.match(s) print info.groups() ('Michael Schenker Group ', 'House of Blues Dallas ', '3/26') ``` To get at each group individual, just call them on the `info` object: ``` print info.group(1) # or info.groups()[0] print '"%s","%s","%s"' % (info.group(1), info.group(2), info.group(3)) "Michael Schenker Group","House of Blues Dallas","3/26" ``` The hard thing about regex in this case is making sure you know all the known possible characters in the title. If there are non-alpha chars in the 'Michael Schenker Group' part, you'll have to adjust the regex for that part to allow them. The pattern above breaks down as follows, which is parsed left to right: `([\w\s]+)` : Match any word or space characters (the plus symbol indicates that there should be one or more such characters). The parentheses mean that the match will be captured as a group. This is the "Michael Schenker Group " part. If there can be numbers and dashes here, you'll want to modify the pieces between the square brackets, which are the possible characters for the set. `\(` : A literal parenthesis. The backslash escapes the parenthesis, since otherwise it counts as a regex command. This is the "(" part of the string. `([\w\s]+)` : Same as the one above, but this time matches the "House of Blues Dallas " part. In parentheses so they will be captured as the second group. `(\d+/\d+)` : Matches the digits 3 and 26 with a slash in the middle. In parentheses so they will be captured as the third group. `\)` : Closing parenthesis for the above. The python intro to regex is quite good, and you might want to spend an evening going over it <http://docs.python.org/library/re.html#module-re>. Also, check Dive Into Python, which has a friendly introduction: <http://diveintopython3.ep.io/regular-expressions.html>. EDIT: See zacherates below, who has some nice edits. Two heads are better than one!
Regular expressions are a great solution to this problem: ``` >>> import re >>> s = 'Michael Schenker Group (House of Blues Dallas 3/26' >>> re.match(r'(.*) \((.*) (\d+/\d+)', s).groups() ('Michael Schenker Group', 'House of Blues Dallas', '3/26') ``` As a side note, you might want to look at the [Universal Feed Parser](http://feedparser.org/) for handling the RSS parsing as feeds have a bad habit of being malformed. **Edit** In regards to your comment... The strings occasionally being wrapped in "s rather than 's has to do with the fact that you're using repr. The repr of a string is usually delimited with 's, unless that string contains one or more 's, where instead it uses "s so that the 's don't have to be escaped: ``` >>> "Hello there" 'Hello there' >>> "it's not its" "it's not its" ``` Notice the different quote styles.
Python parsing
[ "", "python", "regex", "parsing", "text-parsing", "" ]
I'm trying to write a plugin that will add a few methods to a jQuery wrapper object. Basically, I want to initialize it like this: ``` var smart = $('img:first').smartImage(); ``` The 'smartImage' plugin would attach 2 methods to the object referenced by 'smart', so I'll be able to do something like: ``` smart.saveState(); // do work smart.loadState(); ``` Unfortunately, I can't figure out how to attach these 2 methods to the wrapper object. The code I have follows the typical jQuery plugin pattern: ``` (function($) { $.fn.smartImage = function() { return this.each(function() { $(this).saveState = function() { /* save */ } $(this).loadState = function() { /* load */ } } } } ``` After I call smartImage(), neither 'saveState' nor 'loadState' is defined. What am I doing wrong?
You cannot attach methods/properties in they way you have demonstrated, because as you said, the jQuery object is just a wrapper around whatever DOM elements it contains. You can certainly attach methods/properties to it, but they will no persist when they are selected by jQuery again. ``` var a = $('.my-object'); a.do_something = function(){ alert('hiya'); } a.do_something(); // This alerts. var b = $('.my-object'); b.do_something(); // Freak-out. ``` If you want a method to exist on the jQuery object when recovering it a second time, it needs to be assigned to `jQuery.fn`. So you *could* define your secondary method, assign it to the jQuery.fn, and use the jQuery data setup to maintain state for you... ``` $.fn.setup_something = function() { this.data('my-plugin-setup-check', true); return this; } $.fn.do_something = function() { if (this.data('my-plugin-setup-check')) { alert('Tada!'); } return this; } var a = $('.my-object').setup_something(); a.do_something(); // Alerts. $('.my-object').do_something(); // Also alerts. ``` I suggest you look at <http://docs.jquery.com/Internals/jQuery.data> and <http://docs.jquery.com/Core/data#name>
You are actually returning a jQuery object in the smartImage() function. That is the correct way to write a jQuery plugin, so that you can chain that with other jQuery functions. I'm not sure if there is a way to do what you want. I would recommend the following: ``` (function($) { var smartImageSave = function() { return this.each(function() { } ); }; var smartImageLoad = function() { return this.each(function() { } ); }; $.fn.extend( { "smartImageSave":smartImageSave, "smartImageLoad":smartImageLoad }); }); var $smart = $("img:first"); $smart.smartImageSave(); $smart.smartImageLoad(); ``` That's one technique that I am familiar with and have used successfully.
jQuery: Is it possible to attach fields/methods to a jQuery wrapper object?
[ "", "javascript", "jquery", "plugins", "" ]
I'm tossing around the idea of using the Activator class in order to get access to resources in an assembly that I would otherwise create a circular reference for (dependency injection). I've done it before with vanilla classes that I needed a reference to, but my question is: can I use the Activator to get access to a static class? The part that's tripping me up is that the Activator returns to you a *instance* of the object, whereas a static class has no instance. Is this possible?
You do not need the Activator to call the method. You use [MethodInfo.Invoke](http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx) directly. The first parameter can be left null.
GvS is correct - here is an example of the usage: ``` using System; using System.Reflection; class Program { static void Main() { Type type = Type.GetType("Foo"); MethodInfo info = type.GetMethod("Bar"); Console.WriteLine(info.Invoke(null, null)); } } static class Foo { public static String Bar() { return "Bar"; } } ```
Activator and static classes
[ "", "c#", "reflection", "static", "activator", "" ]
I've got a relatively expensive data-fetching operation that I want to cache the results of. This operation is called from `const` methods, roughly like this: ``` double AdjustData(double d, int key) const { double factor = LongRunningOperationToFetchFactor(key); return factor * d; } ``` I'd like `AdjustData` to remain `const`, but I want to cache out the factor so I only fetch it the first time. At present I'm using a `mutable map<int, double>` to store the result (the map being from `key` to `factor`), but I'm thinking using a function-scoped static might be a better solution - this factor is only needed by this function, and is irrelevant to the rest of the class. Does that seem like a good way to go? Are there any better options? What things might I think about, particularly with regard to thread-safety. Thanks, Dom
I would wrap the implementation of LongRunningOperationToFetchFactor with something like this. I am using Boost scoped locks but you can so something similar with other locking frameworks. ``` #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <map> using namespace std; static boost::mutex myMutex; static map<int,double> results; double CachedLongRunningOperationToFetchFactor( int key ) { { boost::mutex::scoped_lock lock(myMutex); map<int,double>::iterator iter = results.find(key); if ( iter != results.end() ) { return (*iter).second; } } // not in the Cache calculate it result = LongRunningOperationToFetchFactor( key ); { // we need to lock the map again boost::mutex::scoped_lock lock(myMutex); // it could be that another thread already calculated the result but // map assignment does not care. results[key] = result; } return result; } ``` If this really is a long running operation then the cost of locking the Mutex should be minimal. It was not quite clear from you question but if the function LongRunningOperationToFetchFactor is a member function of you class then you want the map the be mutable map in that same class. I single static mutex for access is still fast enough though.
I would *not* make this cache a local static. The mutable map is *the* solution for caching results. Otherwise it will make your function useless, as different objects of your class will share the same cache, as the local static cache is the same for all objects. You can use the local static if the result does not depend on the object though. But then i would ask myself why the function is a non-static member of your object, if it does not need to access any state of it. As you say it should be thread-safe - if different threads can call the member function on the same object, you probably want to use a mutex. `boost::thread` is a good library to use.
Caching expensive data in C++ - function-scoped statics vs mutable member variables
[ "", "c++", "static", "thread-safety", "mutable", "" ]
I'm working on a Facebook-like toolbar for my website. There's a part of the toolbar where a user can click to see which favorite members of theirs are online. I'm trying to figure out how to get the div element that pops up to grow based on the content that the AJAX call puts in there. For example, when the user clicks "Favorites Online (4)", I show the pop up div element with a fixed height and "Loading...". Once the content loads, I'd like to size the height of the div element based on what content was returned. I can do it by calculating the height of each element \* the number of elements but that's not very elegant at all. Is there a way to do this with JavaScript or CSS? (note: using JQuery as well). Thanks. JavaScript: ``` function favoritesOnlineClick() { $('#favoritesOnlinePopUp').toggle(); $('#onlineStatusPopUp').hide(); if ($('#favoritesOnlinePopUp').css('display') == 'block') { loadFavoritesOnlineListing(); } } ``` CSS and HTML: ``` #toolbar { background:url('/_assets/img/toolbar.gif') repeat-x; height:25px; position:fixed; bottom:0px; width:100%; left:0px; z-index:100; font-size:0.8em; } #toolbar #popUpTitleBar { background:#606060; height:18px; border-bottom:1px solid #000000; } #toolbar #popUpTitle { float:left; padding-left:4px; } #toolbar #popUpAction { float:right; padding-right:4px; } #toolbar #popUpAction a { color:#f0f0f0; font-weight:bold; text-decoration:none; } #toolbar #popUpLoading { padding-top:6px; } #toolbar #favoritesOnline { float:left; height:21px; width:160px; padding-top:4px; border-right:1px solid #606060; text-align:center; } #toolbar #favoritesOnline .favoritesOnlineIcon { padding-right:5px; } #toolbar #favoritesOnlinePopUp { display:block; border:1px solid #000000; width:191px; background:#2b2b2b; float:left; position:absolute; left:-1px; top:-501px; /*auto;*/ height:500px;/*auto;*/ overflow:auto; } #toolbar #favoritesOnlineListing { font-size:12px; } <div id="toolbar"> <div id="favoritesOnline" style=" <?php if ($onlinestatus == -1) { echo "display:none;"; } ?> "> <img class="favoritesOnlineIcon" src="/_assets/img/icons/favorite-small.gif" /><a href="javascript:favoritesOnlineClick();">Favorites Online (<span id="favoritesOnlineCount"><?php echo $favonlinecount; ?></span>)</a> <div id="favoritesOnlinePopUp"> <div id="popUpTitleBar"> <div id="popUpTitle">Favorites Online</div> <div id="popUpAction"><a href="javascript:closeFavoritesOnline();">x</a></div> </div> <div id="favoritesOnlineListing"> <!-- Favorites online content goes here --> </div> </div> </div> </div> ```
Maybe you could remove the height property (make sure it's not set in the CSS) and let the DIV expand in height by itself.
Make it a float element and don't use a clearing element after it.
Dynamically changing height of div element based on content
[ "", "javascript", "jquery", "html", "css", "" ]
When I try to run the following statement, an error message is returned: Server: Msg 208, Level 16, State 1, Line 1 Invalid object name 'vendortofaultypeitemsmap'. SQL Help indicates this message appears when "an object that does not exist is referenced". This table does exist and returns values if I run \*select \* from vendortofaulttypeitemsmap\*. Can someone help me pinpoint what is wrong with the statement below that is causing the error message? Thanks in advance. ``` select vendortofaulttypeitemsmap.vendorid, vendortofaulttypeitemsmap.faultypeitemguid, guid_faulttypeitems.faulttypeitemname, vendortoworkactionmap.workactionitemguid, guid_workactionitem.workactionitemname from vendortofaultypeitemsmap inner join guid_faulttypeitems on vendortofaulttypeitemsmap.faultypeitemguid= guid_faulttypeitems.faultypeitemguid inner join guid_workactionitem on vendortoworkactionmap.workactionitemguid= guid_workactionitem.workactionitemguid where vendortofaulttypeitemsmap.vendorid=45 ```
You have a typo. It is either vendortofaultypeitemsmap or vendortofaulttypeitemsmap.
You missed a 't' vendortofaultTypeitemsmap.
Error Returned from a Select/Inner Join Statement
[ "", "sql", "sql-server", "" ]
I want to test whether a JavaScript variable has a value. ``` var splitarr = mystring.split( " " ); aparam = splitarr [0] anotherparam = splitarr [1] //.... etc ``` However the string might not have enough entries so later I want to test it. ``` if ( anotherparm /* contains a value */ ) ``` How do I do this?
In general it's sort of a gray area... what do you mean by "has a value"? The values `null` and `undefined` are legitimate values you can assign to a variable... The String function `split()` always returns an array so use the `length` property of the result to figure out which indices are present. Indices out of range will have the value `undefined`. But technically (outside the context of `String.split()`) you could do this: ``` js>z = ['a','b','c',undefined,null,1,2,3] a,b,c,,,1,2,3 js>typeof z[3] undefined js>z[3] === undefined true js>z[3] === null false js>typeof z[4] object js>z[4] === undefined false js>z[4] === null true ```
``` if (typeof anotherparm == "undefined") ```
How can I test whether a variable has a value in JavaScript?
[ "", "javascript", "" ]
I have an Informix database containing measured temperature values for quite a few different locations. The measurements are taken every 15 min for all locations and then loaded with a timestamp into the same table. Table looks like this: ``` locId dtg temp aaa 2009-02-25 10:00 15 bbb 2009-02-25 10:00 20 ccc 2009-02-25 10:00 24 aaa 2009-02-25 09:45 13 ccc 2009-02-25 09:45 16 bbb 2009-02-25 09:45 18 ddd 2009-02-25 09:45 12 aaa 2009-02-25 09:30 11 ccc 2009-02-25 09:30 14 bbb 2009-02-25 09:30 15 ddd 2009-02-25 09:30 10 ``` Now I would like a query that present me with the change in temperature between the two last measurements for all stations. And also, only the ones that has an updated measurement. For example in the table above, location ddd would not be included. So the result becomes: ``` locId change aaa 2 bbb 2 ccc 8 ``` I have tried alot but I can´t find any good solution. In reality it is about 700 locations that is asked from a web page so I think the query needs to be fairly efficient. Would really appreciate some help! //Jesper
``` set now = select max(dtg) from table; set then = select max(dtg) from table where dtg < now; select locID, old.temp-new.temp from table as old join table as new on old.locId = new.locID where old.dtg = then and new.dtg = now; ``` --- assumes that all times will be exact
Thanks to uglysmurf for providing the data in an SQL format. Using IDS (IBM Informix Dynamic Server) version 11.50, the following query works. ``` CREATE TEMP TABLE temps ( locId CHAR(3), dtg DATETIME YEAR TO MINUTE, temp SMALLINT ); INSERT INTO temps VALUES ('aaa', '2009-02-25 10:00', 15); INSERT INTO temps VALUES ('bbb', '2009-02-25 10:00', 20); INSERT INTO temps VALUES ('ccc', '2009-02-25 10:00', 24); INSERT INTO temps VALUES ('aaa', '2009-02-25 09:45', 13); INSERT INTO temps VALUES ('ccc', '2009-02-25 09:45', 16); INSERT INTO temps VALUES ('bbb', '2009-02-25 09:45', 18); INSERT INTO temps VALUES ('ddd', '2009-02-25 09:45', 12); INSERT INTO temps VALUES ('aaa', '2009-02-25 09:30', 11); INSERT INTO temps VALUES ('ccc', '2009-02-25 09:30', 14); INSERT INTO temps VALUES ('bbb', '2009-02-25 09:30', 15); INSERT INTO temps VALUES ('ddd', '2009-02-25 09:30', 10); SELECT latest.locID, latest.temp, prior.temp, latest.temp - prior.temp as delta_temp, latest.dtg, prior.dtg FROM temps latest, temps prior WHERE latest.locId = prior.locId AND latest.dtg = prior.dtg + 15 UNITS MINUTE AND latest.dtg = (SELECT MAX(dtg) FROM temps); ``` Results (more columns than requested, but you can easily trim the select list): ``` aaa 15 13 2 2009-02-25 10:00 2009-02-25 09:45 ccc 24 16 8 2009-02-25 10:00 2009-02-25 09:45 bbb 20 18 2 2009-02-25 10:00 2009-02-25 09:45 ``` Note that this solution does not depend on CURRENT (or NOW); it works on the latest recorded data. The only part of the SELECT statement that is IDS-specific is the '`+ 15 UNITS MINUTE`'; that could also be written as '`+ INTERVAL(15) MINUTE TO MINUTE`' in Informix, and as '`+ INTERVAL '15' MINUTE`' in standard SQL (if the DBMS supports INTERVAL types). The use of DATETIME YEAR TO MINUTE in the table is Informix-specific; in a context like this, it is useful not to store information you are not interested in (such as the seconds).
SQL to find the difference between two rows
[ "", "sql", "informix", "" ]
I´m trying to break a number into an array of numbers (in php) in the way that for example: * 25 becomes (16, 8, 1) * 8 becomes (8) * 11 becomes (8, 2, 1) I don´t know what the correct term is, but I think the idea is clear. My solution with a loop is pretty straightforward: ``` $number = rand(0, 128); $number_array_loop = array(); $temp_number = $number; while ($temp_number > 0) { $found_number = pow(2, floor(log($temp_number, 2))); $temp_number -= $found_number; $number_array_loop[] = $found_number; } ``` I also have a recursive solution but I can´t get that to work without using a global variable (don´t want that), the following comes close but results in arrays in arrays: ``` function get_numbers($rest_number) { $found_number = pow(2, floor(log($rest_number, 2))); if ($found_number > 0) { $temp_array[] = get_numbers($rest_number - $found_number); $temp_array[] = $found_number; } return $temp_array; } $number_array_recursive = array(); $number_array_recursive = get_numbers($number); ``` However, using something like **pow(floor(log()))** seems a bit much for a simple problem like this. It seems to me that the problem calls for a recursive solution with some very simple maths, but I just don´t see it.
You can check each bit of the input number with the following (untested) function. ``` function checkBit($var, $pos) { return ($var & (1 << $pos)); } ``` It checks the bit at position $pos in the variable $var by using a bitwise AND function. I'll show you with 4-bit numbers for brevity. * 1 = 0001 * 2 = 0010 * 4 = 0100 * 8 = 1000 If I want to check position 0 (the rightmost bit) of the number 3, I'd call the function like this: ``` $number = 3; checkBit($number, 0); ``` Internally, checkBit is going to shift the constant 1 to the left 0 times because I passed in a 0. It's then going to bitwise AND (&) the result with the number I passed in, 3. Since 3 = 0011 and 1 = 0001 the result is true, since the 0th bit is set in both arguments to the bitwise AND operator.
You could just get the binary representation of the number - a 1 means include that power of 2, a zero means don't i.e. ``` $binary_number = decbin($test_number); $binary_string = "${binary_number}"; for ($i = 0; $i < strlen($binary_string); $i++) { if ($binary_string[strlen($binary_string) - $i - 1] == "1") { $num_out = pow(2, $i); print "${num_out} "; } } ``` This is tested and work ok but there are probably better ways of doing syntactically in PHP.
Should I use loop or recursive function?
[ "", "php", "math", "recursion", "loops", "" ]
We are currently discussing whether Extension methods in .NET are bad or not. Or under what circumstances Extension methods can introduce hard to find bugs or in any other way behave unexpectedly. We came up with: * Writing an extension method for types that are not under your control (e.g. extending DirectoryInfo with GetTotalSize(), etc...) is bad, because the owner of the API could introduce a method that hides our extension - and might have different edge cases. For example testing for null in an extension method will automatically translate into a NullReferenceException if the extension method is no longer used due to hiding. Question: * Are there any other dangerous situations than "hiding" that we are not thinking of? Edit: Another very dangerous situation. Suppose you have an extension method: ``` namespace Example.ExtensionMethods { public static class Extension { public static int Conflict(this TestMe obj) { return -1; } } } ``` And use it: ``` namespace Example.ExtensionMethods.Conflict.Test { [TestFixture] public class ConflictExtensionTest { [Test] public void ConflictTest() { TestMe me = new TestMe(); int result = me.Conflict(); Assert.That(result, Is.EqualTo(-1)); } } } ``` Notice that the namespace where you use it is longer. Now you reference a dll with this: ``` namespace Example.ExtensionMethods.Conflict { public static class ConflictExtension { public static int Conflict(this TestMe obj) { return 1; } } } ``` And your Test will fail! It will compile without a compiler error. It will **simply fail**. Without you even having to specify "using Example.ExtensionMethods.Conflict". The compiler will walk the namespace name and find Example.ExtensionMethods.Conflict.ConflictExtension before Example.ExtensionMethods.Extension and will use that **without ever complaining about ambiguous extension methods**. Oh the horror!
Some curiosities: * extension methods might be called on `null` instances; this might be confusing (but sometimes useful) * the "hiding" issue is a biggie if they have different intent * equally, you might get a different extension method with the same name from 2 different namespaces; if you only have *one* of the two namespaces, this could lead to inconsistent behaviour (depending on which)... * ...but if somebody adds a *similar* (same signature) extension method in a second namespace that your code uses, it will break at compile time (ambiguous) (**edit**) And of course, there is the "`Nullable<T>`/`new()`" bomb ([see here](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/194671#194671))...
I disagree, the whole point of extension methods is to add your members to black boxed classes. Like everything else there are pitfalls, you must be mindful in naming, implementation and understand the pecking order of the methods.
When do Extension Methods break?
[ "", "c#", ".net", "extension-methods", "" ]
I can get/set registry values using the Microsoft.Win32.Registry class. For example, ``` Microsoft.Win32.Registry.SetValue( @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", "MyApp", Application.ExecutablePath); ``` But I can't delete any value. How do I delete a registry value?
To delete the value set in your question: ``` string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run"; using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true)) { if (key == null) { // Key doesn't exist. Do whatever you want to handle // this case } else { key.DeleteValue("MyApp"); } } ``` Look at the docs for [`Registry.CurrentUser`](http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.currentuser.aspx), [`RegistryKey.OpenSubKey`](http://msdn.microsoft.com/en-us/library/xthy8s8d.aspx) and [`RegistryKey.DeleteValue`](http://msdn.microsoft.com/en-us/library/dk8b3th2.aspx) for more info.
To delete all subkeys/values in the tree (~recursively), here's an extension method that I use: ``` public static void DeleteSubKeyTree(this RegistryKey key, string subkey, bool throwOnMissingSubKey) { if (!throwOnMissingSubKey && key.OpenSubKey(subkey) == null) { return; } key.DeleteSubKeyTree(subkey); } ``` Usage: ``` string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run"; using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true)) { key.DeleteSubKeyTree("MyApp",false); } ```
How to delete a registry value in C#
[ "", "c#", "registry", "" ]
How do I check if an object has some attribute? For example: ``` >>> a = SomeClass() >>> a.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property' ``` How do I tell if `a` has the attribute `property` before using it?
Try [`hasattr()`](https://docs.python.org/3/library/functions.html#hasattr): ``` if hasattr(a, 'property'): a.property ``` See [zweiterlinde's answer](https://stackoverflow.com/a/610923/117030) below, who offers good advice about asking forgiveness! A very pythonic approach! The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than `hasattr`. If the property is likely to not be there most of the time, or you're not sure, using `hasattr` will probably be faster than repeatedly falling into an exception block.
As [Jarret Hardie](https://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610893#610893) answered, `hasattr` will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL). See these references: [EAFP vs LBYL (was Re: A little disappointed so far)](http://web.archive.org/web/20070929122422/http://mail.python.org/pipermail/python-list/2003-May/205182.html) [EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python](https://web.archive.org/web/20180411011411/http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl) ie: ``` try: doStuff(a.property) except AttributeError: otherStuff() ``` ... is preferred to: ``` if hasattr(a, 'property'): doStuff(a.property) else: otherStuff() ```
How to check if an object has an attribute?
[ "", "python", "class", "object", "attributes", "attributeerror", "" ]
I have a text file with a lot of datetime strings in isoformat. The strings are similar to this: ``` '2009-02-10 16:06:52.598800' ``` These strings were generated using `str(datetime_object)`. The problem is that, for some reason, `str(datetime_object)` generates a different format when the datetime object has microseconds set to zero and some strings look like this: ``` '2009-02-10 16:06:52' ``` How can I parse these strings and convert them into a [datetime object](http://docs.python.org/library/datetime.html#datetime.datetime)? It's very important to get all the data in the object, including microseconds. NOTE: I have to use **Python 2.5**, the format directive `%f` for microseconds doesn't exist in 2.5.
Alternatively: ``` from datetime import datetime def str2datetime(s): parts = s.split('.') dt = datetime.strptime(parts[0], "%Y-%m-%d %H:%M:%S") return dt.replace(microsecond=int(parts[1])) ``` Using `strptime` itself to parse the date/time string (so no need to think up corner cases for a regex).
Use the dateutil module. It supports a much wider range of date and time formats than the built in Python ones. You'll need to **easy\_install dateutil** for the following code to work: ``` from dateutil.parser import parser p = parser() datetime_with_microseconds = p.parse('2009-02-10 16:06:52.598800') print datetime_with_microseconds.microsecond ``` results in: ``` 598799 ```
Parsing datetime strings with microseconds in Python 2.5
[ "", "python", "datetime", "parsing", "python-2.5", "" ]
I have asp.net 3.5 website, and i want to put an ajax uploader, but i want this ajax uploader to: 1. don't refresh the page while/after uploading 2. easy to integrate 3. free 4. Not swf upload control 5. i will use it in uploading images, so want a simple way to get the uploaded image file name, and be able to tell it in which folder to upload to. any one know a good one?
I found a few different options out there. I haven't used any of them, but I will most likely look into the 3rd option here in the near future. * <http://en.fileuploadajax.subgurim.net/> * <http://ajaxuploader.com/> * <http://mattberseth.com/blog/2008/07/aspnet_file_upload_with_realti.html>
Check [<http://krystalware.com/Products/SlickUpload/>](http://krystalware.com/Products/SlickUpload/) Free trial never ends, but it puts a little "powered by" notice on your site.
Whats the best, most simple ajax file uploader?
[ "", ".net", "asp.net", "javascript", "ajax", "" ]
I have read a bit about [Design-Time Attributes for Components](http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx). There I found an attribute called [CategoryAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.categoryattribute.aspx). On that page it says that > The CategoryAttribute class defines the following common categories: And then lists up a number of common categories. One of them are for example [Appearance](http://msdn.microsoft.com/en-us/library/system.componentmodel.categoryattribute.appearance.aspx). I thought, brilliant! Then I can use `[Category.Appearance]` instead of `[Category("Appearance")]`! But apparently I couldn't? Tried to write it, but Intellisense wouldn't pick it up and it wouldn't compile. Am I missing something here? Was it maybe not this those properties were for? If not, what are they for? If they are, how do I use them? And yes, I do have the correct `using` to have access to the `CategoryAttribute`, cause `[Category("Whatever")]` do work. I'm just wondering how I use those defined common categories.
As you can see on MSDN it's only a getter property, not a setter. ``` public static CategoryAttribute Appearance { get; } ``` In fact, here's what the code looks like using Reflector: ``` public static CategoryAttribute Appearance { get { if (appearance == null) { appearance = new CategoryAttribute("Appearance"); } return appearance; } } ``` So it doesn't do a heck of a lot. The only use I can see for it, is something like this: ``` foreach (CategoryAttribute attrib in prop.GetCustomAttributes(typeof(CategoryAttribute), false)) { bool result = attrib.Equals(CategoryAttribute.Appearance); } ``` Basically, when using reflection to look at the class, you can easily check which category this belongs to without having to do a String comparison. But you can't use it in the manner you're trying to unfortunately.
The static property is accessed via CategoryAttribute.Appearance. But the attribute system does not allow you to invoke code in an attribute declaration and I guess that is why it wont compile for you. You will probably have to settle for [Category("Appearance")].
C#: How to use CategoryAttribute.Appearance Property
[ "", "c#", "user-controls", "attributes", "windows-forms-designer", "" ]
> **Possible Duplicate:** > [What is the C# Using block and why should I use it?](https://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it) I have seen the using statement used in the middle of a codeblock what is the reason for this?
The **using** syntax can(should) be used as a way of defining a scope for anything that implements [IDisposable](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx). The using statement ensures that Dispose is called if an exception occurs. ``` //the compiler will create a local variable //which will go out of scope outside this context using (FileStream fs = new FileStream(file, FileMode.Open)) { //do stuff } ``` Alternatively you could just use: ``` FileStream fs; try{ fs = new FileStream(); //do Stuff } finally{ if(fs!=null) fs.Dispose(); } ``` [Extra reading from MSDN](http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx) C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible. The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
It is often used when opening a connection to a stream or a database. It behaves like a try { ... } finally { ... } block. After the *using* block, the IDisposable object that was instantiated in the parenthesis will be closed properly. ``` using (Stream stream = new Stream(...)) { } ``` With this example, the stream is closed properly after the block.
Using the using statement in C#
[ "", "c#", "using", "" ]
I am trying to create a webpage where users can insert a pin (like google map) in between the text using context menu. My problem is that i do not know how to insert the pin at the exact position. Using the DOM I can arrive only to the nearest DIV (by using **this**) but a DIV contains a lot of text and the PIN has to be positioned next to the text. I can obtain the position of the mouse click using pageX and pageY but dont know how to insert an element at that position. I tried in JQuery: insertAfter, prepend, append but not getting the desired result. Any idea how to solve this problem. regards, choesang tenzin ``` $("#Content").rightClick( function(e) { $("<div class='pin'/>").insertAfter(this); }); ```
Thanks alot for all your ideas. I have come up with another way to do it. I am using the "RANGE" to insert directly into the clicked zone (div) and not after or before it and adding z-indexes. The positive points with this is: 1. It is really into the text and not as a layer 2. texts flow around the pin (text makes space for the pin) ``` $("div").click( function(e) { //the following works only for FF at the moment var range = window.getSelection().getRangeAt(0); var pin = document.createElement('img'); pin.setAttribute('src','pin_org.png'); pin.setAttribute('class','pin'); range.insertNode(pin); }); $("img.pin").live( 'mouseover', function () { alert("hovered!!"); ```
``` $("#Content").rightClick( function(e) { var myTop = ...; var myRight= ...; $("<div class='pin' style='position:absolute; top: ' + myTop +'px; right: ' + myRight + 'px;/>").insertAfter(this); }); ``` sorry, i don't remember how to get x and y from the e parameter. Also, you will need to convert x,y of mouse click to x,y relative to #content element.
How to insert an element in DIV at position X Y
[ "", "javascript", "jquery", "events", "" ]
I have a table with two columns, userID and contentID. Basically this table is used to assign access to certain content to specific users. I have the request of every user that is assigned to content A also be assigned to content B. So how would I write a new row with this data (userid, [id of content B]) for each row that has (userid, [id of content A])? OK I tried what the top two posts said and it converted it to: ``` INSERT INTO tbl_courseAccess (contentid) SELECT 11 AS Expr1 WHERE (contentid = 6) ``` and didn't work, so I'm not sure what I did wrong, here is what I tried to use: ``` insert into tbl_contentAccess (userid, contentid) select userid, 11 where contentid = 6 ``` OK I found a new solution, don't worry about this anymore, thanks everyone.
``` insert into <table>(userid, contentid) select userid, [content b id] from <table> where contentid = [content a id])) ``` **Corrected:** Typing too fast to race you other answerers
``` insert into [tablename] (userid, contentid) select userid, [id of content B] where contentid = [id of content A] ```
SQL FOR EACH?
[ "", "sql", "" ]
I just want to flip a boolean based on what it already is. If it's true - make it false. If it's false - make it true. Here is my code excerpt: ``` switch(wParam) { case VK_F11: if (flipVal == true) { flipVal = false; } else { flipVal = true; } break; case VK_F12: if (otherVal == true) { otherValVal = false; } else { otherVal = true; } break; default: break; } ```
You can flip a value like so: ``` myVal = !myVal; ``` so your code would shorten down to: ``` switch(wParam) { case VK_F11: flipVal = !flipVal; break; case VK_F12: otherVal = !otherVal; break; default: break; } ```
Clearly you need a factory pattern! ``` KeyFactory keyFactory = new KeyFactory(); KeyObj keyObj = keyFactory.getKeyObj(wParam); keyObj.doStuff(); class VK_F11 extends KeyObj { boolean val; public void doStuff() { val = !val; } } class VK_F12 extends KeyObj { boolean val; public void doStuff() { val = !val; } } class KeyFactory { public KeyObj getKeyObj(int param) { switch(param) { case VK_F11: return new VK_F11(); case VK_F12: return new VK_F12(); } throw new KeyNotFoundException("Key " + param + " was not found!"); } } ``` :D ``` </sarcasm> ```
Easiest way to flip a boolean value?
[ "", "c++", "c", "boolean", "boolean-logic", "" ]
I'm writing a diagram editor in java. This app has the option to export to various standard image formats such as .jpg, .png etc. When the user clicks File->Export, you get a `JFileChooser` which has a number of `FileFilter`s in it, for `.jpg`, `.png` etc. Now here is my question: Is there a way to have the extension of the default adjust to the selected file filter? E.g. if the document is named "lolcat" then the default option should be "lolcat.png" when the png filter is selected, and when the user selects the jpg file filter, the default should change to "lolcat.jpg" automatically. Is this possible? How can I do it? edit: Based on the answer below, I wrote some code. But it doesn't quite work yet. I've added a `propertyChangeListener` to the `FILE_FILTER_CHANGED_PROPERTY`, but it seems that within this method `getSelectedFile()` returns null. Here is the code. ``` package nl.helixsoft; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.filechooser.FileFilter; public class JFileChooserTest { public class SimpleFileFilter extends FileFilter { private String desc; private List<String> extensions; private boolean showDirectories; /** * @param name example: "Data files" * @param glob example: "*.txt|*.csv" */ public SimpleFileFilter (String name, String globs) { extensions = new ArrayList<String>(); for (String glob : globs.split("\\|")) { if (!glob.startsWith("*.")) throw new IllegalArgumentException("expected list of globs like \"*.txt|*.csv\""); // cut off "*" // store only lower case (make comparison case insensitive) extensions.add (glob.substring(1).toLowerCase()); } desc = name + " (" + globs + ")"; } public SimpleFileFilter(String name, String globs, boolean showDirectories) { this(name, globs); this.showDirectories = showDirectories; } @Override public boolean accept(File file) { if(showDirectories && file.isDirectory()) { return true; } String fileName = file.toString().toLowerCase(); for (String extension : extensions) { if (fileName.endsWith (extension)) { return true; } } return false; } @Override public String getDescription() { return desc; } /** * @return includes '.' */ public String getFirstExtension() { return extensions.get(0); } } void export() { String documentTitle = "lolcat"; final JFileChooser jfc = new JFileChooser(); jfc.setDialogTitle("Export"); jfc.setDialogType(JFileChooser.SAVE_DIALOG); jfc.setSelectedFile(new File (documentTitle)); jfc.addChoosableFileFilter(new SimpleFileFilter("JPEG", "*.jpg")); jfc.addChoosableFileFilter(new SimpleFileFilter("PNG", "*.png")); jfc.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent arg0) { System.out.println ("Property changed"); String extold = null; String extnew = null; if (arg0.getOldValue() == null || !(arg0.getOldValue() instanceof SimpleFileFilter)) return; if (arg0.getNewValue() == null || !(arg0.getNewValue() instanceof SimpleFileFilter)) return; SimpleFileFilter oldValue = ((SimpleFileFilter)arg0.getOldValue()); SimpleFileFilter newValue = ((SimpleFileFilter)arg0.getNewValue()); extold = oldValue.getFirstExtension(); extnew = newValue.getFirstExtension(); String filename = "" + jfc.getSelectedFile(); System.out.println ("file: " + filename + " old: " + extold + ", new: " + extnew); if (filename.endsWith(extold)) { filename.replace(extold, extnew); } else { filename += extnew; } jfc.setSelectedFile(new File (filename)); } }); jfc.showDialog(frame, "export"); } JFrame frame; void run() { frame = new JFrame(); JButton btn = new JButton ("export"); frame.add (btn); btn.addActionListener (new ActionListener() { public void actionPerformed(ActionEvent ae) { export(); } }); frame.setSize (300, 300); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFileChooserTest x = new JFileChooserTest(); x.run(); } }); } } ```
It looks like you can listen to the `JFileChooser` for a change on the `FILE_FILTER_CHANGED_PROPERTY` property, then change the extension of the selected file appropriately using `setSelectedFile()`. --- EDIT: You're right, this solution doesn't work. It turns out that when the file filter is changed, the selected file is removed if its file type doesn't match the new filter. That's why you're getting the `null` when you try to `getSelectedFile()`. Have you considered adding the extension later? When I am writing a `JFileChooser`, I usually add the extension after the user has chosen a file to use and clicked "Save": ``` if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); String path = file.getAbsolutePath(); String extension = getExtensionForFilter(fileChooser.getFileFilter()); if(!path.endsWith(extension)) { file = new File(path + extension); } } ``` --- ``` fileChooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { FileFilter filter = (FileFilter)evt.getNewValue(); String extension = getExtensionForFilter(filter); //write this method or some equivalent File selectedFile = fileChooser.getSelectedFile(); String path = selectedFile.getAbsolutePath(); path.substring(0, path.lastIndexOf(".")); fileChooser.setSelectedFile(new File(path + extension)); } }); ```
You can also use a PropertyChangeListener on the SELECTED\_FILE\_CHANGED\_PROPERTY prior to attaching your suffix. When the selected file gets checked against the new filter (and subsequently set to null), the SELECTED\_FILE\_CHANGED\_PROPERTY event is actually fired *before* the FILE\_FILTER\_CHANGED\_PROPERTY event. If the evt.getOldValue() != null and the evt.getNewValue() == null, you know that the JFileChooser has blasted your file. You can then grab the old file's name (using ((File)evt.getOldValue()).getName() as described above), pull off the extension using standard string parsing functions, and stash it into a named member variable within your class. That way, when the FILE\_FILTER\_CHANGED event is triggered (immediately afterwards, as near as I can determine), you can pull that stashed root name from the named member variable, apply the extension for the new file filter type, and set the JFileChooser's selected file accordingly.
adjust selected File to FileFilter in a JFileChooser
[ "", "java", "swing", "jfilechooser", "" ]
I have a stored procedure returning ID, Name, Descriptions and takes no input parameters. However, I am interested in how many results do I get. I expected something like this work: ``` SELECT COUNT(*) FROM EXEC MyStoredProcedure ``` But I get the following error in SqlServer Managment Studio: Incorrect syntax near the keyword 'EXEC'. Could you show me a little code example how can I do that?
This won't work. May I suggest: ``` exec MyStoredProcedure select @@rowcount ``` Alternatively you could return the count as an output parameter
``` SELECT @@ROWCOUNT ```
Counting results of stored procedure
[ "", "sql", "stored-procedures", "" ]
In this [article](http://msdn.microsoft.com/en-us/library/0603949d(VS.80).aspx) the keyword extern can be followed by "C" or "C++". Why would you use 'extern "C++"'? Is it practical?
The language permits: ``` extern "C" { #include "foo.h" } ``` What if foo.h contains something which requires C++ linkage? ``` void f_plain(const char *); extern "C++" void f_fancy(const std::string &); ``` That's how you keep the linker happy.
There is no real reason to use `extern "C++"`. It merely make explicit the linkage that is the implicit default. If you have a class where some members have extern "C" linkage, you may wish the explicit state that the others are extern "C++". Note that the C++ Standard defines syntactically `extern "anystring"`. It only give formal meanings to `extern "C"` and `extern "C++"`. A compiler vendor is free to define `extern "Pascal"` or even `extern "COM+"` if they like.
Why would you use 'extern "C++"'?
[ "", "c++", "c", "" ]
I wanted to speed up compilation so i was thinking i could have my files be build on a ramdisk but also have it flushed to the filesystem automatically and use the filesystem if there is not enough ram. I may need something similar for an app i am writing where i would like files to be cached in ram and flushed into the FS. What are my options? Is there something like this that already exist? (perhaps fuse?) The app is a toy app (for now) and i would need to compile c++ code repeatedly. As we know, the longer it takes to compile when there is a specific problem to solve before progressing. the less we can get done.
Ram-disks went the way of the dodo with the file system cache. It can make much better decisions than a static cache, having awareness of RAM usage by other programs and the position of the disk write head. The lazy write-back is for free.
Compilation is CPU-bound, not disk bound. If you utilize all your CPU cores using the appropriate build flag, you can easily saturate them on typical PCs. Unless you have some sort of supercomputer, I don't think this will speed things up much. For VS2008 this flag is [`/MP`](http://msdn.microsoft.com/en-us/library/bb385193.aspx). It also exists on [VS2005](http://blog.280z28.org/archives/2007/10/17/).
ramdisk with a file mirror
[ "", "c++", "windows", "filesystems", "ramdisk", "" ]
When writing my first asp.net MVC application using C#, I see that there are some variables whose name start with an underscore character(\_). What does this mean? Is there any specific meaning for this?
There's no language-defined meaning - it's just a convention some people use to distinguish instance variables from local variables. Other variations include m\_foo (and s\_foo or g\_foo or static variables) or mFoo; alternatively some people like to prefix the local variables (and parameters) instead of the instance variables. Personally I don't use prefixes like this, but it's a style choice. So long as everyone working on the same project is consistent, it's usually not much of an issue. I've seen some *horribly* inconsistent code though...
In general, this means private member fields.
What does variable names beginning with _ mean?
[ "", "c#", "asp.net", "syntax", "variables", "naming-conventions", "" ]