Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered [here](https://stackoverflow.com/questions/379722/is-f-really-better-than-c-for-math), but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places. **Edit:** It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point [here](https://stackoverflow.com/questions/142985/is-a-program-f-any-more-efficient-execution-wise-than-c) was the following answer: > F# provides some performance-related > features that can make a difference. > > Firstly, the implementation of > delegates on .NET is currently quite > inefficient and, consequently, F# uses > its own FastFunc type for > high-performance first-class > functions. > > Secondly, F# uses .NET metadata to > convey inline functions so that they > can be exported across APIs and, of > course, that can dramatically improve > performance in certain circumstances. > > Finally, pattern matching can be > extremely laborious to express in C# > because the language lacks pattern > matching but it is almost impossible > to maintain optimized C# code > equivalent to many non-trivial pattern > matches. In contrast, the F# compiler > aggressively optimizes pattern matches > during compilation. > > Conversely, the C# compiler is better > at optimizing loops using IEnumerables > and is better at optimizing > computations over value types (e.g. > complex arithmetic). > > Cheers, Jon Harrop.
**Yes, F# will perform better.** Here are some performance results for a single-thread algorithm implemented in different languages (benchmarking activation function approaches for the neural networks): **C#:** ``` 10^7 iterations using Sigmoid1() took 3899,1979 ms 10^7 iterations using Sigmoid2() took 411,4441 ms ``` **Pure C:** ``` 10^7 iterations using sigmoid1: 628 ms 10^7 iterations using sigmoid2: 157 ms ``` **F#:** ``` 10^7 iterations using sigmoid1: 588.843700 ms 10^7 iterations using sigmoid2: 156.626700 ms ``` [More details](http://rabdullin.com/journal/2009/1/6/f-has-better-performance-than-c-in-math.html)
F# will behave the same as C# for calculations (since it is all just IL). Just sure to represent your vector as a struct - since you will be constructing many of those objects which are short lived. Units of measure has zero impact on performance, in fact at compile time the units of measure information is removed entirely. So you actually cannot tell that your F# code has units of measure on it.
Will F# perform well when writing math functions for a C# program?
[ "", "c#", "performance", "f#", "" ]
How expensive is it to perform the dereference operation on a pointer? I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.
Dereferencing, when translated into machine code, can mean different things depending on what you do with the dereferenced object. Accessing a single member of a class through a pointer is typically cheap. For example if c is a pointer to an instance of `class C` with an `int` member n then something like this: ``` int n = c->n; ``` Might translate into one or two machine instructions and might load a register with a single memory access. On the other hand this implies making a complete copy of the object pointed to by c: ``` C d = *c; ``` The cost of this will depend on the size of C, but note that it is the copy that is the major expense and the 'dereference' part is really just 'using' the pointer address in the copy instructions. Note that accessing members of large objects typically requires pointer offset calculation and memory access whether or not the object is a local object or not. Typically only very small objects are optimized to live only in registers. If you are concerned about the cost of pointers over references then don't be. The difference between these are a language semantics difference and by the time the machine code is generated pointer and reference access look exactly the same.
It depends on what you do with the dereferenced pointer. A mere dereference operation does nothing in itself. It just gets an lvalue of type `T` which represents your object, if your pointer is a `T*` ``` struct a { int big[42]; }; void f(a * t) { // does nothing. Only interesting for standard or compiler writers. // it just binds the lvalue to a reference t1. a & t1 = *t; } ``` If you actually get the value out of that object denoted by the lvalue returned by the dereference operation, the compiler has to copy the data the object contains. For a simple POD, that is just a mere `memcpy`: ``` a aGlobalA; void f(a * t) { // gets the value of of the object denoted by *t, copying it into aGlobalA aGlobalA = *t; } ``` My gcc port outputs this code for f: ``` sub $29, $29, 24 ; subtract stack-pointer, creating this frame stw $31, $29, 20 ; save return address add $5, $0, $4 ; copy pointer t into $5 (src) add $4, $0, aGlobalA ; load address of aGlobalA into $4 (dst) add $6, $0, 168 ; put size (168 bytes) as 3rd argument jal memcpy ; call memcpy ldw $31, $29, 20 ; restore return address add $29, $29, 24 ; add stack-pointer, destroying this frame jr $31 ``` Optimized machine code would use in-line code instead of a call to `memcpy`, but that's really just an implementation detail. What is important is, that merely `*t` isn't executing any code, but accessing the value of that object actually needs to copy it. Would we have to do with a type having a user defined copy assignment operator, affairs are more complex: ``` struct a { int big[42]; void operator=(a const&) { } }; ``` The code for the same function `f` now looks like: ``` sub $29, $29, 8 add $29, $29, 8 jr $31 ``` Hah. But it wasn't such a surprise, wasn't it? After all, the compiler is supposed to call our `operator=`, and if it does nothing, the whole function also does nothing! ### Conclusion I think the conclusion we can draw is, it all depends on how the returned value of `operator*` is used. If we have just a pointer that we dereference, we see above that the code generated largely depends on the circumstances. I haven't showed how it behaves if we dereference a class type having overloaded `operator*` . But essentially, it's just behaving like we saw with `operator=`. All measurements were done with `-O2`, so the compiler properly inlined calls :)
How expensive is it to dereference a pointer?
[ "", "c++", "pointers", "" ]
``` ::GetSystemMetrics (SM_CYBORDER) ``` ...comes back with 1 and I know the title bar is taller than ONE pixel :/ I also tried: ``` RECT r; r.left = r.top = 0; r.right = r.bottom = 400; ::AdjustWindowRect (& r, WS_OVERLAPPED, FALSE); _bdW = (uword)(r.right - r.left - 400); _bdH = (uword)(r.bottom - r.top - 400); ``` But border w,h came back as 0. In my WM\_SIZE handler, I need to make sure the window's height changes in "steps" so, for example a whole new line of text could fit in the window with no "junky partial line space" at the bottom. But ::MoveWindow needs the dimensions WITH the border space added in. SOMEbody must have done this before... Thanks for any help :)
The [GetWindowRect](http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx) and [GetClientRect](http://msdn.microsoft.com/en-us/library/ms633503(VS.85).aspx) functions can be used calculate the size of all the window borders. Suite101 has a article on [resizing a window and the keeping client area at a know size](http://suite101.com/article/client-area-size-with-movewindow-a17846). Here is their sample code: ``` void ClientResize(HWND hWnd, int nWidth, int nHeight) { RECT rcClient, rcWind; POINT ptDiff; GetClientRect(hWnd, &rcClient); GetWindowRect(hWnd, &rcWind); ptDiff.x = (rcWind.right - rcWind.left) - rcClient.right; ptDiff.y = (rcWind.bottom - rcWind.top) - rcClient.bottom; MoveWindow(hWnd,rcWind.left, rcWind.top, nWidth + ptDiff.x, nHeight + ptDiff.y, TRUE); } ```
``` int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); ``` In fact, the above result might be equal to: ``` GetClientRect(hWnd, &rcClient); GetWindowRect(hWnd, &rcWind); int border_thickness = ((rcWind.right - rcWind.left) - rcClient.right) / 2; ``` but `GetSystemMetrics(SM_CXSIZEFRAME)` is easier to be used.
window border width and height in Win32 - how do I get it?
[ "", "c++", "winapi", "" ]
Client side rendering is useful when we want to use wiki like syntax. Unfortunately I have not found any library which gives wiki syntax rendering in GWT client side. Does anyone knows such an API/library?
Also quite nice: <http://code.google.com/p/gwtwiki/>
One of the XWiki developers writes in his blog, that they've developed a GWT based Wiki editor: * [XWiki development in overdrive for 2009](http://massol.myxwiki.org/xwiki/bin/view/Blog/XWikiDevOverride)
Wiki rendering in GWT
[ "", "java", "gwt", "wiki", "" ]
i have: ``` for i in range(2,n): if(something): do something else: do something else i = 2 **restart the loop ``` But that doesn't seem to work. Is there a way to restart that loop? Thanks
You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer. perhaps a: ``` i=2 while i < n: if something: do something i += 1 else: do something else i = 2 #restart the loop ```
Changing the index variable `i` from within the loop is unlikely to do what you expect. You may need to use a `while` loop instead, and control the incrementing of the loop variable yourself. Each time around the `for` loop, `i` is reassigned with the next value from `range()`. So something like: ``` i = 2 while i < n: if(something): do something else: do something else i = 2 # restart the loop continue i += 1 ``` In my example, the [`continue`](http://python.org/doc/2.5/ref/continue.html) statement jumps back up to the top of the loop, skipping the `i += 1` statement for that iteration. Otherwise, `i` is incremented as you would expect (same as the `for` loop).
python: restarting a loop
[ "", "python", "loops", "" ]
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time. I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes. ``` //in namespace base class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt { public: virtual base::Texture *GetTexture()=0; virtual unsigned GetWidth()=0; virtual unsigned GetHeight()=0; virtual float GetCentreX()=0; virtual float GetCentreY()=0; virtual void SetCentre(float x, float y)=0; virtual void Draw(float x, float y)=0; virtual void Draw(float x, float y, float angle)=0; virtual void Draw(float x, float y, float scaleX, flota scaleY)=0; virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0; }; ``` The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's. I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture\*) EDIT: When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc. The resulting dll could be imported in python just with "import [dllname]". ``` //dll compiled as cpputill.pyd extern "C" void initcpputill()//only exported method { static CppUtill* cpputill = new CppUtill; } class CppUtill : public Py::ExtensionModule<CppUtill> { public: CppUtill() : Py::ExtensionModule<CppUtill>("cpputill") { ExampleClass::init_type(); add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass"); add_varargs_method("HelloWorld", &CppUtill::HelloWorld, "HelloWorld(), print Hello World to console"); initialize("C Plus Plus module"); } ... class ExampleClass ... static void init_type() { behaviors().name("ExampleClass"); behaviors().doc ("example class"); behaviors().supportGetattr(); add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1"); } ``` How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?
Easiest way to do this, IMHO, is to have a simple C function that returns a pointer to an interface described elsewhere. Then your app, can call all of the functions of that interface, without actually knowing what class it is using. Edit: Here's a simple example. In your main app code, you create a header for the interface: ``` class IModule { public: virtual ~IModule(); // <= important! virtual void doStuff() = 0; }; ``` Main app is coded to use the interface above, without any details on the actual implementation of the interface. ``` class ActualModule: public IModule { /* implementation */ }; ``` Now, the modules - the DLL's have the actual implementations of that interface, and those classes don't even have to be exported - `__declspec (dllexport)` isn't needed. The only requirement for the modules is to export a single function, that would create and return an implementation of the interface: ``` __declspec (dllexport) IModule* CreateModule() { // call the constructor of the actual implementation IModule * module = new ActualModule(); // return the created function return module; } ``` note: error checking left out - you'd usually want to check, if new returned the correct pointer and you should protect yourself from the exceptions that might be thrown in the constructor of the `ActualModule` class. Then, in your main app, all you need is to simply load the module (`LoadLibrary` function) and find the function `CreateModule` (`GetProcAddr` function). Then, you use the class through the interface. Edit 2: your RefCount (base class of the interface), can be implemented in (and exported from) the main app. Then all your module would need to link to the lib file of the main app (yes! EXE files can have LIB files just like DLL files!) And that should be enough.
You are re-inventing COM. Your RefCounted class is IUnknown. Your abstract class is an interface. A COM server in a DLL has an entrypoint named DllGetClassObject(), it is a class factory. There is lots of documentation available from Microsoft on COM, poke around a bit to see how they did it.
C++: Dynamically loading classes from dlls
[ "", "c++", "windows", "class", "dll", "" ]
I'm building what could be called the DAL for a new app. Unfortunately, network connectivity to the database is a real problem. I'd like to be able to temporarily block network access within the scope of my test so that I can ensure my DAL behaves as expected under those circumstances. UPDATE: There are many manual ways to disable the network, but it sure would be nice if I could enable/disable within the test itself.
For the time being, I'm just "disabling" the network by setting a bogus static IP as follows: ``` using System.Management; class NetworkController { public static void Disable() { SetIP("192.168.0.4", "255.255.255.0"); } public static void Enable() { SetDHCP(); } private static void SetIP(string ip_address, string subnet_mask) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO("IPEnabled")) { try { ManagementBaseObject setIP = default(ManagementBaseObject); ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic"); newIP("IPAddress") = new string[] { ip_address }; newIP("SubnetMask") = new string[] { subnet_mask }; setIP = objMO.InvokeMethod("EnableStatic", newIP, null); } catch (Exception generatedExceptionName) { throw; } } } } private static void SetDHCP() { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { // Make sure this is a IP enabled device. Not something like memory card or VM Ware if ((bool)mo("IPEnabled")) { ManagementBaseObject newDNS = mo.GetMethodParameters("SetDNSServerSearchOrder"); newDNS("DNSServerSearchOrder") = null; ManagementBaseObject enableDHCP = mo.InvokeMethod("EnableDHCP", null, null); ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); } } } } ```
Write a wrapper to the network class connectivity class you're using (e.g. WebClient) with an on-off switch :) Either that, or block your application in the firewall.
How to simulate network failure for test purposes (in C#)?
[ "", "c#", "testing", "network-programming", "" ]
I am looking to convert pixes to inches and vice versa. I understand that I need DPI, but I am not sure how to get this information (e.g. I don't have the `Graphics` object, so that's not an option). Is there a way?
On a video device, any answer to this question is typically not very accurate. The easiest example to use to see why this is the case is a projector. The output resolution is, say, 1024x768, but the DPI varies by how far away the screen is from the projector apeture. WPF, for example, always assumes 96 DPI on a video device. Presuming you still need an answer, regardless of the accuracy, and you don't have a Graphics object, you can create one from the screen with some P/Invoke and get the answer from it. ``` Single xDpi, yDpi; IntPtr dc = GetDC(IntPtr.Zero); using(Graphics g = Graphics.FromHdc(dc)) { xDpi = g.DpiX; yDpi = g.DpiY; } if (ReleaseDC(IntPtr.Zero) != 0) { // GetLastError and handle... } [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr hwnd); [DllImport("user32.dll")] private static extern Int32 ReleaseDC(IntPtr hwnd); ```
There's, physically, no real way without knowing the DPI. Pixels are discrete, inches are not, if you're talking inches on your monitor, you need to know (at the very least) the resolution (and pixel aspect ratio) and the size of the visible monitor area in order to calculate your DPI. The resolution is usually possible to fetch somewhere (I'm not a C# or .NET programmer, so I can't help you there), but the size of the monitor is usually not available. If an estimate is good enough then have the user enter the size of the monitor (i.e. 21" or whatever) and solve for DPI: ``` (resX/DPI)^2 + (resY/DPI)^2 = screenDiagonal^2 ``` giving (assuming you know the diagonal and the resolution) ``` DPI = sqrt(resX^2+resY^2)/screenDiagonal ``` This is just an estimate, as monitors are never exactly 21" (.. or whatever), and the pixel aspect ratio is hardly ever exactly 1:1. If you're talking inches on paper, then, quite naturally you need to know the DPI of your printer (or, more accurately, the current printer settings).
Convert Pixels to Inches and vice versa in C#
[ "", "c#", "winforms", "system.drawing", "" ]
Is there a straightforward way to list the names of all modules in a package, without using `__all__`? For example, given this package: ``` /testpkg /testpkg/__init__.py /testpkg/modulea.py /testpkg/moduleb.py ``` I'm wondering if there is a standard or built-in way to do something like this: ``` >>> package_contents("testpkg") ['modulea', 'moduleb'] ``` The manual approach would be to iterate through the module search paths in order to find the package's directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?
Maybe this will do what you're looking for? ``` import imp import os MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo') def package_contents(package_name): file, pathname, description = imp.find_module(package_name) if file: raise ImportError('Not a package: %r', package_name) # Use a set because some may be both source and compiled. return set([os.path.splitext(module)[0] for module in os.listdir(pathname) if module.endswith(MODULE_EXTENSIONS)]) ```
Using [python2.3 and above](http://docs.python.org/library/pkgutil.html), you could also use the `pkgutil` module: ``` >>> import pkgutil >>> [name for _, name, _ in pkgutil.iter_modules(['testpkg'])] ['modulea', 'moduleb'] ``` **EDIT:** Note that the parameter for `pkgutil.iter_modules` is not a list of modules, but a list of paths, so you might want to do something like this: ``` >>> import os.path, pkgutil >>> import testpkg >>> pkgpath = os.path.dirname(testpkg.__file__) >>> print([name for _, name, _ in pkgutil.iter_modules([pkgpath])]) ```
Is there a standard way to list names of Python modules in a package?
[ "", "python", "module", "package", "" ]
Has someone experience with database comparison tools? Which one you would recommend? We are currently using "SQLCompare" from Redgate, but I am curious to know if there are better tools on the market. The main requirement is that they should be able to compare scripts folder against a live database. Thanks, Dimi
SQL Compare is pretty good. I've also used SQL Delta which provided better delta scripts. Also if you are a visual studio user, Visual Studio Team System Database Edition is not a bad way to go (includes MSBuild tasks to automate your DB builds and versioning). And VSTS DB (aka data dude) is also free now if you are licensed for VSTS Developer edition.
I work for Innovartis and we make DB Ghost which is something you may want to look at. It can do what you want - compare scripts to a database. It can do this in a single step using the change manager by building and comparing. It is very, very fast. Building the database also gives you the added benefit of dependency checking of the database just in case someone has broken one piece of database code by changing or introducing another. We believe the software offers a way to manage database changes quickly and cost effectively and combined with your source control can give you total control. Like team system but much, much cheaper. Script, Build, Compare, Upgrade, Create a change script, Deploy, & Copy database function which is free. www.dbghost.com
DB comparison tools
[ "", "sql", "sql-server", "comparison", "compare", "" ]
I am include a huge javascript file(500K) in my HTML. Is there a smart way to know if it has been loaded. One way I can think of is to have a variable in its constructor to initialize and inform me . The loading is asynchronous and I cannot proceed until function s of that JS are included. Thanks
By using jQuery you can handle a callback function that runs when the script file is loaded: ``` $.getScript("yourScriptFile.js", function(){ // What to do when the script is loaded }); ``` [Docs](http://docs.jquery.com/Ajax/jQuery.getScript)
As an clarification on Oscar's answer: ``` <script type='text/javascript' src='script.js'></script> <script type='text/javascript'> alert('the file has loaded!'); //Anything here will not be executed before the script.js was loaded </script> ``` Also if the file is huge, it might be better to load it after the page has loaded, so that you, on slow connections can use the page before it's loaded: ``` <head> <script type='text/javascript' src='script.js'></script> </head> <body> Nothing here will be rendered until the script has finished loading </body> ``` Better is to: ``` <head> </head> <body> I will be rendered immidiatly </body> <script type='text/javascript' src='script.js'></script> </html> ``` That way users get the page fast and only then have to wait for the javascript functionality.
Inclusion of a js file in HTML
[ "", "javascript", "header", "" ]
I am trying to fire an event on the right and left arrow key presses with jQuery. Using the following code, I can fire events on any of the alphanumeric keys, but the cursor keys (up, down, left, right) fire nothing. I am developing the site primarily for IE users because it is a line of business app. Am I doing something wrong here? ``` $('document').keypress(function(e){ switch (e.which) { case 40: alert('down'); break; case 38: alert('up'); break; case 37: alert('left'); break; case 39: alert('right'); break; default: alert('???'); } }); ```
**e.which** doesn't work in IE try **e.keyCode**, also you probably want to use keydown() instead of keypress() if you are targeting IE. See <http://unixpapa.com/js/key.html> for more information.
With jQuery, I've done it [this way](http://www.rambeck.com/blog/2008/05/jquery-enter-tab): ``` function checkKey(e){ switch (e.keyCode) { case 40: alert('down'); break; case 38: alert('up'); break; case 37: alert('left'); break; case 39: alert('right'); break; default: alert('???'); } } if ($.browser.mozilla) { $(document).keypress (checkKey); } else { $(document).keydown (checkKey); } ``` Also, try these plugins, which looks like they do all that work for you: <http://www.openjs.com/scripts/events/keyboard_shortcuts> <http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/>
jQuery keypress() event not firing?
[ "", "javascript", "jquery", "internet-explorer", "" ]
I'm trying to create a bookmarklet that will start off an AJAX call to an aspx page I've written. The code tests out perfectly when I place the javascript in a static html page, but when I try and call it off from a bookmarklet, the code will just hang at the xmlHttp.open("GET", url, true) part. The code of the bookmarklet is basically this (found on several examples on the web): ``` javascript:(function(){ var s, d=document, a=function(o){ d.body.appendChild(o) }; s=d.createElement('script'); s.type='text/javascript'; s.src='http://localhost/squirt/sq.js'; a(s) })(); ``` This adds the contents of sq.js (the ajax call + some other processing) to whatever page the browser is currently at, and then calls off the ajax to my aspx page. I'm using ASP 2.0 (with VS2008) and IIS 7. So far I've just been testing it on my home network. I assume there must be some sort of permissions issue with the ajax call from an outside page, since, like I said, everything works fine from a static page. Is this an IIS setting I need to change to allow the call, or am I doing something completely wrong?
The XMLHttpRequest object is subject to a Same Origin Policy. This is why the script your bookmarklet is loading can't use an XHR to get data from your server unless it's embedded in a page from your server. Script added by dynamically adding a script tag will work though, as you can tell - your bookmarklet can load script from a different origin. So there's your answer. Don't use an XMLHttpRequest object: dynamically load your script in the same way the bookmarklet does. This is how JSONP works (actually there's a bit more to JSONP but that's how it gets around the SOP) Actually, why not just use [JSONP](http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/)
Injecting JavaScript code on the page still has the same permission issues as code that is there normally. You can not make an Ajax call to a different domain. So if you are calling localhost from example.com, it is not going to work. You might want to look at returning JSON from your service and make JSON calls with a script tag. Eric
AJAX call to asp from bookmarklet
[ "", "asp.net", "javascript", "ajax", "asp.net-ajax", "" ]
I have a class called User with static function loginRequired(), which returns false if the user is logged in and true if the user is logged out. It also appends an error to an error class that I created that tells the person using the site that they must be logged in to view the content. The idea is that for the top of each function that would require the user to be logged in, we write this code: ``` if(User::loginRequired()) return; ``` Which will output the error and immediately return from the function. I would rather do this, however: ``` User::loginRequired(); ``` And return from the calling function inside of the loginRequired function... but because loginRequired() is in a separate class in a separate file, this won't work. Is it possible to return from the function that calls loginRequired(), within loginRequired()? Thanks.
The way I've seen a number of open source apps handle this is by having a `require_login()` function which performs a redirect should the user not be logged in.
I'm not sure you can do exactly what you want, however, you might want to look at using [exceptions](https://www.php.net/exceptions). This would allow you to throw an exception in the User::loginRequired function and catch it at some higher level. You could also look at using the [exit()](https://www.php.net/exit) PHP function.
PHP Return from function in another file
[ "", "php", "return", "" ]
Is there a difference or is one better than the other of the following: ``` $var = ''; ... $var .= 'blah blah'; $var .= $var2; $var .= 'blah blah'; ``` Or ``` $var = ''; ... $var .= 'blah blah' . $var2 . 'blah blah'; ``` Is there a speed difference or is there a reason why you'd pick one over the other?
There is a small difference if you echo the string. ``` echo $var1,$var2,$var3 // comma (echo with multiple arguments) ``` is slightly faster than ``` echo $var1.$var2.$var3 // dot (concat and echo) ```
Both PEZ and Topbit are correct. I just want to point out something I think looks better than has been seen here: ``` $var = "line 1 \n"; $var .= "line 2 \n"; ``` versus ``` $var = "line 1 \n" . "line 2 \n"; ``` I much prefer the second one to the first one as visually it is obvious your result is the one string $var. It also prevents stupid bugs like: ``` $var = "line 1 \n"; $var .= "line 2 \n"; $vat .= "line 3 \n"; $var .= "line 4 \n"; ```
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
[ "", "php", "concatenation", "" ]
I am using xml.net in web application When I try load xml through an http internet url using: xmlDoc.Load("http://....") i get an error:"connected host has failed to respond" Anyone knows the fix for this? Thanks
Connected Host has failed to respond is because you've not go the uri correct or you're not allowed to access it, or it's not responding to you, or it's down. http doesn't really care what it transmits.
It probably means exactly what it says: the web server responsible for requests at the URL you specify isn't sending back responses. Something's going wrong on the web server, and if so, you can't do anything about someone's web server out there in the cloud not functioning properly. You can, however, accept the fact that not every URL will work, and that you'll have to catch the Exception that the XmlDocument or XDocument is throwing. It's reasonable to expect that this scenario may occur. Thus, you need to programming defensively and by including the appropriate exception handling to handle such cases. EDIT: So you can access it from outside the .NET framework eh? Perhaps try using an HTTP debugger, like Fiddler, and compare the request your XML document object makes to the request your browser makes. What header fields are different? Is there a header that the browser includes that the XML document object doesn't? Or are there different header values between the two, that may be causing the .NET request not to be responded to? Go figure.
Loading an xml from an http url
[ "", "c#", "" ]
If I have a table with a title column and 3 bit columns (f1, f2, f3) that contain either 1 or NULL, how would I write the LINQ to return the title with the count of each bit column that contains 1? I'm looking for the equivalent of this SQL query: ``` SELECT title, COUNT(f1), COUNT(f2), COUNT(f3) FROM myTable GROUP BY title ``` I'm looking for the "best" way to do it. The version I came up with dips into the table 4 times when you look at the underlying SQL, so it's too slow.
Here's the solution I came up with. Note that it's close to the solution proposed by @OdeToCode (but in VB syntax), with one major difference: ``` Dim temp = _ (From t In context.MyTable _ Group t.f1, t.f2, t.f3 By t.title Into g = Group _ Select title, g).ToList Dim results = _ From t In temp _ Select t.title, _ f1_count = t.g.Count(Function(x) If(x.f1, False)), _ f2_count = t.g.Count(Function(x) If(x.f2, False)), _ f3_count = t.g.Count(Function(x) If(x.f3, False)) ``` The first query does the grouping, but the ToList gets the grouped data as-is from the server. Eliminating the counting here keeps the resulting SQL statement from producing sub-SELECTs for each count. I do the counting in the second query locally. This works since I know the first query will return a manageable number of rows. If it were returning millions of rows, I'd probably have to go in another direction.
If you want to stick to a LINQ query and use an anonymous type, the query could look like: ``` var query = from r in ctx.myTable group r by r.title into rgroup select new { Title = rgroup.Key, F1Count = rgroup.Count(rg => rg.f1 == true), F2Count = rgroup.Count(rg => rg.f2 == true), F3Count = rgroup.Count(rg => rg.f3 == true) }; ``` The trick is to recognize that you want to count the number of true fields (it gets mapped as a nullable bool), which you can do with the Count operator and a predicate. More info on the LINQ group operator here: [The Standard LINQ Operators](http://www.odetocode.com/Articles/739.aspx)
LINQ COUNT on multiple columns
[ "", ".net", "sql", "linq", "linq-to-sql", "" ]
I have two projects, the DLL project which has all my logic and data access stuff, and the ASP.NET project which does my forms etc. I am a bit confused. I thought if I added the System.Web namespace reference to the DLL project I would be able to reference the Session state information of the ASP.NET page. I could use each page to get the session info out and pass it to the DLL for the processing but would love to be able to process things directly from the DLL class(s). Is this possible? I have fiddled with the System.Web namespace and just seem able to get a reference to the Session variable. Thanks all. Jon
You should be able to use HttpContext.Current.Session # Edit While yes I agree you should not tightly couple your Business Logic DAL or etc assemblies to ASP.Net session. There are plenty of valid cases for accessing HTTP Context outside of a web project. Web Controls is probably one of the best examples, reusable HTTP modules, etc.. Now one option, if you want to have your DLL pull the stuff from Session, is to abstract out session. So you could define an interface like IStorage, that your library will know how to use. Then you can have a SessionStorage or MemoryStorage class and use IoC to inject the appropriate class into your library classes. This gives you the freedom to code it how you wanted it to be coded without tying your code to Session. Oh and one other benefit if done properly can be used to not tie your code to the session on the web either.
As long as the Assembly is loaded in the scope of the Session, it will have access. Although this type of tight coupling isn't really recommended.
Can I use ASP.NET Session[] variable in an external DLL
[ "", "c#", "asp.net", "session-state", "session-variables", "" ]
In our current project we are providing a PDF download that can be customized by the user through an HTML form he submits. It takes several seconds to dynamically generate the PDF and I'd like to visualize this, e.g. by disabling the submit button until the download starts. Unfortunately, I couldn't find a way to detect when the download starts\*. So I wouldn't know when to re-enable the submit button. I already tried to specify an IFrame as the target of my HTML form, hoping that the `onload` event would be triggered. It is not, however -- probably because the PDF is sent with a "`Content-disposition: attachment`" header and it is not actually loaded into the IFrame. The only solution I can think of right now involves generating the PDF to a temporary file on the server, which I would like to avoid. \*)Let me clarify this: I wouldn't need to know if the download was finished or even if it was really started. I'd like to detect the point at which the browser will ask the user whether to open or to save the file. I guess this happens when the browser receives the HTTP header.
What you want is to be able to detect when the size of the downloaded file changes from 0 to a positive value. As far as I know it is impossible to do that with javascript - you need a plug-in that can access the client's file system. A recommended work around: Create a session per download. Have the client poll the server about the status of the download. This could be "non existed", "not started", "started", "finished". You need some server's side work to persist and update the status of the download plus an AJAX framework.
If I was you I would do an AJAX call to the server with the information, generate the file, then return the file name/id/whatever back to the javascript, which then makes window.location something like download.php?id=x (but the file was already generated, so it is just setting the headers and reading it out) at which point you can re-enable the submit.
Is there a way to detect the start of a download in JavaScript?
[ "", "javascript", "html", "iframe", "download", "" ]
How do I go about if I need to initialize an object's base with existing object? For example, in this scenario: ``` public class A { public string field1; public string field2; } public class B : A { public string field3; public void Assign(A source) { this.base = source; // <-- will not work, what can I do here? } } ``` Assign() method can, obviously assign values to the base class field-by-field, but isn't there a better solution? Since class B inherits from A, there must be a way to just assign A to the B.base In C++ this would be a trivial thing to do, but I can't seem to grasp how to do this in .NET
Unfortunately `base` is readonly. [Edit] Well perhaps not so unfortunate. The relationship between a base class and a child class is `IS-A` not `HAS-A`. By allowing a child class to change the instance of the base class you are allowing the child class to change its own reference since it `IS-A` base class. If you truly need this functionality then I would suggest you change your inheritance model to reflect what you truly want to do. Something like this: ``` public class A { public string field1; public string field2; } public class B { public string field3; public A a; public void Assign(A source) { this.a = source; } } ``` seems more appropriate and has clearer meaning and functionality.
``` public Assign(A a) { foreach (var prop in typeof(A).GetProperties()) { this.GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(a, null),null); } } ``` Basically, it uses reflection to get all the properties of the base and assign the values of this, to all the values that exist in A. EDIT: To all you naysayers out there, I quickly tested this now with a base class that had 100 integer variables. I then had this assign method in a subclass. It took 46 milliseconds to run. I don't know about you, but I'm totally fine with that.
Initialize base class in .NET
[ "", "c#", ".net", "oop", "" ]
I have an HTML page with a typical structure: ``` <html> <head> <script src="..." ></script> <style>...</style> </head> <body> content </body> <script> var success_callback = function(data) { // REPLACE PAGE CONTENT & STRUCTURE WITH "data" } ajax(url, params, success_callback); </script> </html> ``` Do you think it is possible ? I've already tried to give the html tag an id and doing `$(id).replace(data);` with no success. Don't ask me why, but that is what I need (I'm working with a special "mashup builder" site... it is a long story). **EDIT** : I forgot to say that **scripts in the received content have to be executed**, even external scripts included using `<script src="...">`.
The simplest way is to set the new HTML content using: ``` document.open(); document.write(newContent); document.close(); ```
try this with **jQuery**: ``` $('body').load( url,[data],[callback] ); ``` Read more at [docs.jquery.com / Ajax / load](http://docs.jquery.com/Ajax/load#urldatacallback)
Replace HTML page with contents retrieved via AJAX
[ "", "javascript", "html", "ajax", "dom", "" ]
Could someone give some info regarding the different character sets within visual studio's project properties sheets. The options are: None Unicode Multi byte I would like to make an informed decision as to which to choose. Thanks.
All new software should be Unicode enabled. For Windows apps that means the UTF-16 character set, and for pretty much everyone else UTF-8 is often the best choice. The other character set choices in Windows programming should only be used for compatibility with older apps. They do not support the same range of characters as Unicode.
`Multibyte` takes exactly 2 bytes per character, `none` exactly 1, `unicode` varies. `None` is not good as it doesn't support non-latin symbols. It's very boring if some non-English user tries to input their name into edit box. Do not use `none`. If you do not use custom computation of string lengths, from programmer's point of view `multibyte` and `unicode` do not differ as long as use use `TEXT` macro to wrap your string constants. Some libraries explicitly require certain encoding (`DirectShow` etc.), just use what they want.
Which character set to choose when compiling a c++ dll
[ "", "c++", "character-encoding", "" ]
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example, ``` """Hello, I am a multiline comment""" ``` and ``` '''Hello, I am a multiline comment''' ``` But technically speaking these are strings, correct? I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /\* \*/ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments". Guido has [tweeted](https://twitter.com/gvanrossum/status/112670605505077248) about this: > Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
Multi-line comments are easily breakable. What if you have the following in a simple calculator program? ``` operation = '' print("Pick an operation: +-*/") # Get user input here ``` Try to comment that with a multi-line comment: ``` /* operation = '' print("Pick an operation: +-*/") # Get user input here */ ``` Oops, your string contains the end comment delimiter.
Why doesn't Python have multiline comments?
[ "", "python", "comments", "multiline", "" ]
I learned that compiler will expand macros while compiling. Templates are also expanded at the compile time. Is there any way to see this expanded code? I am compiling using Visual Studio 2008. any thoughts?
The VC++ compiler (cl.exe) supports a few command line switches for this: ``` /E preprocess to stdout /P preprocess to file /EP preproscess to stdout with no #lines ``` Additional command-line switches can be added in your project properties. In my version (VC2005), Configuration Options -> C/C++ -> Command Line -> Additional Options
The compiler doesn't actually do any of the macro expansion. That is the task of the pre-processor. It all appears as one step, but the compiler actually forks out to a separate pre-processor tasks and traps the output for you. Templates are not "expanded" at compile time. They are instantiated on use during compile. The difference is that the compiler immediately generates object code for the template; there's no intermediate source code that comes out. You can't look at the instantiated template code as source, it's dumped out as assembly when it's needed. If you have GCC you can also call the pre-processor directly using 'cpp' with the right arguments (mostly include paths and command line macro definitions). Others have answered for MSVC.
Viewing compiler expanded code - C++
[ "", "c++", "templates", "macros", "compiler-construction", "" ]
I have this function... ``` private string dateConvert(string datDate) { System.Globalization.CultureInfo cultEnGb = new System.Globalization.CultureInfo("en-GB"); System.Globalization.CultureInfo cultEnUs = new System.Globalization.CultureInfo("en-US"); DateTime dtGb = Convert.ToDateTime(datDate, cultEnGb.DateTimeFormat); datDate = dtGb.ToString(cultEnUs.DateTimeFormat.ShortDatePattern); return datDate; } ``` But I want it with the leading zero still on lower digits (1-9) so the date is 11-09-2009 (mm-dd-yyyy)... Now If I wasn't converting it id use string.Format("{0:d}", dateVar) how do I do this in the conversion? **\*\*\*\*\* Solution \*\*\*\*\*** Used a slightly modified version of the answer below (i.e. one that would render). ``` Convert.ToDateTime(datDate).ToString("MM-dd-yyyy"); ```
``` return dateTimeValue.ToString("MM-dd-yyyy"); ```
Can't you use the `string.Format` after you've done the conversion? ie `return string.Format("{0:d}", datDate);`
Leading Zero Date Format C#
[ "", "c#", "datetime", "" ]
I have a GridView bound to an `ICollection<UserAnswer>` that needs to show two columns: ``` <asp:GridView ID="UserAnswersGridView" runat="server"> <Columns> <asp:BoundField DataField="Question.Name" HeaderText="Question Name" SortExpression="QuestionID" /> <asp:BoundField DataField="Score" HeaderText="Score" SortExpression="Score" /> </Columns> </asp:GridView> ``` But I get the error: > A field or property with the name 'Question.Name' was not found on the selected data source. Each `UserAnswer` has a `QuestionId` value which is what I would use to query the question name. In code, I would just call `userAssessment.Question.Name`, but how would I do this with a bound column in a GridView without creating a new type? For reference this is the method that returns the data: ``` public static ICollection<UserAnswer> GetUserAnswers(Int32 userAssessmentId) { DataContext database = new DataContext(GetConnectionString()); return database.UserAnswers.Where(u => u.UserAssessmentId == userAssessmentId).ToList(); } ``` Sorry if this explanation isn't very clear!
I believe that `GridView` only supports properties of the immediate type. Is repeater or anything similar an option? That gives you more flexibility. Alternatively, you can add shim properties to the type via a partial class: ``` namespace YourLinqNamespace { partial class UserAnswer { public string QuestionName {get {return Question.Name;}} } } ``` You can't use this in filters (`Where` etc), but you should be able to use it on returned objects without issue. Note that you might want to use `LoadWith` to save the round-trips: ``` DataLoadOptions options = new DataLoadOptions(); options.LoadWith<UserAnswer>(x=>x.Question); database.LoadOptions = options; ```
You could also use the ItemDataBoundEvent to set the field in code behind. Or you could use an anonymous type this is sort of like Marc's shim property concept, but you wouldn't be modifying your domain model. ``` from u in database.UserAnswers Where u.UserAssessmentId == userAssessmentId select new { QuestionName=u.Question.Name, Answer = u.Answer //etc etc }; ``` As Marc pointed out you shouldn't return an Anonymous type from a method, I've used trick when manually binding to the data source so: myGrid.DataSource= from u etc.... In my opinion using my first suggestion is better and handle it in the item data bound event.
Show joined value on bound field without custom type?
[ "", "c#", "asp.net", "linq", "" ]
How to implement a panel that would support line wrapping and line breaking? I would only add textual labels and line breaks to this panel. The labels should flow from left to right, wrapping to the next "line" if needed. The line breaks would cause a jump to the next line. I would also like to make the panel vertically scrollable. The solution should work in Java 5. SwingX can be used. Clarification: The textual labels are actually `JXHyperlink`s (from SwingX), i.e. the panel contains clickable labels. This is the reason I cannot just use `JTextArea`.
I found `JTextPane`, which I had overlooked before for some reason. This class does what I need. Thanks for your help though. :)
UPDATE: I missed the request for hyperlink support. Don't know how to do that w/o using the EditorPane. JTextArea does exactly what you've described. ``` JTextArea textArea = new JTextArea(); JScrollPanel sPane = new JScrollPane(textArea); ```
Panel with line wrapping and line breaking in Java Swing
[ "", "java", "swing", "user-interface", "jpanel", "jtextpane", "" ]
I was trying to build [Boost C++ Libraries](http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries) for last two hours and stopped without any result. Since I am new to C++, I am unable to get the build right. How can I build it correctly using Visual Studio 2008? I need to use the BCP tool to extract a subset of library. So I need to build BCP first, right? How to do this? When I tried to build it, I got the following error > *fatal error LNK1104: cannot open file 'libboost\_filesystem-vc90-mt-gd-1\_37.lib'.* Where can I get the above given library file?
First, you need to have the proper PATH, INCLUDE and LIB environment variables in your command shell. For this, call the file "`vcvarsall.bat`" (or similar) with parameter: ``` vcvarsall.bat x86 ``` Next you have to build bjam (you can also download it from the Boost page, but it's almost as quick). Go to the `tools\jam\src` folder in Boost and type: ``` build.bat ``` It should produce a subfolder `bin.ntx86` that contains bjam.exe. For convenience, copy it to the Boost main folder. Next, you can build bcp. Go into the `tools\bcp` folder and type: ``` ..\..\bjam.exe --toolset=msvc ``` Back in the Boost main folder you can then build any library you wish: ``` bjam toolset=msvc –-with-{library} ``` where `{library}` is one of the libraries to build. All buildable libraries can be shown with: ``` bjam –-show-libraries ``` There are many more bjam build parameters. Some parameters with keywords you can specify are: ``` variant=debug|release link=shared|static threading=multi|single ``` An example would be: ``` bjam toolset=msvc –-with-filesystem threading=multi variant=debug stage ``` For more infos, visit the [Boost documentation pages](http://www.boost.org/doc/libs). Edit: Updated link to point to most recent Boost documentation Edit: Corrected options --with-{library} and –-show-libraries
The current version of Boost (1.50.0) uses Boost.Build. The new workflow for building bcp is as follows: from the root Boost directory, type: ``` bootstrap.bat ``` Then, once Boost.Build has been built, type: ``` b2 tools/bcp ```
Building Boost BCP
[ "", "c++", "boost", "" ]
I tried searching here for a similar solution but didn't see one so I was wondering what is the best way to accomplish the following. I have a table with 17 million + rows all have a unique ID. We have recently created a new table that will be used in conjunction with the previous table where the foreign key of the new table is the unique id of the old table. For ex. Table 1 - id, field1, field2, field3... table 2 - table1.id, field1 ... The problem is since we are migrating this into a live environment, we need to back fill table 2 with a row containing the id from table 1 for each row in table 1. ex, table 1 - 1, test, null table 2 now needs to have: 1, null, ... and so on for each row that is in table1. The main issue is that the ids are not all sequential in table 1 so we will have to read from table 1 and then insert based of the id of found into table 2. Is there any easier way to go about this? Also to clarify, table 2 will be new data and the only thing that it will contain from table 1 is the id to keep the foreign key relationship Also this is sql server 2000
You need to read this article. [What are the most common SQL anti-patterns?](https://stackoverflow.com/questions/346659/what-are-the-most-common-sql-anti-patterns#346679) > The main issue is that the ids are not all sequential in table 1 so we will have to read from table 1 and then insert based of the id of found into table 2 Yes, look at my answer in the above article and write a key-walking loop using Item #2. Make sure when you write the insert statement, you provide a fieldlist - as I say in Item #1.
If I understand correctly, you want one record in table2 for each record in table1. Also I believe that apart from the reference to table1, table2 should initially contain blank rows. So assuming ``` table1 (ID, field1, field2, ...) table2 (ID, table1_ID, fieldA, fieldB,...) -- where table1_ID is a reference to ID of table1 ``` After creating table2 you can simply run this insert statement ``` insert into table2(table1_ID) select ID from table1 ```
Insert row in table for each id in another table
[ "", "sql", "t-sql", "" ]
ModelMultipleChoiceField doesn't select initial choices and I can't make the following fix (link below) work in my example: <http://code.djangoproject.com/ticket/5247#comment:6> My models and form: ``` class Company(models.Model): company_name = models.CharField(max_length=200) class Contact(models.Model): company = models.ForeignKey(Company) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Action(models.Model): company = models.ForeignKey(Company, blank=True, null=True) from_company = models.ManyToManyField(Contact, verbose_name='Participant(s) from "Company"', blank=True, null=True) class Action_Form(ModelForm): from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.none(), widget=forms.CheckboxSelectMultiple()) class Meta: model = Action ``` What I do and the results: ``` >>> contacts_from_company = Contact.objects.filter(company__exact=1) # "1" for test, otherwise a variable >>> form = Action_Form(initial={'from_company': [o.pk for o in contacts_from_company]}) # as suggested in the fix >>> print form['from_company'] <ul> </ul> >>> print contacts_from_company [<Contact: test person>, <Contact: another person>] >>> form2 = Action_Form(initial={'from_company': contacts_from_company}) >>> print form2['from_company'] <ul> </ul> >>> form3 = Action_Form(initial={'from_company': Contact.objects.all()}) >>> print form3['from_company'] <ul> </ul> ``` The way I was hoping it would work: 1. My view gets "company" from request.GET 2. It then filters all "contacts" for that "company" 3. Finally, it creates a form and passes those "contacts" as "initial={...}" **Two questions:** **1. [not answered yet]** How can I make ModelMultipleChoiceField take those "initial" values? **2. [answered]** As an alternative, can I pass a variable to Action\_Form(ModelForm) so that in my ModelForm I could have: ``` from_company = forms.ModelMultipleChoiceField(queryset=Contact.objects.filter(company__exact=some_id) # where some_id comes from a view ```
You will need to add an `__init__` method to `Action_Form` to set your initial values, remembering to call `__init__` on the base `ModelForm` class via **super**. ``` class Action_Form(forms.ModelForm): def __init__(self, *args, **kwargs): super(Action_Form, self).__init__(*args, **kwargs) self.fields['from_company'].queryset = Contact.object.filter(... ``` If you plan to pass your filter params as keyword args to `Action_Form`, you'll need to remove them prior invoking super: ``` myfilter = kwargs['myfilter'] del kwargs['myfilter'] ``` or, probably better: ``` myfilter = kwargs.pop('myfilter') ``` For more information, here's another link referring to [Dynamic ModelForms in Django](http://www.rossp.org/blog/2008/dec/15/modelforms/).
I'm replying for 1) > 1. How can I make ModelMultipleChoiceField take those "initial" values? This could be done in your `Action_Form` `__init__` method using ModelMultipleChoiceField `initial` attribute. As it says in the Django source code (*db/models/fields/related.py*) in `def formfield(self, **kwargs)`: ``` # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. ``` So you need to give it a list of IDs: ``` class Action_Form(forms.ModelForm): def __init__(self, *args, **kwargs): super(Action_Form, self).__init__(*args, **kwargs) self.fields['from_company'].initial = [c.pk for c in Contact.object.filter()] ```
Django: ModelMultipleChoiceField doesn't select initial choices
[ "", "python", "django", "django-models", "django-forms", "" ]
I found out that build time of C# solution with many projects gets much faster if you don't have "copy local" enabled everywhere. I did some tests and it seems that (for our solution at least) we could increase build time by factor 2-3 just by removing "Copy local". This probably means we have to store libraries in some common directory. Any suggestion/best practices how to acheive this? Note that I would like to keep references to projects, not to DLLs.
We retarget the output directory of projects to be ../../Debug (or ../../Release) Our libs are placed in these directories as well. We set the reference paths in each project to be the Debug or Release directory accordingly (this setting is persisted in the user files since it is an absolute rather than relative reference) We keep project references as project references, All dll references have copy local false and specific version false unless they are system level dlls we know will be in the GAC on all deployed machines. This works a treat and manual builds in the IDE mimic scripted builds from the command line (using MSBuild) Test projects not for deployment do not direct their output to the centralized Debug|Release directory, they just use the standard default location (and do use copy local to avoid issues with locking) The library versions may be changed by the automated build process replacing the dlls in the Debug and Release directories.
I recommend building to ..\..\Build if your application is spread across solutions. (If you only have one solution, you may consider ..\Build.) Visual studio will, by default, pick up reference files in it's output folder. When building without VS using MSBuild, though, you must add the build folder as a reference path as shown in the example below: ``` <Target Name="BuildApp"> <MSBuild Projects="@(ProjectReference)" Targets="Rebuild" Properties="ReferencePath=..\..\Build;$(LibraryFolder)" > </MSBuild> <OnError ExecuteTargets="BuildFailed" /> </Target> ``` The example also takes me to my second argument. I **do not** think you should use your build folder as library folder, since this may lead to individual projects erroneously overwriting library assemblies e.g. by using Copy Local. You should have strict control over your library versions, so I suggest you keep this separated. (Developers would need to add this path in VS as a reference path.) You may also choose to separate ..\..\Build into ..\..\Release and ..\..\Debug as [suggested by ShuggyCoUk](https://stackoverflow.com/questions/488043/optimizing-visual-studio-solution-build-where-to-put-dll-files/488272#488272).
Optimizing Visual Studio solution build - where to put DLL files?
[ "", "c#", "visual-studio-2008", "msbuild", "build", "" ]
I try to clear my listview but the clear method doesn't work: ``` myListView.Items.Clear(); ``` This doen't work. When i put a breakpoint at this line, the line is executed, but my listview isn't empty. How come?? I fill my listview by setting it's datasource to a datatable. My solution now is to set the datasource to an empty datatable. I just wonder why clear don't do the trick? I use a master page. Here some code of a content page when a button is pressed. The method SearchTitle fills the ListView. Relevant code: ``` protected void Zoek() { // Clear listbox ListView1.DataSource = new DataTable(); ListView1.DataBind(); switch (ddlSearchType.SelectedValue) { case "Trefwoorden": SearchKeyword(); break; case "Titel": SearchTitle(); break; case "Inhoud": SearchContent(); break; } } ``` Method that fills the ListView ``` private void SearchTitle() { // Make panel visible pnlResult.Visible = true; pnlKeyword.Visible = false; Search Search = new Search(txtSearchFor.Text); ListView1.DataSource = Search.SearchTitle(); ListView1.DataBind(); } ```
How about ``` DataSource = null; DataBind(); ```
Try this ... ``` myListView.DataSource = null; myListView.Items.Clear(); ```
C# Clear all items in ListView
[ "", "c#", "listview", "" ]
I have a class that defines a read-only property that effectively exposes a private field, something like this: ``` public class Container { private List<int> _myList; public List<int> MyList { get { return _myList;} } public Container() : base () { _myList = new List<int>(); } // some method that need to access _myList public SomeMethod(int x) { _myList.Add(x); } } ``` now it's impossible for the consumer to manage my property directly, so code like aContainer.MyList = new List(); generates a compile-time error. However, the consumer is absolutely free to call all sorts of methods on the reference he got, so this is perfectly valid code ``` Container c = new Container(); Console.WriteLine(c.MyList.Count); c.MyList.Add(4); Console.WriteLine(c.MyList.Count); ``` which kind of defeats the whole read-only concept. Is there any sane workaround that would enable me to have a real read-only reference propery? P.S. I cannot just return a copy of the list because then the user will think that he made all the changes necessary, but alas... they will be gone.
The reference is ["readonly"](http://msdn.microsoft.com/en-us/library/acdd6hb7(VS.71).aspx), the the actual object. I.e. you can't replace the reference with another object. So if you have a class that breaks it like this: ``` public class Container { private readonly List<int> _myList; public List<int> MyList { get { return _myList;} } public Container() : base () { _myList = new List<int>(); } public void BreakReadOnly() { _myList = new List<int>(); } } ``` …then it won't even compile. It's because a readonly field can't be reassigned with any other object. In this case `BreakReadOnly` will try to assign a new list. If you really want a readonly collection of it then you can do it like this: ``` public ReadOnlyCollection<int> MyList { get { return _myList.AsReadOnly(); } } ``` Hope this helps. **Updated**: Removed use of IEnumerable.
Don't return a direct reference to your list. Instead return a ReadOnlyCollection wrapped around it, or if the List<> return type is set in stone, return a copy of your list. They can do whatever they want to the copy without affecting the original.
Restricting access to method calls on read-only properties
[ "", "c#", "properties", "readonly", "" ]
If I use the `new` keyword in my library (which is built differently than my main app), when I delete it in my main app with `delete`, is there a chance that I may get a crash/error?
yes indeedy. In particular you see problems with debug/release heaps being different, also if your library uses placement new, or any custom heap you'll have a problem. The Debug/Release issue is by far the most common though.
It depends. If you're talking about a static library, then you'll probably be OK -- the code will run in the same context as the main program, using the same C++ runtime library. This means that `new` and `delete` will use the same heap. If you're talking about a shared library (a DLL), then you probably won't be OK. The code running in the DLL might be using a different C++ runtime library, which means that the layout of the heap will be different. The DLL might be using a different heap altogether. Calling `delete` (in the main program) on a pointer allocated by the DLL (or vice versa) will lead to (at best) an immediate crash or (at worst) memory corruption that'll take a while to track down. You've got a couple of options. The first is to use the "factory method" pattern to create and delete these objects: ``` Foo *CreateFoo(); void DeleteFoo(Foo *p); ``` These should *not* be implemented in the header file. Alternatively, you can define a `Destroy` method on the object: ``` class Foo { ~Foo(); public: virtual void Destroy(); }; ``` ...again, don't implement this in the header file. You'd implement it thus: ``` void Foo::Destroy() { delete this; // don't do anything that accesses this object past this point. } ``` Note that the destructor for Foo is private, so that you have to call `Foo::Destroy`. Microsoft COM does something similar, where it defines a `Release` method that deletes the object when its reference count drops to zero.
C++ mix new/delete between libs?
[ "", "c++", "libs", "" ]
I have the following table in MSSQL2005 ``` id | business_key | result 1 | 1 | 0 2 | 1 | 1 3 | 2 | 1 4 | 3 | 1 5 | 4 | 1 6 | 4 | 0 ``` And now i want to group based on the business\_key returning the complete entry with the highest id. So my expected result is: ``` business_key | result 1 | 1 2 | 1 3 | 1 4 | 0 ``` I bet that there is a way to achieve that, i just can't see it at the moment.
An alternative solution, which may give you better performance (test both ways and check the execution plans): ``` SELECT T1.id, T1.business_key, T1.result FROM dbo.My_Table T1 LEFT OUTER JOIN dbo.My_Table T2 ON T2.business_key = T1.business_key AND T2.id > T1.id WHERE T2.id IS NULL ``` This query assumes that the ID is a unique value (at least for any given business\_key) and that it is set to NOT NULL.
``` select drv.business_key, mytable.result from mytable inner join ( select business_key, max(id) as max_id from mytable group by business_key ) as drv on mytable.id = drv.max_id ```
SQL Server: Only last entry in GROUP BY
[ "", "sql", "sql-server", "group-by", "" ]
In the code below I tried in two ways to access the parent version of methodTwo, but the result was always 2. Is there any way to get the 1 result from a ChildClass instance without modifying these two classes? ``` class ParentClass { public int methodOne() { return methodTwo(); } virtual public int methodTwo() { return 1; } } class ChildClass : ParentClass { override public int methodTwo() { return 2; } } class Program { static void Main(string[] args) { var a = new ChildClass(); Console.WriteLine("a.methodOne(): " + a.methodOne()); Console.WriteLine("a.methodTwo(): " + a.methodTwo()); Console.WriteLine("((ParentClass)a).methodTwo(): " + ((ParentClass)a).methodTwo()); Console.ReadLine(); } } ``` **Update** ChrisW posted this: > From outside the class, I don't know > any easy way; but, perhaps, I don't > know what happens if you try > reflection: use the Type.GetMethod > method to find the MethodInfo > associated with the method in the > ParentClass, and then call > MethodInfo.Invoke That answer was deleted. I'm wondering if that hack could work, just for curiosity.
At the IL level, you could probably issue a `call` rather than a `callvirt`, and get the job done - but if we limit ourselves to C# ;-p (**edit** darn! the runtime stops you: `VerificationException`: "Operation could destabilize the runtime."; remove the `virtual` and it works fine; too clever by half...) Inside the `ChildClass` type, you can use `base.methodTwo()` - however, this is not possible externally. Nor can you go down more than one level - there is no `base.base.Foo()` support. However, if you disable polymorphism using method-hiding, you can get the **answer** you want, but for bad reasons: ``` class ChildClass : ParentClass { new public int methodTwo() // bad, do not do { return 2; } } ``` Now you can get a different answer from the same object depending on whether the variable is defined as a `ChildClass` or a `ParentClass`.
Inside of `ChildClass.methodTwo()`, you can call `base.methodTwo()`. Outside of the class, calling `((ParentClass)a).methodTwo()` **will** call `ChildClass.methodTwo`. That's the whole reason why virtual methods exist.
Is there any way to call the parent version of an overridden method? (C# .NET)
[ "", "c#", ".net", "inheritance", "" ]
In an ASP.NET MVC application, I'm making logic for Admin to accept or reject new members. I'm showing a list of members and two buttons Accept and Reject, like this: ``` <% foreach (var mm in (ViewData["pendingmembers"] as List<MyMember>)) %> <% { %> <tr><td>Username:<%=mm.UserName %></td><td> <tr><td>Firstname:<%=mm.FirstName %></td><td> ...etc... <tr> <td> <% using (Html.BeginForm("AcceptPendingUser", "Admin")) { %> <input type="submit" value="Accept" /> <% } %> </td> <td> <% using (Html.BeginForm("RejectPendingUser", "Admin")) { %> <input type="submit" value="Reject" /> <% } %> </td> </tr> <% } %> ``` So, the list of pending member data is in a list of MyMember-objects. Each MyMember object will be printed out member and two buttons are setup for the admin to either accept or reject a pending member. Then, in the controller I'm separating the handling of those two input fields/forms, like this: ``` public ActionResult AcceptPendingUser() { // TODO: Add code to save user into DB and send welcome email. return RedirectToAction("Index"); } public ActionResult RejectPendingUser() { // TODO: Add code to remove user from PendingUsers list and send rejection email. return RedirectToAction("Index"); } ``` I would like to directly get the object next to the button the user pressed. How can I send the MyMember object from the View to the controller? Or how do I send perhaps a numeric index with button press? Maybe with a hidden field?
The simplest option would probably be a hidden input: ``` <input type="hidden" value="<%=mm.Key%>" name="key" id="key" /> ``` (name accordingly; in each form) The two controller would then take an argument called "key" (rename to suit). If you want to parse the object from multiple inputs, you'll need a `ModelBinder`. Of course, rather than 2\*n forms, you might consider either query-string based urls, or use something like jQuery (or some other script helper) to submit the data without needing the forms (if script is available).
Instead of using an HTML button consider using an ActionLink and construct it to include the id of the member being approved. Another alternative would be to have a checkbox (whose value is the id of the member being approved) that the admin can select for each member to be approved and a similar one for reject and one each approve/reject buttons for the entire form.
Passing data from View to Controller
[ "", "c#", ".net", "asp.net-mvc", "view", "controller", "" ]
I am trying to use jCarousel plugin for jQuery in order to provide my website users with scrollable (horizontal) content. The content I am mentioning is basically user defined `<li>` elements, styled so that they have a feel and look of a tab. so basically I am trying to achieve the same effect of the tabs in pageflakes.com. As you may imagine, the users are creating tabs and providing tab names by themselves.. jCarousel needs you to specify a fixed width for the content e.g., all their examples are based upon images that have fixed height and width. but in my case I have not control over what the user will name his/her tab...making it impossible for me to guess the width of the total container div. I have tried using a silly method such as guessing the width programatically assuming each letter being approx 5 pixels and multiplying 5 with the length of the word they have given as a name for a tab. even in this case, i needed to manipulate the css file dynamically which I am not sure how to do and even if it is feasable to do so.. Any solutions appreciated... ``` <lu> <li class='MyTab' id='578'>This is my tab</li> <li class='MyTab' id='579'>of which I can</li> <li class='MyTab' id='580'>never guess</li> <li class='MyTab' id='581'><img src='img/bullet_key.png' /> The length of</li> </lu> ``` The above html is produced programatically through ajax\_tabs\_output.aspx, loaded into a javascript array and the jCarousel takes care of the rest.. ``` function outputTabsArray() { $.ajax({ url: 'ajax_tabs_output.aspx', type: 'get', data: 'q=array', async: false, success: function(out) { tabs_array = out; } }); }// end outputTabsArray function mycarousel_itemLoadCallback(carousel, state) { for (var i = carousel.first; i <= carousel.last; i++) { if (carousel.has(i)) { continue; } if (i > tabs_array.length) { break; } carousel.add(i, mycarousel_getItemHTML(tabs_array[i-1])); } }; /** * Item html creation helper. */ function mycarousel_getItemHTML(item) { return '<div class="MyTab" id="' + item.tab_id + "'>" + item.tab_name + '</div>'; }; $('#mycarousel').jcarousel({ size: tabs_array.length, itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback} }); ```
The closest thing to what you want is probably [jscrollhorizontalpane](http://plugins.jquery.com/project/jscrollhorizontalpane). I've never used it so I can't vouch for it's effectiveness as a solution to this specific problem. This sort of widget shouldn't be to hard to make if you want to attempt it. I'll break down the approximate method I would use: **Make sure to use plenty of wrappers.** ``` <div class="scrollable"> <div class="window"> <div class="space"> <ul class="tabs"> <li class="tab">...</li> <li class="tab">...</li> <li class="tab">...</li> </ul> </div> </div> <a href="#" class="left">&larr;</a> <a href="#" class="right">&rarr;</a> </div> ``` What we'll be doing is shifting the "*space*" element back and forth inside "*window*" element. This can be done by setting `position:relative` to "*window*" and `position:absolute` to "*space*" and then shift it about using `left:-??px`, but I'll use the `scrollLeft` property. **Add some CSS.** ``` .window { overflow : hidden; width : 100%; } .space { width : 999em; /* lots of space for tabs */ overflow : hidden; /* clear floats */ } .tabs { float : left; /* shrink so we can determine tabs width */ } .tab { float : left; /* line tabs up */ } ``` This is just the basic stuff that the technique needs. Some of this stuff could be applied by jQuery, **Add events to window resize.** ``` $(window) .resize(function () { var sz = $('.window'); var ul = sz.find('ul'); if ( sz.width() < ul.width() ) { $('.scrollable a.left, .scrollable a.right').show(); } else { $('.scrollable a.left, .scrollable a.right').hide(); } }) .trigger('resize'); ``` **Add events to scroll buttons.** ``` $('.scrollable a.left').hover( function (e) { var sz = $('.window'); sz.animate({ scrollLeft : 0 }, 1000, 'linear'); }, function (e) { $('.window').stop(); }); $('.scrollable a.right').hover( function (e) { var sz = $('.window'); var margin = sz.find('ul').width() - sz.width(); sz.animate({ scrollLeft : margin }, 1000, 'linear'); }, function (e) { $('.window').stop(); }); ``` Done! The widths could also be calculated by looping through the "*tab*" elements and summing upp `outerWidth`. This is unnecessary if you have full control but might be a better choice for a full standalone plugin.
What you're looking for isn't tabs, but draggable panels. One example can be found here, called [JQuery Portlets](http://host.sonspring.com/portlets/). The related blog entry about Portlets can be found [here](http://sonspring.com/journal/jquery-portlets). You may also want to look into [JQuery UI](http://ui.jquery.com/)'s Draggable, Droppable, and Sortable plugins.
jCarousel with unknown content width
[ "", "javascript", "jquery", "jquery-plugins", "jcarousel", "" ]
There was [another thread about this](https://stackoverflow.com/questions/7477/autosizing-textarea), which I've tried. But there is one problem: the `textarea` doesn't shrink if you delete the content. I can't find any way to shrink it to the correct size - the `clientHeight` value comes back as the full size of the `textarea`, not its contents. The code from that page is below: ``` function FitToContent(id, maxHeight) { var text = id && id.style ? id : document.getElementById(id); if ( !text ) return; var adjustedHeight = text.clientHeight; if ( !maxHeight || maxHeight > adjustedHeight ) { adjustedHeight = Math.max(text.scrollHeight, adjustedHeight); if ( maxHeight ) adjustedHeight = Math.min(maxHeight, adjustedHeight); if ( adjustedHeight > text.clientHeight ) text.style.height = adjustedHeight + "px"; } } window.onload = function() { document.getElementById("ta").onkeyup = function() { FitToContent( this, 500 ) }; } ```
This works for me (Firefox 3.6/4.0 and Chrome 10/11): ``` var observe; if (window.attachEvent) { observe = function (element, event, handler) { element.attachEvent('on'+event, handler); }; } else { observe = function (element, event, handler) { element.addEventListener(event, handler, false); }; } function init () { var text = document.getElementById('text'); function resize () { text.style.height = 'auto'; text.style.height = text.scrollHeight+'px'; } /* 0-timeout to get the already changed text */ function delayedResize () { window.setTimeout(resize, 0); } observe(text, 'change', resize); observe(text, 'cut', delayedResize); observe(text, 'paste', delayedResize); observe(text, 'drop', delayedResize); observe(text, 'keydown', delayedResize); text.focus(); text.select(); resize(); } ``` ``` textarea { border: 0 none white; overflow: hidden; padding: 0; outline: none; background-color: #D0D0D0; } ``` ``` <body onload="init();"> <textarea rows="1" style="height:1em;" id="text"></textarea> </body> ``` *If you want try it on [jsfiddle](http://jsfiddle.net/hmelenok/WM6Gq/)* It starts with a single line and grows only the exact amount necessary. It is ok for a single `textarea`, but I wanted to write something where I would have many many many such `textarea`s (about as much as one would normally have lines in a large text document). In that case it is really slow. (In Firefox it's insanely slow.) So I really would like an approach that uses pure CSS. This would be possible with `contenteditable`, but I want it to be plaintext-only.
# A COMPLETE YET SIMPLE SOLUTION Updated **2023-06-08** *(Added native js for updating via js injection)* The following code will work: * On key input. * With pasted text *(right click & ctrl+v).* * With cut text *(right click & ctrl+x).* * With pre-loaded text. * With all textareas *(multiline textboxes)* site wide. * With **Firefox** *(v31-109 tested).* * With **Chrome** *(v37-108 tested).* * With **IE** *(v9-v11 tested).* * With **Edge** *(v14-v108 tested).* * With **IOS Safari**. * With **Android Browser**. * With JavaScript **strict mode**. --- ## OPTION 1 *(With jQuery)* This option requires [jQuery](https://jquery.com/) and has been tested and is working with **1.7.2** - **3.6.3** **Simple** *(Add this jQuery code to your master script file and forget about it.)* ``` $("textarea").each(function () { this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;"); }).on("input", function () { this.style.height = 0; this.style.height = (this.scrollHeight) + "px"; }); ``` ``` <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.3.min.js"></script> <textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea> <textarea placeholder="Type, paste, cut text here..."></textarea> ``` `Test on jsfiddle` --- ## OPTION 2 *(Pure JavaScript)* **Simple** *(Add this JavaScript to your master script file and forget about it.)* ``` const tx = document.getElementsByTagName("textarea"); for (let i = 0; i < tx.length; i++) { tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;"); tx[i].addEventListener("input", OnInput, false); } function OnInput() { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + "px"; } ``` ``` <textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea> <textarea placeholder="Type, paste, cut text here..."></textarea> ``` `Test on jsfiddle` --- ## OPTION 3 *(jQuery Extension)* Useful if you want to apply further chaining to the textareas, you want to be auto-sized. ``` jQuery.fn.extend({ autoHeight: function () { function autoHeight_(element) { return jQuery(element) .css({ "height": 0, "overflow-y": "hidden" }) .height(element.scrollHeight); } return this.each(function() { autoHeight_(this).on("input", function() { autoHeight_(this); }); }); } }); ``` Invoke with `$("textarea").autoHeight()` --- ## UPDATING TEXTAREA VIA JAVASCRIPT When injecting content into a textarea via JavaScript, append the following line of code to invoke the resize function. **jQuery** ``` $("textarea").trigger("input"); ``` **Pure JavaScript** ``` document.getElementsByTagName("textarea")[0].dispatchEvent(new Event('input', { bubbles: true })); ``` --- ## PRESET TEXTAREA HEIGHT To fix the initial height of the textarea you will need to add another condition: ``` const txHeight = 16; const tx = document.getElementsByTagName("textarea"); for (let i = 0; i < tx.length; i++) { if (tx[i].value == '') { tx[i].setAttribute("style", "height:" + txHeight + "px;overflow-y:hidden;"); } else { tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;"); } tx[i].addEventListener("input", OnInput, false); } function OnInput(e) { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + "px"; } ``` ``` <textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea> <textarea placeholder="Type, paste, cut text here..."></textarea> ```
Creating a textarea with auto-resize
[ "", "javascript", "html", "resize", "height", "textarea", "" ]
I have a large query (not written by me, but I'm making some modifications). One thing that kind of bugs me is that I've got the same COALESCE function in about four places. Is there a way to factor that out, possibly by joining with a select from DUAL? Is there a performance benefit to factoring it out? Here is the query slightly bolwderized: ``` select tbl1.gid [snip] ,COALESCE(t1_end_dt, t6_actl_end_dt,t6_calc_end_dt) perd_end_dt ,t1_end_dt FROM tbl1 .... JOIN tbl2 ON (t2_pk = wpck_wrkr_id AND t2_ind_1 ='Y' AND COALESCE(t1_end_dt, t6_actl_end_dt, t6_calc_end_dt) BETWEEN t2_strt_dt AND t2_end_dt) JOIN tbl3 ON (t3_pk = t2_fk_t3_pk AND COALESCE(t1_end_dt, t6_actl_end_dt, t6_calc_end_dt) BETWEEN t3_strt_dt AND t3_end_dt) LEFT JOIN tbl4 tbl4_a ON (tbl4_a.t4_pk = chkw_wkt_id) ..... GROUP BY tbl1.gid ..... ,COALESCE(t1_end_dt, t6_actl_end_dt, t6_calc_end_dt) ,COALESCE(tbl4_b.t4_or_id, tbl4_a.t4_or_id, t7_or_id ) ,t1_end_dt ORDER BY perd_end_dt ``` Note that I already factored out one of the COALESCEs by naming it pred\_end\_dt in the SELECT and then referring to it by that name in the ORDER BY.
You should be able to replace the occurrence in the GROUP BY clause with your column alias `perd_end_dt`. But the occurrences in JOIN conditions cannot use the column alias. This does have an impact on performance. I don't think the JOIN conditions can use an index the way they are written currently. However, it's only one term in the JOIN condition, so the impact might be very slight. That is, the terms involving `t2_pk` and `t2_ind_1` may already reduce the rowset so the date comparison only has to deal with a small set. It depends on how many rows we're talking about and how the data is distributed. One way to factor out the `COALESCE()` and take advantage of indexing would be to create a redundant column which is the result of that expression. Use triggers to make sure it has the right value after every insert or update. Then index the column. But like I said, it might be more trouble than it's worth. It'd be more work, and you should be sure that this change would make the code more maintainable, more correct, or more speedy. --- Another option would be to define an alias for the `COALESCE()` expression in a subquery. I can't tell which tables the columns come from, because you're not qualifying them with table aliases. But if I can assume they're all columns of `tbl1`: ``` ... FROM ( SELECT COALESCE(t1_end_dt, t6_actl_end_dt, t6_calc_end_dt) perd_end_dt, t1_fk_t2_pk FROM tbl1) t1 JOIN tbl2 ON (tbl2.t2_pk = t1.t1_fk_t2_pk AND tbl2.t2_ind_1 = 'Y' AND t1.perd_end_dt BETWEEN tbl2.t2_strt_dt AND tbl2.t2_end_dt) ... ```
Maybe you can use a with clause? ``` with data as ( select COALESCE(t1_end_dt, t6_actl_end_dt,t6_calc_end_dt) perd_end_dt , ..... , ... from tbl1 ) select ... from data , .... where .... ```
Factor out COALESCE function?
[ "", "sql", "oracle", "coalesce", "" ]
In Java, we're using the following package to programmatically create excel documents: ``` org.apache.poi.hssf ``` If you attempt to set a sheet's name (NOT file, but internal Excel sheet), you will get an error if: * The name is over 31 characters * The name contains any of the following characters: / \ \* ? [ ] However, after creating a document with a sheet name of: > @#$%&()+~`"':;,.| No error is output, and everything seems fine in Java. When you open the excel file in Office 2003, it will give you an error saying that the sheet name was invalid and that it renamed it to something generic like "Sheet 1". I don't know much about the previously stated package that we're using, but it looks like it's not correctly filtering invalid Excel sheet names. Any idea of how I can filter out all known invalid characters? I'm hesitant to simply filter out all non-word characters.
I think the problem is the colon, not the exclamation point. If you open Excel and try to manually edit a sheet name, the only characters it doesn't let you type are [ ] \* / \ ? : If you paste one of those characters in, you get the following error: (Excel 2003) > While renaming a sheet or chart, you > entered an invalid name. Try one of > the following: > > * Make sure the name you entered does not exceed 31 characters. > * Make sure the name does not contain any of the following > characters: : \ / ? \* [ or ] > * Make sure you did not leave the name blank.
You can use the Apache POI's WorkbookUtil.createSafeSheetName(String s) to safely create your Sheet Name. <http://poi.apache.org/apidocs/org/apache/poi/ss/util/WorkbookUtil.html>
Valid characters for Excel sheet names
[ "", "java", "excel", "" ]
I need to enable the [mcrypt](https://www.php.net/manual/en/book.mcrypt.php) functions on my website, except I'm on a shared host (running linux) and obviously don't have access to the `php.ini` file. There does seem to be options for installing PEAR modules but a search told me mcrypt wasn't available. Is there any way I can do this, short of begging technical support to help me? --- Update: Looking around a bit more, it looks like I might be able to use the `dl()` function to dynamically load a library at run time. Since I'm only using the mcrypt functions in one spot, I could probably get away with doing this since the performance hit (I assume there is a hit) should be minimal. The only problem now is how to get the `libmcrypt.so` file? --- Another update: I've downloaded the libmcrypt.tar.bz2 file from Sourceforge and run `./configure`, `make`, and then copied the `libmcrypt.so.4.4.8` file into my home directory (as `libmcrypt.so`), but now I can't find where to put it so that the `dl()` function will find it.
The MCrypt Sourceforge page should have it <http://mcrypt.sourceforge.net/> To compile it just: ``` wget http://superb-east.dl.sourceforge.net/sourceforge/mcrypt/libmcrypt-2.5.8.tar.gz tar -xzvf libmcrypt-2.5.8.tar.gz cd libmcrypt-2.5.8 ./configure make sudo make install ``` EDIT: Can you reference it with a direct path? What have you tried? Edit2: It seems that you can only load moduals from the extensions directory set in the php.ini and you cannot override extensions\_dir with ini\_set so you will either have to convince your host to install it or if they allow you to have your own php.ini (many do usually in [username]/php.ini) then you could set the extensions\_dir in there and load the modual with that.
Really the best way is to tell your ISP to include mcrypt support. Even if you bundle your own PHP extension and load it with dl(), there is no guarantee it is going to work after a PHP upgrade, as PHP is sometimes very version-number picky.
Installing PHP extensions on shared hosting
[ "", "php", "" ]
I have a `<div>` that holds a google ad. My website is mostly AJAX and there is no need for a browser refresh. That means my ads will not refresh either, which isn't ideal, a user staring at one ad all day. So I wanted a way to refresh a particular `<div>` on a page. I found many solutions but they didn't work. For example, using JQuery's html function: ``` $("#ads").html("google ad script here"); ``` This managed to refresh the whole page no idea how. I can also make an AJAX request to a HTML page that contains the Google ad but I am guessing it will have the same effect as the above attempt. I do not want to use iFrames. Is there any other option open to me? My pea brain can not think of anymore. :) ## EDIT: It is allowed since I will be initiating the refresh only when a user clicks a link. A prime example is Yahoo Mail - their new AJAX mailbox uses this same method, when a user clicks a link then a new ad is shown.
As both of the other answers state, refreshing your AdSense advertisements automatically isn't allowed. I understand that you only intend to refresh the ad in response to user action, but it *still* isn't allowed, even though it should be! Remember, the reason why you want to update the advertisements is so that you can show new ones. Displaying an advertisement is called an "impression." When you use code to refresh the ads, you are automatically generating ad impressions. [AdSense Program Policies](https://www.google.com/adsense/support/bin/answer.py?hl=en&answer=48182 "AdSense Program Policies") state (emphasis mine): > Invalid Clicks and Impressions > > Clicks on Google ads must result from genuine user interest. **Any method that artificially generates clicks or impressions on your Google ads is strictly prohibited.** These prohibited methods include but are not limited to repeated manual clicks or impressions, using robots, automated click and impression generating tools, third-party services that generate clicks or impressions such as paid-to-click, paid-to-surf, autosurf, and click-exchange programs, or any deceptive software. Refreshing your advertisements is a violation of the letter of the rule against generating impressions. With that said, I think any reasonable person would agree that refreshing advertisements in an AJAX app *in response to user behavior* (e.g. in response to a click) isn't a violation of the *spirit* of the rule. For example, imagine rewriting your entire app to stop using AJAX. That's clearly a worse experience for your users (it's slower, the page flashes on every click, the page can't dynamically update in the background), but, by a technicality, it's not a violation of the AdSense Program Policies. Clearly Google *meant* to prohibit automatically replacing the advertisements every five seconds (creating a "slideshow" of advertisements). Google also meant to prohibit making your site look more attractive to advertisers by appearing to have more visits than you actually have. I'm sure they didn't *intend* to prevent you from designing a high-performance AJAX website... but unfortunately sometimes rules have unintended consequences. Of course, as you originally pointed out, you CAN still refresh your advertisements if you embed them in an iframe and modify its location. ([Here's how to use iframes in an AJAX application to refresh AdSense](http://www.jguru.com/forums/view.jsp?EID=1305379 "Here's how to use iframes in an AJAX application to refresh AdSense").) You rejected iframes in your initial question, perhaps because you knew that using iframes would violate Google's policies... but if you insist on breaking the rules, you might as well break them all the way! ;-) Ultimately, I think you'll find that generating impressions this way isn't worth the risk: you'll "refresh" the ads only to find that Google is just showing you the exact same ads as before.
The new Google DFP 'tags' allow specifically 'ad refreshing for AJAX' > refresh > > pubService.refresh(slots) > Refreshes the specified array of slots on the page with new ads. > > Parameters: > > array slots - Optional array of slots to refresh. If not supplied, all ad slots are refreshed. > Example: > > var slot1 = googletag.defineUnit("/1234567/leaderboard", [728, 90], "div-1").addService(googletag.pubads()); > > var slot2 = googletag.defineUnit("/1234567/skyscraper", [160, 600], "div-2").addService(googletag.pubads()); > > // The call to refresh fetches a new ad for each slot > > googletag.pubads().refresh([slot1, slot2]); > <http://support.google.com/dfp_sb/bin/answer.py?hl=en&answer=2372721&expand=pubservice_details#refresh>
Refresh a Div that has a Google ad inside it
[ "", "javascript", "ajax", "html", "refresh", "google-ads-api", "" ]
I'm sure this must be a common problem. I've got a class that in an ideal world would have the following constructors ``` public Thing(string connectionString) public Thing(string fileName) ``` Obviously this isn't allowed because the signatures are the same. Does anybody know of an elegant solution to this problem?
You can used the named constructor idiom: ``` public class Thing { private string connectionString; private string filename; private Thing() { /* Make this private to clear things up */ } public static Thing WithConnection(string connectionString) { var thing = new Thing(); thing.connectionString = connectionString; return thing; } public static Thing WithFilename(string filename) { var thing = new Thing(); thing.filename = filename; return thing; } } ```
Well, there are several potentials - what's considered elegent depends on the usage scenario. * Static factory methods, that call into a private constructor. ``` static Thing thingWithFileName(string fileName) ``` * Create a different type for one of the parameters, or use a builtin. Rather than a string fileName, you could use a System.IO.FileStream. This is also more type safe, as I can't accidently pass the wrong data into the wrong static method, or field. * Pass a second parameter to the constructor, either an enum or a boolean, indicating the intent of the first parameter ``` enum ThingType { FileName, ConnectionString } Thing(string str, ThingType type) ... ``` * Subclass Thing, so you have a ConnectionTypeThing and a FileBackedThing * Completely eliminate Thing doing it's connection, and have preconnected data sources provided. So you end up with ``` Thing(InputStream dataSource) ``` or something analogous. My "elegance" money goes on either the first or second suggestions, but I'd need more context to be happy with any choice.
C# constructors with same parameter signatures
[ "", "c#", ".net", "" ]
I have a customer index page that displays customer lists. I have a search functionality within this page and I want the url to be <http://mysite/search?id=434> when i perform the search. The index page will also display the search result. Thanks
``` public class CustomerController : Controller ... public ActionResult Search(int id) { ViewData["SearchResult"] = MySearchBLL.GetSearchResults(id); return View("Index"); } ... ``` Hope this helps
No, you shouldn't have. Just use `View("ViewName");` in the controller to show the appropriate view in other actions.
Do I need to have a View Page for every Action in ASP.NET MVC?
[ "", "c#", "asp.net-mvc", "" ]
I am automating some profiling tasks and want to log heap space and generation sizes real-time. The [profiling API](http://msdn.microsoft.com/en-us/library/bb384547.aspx) seems awfully complicated for what I need, and it seems to listen in on individual allocations and collections, which isn't that important to me. Profiling tools are a great help of course, but I was looking for a more flexible, programmable interface.
The term 'current memory usage' is a little loosely defined. Do you mean the working set? Whatever it means, you can use different properties such as `VirtualMemorySize`, `WorkingSet`, `PrivateMemorySize`, etc. from the process class to retrieve it. ``` long workingSet = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64; ```
There are performance counters for a lot of this stuff and if you can't use Perfmon, you can access counters through the Diagnostics API.
Is there a way to retrieve a C# app's current memory usage?
[ "", "c#", ".net", "garbage-collection", "clr", "memory-management", "" ]
I have to perform the following SQL query: ``` select answer_nbr, count(distinct user_nbr) from tpoll_answer where poll_nbr = 16 group by answer_nbr ``` The LINQ to SQL query ``` from a in tpoll_answer where a.poll_nbr = 16 select a.answer_nbr, a.user_nbr distinct ``` maps to the following SQL query: ``` select distinct answer_nbr, distinct user_nbr from tpoll_answer where poll_nbr = 16 ``` So far, so good. However the problem raises when trying to GROUP the results, as I'm not being able to find a LINQ to SQL query that maps to the first query I wrote here (thank you [LINQPad](http://www.linqpad.net/) for making this process a lot easier). The following is the only one that I've found that gives me the desired result: ``` from answer in tpoll_answer where answer.poll_nbr = 16 _ group by a_id = answer.answer_nbr into votes = count(answer.user_nbr) ``` Which in turns produces the follwing ugly and non-optimized at all SQL query: ``` SELECT [t1].[answer_nbr] AS [a_id], ( SELECT COUNT(*) FROM ( SELECT CONVERT(Bit,[t2].[user_nbr]) AS [value], [t2].[answer_nbr], [t2].[poll_nbr] FROM [TPOLL_ANSWER] AS [t2] ) AS [t3] WHERE ([t3].[value] = 1) AND ([t1].[answer_nbr] = [t3].[answer_nbr]) AND ([t3].[poll_nbr] = @p0) ) AS [votes] FROM ( SELECT [t0].[answer_nbr] FROM [TPOLL_ANSWER] AS [t0] WHERE [t0].[poll_nbr] = @p0 GROUP BY [t0].[answer_nbr] ) AS [t1] -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [16] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 ``` Any help will be more than appreciated.
There isn't direct support for `COUNT(DISTINCT {x}))`, but you can simulate it from an `IGrouping<,>` (i.e. what `group by` returns); I'm afraid I only "do" C#, so you'll have to translate to VB... ``` select new { Foo= grp.Key, Bar= grp.Select(x => x.SomeField).Distinct().Count() }; ``` Here's a Northwind example: ``` using(var ctx = new DataClasses1DataContext()) { ctx.Log = Console.Out; // log TSQL to console var qry = from cust in ctx.Customers where cust.CustomerID != "" group cust by cust.Country into grp select new { Country = grp.Key, Count = grp.Select(x => x.City).Distinct().Count() }; foreach(var row in qry.OrderBy(x=>x.Country)) { Console.WriteLine("{0}: {1}", row.Country, row.Count); } } ``` The TSQL isn't quite what we'd like, but it does the job: ``` SELECT [t1].[Country], ( SELECT COUNT(*) FROM ( SELECT DISTINCT [t2].[City] FROM [dbo].[Customers] AS [t2] WHERE ((([t1].[Country] IS NULL) AND ([t2].[Country] IS NULL)) OR (([t1] .[Country] IS NOT NULL) AND ([t2].[Country] IS NOT NULL) AND ([t1].[Country] = [ t2].[Country]))) AND ([t2].[CustomerID] <> @p0) ) AS [t3] ) AS [Count] FROM ( SELECT [t0].[Country] FROM [dbo].[Customers] AS [t0] WHERE [t0].[CustomerID] <> @p0 GROUP BY [t0].[Country] ) AS [t1] -- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) [] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1 ``` The results, however, are correct- verifyable by running it manually: ``` const string sql = @" SELECT c.Country, COUNT(DISTINCT c.City) AS [Count] FROM Customers c WHERE c.CustomerID != '' GROUP BY c.Country ORDER BY c.Country"; var qry2 = ctx.ExecuteQuery<QueryResult>(sql); foreach(var row in qry2) { Console.WriteLine("{0}: {1}", row.Country, row.Count); } ``` With definition: ``` class QueryResult { public string Country { get; set; } public int Count { get; set; } } ```
The Northwind example cited by Marc Gravell can be rewritten with the City column selected directly by the group statement: ``` from cust in ctx.Customers where cust.CustomerID != "" group cust.City /*here*/ by cust.Country into grp select new { Country = grp.Key, Count = grp.Distinct().Count() }; ```
LINQ to SQL using GROUP BY and COUNT(DISTINCT)
[ "", "c#", "linq", "linq-to-sql", "" ]
I have created custom MembershipUser, MembershipProvider and RolePrivoder classes. These all work and I am very happy with it, apart from one thing. I have an extra field in the "Users" table. I have an overridden method for CreateUser() that takes in the extra variable and puts it into the DB. My issues is that I want to be able to have this called from the Create User Wizard control. I have customized the control to have a drop down to populate my extra field. I have used the following code to store that piece of info but I am at a loss of how I either use the profile or call my custom CreateUser Method: ``` // Create an empty Profile for the newly created user ProfileCommon p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true); // Populate some Profile properties off of the create user wizard p.CurrentLevel = Int32.Parse(((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("clevel")).SelectedValue); // Save profile - must be done since we explicitly created it p.Save(); ``` Thank you for any and all help Jon Hawkins
I think your solution is the "easiest" you're going to get. You could create your own wizard and call the correct method, but that's a lot more work. The only thing I could recommend is using the [OnCreatedUser](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.createuserwizard.oncreateduser.aspx) event instead. reference: [4guysfromrolla](https://web.archive.org/web/20210612120823/https://aspnet.4guysfromrolla.com/articles/070506-1.aspx)
This is not the answer but I found a work around, would still like to know if someone could answer the question directly... ``` public void UpdateCurrentLvl_OnDeactivate(object sender, EventArgs e) { int level = Int32.Parse(((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("clevel")).SelectedValue); MyMembershipUser myUser = (MyMembershipUser)Membership.GetUser(CreateUserWizard1.UserName); myUser.CurrentLVL = level; Membership.UpdateUser(myUser); } ``` In my first CreateUserWizardStep if put the method above to fire on deactivate. As at this point it has inserted the user into the DB I can get the User out, cast to my MembershipUser class, set the variable and all the update method. As I say this is a work around from the way I would liked to have solved it but it works. Thanks
C# asp.net custom MembershipUser.createUser() method, call it from createuserwizard control
[ "", "c#", "createuserwizard", "membershipuser", "" ]
I am building an content serving application composing of a cluster of two types of node, ContentServers and ContentBuilders. The idea is to always serve fresh content. Content is fresh if it was built recently, i.e. Content.buildTime < MAX\_AGE. Requirements: \*ContentServers will only have to lookup content and serve it up (e.g. from a distributed cache or similar), no waiting for anything to be built except on first request for each item of Content. \*ContentBuilders should be load balanced, should rebuild Content just before it expires, should only build content that is actually being requested. The built content should be quickly retrievable by all ContentServers What architecture should I use? I'm currently thinking a distributed cache (EhCache maybe) to hold the built content and a messaging queue (JMS/ActiveMQ maybe) to relay the Content requests to builders though I would consider any other options/suggestions. How can I be sure that the ContentBuilders will not build the same thing at the same time and will only build content when it nears expiry? Thanks.
Honestly I would rethink your approach and I'll tell you why. I've done a lot of work on distributed high-volume systems (financial transactions specifically) and your solution--if the volume is sufficiently high (and I'll assume it is or you wouldn't be contemplating a clustered solution; you can get an awful lot of power out of one off-the-shelf box these days)--then you will kill yourself with remote calls (ie calls for data from another node). I will speak about Tangosol/Oracle Coherence here because it's what I've got the most experience with, although Terracotta will support some or most of these features and is free. In Coherence terms what you have is a partitioned cache where if you have *n* nodes, each node possesses *1/n* of the total data. Typically you have redundancy of at least one level and that redundancy is spread as evenly as possible so each of the other *n-1* nodes possesses *1/n-1* of the backup nodes. The idea in such a solution is to try and make sure as many of the cache hits as possible are local (to the same cluster node). Also with partitioned caches in particular, writes are relatively espensive (and get more expensive with the more backup nodes you have for each cache entry)--although write-behind caching can minimize this--and reads are fairly cheap (which is what you want out of your requirements). So your solution is going to ensure that **every** cache hit will be to a remote node. Also consider that generating content is undoubtedly much more expensive than serving it, which I'll assume is why you came up with this idea because then you can have more content generators than servers. It's the more tiered approach and one I'd characterize as horizontal slicing. You will achieve much better scalability if you can vertically slice your application. By that I mean that each node is responsible for storing, generating and serving a subset of all the content. This effectively eliminates internode communication (excluding backups) and allows you to adjust the solution by simply giving each node a different sized subset of the content. Ideally, whatever scheme you choose for partitioning your data should be reproducible by your Web server so it knows exactly which node to hit for the relevant data. Now you might have other reasons for doing it the way you're proposing but I can only answer this in the context of available information. I'll also point you to a [summary of grid/cluster technologies for Java](https://stackoverflow.com/questions/383920/what-is-the-best-library-for-java-to-grid-cluster-enable-your-application#383929) I wrote in response to another question.
You may want to try [Hazelcast](http://www.hazelcast.com). It is open source, peer2peer, distributed/partitioned map and queue with eviction support. Import one single jar, you are good to go! Super simple.
What architecture? Distribute content building across a cluster
[ "", "java", "architecture", "cluster-computing", "" ]
Sometimes, when I open the a file like so: ``` FILE *file = fopen(fname, "wb"); if(!file) printf("Error code: %d\n",ferror(file)); ``` I get a result of 32. What does this mean? Specifically, for eMbedded Visual C++ 4.0 Also, it seems like eVC does not support perror/errno :(
You are using ferror() in a wrong way: it works only on a valid (non-null) file handle. Passing it NULL (in the case fopen() fails) causes UB, which manifests in your case by printing a random value (not trapping on NULL pointer access suggests that the underlying platform does not have memory protection).
you should try to test what perror says the error message is. Use like this: ``` perror("fopen"); ``` it will output a message like this: ``` fopen: <error description here> ``` I imagine, since you are using ferror when your file object is NULL, that error 32 is just random garbage as another posted mentioned, probably lack of NULL pointer trapping. use errno/perror to get the error that prevented you from opening the file. in fact, it is illegal to pass a NULL pointer to ferror. EDIT: I find it surprising that both perror and errno aren't supported with that compiler. I recommend that you find the **correct** error detection functions and use that. ferror certainly isn't it in this case. EDIT: look into [GetLastError()](http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx) and [FormatMessage()](http://msdn.microsoft.com/en-us/library/ms679351(VS.85).aspx), they should be supported. <http://msdn.microsoft.com/en-us/library/ms680582(VS.85).aspx> also has an example of there usage. Though you will likely need to replace the microsoft "safe string" functions which ordinary C ones. (ex: StringCchPrintf -> \_snprintf/sprintf) A little googling shows that this might work for you. It's not my code, but looks reasonable: ``` // OS provides a system error string DWORD dwError = GetLastError(); CString csDescription; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), csDescription.GetBuffer(255), nSize, NULL ); csDescription.ReleaseBuffer(); ```
ferror(file) == 32
[ "", "c++", "c", "evc4", "" ]
How can I read/write serializable object instances to a RandomAccessFile in Java? I want to be able to do this the same way you do it in c++ through structs. In java only ObjectInputStreams/ObjectOutputStreamscan can read/Write objects. I am amazed Java does not have something already implemented.
I can see why you would want to do this to read legacy file formats. In that case, default Java serialization mechanisms are a hindrance, not a help. To a degree, you *can* read/write struct-like classes using reflection. Sample code: ``` public static class MyStruct { public int foo; public boolean bar = true; public final byte[] byteArray = new byte[3]; } public static void main(String[] args) throws IOException { LegacyFileHandler handler = new LegacyFileHandler(); MyStruct struct = new MyStruct(); RandomAccessFile file = new RandomAccessFile("foo", "rw"); try { for (int i = 0; i < 4; i++) { struct.foo = i; handler.write(file, struct); } struct = readRecord(file, handler, 2); System.out.println(struct.foo); } finally { file.close(); } } private static MyStruct readRecord(RandomAccessFile file, LegacyFileHandler handler, int n) throws IOException { MyStruct struct = new MyStruct(); long pos = n * handler.sizeOf(struct); file.seek(pos); handler.read(file, struct); return struct; } ``` The handler class; can handle primitive types and byte arrays, but nothing else: ``` public class LegacyFileHandler { private final Map<Class<?>, Method> readMethods = createReadMethodMap(); private final Map<Class<?>, Method> writeMethods = createWriteMethodMap(); private Map<Class<?>, Method> createReadMethodMap() { Class<DataInput> clazz = DataInput.class; Class<?>[] noparams = {}; try { Map<Class<?>, Method> map = new HashMap<Class<?>, Method>(); map.put(Boolean.TYPE, clazz.getMethod("readBoolean", noparams)); map.put(Byte.TYPE, clazz.getMethod("readByte", noparams)); map.put(Character.TYPE, clazz.getMethod("readChar", noparams)); map.put(Double.TYPE, clazz.getMethod("readDouble", noparams)); map.put(Float.TYPE, clazz.getMethod("readFloat", noparams)); map.put(Integer.TYPE, clazz.getMethod("readInt", noparams)); map.put(Long.TYPE, clazz.getMethod("readLong", noparams)); map.put(Short.TYPE, clazz.getMethod("readShort", noparams)); return map; } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } } private Map<Class<?>, Method> createWriteMethodMap() { Class<DataOutput> clazz = DataOutput.class; try { Map<Class<?>, Method> map = new HashMap<Class<?>, Method>(); map.put(Boolean.TYPE, clazz.getMethod("writeBoolean", new Class[] { Boolean.TYPE })); map.put(Byte.TYPE, clazz.getMethod("writeByte", new Class[] { Integer.TYPE })); map.put(Character.TYPE, clazz.getMethod("writeChar", new Class[] { Integer.TYPE })); map.put(Double.TYPE, clazz.getMethod("writeDouble", new Class[] { Double.TYPE })); map.put(Float.TYPE, clazz.getMethod("writeFloat", new Class[] { Float.TYPE })); map.put(Integer.TYPE, clazz.getMethod("writeInt", new Class[] { Integer.TYPE })); map.put(Long.TYPE, clazz.getMethod("writeLong", new Class[] { Long.TYPE })); map.put(Short.TYPE, clazz.getMethod("writeShort", new Class[] { Integer.TYPE })); return map; } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } } public int sizeOf(Object struct) throws IOException { class ByteCounter extends OutputStream { int count = 0; @Override public void write(int b) throws IOException { count++; } } ByteCounter counter = new ByteCounter(); DataOutputStream dos = new DataOutputStream(counter); write(dos, struct); dos.close(); counter.close(); return counter.count; } public void write(DataOutput dataOutput, Object struct) throws IOException { try { Class<?> clazz = struct.getClass(); for (Field field : clazz.getFields()) { Class<?> type = field.getType(); if (type == byte[].class) { byte[] barray = (byte[]) field.get(struct); dataOutput.write(barray); continue; } Method method = writeMethods.get(type); if (method != null) { method.invoke(dataOutput, field.get(struct)); continue; } throw new IllegalArgumentException("Type " + struct.getClass().getName() + " contains unsupported field type " + type.getName() + " (" + field.getName() + ")"); } } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } } public void read(DataInput dataInput, Object struct) throws IOException { try { Class<?> clazz = struct.getClass(); Object[] noargs = {}; for (Field field : clazz.getFields()) { Class<?> type = field.getType(); if (type == byte[].class) { byte[] barray = (byte[]) field.get(struct); dataInput.readFully(barray); continue; } Method method = readMethods.get(type); if (method != null) { Object value = method.invoke(dataInput, noargs); field.set(struct, value); continue; } throw new IllegalArgumentException("Type " + struct.getClass().getName() + " contains unsupported field type " + type.getName() + " (" + field.getName() + ")"); } } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } } } ``` This code has only undergone cursory testing. There are problems with trying to generalise reading/writing data like this. * Dealing with any object type is tricky as you have to convert them to byte arrays yourself and ensure they remain a fixed size. * The biggest problem will probably be keeping all your strings the correct length - you'll need to know a bit about unicode to understand the relationship between character count and encoded byte size. * Java uses network byte order and doesn't really have unsigned types. If you're reading legacy data, you might need to do some bit manipulation. If I needed to handle a binary format, I would probably encapsulate the functionality in specialized classes which would be able to write/read their state to/from an I/O source. You'll still have the problems in the above list, but it is a more object-oriented approach. If I had the freedom to choose the file format, I would go with what [waqas suggested](https://stackoverflow.com/questions/475655/is-there-a-way-for-reading-writing-serializable-objects-to-a-randomaccesfile#475704) and use a database.
Write the data to a ByteArrayOutputStream, via a ObjectOutputStream and then you can put the byte[] into the random access file. You can do the reverse much the same way. However, why are you trying to do this? I suspect there are products which do this for you such as caches which can be persisted to disk. In this cause you can have just a Map which you put objects into and the library takes care of the rest.
Is there a way for reading/writing serializable objects to a RandomAccesFile?
[ "", "java", "serialization", "" ]
I am generating an Assembly on the fly using Reflection.Emit and then saving it. It contains one Type and a static Main() method in it. .NET is kind enough to automatically reference a required assembly. However, in Main(), there is a call to a method from another assembly and it doesn't get referenced in the standard way. When the assembly is executed, the runtime looks for this assembly and cannot find it, which is a problem. Reflector can detect this and shows this extra assembly under the "depends" list. How can I retrieve these implicit dependencies using the Reflection API? Thanks
Thanks for the responses guys, I have managed to resolve the problem. Here's what happens: AssemblyBuilder builder = ... // generate assembly builder.GetReferencedAssemblies(); => It will NOT return a reference to the assembly used in the method body even though I have called Save() already - it seems to return only the assemblies loaded in memory already. Assembly.ReflectionOnlyLoadFrom(filename).GetReferencedAssemblies() => works fine
Have you tried Assembly.GetReferencedAssemblies? It returns the AssemblyName of the referenced assemblies.
Finding all assembly dependencies, Reflector style
[ "", "c#", "reflection", "reflection.emit", "" ]
I saw this question asking about whether [globals are bad](https://stackoverflow.com/questions/484635/are-global-variables-bad). As I thought about the ramifications of it, the only argument I could come up with that they're necessary in some cases might be for performance reasons. But, I'm not really sure about that. So my question is, would using a global be faster than using a get/set method call?
A more appropriate comparison would be between accessing a global *(a static)* and a local. Indeed a global is faster because accessing a local requires the variable offset to be added to the value of the stack pointer. However, you will never, *ever* need to worry about this. Try concentrating on things that matter, such as making your code be readable, writable, and working.
A good modern compiler should inline the get/set method calls such that there's probably no real difference. In almost any case it's much more important to worry about whether statics/globals are going to cause you a headache than the performance implications, which are going to be nearly undetectable anyway.
C/C++ Performance Globals vs Get/Set Methods
[ "", "c++", "c", "performance", "methods", "global", "" ]
I'm in a curious situation where I previously had no problem achieving what I'm looking for. The following code is a part of an HTML page which is to host a TinyMCE rich textbox: ``` ... <textarea id="editing_field">This text is supposed to appear in the rich textbox</textarea> ... ``` At first this worked as intended, creating a rich textbox with the enclosed text in it. At some point, though, the TinyMCE code decided that the textarea HTML should be transformed to the following: ``` <textarea id="editing_field" style="display: none;"/> This text is supposed to appear in the rich textbox ``` This renders the text below the textbox which is not exactly ideal. I don't have a clue what caused this change of behavior, though I'm also using jQuery along with it if that could have any effect. I can work around the problem by loading content into the textbox with javascript after the page has loaded, either by using ajax or by hiding the text in the HTML and just moving it. However, I would like to emit the text into the textbox directly from PHP if at all possible. Anyone knows what is going on here and how to fix it? **Update 2:** I have succesfully reproduced the situattion which causes the change of behavior: At first I just had plain text in the textarea as in the first code snippet. However, after saving the content the text would look like this: ``` <p>This text is supposed to appear in the rich textbox</p> ``` The presence of the `p` tag causes TinyMCE to trigger the transformation between an enclosing textarea to a textarea which is just a single tag (as illustrated above). **Update 1:** added TinyMCE config file: ``` tinyMCE.init({ // General options mode : "exact", elements : "editing_field", theme : "advanced", skin : "o2k7", skin_variant : "black", plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", save_onsavecallback : "saveContent", // Theme options theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull", theme_advanced_buttons2 : "search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,forecolor,backcolor", theme_advanced_buttons3 : "hr,removeformat,|,sub,sup,|,charmap,emotions,|,print,|,fullscreen,code", theme_advanced_buttons4 : "styleselect,formatselect,fontselect,fontsizeselect", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : false, // Drop lists for link/image/media/template dialogs template_external_list_url : "lists/template_list.js", external_link_list_url : "lists/link_list.js", external_image_list_url : "lists/image_list.js", media_external_list_url : "lists/media_list.js", // Replace values for the template plugin template_replace_values : { username : "Some User", staffid : "991234" }, width : "450", height : "500" }); ```
It appears that I have solved the problem, unless there are any edge cases which ruins the solution. I use the following PHP code on page content before I save it to the database: ``` $content = str_replace(chr(10), "", $content); $content = str_replace(chr(13), "", $content); $content = str_ireplace('<','&#x200B;<',$content); ``` What it does is it removes any newlines and then prepend a zero-width invisible character before any beginning tag. This text is then later inserted between the textarea tags before TinyMCE does its magic. I don't know why but this does not trigger the problem and the appended characters are not shown in the final html or in the html view of TinyMCE, so the only problems I can see with this solution is the performance hit. A detail is that it appears only the start tags need to be prepended in this way, but I haven't taken this into consideration here, for simplicity.
If you don't call tinyMCE's JavaScript function, you may have to deal with browser compatibility issues. If you only have one tinymce box on the page, you can just do this: ``` tinyMCE.activeEditor.setContent('<span>some</span>'); ``` You can also set a format such as BBCode. Check out the [setContent](http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.setContent) documentation. I would have your PHP code echo out the HTML into a JavaScript function and have it called with `onload`: ``` function loadTinyMCE($html) { echo " <script type="text/javascript">function loadDefaultTinyMCEContent(){ tinyMCE.activeEditor.setContent('$html'); }</script> "; } ``` then ``` <body onload="loadDefaultTinyMCEContent()"> ``` If you don't want to use the page `onload` event, tinymce has an init option called [oninit](http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/oninit) that functions similarly. Alternatively, [setupcontent\_callback](http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/setupcontent_callback) gives you direct access to the iframe.
How to set the initial text in a TinyMCE textarea?
[ "", "javascript", "tinymce", "textarea", "" ]
I need to be able to modify every single link in an HTML document. I know that I need to use the `SoupStrainer` but I'm not 100% positive on how to implement it. If someone could direct me to a good resource or provide a code example, it'd be very much appreciated. Thanks.
Maybe something like this would work? (I don't have a Python interpreter in front of me, unfortunately) ``` from bs4 import BeautifulSoup soup = BeautifulSoup('<p>Blah blah blah <a href="http://google.com">Google</a></p>') for a in soup.findAll('a'): a['href'] = a['href'].replace("google", "mysite") result = str(soup) ```
``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('<p>Blah blah blah <a href="http://google.com">Google</a></p>') for a in soup.findAll('a'): a['href'] = a['href'].replace("google", "mysite") print str(soup) ``` This is Lusid's solution, but since he didn't have a Python interpreter in front of him, he wasn't able to test it and it had a few errors. I just wanted to post the working condition. Thank's Lusid!
BeautifulSoup - modifying all links in a piece of HTML?
[ "", "python", "beautifulsoup", "" ]
I have some MATLAB code and some Java code that need to talk with each other. I was getting a `NoSuchMethodError`. When I pass a MATLAB double array to a Java method that accepts `double[]` argument. So I write a simple "hello world" to get the class of an object passed to the method ``` public void printArray(Object array) { System.out.println(array.getClass()); System.out.println(array.getClass().getPackage()); } ``` Calling this method from MATLAB, I get this interesting output: ``` >> a.printArray(2) class java.lang.Double package java.lang >> a.printArray('hello') class java.lang.String package java.lang >> a.printArray(true) class java.lang.Boolean package java.lang >> a.printArray([2 3 4]) class [D null >> a.printArray([true false]) class [Z null ``` Can someone explain whats happening. I have MATLAB R14 and the Java class is compiled with 1.3 compatibility.
I think the original problem has been [updated by the OP](https://stackoverflow.com/questions/464216/strange-classes-passed-from-matlab-to-java#466400), so I'll take the chance to summarize our findings so far: * We have established that the sample code in the original question produces the expected behavior. **MATLAB passes data as primitives to Java, and Java performs the appropriate autoboxing to Objects.** As pointed out in [Matthew Simoneau's reply](https://stackoverflow.com/questions/464216/strange-classes-passed-from-matlab-to-java#466086), MATLAB explains how it matches its data types to Java data types in the "[Passing Data to a Java Method](http://www.mathworks.com/help/matlab/matlab_external/passing-data-to-a-java-method.html)" section of its documentation. The surprising thing is that a single MATLAB data type may match different Java data types, e.g. `logical` matches `boolean`, `byte`, `short`, `int`, `long`, `float`, and `double`, in that order of precedence. * The `NoSuchMethodError` that the OP initially encountered was caused by the use of a wrong method. This is [no longer a problem](https://stackoverflow.com/questions/464216/strange-classes-passed-from-matlab-to-java#466400). **Using `double[]` as the method argument works.** * **The "strange" class names (`[D` and `[Z`) are actually notations used by Java to describe arrays of primitive types.** The API explains the usage in [Class.getName()](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getName()). Case closed =)
MATLAB has a set of heuristics to convert MATLAB data types to the type required by the Java method being called. The full details are described in [Passing Data to a Java Method](http://www.mathworks.com/help/matlab/matlab_external/passing-data-to-a-java-method.html) in the MATLAB documentation. The method's signature, `void printArray(Object array)`, doesn't give MATLAB much information about what Java really wants. This is why you're seeing a variety of types, depending on how you call it. With respect to your original question, I'm not sure why this wouldn't be working for you. Give a close look at [Passing Built-In Types](http://www.mathworks.com/help/matlab/matlab_external/passing-data-to-a-java-method.html#f61465). It gives the sample MATLAB code ``` poly = java.awt.Polygon([14 42 98 124], [55 12 -2 62], 4); ``` where the corresponding Java method has the signature ``` public Polygon(int xpoints[], int ypoints[], int npoints) ``` This is a little different than your question because it involves arrays of ints rather than arrays of doubles, but should work identically.
Strange classes passed from MATLAB to Java
[ "", "java", "matlab", "" ]
I would like to execute a stored procedure over each row in a set without using a cursor with something like this: `SELECT EXEC dbo.Sproc @Param1 = Table1.id FROM Table1` I am using T-SQL in SQL Server 2005. I think this might be possible using a function, but I'd like to use a stored procedure if possible (company standards)
9 out of 10 times you can do what you want without a cursor or a while loop. However, if you must use one, I have found that while loops tend to be faster. Also if you do not want to delete or update the table, you can use something like this: ``` DECLARE @id [type] SELECT @id = MIN([id]) FROM [table] WHILE @id IS NOT NULL BEGIN EXEC [sproc] @id SELECT @id = MIN([id]) FROM [table] WHERE [id] > @id END ```
Yes. If you have a column you can use within the table to mark the ones processed, you can use WHILE EXISTS: ``` DECLARE @Id int WHILE EXISTS(SELECT * FROM Table1 WHERE Processed='N') BEGIN SELECT Top 1 @Id = id from Table1 WHERE Procesed='N' EXEC dbo.Sproc @Id UPDATE Table1 SET Processed = 'Y' WHERE Id = @Id END ``` Alternately, dump the ids into a temp table or table variable and delete when finished: ``` DECLARE @HoldTable table (Id int PRIMARY KEY) DECLARE @Id int INSERT INTO @HoldTable SELECT Id FROM Table1 WHILE EXISTS(SELECT * FROM @HoldTable) BEGIN SELECT @Id = id from @HoldTable EXEC dbo.Sproc @Id DELETE FROM @HoldTable where Id = @Id END ```
Is it possible to execute a stored procedure over a set without using a cursor?
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
As of now I'm using below line to print with out dot's ``` fprintf( stdout, "%-40s[%d]", tag, data); ``` I'm expecting the output would be something like following, ``` Number of cards..................................[500] Fixed prize amount [in whole dollars]............[10] Is this a high winner prize?.....................[yes] ``` How to print out dash or dot using fprintf/printf?
A faster approach: If the maximum amount of padding that you'll ever need is known in advance (which is normally the case when you're formatting a fixed-width table like the one you have), you can use a static "padder" string and just grab a chunk out of it. This will be faster than calling `printf` or `cout` in a loop. ``` static const char padder[] = "......................"; // Many chars size_t title_len = strlen(title); size_t pad_amount = sizeof(padder) - 1 - title_len; printf(title); // Output title if (pad_amount > 0) { printf(padder + title_len); // Chop! } printf("[%d]", data); ``` You could even do it in one statement, with some leap of faith: ``` printf("%s%s[%d]", title, padder + strlen(title), data); ```
You can easily do this with iostreams instead of printf ``` cout << setw(40) << setfill('.') << left << tag[i] << '[' << data[i] << ']' << endl; ``` Or if you really need to use fprintf (say, you are passed a FILE\* to write to) ``` strstream str; str << setw(40) << setfill('.') << left << tag[i] << '[' << data[i] << ']' << endl; printf(%s", str.str()); ```
How to print out dash or dot using fprintf/printf?
[ "", "c++", "c", "text", "printf", "" ]
Python 2.5.1 <http://www.cgsecurity.org/wiki/After_Using_PhotoRec> I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks : [EDIT2: Two points: 1. This question was voted down because it was a 'usage' of code, somehow not a programming question. Does it qualify as a coding question? I argue yes. 2. I've gone back and edited the page where the code came from to clarify the need for parameters for the benefit of others.] gyaresu$ python recovery.py Traceback (most recent call last): File "recovery.py", line 8, in source = sys.argv[1] IndexError: list index out of range Script: ``` #!/usr/bin/env python import os import os.path import shutil import string import sys source = sys.argv[1] destination = sys.argv[2] while os.path.exists(source) != True: source = raw_input('Enter a valid source directory\n') while os.path.exists(destination) != True: destination = raw_input('Enter a valid destination directory\n') for root, dirs, files in os.walk(source, topdown=False): for file in files: extension = string.upper(os.path.splitext(file)[1][1:]) destinationPath = os.path.join(destination,extension) if os.path.exists(destinationPath) != True: os.mkdir(destinationPath) if os.path.exists(os.path.join(destinationPath,file)): print 'WARNING: this file was not copied :' + os.path.join(root,file) else: shutil.copy2(os.path.join(root,file), destinationPath) ```
It simply means that the program is expecting two command line arguments: source and destination. If you wish to use the same code in another function, replace sys.argv[1] and [2] with your own variables.
Or you can modify the original script and add ``` if len(sys.argv) != 3: print "Require 2 arguments: %s <source> <destination>" %(sys.argv[0]) sys.exit(1) ``` after the import statements for proper error handling.
Python code for sorting files into folders
[ "", "python", "scripting", "recovery", "" ]
If I have a list of items, say ``` apples pairs pomegranites ``` and I want to identify any that don't exist in the 'fruit' column in an SQL DB table. * Fast performance is the main concern. * Needs to be portable over different SQL implementations. * The input list could contain an arbitrary number of entries. I can think of a few ways to do it, thought I'd throw it out there and see what you folks think.
Since the list of fruits you are selecting from can be arbitrarily long, I would suggest the following: ``` create table FruitList (FruitName char(30)) insert into FruitList values ('apples'), ('pears'), ('oranges') select * from FruitList left outer join AllFruits on AllFruits.fruit = FruitList.FruitName where AllFruits.fruit is null ``` A left outer join should be much faster than "not in" or other kinds of queries.
Make the search list into a string that looks like '|fruit1|fruit2|...fruitn|' and make your where clause: ``` where @FruitListString not like '%|' + fruit + '|%' ``` Or, parse the aforementioned string into a temp table or table variable and do `where not in (select fruit from temptable)`. Depending on the number of items you're searching for and the number of items being searched, this method could be faster.
Best way to check that a list of items exists in an SQL database column?
[ "", "sql", "list", "exists", "" ]
I have encountered a problem that I have not come accross yet when setting up a log in page using php. The page has a error message that relates to line 1 ( `require_once('../Connections/Login.php)` that states > [function.require-once]: failed to open stream: No such file or directory > Fatal Error: require\_once() [function.require]: failed opening required ... (include\_path='.:/usr/share/pear-php5') I know it is probably really simple and stupid, but I'm really struggling to self-troubleshoot and would really value some help please? --- This is where I have been so confused. I also thought the same, that it just couldn't find the file; however the structure is just as you have said: htdocs/comparison.php (the log in page) htdocs/Connections/connComparisonLogin.php Sorry this is going to confuse you, I simplified the actual script in my original question and here is the actual error message: > Warning: require\_once(../Connections/connComparisonLogin.php) [function.require-once]: failed to open stream: No such file or directory in /home/fhlinux135/s/suzukigenuine.com/user/htdocs/comparison.php on line 1 > > Fatal error: require\_once() [function.require]: Failed opening required '../Connections/connComparisonLogin.php' (include\_path='.:/usr/share/pear-php5') in /home/fhlinux135/s/suzukigenuine.com/user/htdocs/comparison.php on line 1 Have I done it all wrong?
I think your require statement should be: ``` require_once 'Connections/connComparisonLogin.php'; ```
Where is your "Connections/Login.php" relative to the currrent php file. php will look for the file relative to the current file, or, in one of the directories specified in the "include\_path" php.ini setting.
Troubleshooting PHP Login connection
[ "", "php", "function", "" ]
I have the following code: ``` $sql = "INSERT INTO table VALUES ('', ...)"; $result = mysql_query($sql, $link) or die(mysql_error()); $id = mysql_insert_id($result) or die('oops'); //mysql_error() instead of oops produces the same result echo $id . "\nDone"; ``` The table that this insert occurs on has an auto-incroment field however all that this outputs is: > Done Am I doing something wrong?
You do not need to pass $result to mysql\_insert\_id you should pass $link variable.
The [`mysql_insert_id()` function](http://www.php.net/manual/en/function.mysql-insert-id.php) expects the first parameter to be a connection resource.
mysql_insert_id doesn't ever seem to work
[ "", "php", "mysql", "" ]
Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found? Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.
A while ago, I put together a package for doing what you want and more. (I needed it for a utility I was writing). It uses the [ASM](http://asm.objectweb.org/) library. You can use reflection, but ASM turned out to perform better. I put my package in an open-source library I have on my website. The library is here: <http://software.clapper.org/javautil/>. You want to start with the [ClassFinder](http://software.clapper.org/javautil/api/org/clapper/util/classutil/ClassFinder.html) class. The utility I wrote it for is an RSS reader that I still use every day, so the code does tend to get exercised. I use ClassFinder to support a plug-in API in the RSS reader; on startup, it looks in a couple of directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect. The library is BSD-licensed, so you can safely bundle it with your code. The source is available. If that's useful to you, help yourself. Update: If you're using Scala, you might find [this library](http://software.clapper.org/classutil/) to be more Scala-friendly.
Spring can do this for you... ``` BeanDefinitionRegistry bdr = new SimpleBeanDefinitionRegistry(); ClassPathBeanDefinitionScanner s = new ClassPathBeanDefinitionScanner(bdr); TypeFilter tf = new AssignableTypeFilter(CLASS_YOU_WANT.class); s.addIncludeFilter(tf); s.scan("package.you.want1", "package.you.want2"); String[] beans = bdr.getBeanDefinitionNames(); ``` N.B. The TypeFilter is important if you want the correct results! You can also use exclusion filters here instead. The Scanner can be found in the spring-context jar, the registry in spring-beans, the type filter is in spring-core.
Find Java classes implementing an interface
[ "", "java", "interface", "" ]
I have a series of checkboxes on an HTML page and I would like to check the checkboxes based on corresponding HTML query string params. e.g. ``` ...path/page.html?i=1&j=1&x=0 ``` would cause a page with three checkboxes to check 1 and 2 on load. Can someone show me how to do this or point me in the direction of a suitable tutorial? Many Thanks, EDIT: A clarification, i, j and x are just picked off the top of my head, but they are boolean variables (1 = true, 0 = false) and each corresponds to a checkbox so: ``` i = one checkbox, the value in the example is 1, so the checkbox should be checked. j = as above x = one checkbox, the value in the example is 0, so the checkbox should not be checked. ```
Partially from [W3Schools](http://www.w3schools.com/JS/tryit.asp?filename=try_dom_input_checked). This file will crate a single checkbox and check it depending on the <http://example.com/index.html?j=>**?** URL ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <script type="text/javascript"> function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } function doStuff() { var GETVars = getUrlVars(); if (GETVars['j']==1) { document.getElementById("myCheck").checked=true; } } </script> <body onload="doStuff();"> <form> <input id='myCheck' type="checkbox" /> </form> </body> </html> ```
``` function decode(s) { return decodeURIComponent(s).replace(/\+/g, " "); } function getQueryParams() { var query = {}; document.location.search.replace( /\??(?:([^=]+)=([^&]*)&?)/g, function () { query[decode(arguments[1])] = decode(arguments[2]); }); return query; } window.onload = function () { var query = getQueryParams(); // check the checkboxes, assuming their ids are query param names var inputs = document.getElementsByTagName("input"); for (var i = 0; i < inputs.length; i++) { var el = inputs[i]; if (el.getAttribute("type") == "checkbox" && el.id in query) { el.checked = query[el.id] == "1"; } } }; ``` And if you're using jQuery, it's much more concise: ``` $(document).ready(function () { $("input[type=checkbox]").each(function () { this.checked = new RegExp("(\\?|&)" + this.id + "=1") .test(document.location.search); }); }); ``` Replace `this.id` with `this.name` if you want to refer to the check boxes by their names instead of ids.
Changing checkboxes using Javascript
[ "", "javascript", "" ]
> **Possible Duplicate:** > [Can’t operator == be applied to generic types in C#?](https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c) I've coded something like this: ``` public bool IsDataChanged() { T value1 = GetValue2; T value2 = GetValue1(); return (valueInDB != valueFromView); } ``` Right now the function doesn't compile with the error "*Operator '!=' cannot be applied to operands of type 'T' and 'T'*". What do I have to do to make this function work ?
You cannot use operators on generic types (except for foo == null which is special cased) unless you add where T : class to indicate it is a reference type (then foo == bar is legal) Use `EqualityComparer<T>`.Default to do it for you. This will **not** work on types which only supply an operator overload for == without also either: * implement `IEquatable<T>` * overrides object.Equals() In general implementing the == operator and not also doing at least one of these would be a very bad idea anyway so this is not likely to be an issue. ``` public bool IsDataChanged<T>() { T value1 = GetValue2; T value2 = GetValue1(); return !EqualityComparer<T>.Default.Equals(value1 , value2); } ``` If you do not restrict to `IEquatable<T>` then the EqualityComparer default fallback may cause boxing when used with value types if they do not implement `IEquatable<T>` (if you control the types which are being used this may not matter). I am assuming you were using =! for performance though so restricting to the Generic type will avoid **accidental** boxing via the Object.Equals(object) route.
That should work for you. ``` public bool test<T>(T test, T test2) where T : class { return (test != test2); } ``` This is simply pasted from the examples that were commented on your question.
c# compare two generic values
[ "", "c#", "generics", "" ]
I am relatively new to C# and each time I begin to work on a C# project (I only worked on nearly mature projects in C#) I wonder why there are no inner classes? Maybe I don't understand their goal. To me, inner classes -- at least private inner classes -- look a lot like "inner procedures" in Pascal / Modula-2 / Ada : they allow to break down a main class in smaller parts in order to ease the understanding. Example : here is what is see most of the time : ``` public class ClassA { public MethodA() { <some code> myObjectClassB.DoSomething(); // ClassB is only used by ClassA <some code> } } public class ClassB { public DoSomething() { } } ``` Since ClassB will be used (at least for a while) only by ClassA, my guess is that this code would be better expressed as follow : ``` public class ClassA { public MethodA() { <some code> myObjectClassB.DoSomething(); // Class B is only usable by ClassA <some code> } private class ClassB { public DoSomething() { } } } ``` I would be glad to hear from you on this subject - Am I right?
Nested classes (probably best to avoid the word "inner" as nested classes in C# are somewhat different to inner classes in Java) can indeed be very useful. One pattern which hasn't been mentioned is the "better enum" pattern - which can be even more flexible than the one in Java: ``` public abstract class MyCleverEnum { public static readonly MyCleverEnum First = new FirstCleverEnum(); public static readonly MyCleverEnum Second = new SecondCleverEnum(); // Can only be called by this type *and nested types* private MyCleverEnum() { } public abstract void SomeMethod(); public abstract void AnotherMethod(); private class FirstCleverEnum : MyCleverEnum { public override void SomeMethod() { // First-specific behaviour here } public override void AnotherMethod() { // First-specific behaviour here } } private class SecondCleverEnum : MyCleverEnum { public override void SomeMethod() { // Second-specific behaviour here } public override void AnotherMethod() { // Second-specific behaviour here } } } ``` We could do with some language support to do some of this automatically - and there are lots of options I haven't shown here, like not actually using a nested class for all of the values, or using the same nested class for multiple values, but giving them different constructor parameters. But basically, the fact that the nested class can call the private constructor gives a lot of power.
The [Framework Design Guidelines](https://rads.stackoverflow.com/amzn/click/com/0321246756) has the best rules for using nested classes that I have found to date. Here's a brief summary list: > 1. Do use nested types when the relationship between type and nested type is such the member-accessibility semantics are desired. > 2. Do *NOT* use public nested types as a logical group construct > 3. Avoid using publicly exposed nested types. > 4. Do *NOT* use nested types if the type is likely to be referenced outside of the containing type. > 5. Do *NOT* use nested types if they need to be instantiated by client code. > 6. Do *NOT* define a nested type as a member of an interface.
Private inner classes in C# - why aren't they used more often?
[ "", "c#", "scope", "inner-classes", "" ]
I've recently started work on a new project using PHP5 and want to use their PDO classes for it. The problem is that the MySQL PDO Driver doesn't support rowCount() so there's no way to run a query and then get the number of affected rows, or rows returned, which is a pretty big issue as far as I'm concerned. I was wondering if anyone else has dealt with this before and what you've done to work around it. Having to do a fetch() or fetchAll() to check if any rows were affected or returned seems like a hack to me, I'd rather just do $stmt->numRows() or something similar.
You can issue a `SELECT FOUND_ROWS()` query right after the original `SELECT` query to get row count. ``` $pdo->query("SELECT * FROM users"); $foundRows = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn(); ``` See also: [MySQL Docs on FOUND\_ROWS()](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows)
For those of you who are using MySQL stored procedures, this solution isn't really feasible. What I would suggest that you do is have your stored procedure create two rowsets. The first one will contain one row and one column, containing the number of records. The second will be the recordset you will use for fetching that number of rows. The number of unlimited rows can be a `SELECT COUNT(*)` with the exact same `WHERE` clause as the second rowset without the `LIMIT`/`OFFSET` clauses. Another idea could be to create a temporary table. Use your `SELECT` statement to populate the temporary table. Then you can use `SELECT COUNT(*) FROM tmpTable` for your first rowset and `SELECT * FROM tmpTable` for your second.
Work-around for PHP5's PDO rowCount MySQL issue
[ "", "php", "pdo", "" ]
What are the cons of some code like this: ``` public class Class1 { public object Property1 { set { // Check some invariant , and null // throw exceptions if not satisfied // do some more complex logic //return value } } } ```
The con would be that if you are doing excessive logic that takes a great period of time, and/or has side effects which don't logically flow from the setting of the property, you are going to have a pretty convoluted class design. Methods are traditionally used to indicate that an action with consequence is being performed, not properties. While you definitely can have logic in them, having too much might give the wrong impression of what you are trying to do, which is assign a value, as opposed to perform an operation. In the end, it all depends on what "do some more complex logic" means.
It's hard to answer the question since "complex logic" is very vague. I see no issues with basic sanity checking on setting of a property and it's very common to need to do some sort of processing on an object when one of its properties changes. Now, if by "complex logic" you mean do things like some crazy database access or creating a network connection to go do something then yes, that would be bad.
Why is considered best practice to have no complex logic in class properties?
[ "", "c#", "properties", "" ]
I’ve had a good look and can’t seem to find out how to select all elements matching certain classes in one jQuery selector statement such as this: ``` $('.myClass', '.myOtherClass').removeClass('theclass'); ``` Any ideas on how to achieve this? The only other option is to do ``` $('.myClass').removeClass('theclass'); $('.myOtherClass').removeClass('theclass'); ``` But I’m doing this with quite a few classes, so it requires much code.
This should work: `$('.myClass, .myOtherClass').removeClass('theclass');` You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want. It's the same as you would do in CSS.
Have you tried this? ``` $('.myClass, .myOtherClass').removeClass('theclass'); ```
Selecting multiple classes with jQuery
[ "", "javascript", "jquery", "jquery-selectors", "" ]
If I wanted to have Python distributed across multiple processors on multiple computers, what would my best approach be? If I have 3 eight-core servers, that would mean I would have to run 24 python processes. I would be using the [multiprocessing library](http://docs.python.org/library/multiprocessing.html), and to share objects it looks like the best idea would be to use a manager. I want all the nodes to work together as one big process, so one manager would be ideal, yet that would give my server a single point of failure. Is there a better solution? Would replicating a manager's object store be a good idea? Also, if the manager is going to be doing all of the database querying, would it make sense to have it on the same machine as the database?
You have two main challenges in distributing the processes: 1. Co-ordinating the work being split up, distributed and re-collected (mapped and reduced, you might say) 2. Sharing the right live data between co-dependent processes The answer to #1 will very much depend on what sort of processing you're doing. If it's easily horizontally partitionable (i.e. you can split the bigger task into several *independent* smaller tasks), a load balancer like [HAProxy](http://haproxy.1wt.eu/) might be a convenient way to spread the load. If the task isn't trivially horizontally partitionable, I'd first look to see if existing tools, like [Hadoop](http://hadoop.apache.org/core/), would work for me. Distributed task management is a difficult task to get right, and the wheel's already been invented. As for #2, sharing state between the processes, your life will be much easier if you share an absolute minimum, and then only share it explicitly and in a well-defined way. I would personally use [SQLAlchemy](http://www.sqlalchemy.org/) backed by your RDBMS of choice for even the smallest of tasks. The query interface is powerful and pain-free enough for small and large projects alike.
I think more information would be helpful, on what sort of thing you are serving, what sort of database you'd use, what sort of latency/throughput requirements you have, etc. Lots of stuff depends on your requirements: eg. if your system is a typical server which has a lot of reads and not so many writes, and you don't have a problem with reading slightly stale data, you could perform local reads against a cache on each process and only push the writes to the database, broadcasting the results back to the caches. For a start, I think it depends on what the manager has to do. After all, worrying about single points of failure may be pointless if your system is so trivial that failure is not going to occur short of catastrophic hardware failure. But if you just have one, having it on the same machine as the database makes sense. You reduce latency, and your system can't survive if one goes down without the other anyway.
Efficient layout for a distributed python server?
[ "", "python", "multiprocessing", "" ]
I have a class that i want to push\_back into a deque. The problem is when i push back i need the original object to be changed thus i need a non const copy ctor. Now if i implement that my const copy ctor gets called. If i removed the const ctor i get an compile error about no available ctors. How do i implement this in a way that i can modify the original struct when i pass it in? i need to modify it bc the class destructs objects when it goes out of scope and i would like to tell it not to do so when there is another instance around. I cant use boost since my platform doesnt support it.
Your problem is that a fundamental requirement of standard containers is that objects are copy-constructible. That not only means that they have a copy constructor, but that also means that if you copy the object, the copy and the original are the same. Your object, however, resembles a move-constructor semantic. That is, after a move, the new object owns the resource, and the old object is empty. That's not supported by deque as of C++03. That is, by the way, the same reason that forbids putting auto\_ptr into a container. The next C++ version, called c++0x will support those move semantics by introducing special move constructors. Until then, you will have to use an object that *shares* ownership when you want to put it into a standard container. That means if you copy your object, and the original goes out of scope, the owned resource is not freed until all the copies go out of scope. Consider using boost::shared\_ptr for example, or wrap it into your class, if you don't want to program your own class managing that.
If you're not doing anything dodgy with resources (see other comments) then making the member variable that you want to change *mutable* will allow you to alter it in a const function.
c++ push_back, non const copy constructor
[ "", "c++", "copy-constructor", "" ]
I have a python sgi script that attempts to extract an rss items that is posted to it and store the rss in a sqlite3 db. I am using flup as the WSGIServer. To obtain the posted content: postData = environ["wsgi.input"].read(int(environ["CONTENT\_LENGTH"])) To attempt to store in the db: ``` from pysqlite2 import dbapi2 as sqlite ldb = sqlite.connect("/var/vhost/mysite.com/db/rssharvested.db") lcursor = ldb.cursor() lcursor.execute("INSERT into rss(data) VALUES(?)", (postData,)) ``` This results in only the first few characters of the rss being stored in the record: ÿþ< I believe the initial chars are the BOM of the rss. I have tried every permutation I could think of including first encoding rss as utf-8 and then attempting to store but the results were the same. I could not decode because some characters could not be represented as unicode. Running python 2.5.2 sqlite 3.5.7 Thanks in advance for any insight into this problem. --- Here is a sample of the initial data contained in postData as modified by the repr function, written to a file and viewed with less: '\xef\xbb\xbf Thanks for the all the replies! Very helpful. --- The sample I submitted didn't make it through the stackoverflow html filters will try again, converting less and greater than to entities (preview indicates this works). \xef\xbb\xbf<?xml version="1.0" encoding="utf-16"?><rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><channel><item d3p1:size="0" xsi:type="tFileItem" xmlns:d3p1="http://htinc.com/opensearch-ex/1.0/">
Before the SQL insertion you should to convert the string to unicode compatible strings. If you raise an UnicodeError exception, then encode the string.encode("utf-8"). Or , you can autodetect encoding and encode it , on his encode schema. [Auto detect encoding](http://code.activestate.com/recipes/52257)
Regarding the insertion encoding - in any decent database API, you should insert `unicode` strings and `unicode` strings only. For the reading and parsing bit, I'd recommend Mark Pilgrim's [Feed Parser](http://www.feedparser.org/). It properly handles BOM, and the license allows commercial use. *This may be a bit too heavy handed if you are not doing any actual parsing on the RSS data.*
What is the correct procedure to store a utf-16 encoded rss stream into sqlite3 using python
[ "", "python", "sqlite", "wsgi", "" ]
From what I've read, any changes to the environment variables in a Python instance are only available within that instance, and disappear once the instance is closed. Is there any way to make them stick by committing them to the system? The reason I need to do this is because at the studio where I work, tools like Maya rely heavily on environment variables to configure paths across multiple platforms. My test code is ``` import os os.environ['FAKE'] = 'C:\\' ``` Opening another instance of Python and requesting `os.environ['FAKE']` yields a `KeyError`. **NOTE:** Portability will be an issue, but the small API I'm writing will be able to check OS version and trigger different commands if necessary. That said, I've gone the route of using the Windows registry technique and will simply write alternative methods that will call shell scripts on other platforms as they become requirements.
Under Windows it's possible for you to make changes to environment variables persistent via the registry with [this recipe](http://code.activestate.com/recipes/416087/), though it seems like overkill. To echo Brian's question, what are you trying to accomplish? There is probably an easier way.
You can using SETX at the command-line. By default these actions go on the USER env vars. To set and modify SYSTEM vars use the /M flag ``` import os env_var = "BUILD_NUMBER" env_val = "3.1.3.3.7" os.system("SETX {0} {1} /M".format(env_var,env_val)) ```
How do I make environment variable changes stick in Python?
[ "", "python", "environment-variables", "" ]
( .NET 2.0, System.Windows.FormsDataGridView and DataTable ) I have 1 datagrid connected to 1 datatable. That datatable contains 1 column: containing objects of my own type "MyObject". MyObject has a *public* string property "MyProp". I want to display 1 column in the grid: showing the string values of the property MyProp of the MyObjects in the table. But I can't seem to get it to work. Schematically: * myTable.Column1.Name: "Obj" * myDataSet contains 1 table: myTable (filled with a few rows) * myBindingSource.datasource = myDataSet * myBindingSource.DataMember = myTable * myDataGridView.DataSource = myBindingSource * in myDataGridView: 1 DataGridViewTextBoxColumn * tryout 1: Column.DataPropertyName="Obj" (generated by default) Displays the result of (overridden) MyObject.ToString() Not really what I want, this function is in use for logging. * tryout 2: GridViewColumn.DataPropertyName="Obj.MyProp" Doesn't display anything (MyProp's *get* is never called) * tryout 3: Made the MyProp property bindable: ``` [Bindable (BindableSupport.Yes)] public string MyProp { ... ``` Samesame, not different from tryout 2 **In short:** GridViewColumn.DataPropertyName doesn't seem to support *drilling further down* into objects in a datatable's column. Anyone any ideas? Thanks in advance! Jan
Try just putting the Obj.MyProp string value into the datatable row. Putting an object into there will require it to be converted into a string representation (Obj.ToString()) which is getting you the output you are seeing. A datatable is much like a spreadsheet, not like an Array(Of objects). You have to treat it as such,.
You can only bind to immediate properties of the data-source. For `DataTable`, this means columns. Two options leap to mind: * don't use `DataTable` - just use a `List<MyObject>` or `BindingList<MyObject>` * (or) override `MyObject.ToString()` to return `MyProp` The second isn't very flexible - I'd go with the first. After all, what is a 1-column `DataTable` really doing for you?
DataGridView - DataTable - displaying properties
[ "", "c#", "datagridview", "datatable", "" ]
What would be the best way to resize images, which could be of any dimension, to a fixed size, or at least to fit within a fixed size? The images come from random urls that are not in my control, and I must ensure the images do not go out of an area roughly 250px x 300px, or 20% by 50% of a layer. I would think that I would first determine the size, and if it fell outside the range, resize by a factor, but I am unsure how to work out the logic to resize if the image size could be anything. edit:I do not have local access to the image, and the image url is in a variable with is output with img src=..., I need a way to specify the values of width and height tags.
It's easy to do with ImageMagick. Either you use convert command line tool via exec or you use <http://www.francodacosta.com/phmagick/resizing-images> . If you use 'convert' you can even tell ImageMagick to just resize larger images and to not convert smaller ones: <http://www.imagemagick.org/Usage/resize/> If you don't have local access, you won't be able to use ImageMagick: ``` <?php $maxWidth = 250; $maxHeight = 500; $size = getimagesize($url); if ($size) { $imageWidth = $size[0]; $imageHeight = $size[1]; $wRatio = $imageWidth / $maxWidth; $hRatio = $imageHeight / $maxHeight; $maxRatio = max($wRatio, $hRatio); if ($maxRatio > 1) { $outputWidth = $imageWidth / $maxRatio; $outputHeight = $imageHeight / $maxRatio; } else { $outputWidth = $imageWidth; $outputHeight = $imageHeight; } } ?> ```
Have you looked at the GD library documentation, particularly the [imagecopyresized](http://uk.php.net/manual/en/function.imagecopyresized.php) method?
Arbitrary image resizing in PHP
[ "", "php", "" ]
I have created an application that runs in the taskbar. When a user clicks the application it pops up etc. What I would like is similar functionality to that in MSN when one of my friends logs in. Apparently this is know as a toast popup? I basically want something to popup from every 20 minutes toast style fom the application in the taskbar. My existing application is winforms based written in C# with .net 3.5
This is pretty simple. You just need to set window in off-screen area and animate it's position until it is fully visible. Here is a sample code: ``` public partial class Form1 : Form { private Timer timer; private int startPosX; private int startPosY; public Form1() { InitializeComponent(); // We want our window to be the top most TopMost = true; // Pop doesn't need to be shown in task bar ShowInTaskbar = false; // Create and run timer for animation timer = new Timer(); timer.Interval = 50; timer.Tick += timer_Tick; } protected override void OnLoad(EventArgs e) { // Move window out of screen startPosX = Screen.PrimaryScreen.WorkingArea.Width - Width; startPosY = Screen.PrimaryScreen.WorkingArea.Height; SetDesktopLocation(startPosX, startPosY); base.OnLoad(e); // Begin animation timer.Start(); } void timer_Tick(object sender, EventArgs e) { //Lift window by 5 pixels startPosY -= 5; //If window is fully visible stop the timer if (startPosY < Screen.PrimaryScreen.WorkingArea.Height - Height) timer.Stop(); else SetDesktopLocation(startPosX, startPosY); } } ```
There's support for notification balloons in Win32 (I'm not a .net programmer), with some useful properties as [old new thing explains](http://blogs.msdn.com/oldnewthing/archive/2005/01/10/349894.aspx). There's also a system wide semaphor which you should lock to prevent more than one popup from any application appearing at once. There's a a couple of pages on the toast semaphor on msdn - [the toast semaphor](http://msdn.microsoft.com/en-us/library/ms632289(VS.85).aspx) and in the [broader context of usability](http://msdn.microsoft.com/en-us/library/aa468595.aspx). I also came across some [example code](http://blogs.msdn.com/coding4fun/archive/2006/10/31/912382.aspx) to use the balloon api from C# while looking, but can't vouch for it.
How to add toast style popup to my application?
[ "", "c#", "winforms", "" ]
OK, so I'm just starting to think how to implement a new graphical plugin for Paint.NET and I will need to know how to find the most common integer in a 2d array of integers. Is there a built-in to C# way to do this? Or, does anyone have a slick way to do it? The array will look something like this: ``` 300 300 300 300 300 300 300 0 150 300 300 300 300 300 0 0 150 300 300 300 300 0 0 0 0 300 300 300 0 0 0 0 150 300 300 0 0 0 0 0 150 300 0 0 0 0 0 0 300 ``` I would need to know that 300 is the most common number in the array. If there is no "most common" then just return the center number (the array dimintions will always be odd x odd) 0. I'll be implementing this using a "brute force" algorithm unless you experts can come up with something faster. Any help would be very much appreciated. Thanks! EDIT: More info... The values will almost always be VERY diverse (more diverse than my example array). The values will be in the range of 0-360. The size of the array will be 5x5 to about 17x17 depending on speed of the algorithm. The result will be calculate once for each pixel in a large image... so faster is better. ;)
Take a look at the LocalHistogramEffect code in Paint.NET, notably LocalHistorgramEffect.RenderRect. I walks the input image, maintaining a histogram of intensities for each source pixel withing 'r' pixels of the destination pixel. As the output pixels are traversed, it adds the leading edge to the histogram and subtracts the trailing edge. It handles all the edge cases well, and is quite fast. It's the basis for the Median, Unfocus, Outline, and Remove Noise effects. Adapting this to support Hue instead of RGB intensity would be rather trivial. The performance is quite good, and for your purposes it operates in O(r^2+w*r+n*w), where r is the radius, w is the width of the image, and n is the number of levels in the histogram. -tjackson
It's at least O(n\*m) any way you slice it -- you are going to have to look at each cell at least once. The place to economize is in where you accumulate the counts of each value before looking for the most common; if your integers vary over a relatively small range (they are uint16, let's say), then you might be able to simply use a flat array instead of a map. I guess you could also keep a running count *x*,*y* of the current top and second-closest candidate for "most common" and early-out as soon as you've less than (n\*m)-(x-y) cells left to look at, since at that point there's no way the runner-up could outpace the top candidate. Integer ops like this are pretty fast; even for a megapixel image the brute force algorithm should only take a couple milliseconds. I notice you've edited your original question to say that the pixels value from 0..255 -- in that case, definitely go with a simple flat array; that's small enough to easily fit into the l1 dcache and a lookup in a flat array is trez quick. **[edit] :** Dealing with the "no most common number" case is very simple once you've built the histogram array: all have you to do is walk through it to find the "most" and "second most" common numbers; if they're equally frequent, then by definition there is no one most common. ``` const int numLevels = 360; // you said each cell contains a number [0..360) int levelFrequencyCounts[numLevels]; // assume this has been populated such that levelFrequencyCounts[i] = number of cells containing "i" int mostCommon = 0, runnerUp = 0; for (int i = 1 ; i < numLevels ; ++i) { if ( levelFrequencyCounts[i] > levelFrequencyCounts[mostCommon] ) { runnnerUp = mostCommon; mostCommon = i; } } if ( levelFrequencyCounts[mostCommon] != levelFrequencyCounts[runnerUp] ) { return mostCommon; } else { return CenterOfInputData; // (something like InputData[n/2][m/2]) } ```
How to find the most common int in a 2d array of ints?
[ "", "c#", "paint.net", "" ]
Following on from my [previous question](https://stackoverflow.com/questions/488294/how-can-i-make-a-windows-batch-file-which-changes-an-environment-variable), is it possible to make a Python script which persistently changes a Windows environment variable? Changes to os.environ do not persist once the python interpreter terminates. If I were scripting this on UNIX, I might do something like: ``` set foo=`myscript.py` ``` But alas, cmd.exe does not have anything that works like sh's back-tick behavior. I have seen a very long-winded solution... it 'aint pretty so surely we can improve on this: ``` for /f "tokens=1* delims=" %%a in ('python ..\myscript.py') do set path=%path%;%%a ``` Surely the minds at Microsoft have a better solution than this! **Note**: exact duplicate of [this question](https://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python).
Your long-winded solution is probably the best idea; I don't believe this is possible from Python directly. This article suggests another way, using a temporary batch file: <http://code.activestate.com/recipes/159462/>
You might want to try [Python Win32 Extensions](http://sourceforge.net/projects/pywin32/), developed by Mark Hammond, which is included in the [ActivePython](http://www.activestate.com/activepython/downloads) (or can be installed separately). You can learn how to perform many Windows related tasks in [Hammond's and Robinson's book](http://oreilly.com/catalog/9781565926219/). Using *PyWin32* to access windows *COM objects*, a Python program can use the [Environment Property](http://msdn.microsoft.com/en-us/library/fd7hxfdd.aspx) of the `WScript.Shell` object - a collection of environment variables.
Can a python script persistently change a Windows environment variable? (elegantly)
[ "", "python", "windows", "scripting", "batch-file", "" ]
I'm debugging someone else's code for a web page that is made with ASP.NET with some javascript effects. It's a form that we are pre-populating with edit-able data, and one of the text boxes is getting populated with an incorrect value. I know that the text box is getting filled with the correct value in the code behind, but somewhere between there and the browser it gets overwritten. In trying to find out where that happened, I came across an interesting situation. If I right-click near the offending element and select "view page source," I can scroll down to the element and see ``` <input name="RecurrenceProperties$TextBox57" type="text" value="HEY ITS THE RIGHT VALUE" id="RecurrenceProperties_TextBox57" /> ``` But the wrong value is in both the rendered html and the IE developer toolbar. This seems like a hell of a clue, but I don't know enough about how "View Source" works to tell what is going on behind the curtain. What happens between the generation of the "View Source" source and the page actually rendering? EDIT: I found where it was going wrong by putting a break-point on everywhere that ID occurs in javascript (not exactly elegant, but I found it). Suggestions to disable javascript and use IE8 were very helpful. thanks.
If you want to see what effect the javascript is having on your page, use IE8 or FireFox/Firebug on the page to see what it is(not) doing. They will also give you information on the Css Style, if the case is actually that the wrong element is displayed, and the right one is hidden.
What you see with "view source" is the raw HTML that has been fetched. The HTML doesn't include any changes that were done via DHTML/JavaScript. --- ## Update Inspired by Manik's comment, here's a cross-browser1 bookmarklet to display what's **rendered** inside `<body>`: ``` javascript:"<pre>"+document.body.innerHTML.replace(/([&<>])/g,function(c){return"&"+{"&":"amp","<":"lt",">":"gt"}[c]+";";})+"</pre>" ``` 1 Doesn't seem to work on Safari though. Anyone know why?
How does IE7's "View Source" button interact with javascript?
[ "", "asp.net", "javascript", "html", "internet-explorer-7", "view-source", "" ]
There is no way to list the functions in a C++ solution for me... I have a class browser but that isn't helpful since this project has no classes. I need a simple list of all the functions in a c++ file and then just double click one to jump to its source (as a side pane, NOT as a dropdown)... I have to be missing something here as I have looked and googled for something so simple.
I've never found a built-in way to do this, in 10 years of working with Visual Studio. However, [Visual Assist X](http://www.visualassist.com/) will do this for you in its Outline View. The down side is that it's not free, but I've found it to be an essential tool for working with C++ in Visual Studio. Well worth the money IMHO.
The object browser / class view lists free-floating functions and types under "global functions and variables", "global type definitions" and "macros and constants" (might read a little different in the English version). It shows all functions from the solution though, not only the ones from a C++ file. The navigation bar between the tabs and the code editor shows all functions in the current C++ file, though it's a combo box, so you need to click once to open it and again to jump to it :)
Why can't I get a decent function browser in Visual Studio 2008?
[ "", "c++", "visual-studio", "visual-studio-2008", "" ]
I heard there is a light implementation of boost where its only smart pointers and a few other very basic stuff. I think i heard it doesnt use any OS functions either. I tried searching for it but found nothing. Does anyone know what it is called or an implementation of boost styled smart pointers that doesnt require OS calls?
You can use bcp, but remember that *using* the Boost libraries only makes you pay for what you use - the smart pointers are all implemented in header-only fashion, meaning there's no OS calls, no compiled library to link to, etc. Thus, if you're not distributing source code, you can download the full boost set, and use only the bits you need, without causing your application any (unasked for) grief.
You can use the [bcp utility](http://www.boost.org/doc/libs/1_52_0/tools/bcp/doc/html/index.html) to extract only the subset of the full tree you need to support a given library. I'm not aware of any freestanding stripped-down Boost implementation though.
boost lite?
[ "", "c++", "boost", "" ]
I am involved in a venture that will port some communications, parsing, data handling functionality from Win32 to Linux and both will be supported. The problem domain is very sensitive to throughput and performance. I have very little experience with performance characteristics of boost and ACE. Specifically we want to understand which library provides the best performance for threading. Can anyone provide some data -- documented or word-of-mouth or perhaps some links -- about the relative performance between the two? EDIT Thanks all. Confirmed our initial thoughts - we'll most likely choose boost for system level cross-platform stuff.
Neither library should really have any overhead compared to using native OS threading facilities. You should be looking at which API is cleaner. In my opinion the boost thread API is significantly easier to use. ACE tends to be more "classic OO", while boost tends to draw from the design of the C++ standard library. For example, launching a thread in ACE requires creating a new class derived from ACE\_Task, and overriding the virtual svc() function which is called when your thread runs. In boost, you create a thread and run whatever function you want, which is significantly less invasive.
Do yourself a favor and steer clear of ACE. It's a horrible, horrible library that should never have been written, if you ask me. I've worked (or rather HAD to work with it) for 3 years and I tell you it's a poorly designed, poorly documented, poorly implemented piece of junk using archaic C++ and built on completely brain-dead design decisions ... calling ACE "C with classes" is actually doing it a favor. If you look into the internal implementations of some of its constructs you'll often have a hard time suppressing your gag reflex. Also, I can't stress the "poor documentation" aspect enough. Usually, ACE's notion of documenting a function consists of simply printing the function's signature. As to the meaning of its arguments, its return value and its general behavior, well you're usually left to figure that out on your own. I'm sick and tired of having to guess which exceptions a function may throw, which return value denotes success, which arguments I have to pass to make the function do what I need it to do or whether a function / class is thread-safe or not. Boost on the other hand, is simple to use, modern C++, extremely well documented, and it just WORKS! Boost is the way to go, down with ACE!
boost vs ACE C++ cross platform performance comparison?
[ "", "c++", "performance", "boost", "cross-platform", "ace-tao", "" ]
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on the user's browser? I know I can use `<noscript>this displays in place of javascript</noscript>` That works fine, but it still runs the javascript. In theory I would want this: if javascript is enabled   run javascript if javascript is not enabled   don't run javascript and give alternative method I am using this jQuery plugin: <http://malsup.com/jquery/cycle/int2.html> When I disable javascript on safari, it displays all three of the items, all within a div. The plugin fades in each item, but with it disabled it displays all three in a row, without fading in and out like it does w/ javascript enabled. With javascript disabled, I would want to stop it from displaying all three items at the same time. I'll show you what it is suppose to look like and what it does when JavaScript is disabled. Disabled view: <http://i42.tinypic.com/212y1j6.png> (notice them 3 stacked on top of eachother) - I want to stop that from happening since the JavaScript is disabled Enabled view: <http://i39.tinypic.com/9gwu3d.png> Here is the code for the div the items are in: ``` $(document).ready(function() { $('#featured-programs-left').cycle({ fx: 'fade', speed: 'slow', timeout: 15000, next: '#next2', prev: '#prev2' }); }); <div id="featured-programs-left"> <div> <a href="http://site.com/academics/majors/emergency_medical_technician_-_paramedic/" title="Emergency Medical Technician - Paramedic"><img src="http://site.com/images/uploads/images/emt.jpg" alt="Emergency Medical Technician - Paramedic" /></a> <strong>Emergency Medical Technician - Paramedic</strong> <p>This unique A.A.S. degree program, a partnership between College and Faxton-St. Luke&#8217;s Healthcare provides the paramedic student the education necessary to function in an</p> <p><a href="http://site.com/academics/majors/emergency_medical_technician_-_paramedic/" title="Learn more about Emergency Medical Technician - Paramedic">Learn more</a></p> </div> <div> <a href="http://site.com/academics/majors/travel_tourism_hospitality_events_management/" title="Travel &amp; Tourism: Hospitality &amp; Events Management"><img src="http://site.com/images/uploads/images/hospitality_event_planning.jpg" alt="Travel &amp; Tourism: Hospitality &amp; Events Management" /></a> <strong>Travel &amp; Tourism: Hospitality &amp; Events Management</strong> <p>This program prepares students for exciting careers in the travel and tourism industry and the hospitality and events planning field. Graduates are prepared to:<br</p> <p><a href="http://site.com/academics/majors/travel_tourism_hospitality_events_management/" title="Learn more about Travel &amp; Tourism: Hospitality &amp; Events Management">Learn more</a></p> </div> <div> <a href="http://site.com/academics/majors/fashion_buying_merchandising/" title="Fashion Buying &amp; Merchandising"><img src="http://site.com/images/uploads/images/fashion_merchandising.jpg" alt="Fashion Buying &amp; Merchandising" /></a> <strong>Fashion Buying &amp; Merchandising</strong> <p>This program prepares graduates for careers throughout the Fashion Industry including positions in buying, fashion merchandising, retail and wholesale sales, retail</p> <p><a href="http://site.com/academics/majors/fashion_buying_merchandising/" title="Learn more about Fashion Buying &amp; Merchandising">Learn more</a></p> </div> </div> ``` CSS for the div's ``` #featured-programs-left img, #featured-programs-right img{ xfloat:left; overflow:auto; xclear:left; xwidth:351px; xpadding:0 5px 5px 0; border:0; } #featured-programs-left, #featured-programs-right { height:625px; float:left; overflow:auto; clear:left; clear:right; width:100%; xborder:2px solid red; } #featured-programs-left div, #featured-programs-right div { xborder:1px solid purple; overflow:auto; clear:left; clear:right; width:352px; height:345px; } #featured-programs-left { float:left; } ```
Somewhat like [Ates's solution](https://stackoverflow.com/questions/488492/noscript-tag-i-need-to-present-alternative-html-if-not-enabled#488536), you can use Javascript to change the content for the users who have it enabled. For example, let's say you have a fancy menu that gives Javascript users super-easy navigation, but is worthless to non-JS users. In the HTML set the display property to 'none' and then use JS to enable it. In your case, where you have content you don't want to show for the non-JS users, you can just hide it by default. The downside is if the browser has JS AND CSS turned off, this won't work. If you're worried about that, you could use JS to insert the content. ``` <html> <head> <script> $(document).ready(function() { $('.jsok').show(); }); </script> <style> .jsok { display: none; } </style> </head> <body> <div class="jsok"><!-- content for JS users here--></div> <div><!-- content for everyone here --></div> <noscript><!-- content for non-js users here --></noscript> </body> </html> ```
An alternative to using `<noscript>` is to hide a certain element with JavaScript as soon as the page loads. If JavaScript is disabled, the element will remain as being displayed. If JavaScript is enabled, your script will be executed and the element will be hidden. ``` window.onload = function () { document.getElementById("no_script").style.display = "none"; } <div id="no_script"> You don't have JavaScript enabled. </div> ``` --- ## Update If you want to do the opposite (show a bit of HTML when JavaScript is enabled), you can always inject new elements into the DOM tree using various methods. Here's one: ``` $(document).ready(function() { $('#container').html($('#content').html()); }); <div id="container"></div> <script type="text/html" id="content"> <div>Your <em>HTML</em> goes here</div> </script> ``` Kudos to [John Resig](http://ejohn.org/blog/javascript-micro-templating/) for the `<script type="text/html">` trick for unobtrusively hiding HTML templates inside HTML. Browsers apparently don't execute or render `<script>` content of an unconventional type.
noscript tag, I need to present alternative html if not enabled
[ "", "javascript", "html", "detect", "" ]
I have a WCF service with three methods. Two of the methods return custom types (these work as expected), and the third method takes a custom type as a parameter and returns a boolean. When calling the third method via a PHP soap client it returns an 'Object reference not set to an instance of an object' exception. **Example Custom Type:** \_ Public Class MyClass ``` Private _propertyA As Double <DataMember()> _ Public Property PropertyA() As Double Get Return _propertyA End Get Set(ByVal value As Double) _propertyA = value End Set End Property Private _propertyB As Double <DataMember()> _ Public Property PropertyB() As Double Get Return _propertyB End Get Set(ByVal value As Double) _propertyB = value End Set End Property Private _propertyC As Date <DataMember()> _ Public Property PropertyC() As Date Get Return _propertyC End Get Set(ByVal value As Date) _propertyC = value End Set End Property ``` End Class **Method:** Public Function Add(ByVal param As MyClass) As Boolean Implements IService1.Add ' ... End Function **PHP client call:** $client->Add(array('param'=>array( 'PropertyA' => 1, 'PropertyB' => 2, 'PropertyC' => "2009-01-01" ))); The WCF service works fine with a .Net client but I'm new to PHP and can't get this to work. Is it possible to create an instance of 'MyClass' in PHP. Any help would be appreciated. Note: I'm using PHP 5 (XAMPP 1.7.0 for Windows). Thanks Matt
I no longer have XAMPP setup in order to test but here is some example code: PHP: ``` $wsdl = "https://....../ServiceName.svc?wsdl"; $endpoint = "https://...../ServiceName.svc/endpointName"; $client = new SoapClient($wsdl, array('location'=>$endpoint)); $container = new stdClass(); $container->request->PropertyA = 'Test 1'; $container->request->PropertyB = 'Test 2'; $container->request->PropertyC = '05/10/2010'; $response = $client->ServiceMethodA($container); ``` request is the name of the parameter expected by the web service. If you have a custom type with references to other custom types you can set those properties as follows: ``` $container->request->OtherCustomType->Property1 = 'Test'; ``` Hope that helps.
I'd be willing to bet it's because you're using a Date type as one of your parameters and it's not serializing properly through PHP. Try using a string and parsing it manually. I know, not very type safe, but what can you do?
WCF service with PHP client - complex type as parameter not working
[ "", ".net", "php", "wcf", "" ]
I have a basic domain object, say like Person or Campaign or Event that is represented by a single table in the database. However, I also have more complicated versions of these objects say like a PersonCampaign or PersonEvent or even CampaignEvent that could theoretically extend one of the base objects. However, for a number of reasons this becomes complicated because PHP does not support multiple inheritance (for example does PersonEvent extend Person or Event). And also because some domain objects are actually factory objects with varying properties and functionality (for example Event is actually subclassed by the type of event like email, call, fax). The easiest solution that I can see is to have the actual nature of the object change based on what data is returned from the data access layer. Does anyone have any suggestions on a better way to handle this? Or is it correct to create unified domain objects that can change properties and behavior based on what is currently available to it from the data access layer?
From a OOP perspective a PersonEvent isn't really a object, its a relation. The Person class could get functions like: ``` get_events() add_event($Event) remove_event($Event) ``` and the Event class ``` get_person() set_person($Person) unset_person() // set person_id to NULL ``` (Assuming a 1:N relation between person and event) The bad part is, this will complicate the data-mapper or wont use the data-mapper at all.
A solution is the encapsulate the other objects: The PersonEvent class contains a Person and an Event. Accessable by either a function $PersonEvent->get\_event() or property $PersonEvent->Event;
Polymorphic Domain Objects Based On Data Mapper
[ "", "php", "oop", "dns", "data-access-layer", "" ]
I'm using Prototype's PeriodicalUpdater to update a div with the results of an ajax call. As I understand it, the div is updated by setting its innerHTML. The div is wrapped in a `<pre>` tag. In Firefox, the `<pre>` formatting works as expected, but in IE, the text all ends up on one line. Here's some sample code found [here](http://forums.devnetwork.net/viewtopic.php?f=13&t=93265) which illustrates the problem. In Firefox, `abc` is on different line than `def`; in IE it's on the same line. ``` <html> <head> <title>IE preformatted text sucks</title> </head> <body> <pre id="test"> a b c d e f </pre> <script type="text/javascript"><!-- var textContent = document.getElementById("test").innerText; textContent = textContent.replace("a", "<span style=\"color:red;\">a</span>"); document.getElementById("test").style.whiteSpace = "pre"; document.getElementById("test").innerHTML = textContent; --></script> </body> </html> ``` Anyone know of a way to get around this problem?
Setting innerHTML fires up an HTML parser, which ignores excess whitespace including hard returns. If you change your method to include the <pre> tag in the string, it works fine because the HTML parser retains the hard returns. You can see this in action by doing a View Generated Source after you run your sample page: ``` <PRE id="test" style="WHITE-SPACE: pre"><SPAN style="COLOR: red">a</SPAN> b c d e f </PRE> ``` You can see here that the hard return is no longer part of the content of the <pre> tag.
Generally, you'll get more consistent results by using DOM methods to construct dynamic content, especially when you care about subtle things like normalization of whitespace. However, if you're set on using innerHTML for this, there is an IE workaround, which is to use the `outerHTML` attribute, and include the enclosing tags. ``` if(test.outerHTML) test.outerHTML = '<pre id="test">'+textContent+'</pre>'; else test.innerHTML = textContent; ``` This workaround and more discussion can be found here: [Inserting a newline into a pre tag (IE, Javascript)](https://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript)
<pre> tag loses line breaks when setting innerHTML in IE
[ "", "javascript", "html", "css", "internet-explorer", "" ]
I have an enum which is used by multiple classes. What is the best way to implement this?
1. Put the enums right in your namespace (or make a new namespace for them) or 2. Put them in a (static?) class somewhere if that makes more sense. I'd keep them in their own file for easy access and good organization either way. I usually wouldn't put them in a class unless they somehow "belong" there. Like you have a Car class with an enum for the types of car, and a Road class and Bridge class that can set limits for types of car. `Car.CarType` seems to be a logical organization for this...
Typically I just throw them into the namespace. It's what Microsoft did writing the .NET framework, so it's what I do too, for consistency you understand :)
C# What is the best way to create an enum that is used by multiple classes?
[ "", "c#", "enums", "" ]
Lots of times in Java logs I'll get something like: ``` Caused by: java.sql.BatchUpdateException: failed batch at org.hsqldb.jdbc.jdbcStatement.executeBatch(jdbcStatement.java:1102) at org.hsqldb.jdbc.jdbcPreparedStatement.executeBatch(jdbcPreparedStatement.java:514) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) ... 113 more ``` Does anyone know how to get the full stacktrace showing (i.e. show the other 113 lines)? --- The [JavaDocs (for Java 7)](http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace%28%29) for Throwable have a pretty detailed explanation of what's going on.
When you see '...113 more', that means that the remaining lines of the 'caused by' exception are identical to the remaining lines from that point on of the parent exception. For example, you'll have ``` com.something.XyzException at ... at ... at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) at ... <the other 113 lines are here>... Caused by: <the above>. ``` The two stack traces 'meet' at AbstractBatcher.executeBatch, line 242, and then from then on the upward call trace is the same as the wrapping exception.
Increase `-XX:MaxJavaStackTraceDepth` JVM option.
How do I stop stacktraces truncating in logs
[ "", "java", "exception", "stack-trace", "" ]
I tried two ways of catching unexpected unhandled exceptions: ``` static void Main() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ErrorHandler.HandleException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { Application.Run(new OCR()); } catch (Exception ex) { ErrorWindow errorWindow = new ErrorWindow(ex); errorWindow.ShowDialog(); Application.Exit(); } } ``` When i execute the application using visual studio, everything works fine. if i use exe file in the bin\Debug folder, the exceptions are not handled. Application behaves as if catch block wasn't there. I'm clueless what's going on. any ideas? edit: exceptio nis not thron in **Load**
I should handle System.Windows.Forms.Application.ThreadException - then it works.
I take it that you have an exception in your Form's `OnLoad` method or `Load` event, then. This is a notorious issue, which isn't helped by the IDE making it behave differently. Basically, you need to make sure that your `OnLoad`/`Load` don't throw... perhaps put the `catch` in there, and set a property you can check afterwards?
Exception refuses to be handled
[ "", "c#", "winforms", "exception", "" ]
I want to detect whether the browser is refreshed or not using PHP, and if the browser is refreshed, what particular PHP code should execute.
If the page was refreshed then you'd expect two requests following each other to be for the same URL (path, filename, query string), and the same form content (if any) (POST data). This could be quite a lot of data, so it may be best to hash it. So ... ``` <?php session_start(); //The second parameter on print_r returns the result to a variable rather than displaying it $RequestSignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true)); if ($_SESSION['LastRequest'] == $RequestSignature) { echo 'This is a refresh.'; } else { echo 'This is a new request.'; $_SESSION['LastRequest'] = $RequestSignature; } ``` In an AJAX situation you'd have to be careful about which files you put this code into so as not to update the LastRequest signature for scripts which were called asynchronously.
When the user hits the refresh button, the browser includes an extra header which appears in the $\_SERVER array. Test for the refresh button using the following: ``` $refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0'; ```
Detect whether the browser is refreshed or not using PHP
[ "", "php", "refresh", "" ]
When I use an import such as ``` <script type="text/javascript" src="http://o.aolcdn.com/dojo/1.2.3/dojo/dojo.xd.js" djConfig="parseOnLoad:true, isDebug: true"></script> ``` I get the error ``` dojox.data.CsvStore is not a constructor ``` for lines such as ``` var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"}); ``` but the error vanishes if I use an import from a local installation of dojo such as ``` <script type="text/javascript" src="dojo-release-1.2.3/dojo/dojo.js" djConfig="parseOnLoad:true, isDebug: true"></script> ``` I would really want to be able to use a CDN hosted dojo installation. Is there a known problem between the DojoX libraries and dojo.xd.js? Thanks in advance, Animesh P.S. The `dojo.require("dojox.data.CsvStore");` declarations are in place. P.P.S The full "working code" is below. Replacing the CSS and JS references with those from the CDN breaks it. ``` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style type="text/css"> @import "dojo-release-1.2.3/dijit/themes/tundra/tundra.css"; @import "dojo-release-1.2.3/dojo/resources/dojo.css" </style> <script type="text/javascript" src="dojo-release-1.2.3/dojo/dojo.js" djConfig="parseOnLoad:true, isDebug: true"></script> <script> dojo.require("dojox.data.CsvStore"); dojo.require("dijit.Tree"); dojo.require("dojo.parser"); </script> <script type="text/javascript"> var stateStore = new dojox.data.CsvStore({url: "states.csv", label: "name"}); </script> </head> <body class="tundra"> <div dojoType="dijit.Tree" store="stateStore" labelAttr="name" label="States"> </div> </body> </html> ```
Reacting to your update: I strongly think you should try with `dojo.addOnLoad()`. Together, the last two `<script>` sections of your `<head>` would become: ``` <script> dojo.addOnLoad(function(){ dojo.require("dojox.data.CsvStore"); dojo.require("dijit.Tree"); dojo.require("dojo.parser"); /* I don't think you really need this line */ var stateStore = new dojox.data.CsvStore({url: "states.csv", label: "name"}); }); </script> ``` The problem with your original code is that you cannot guarantee that the constructor function `dojox.data.CsvStore` has been read by the time you are about to create your `stateStore` instance of it. That's where `dojo.addOnLoad()` comes in, giving you a guarantee that the rest of the javascript was loaded prior to executing the abstract function passed as parameter of `addOnLoad()`. Because it's an issue of timing, your own original code may work sometimes, maybe not others: it would depend on the download speed and the order in which your browser pieces together the various javascript bits. That's why using dojo's remote library may occasionally give different results from using your own local copy of the dojo library. That said, if you are using Firefox 3 (earlier than 3.0.6), then bear in mind what I said about the known bug. In that case, you may want to put that `<script>` block immediately before the closing `</body>` tag... (That option would work on other browsers as well.)
Are you running that code inside `dojo.addOnLoad()`? As in: ``` dojo.addOnLoad(function(){ dojo.require("dojox.data.CsvStore"); var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"}); }); ``` Also, are you using FireFox 3? If so, try putting your `<script></script>` block at the very end of the `<body>` section, just before the closing `</body>` tag. (I know that is not standard practice, but it's related to Firefox's [bug 444322](https://bugzilla.mozilla.org/show_bug.cgi?id=444322), which should be fixed in release 3.0.6.) Other than that, your code seems to be fine, and such strange discrepancies usually boil down to issues of timing with the loading of dojo modules.
dojo.xd.js not recognizing dojox.data.CsvStore
[ "", "javascript", "cdn", "dojo", "" ]
I have an Oracle table that contains a field of LONG RAW type that contains ASCII character data. How can I write a query or view that will convert this to a more easily consumed character string? These are always going to be single-byte characters, FWIW.
Maybe `select ...., to_lob(long_raw) from old_table` (<http://www.psoug.org/reference/convert_func.html>) or ``` UTL_RAW.CAST_TO_VARCHAR2(b) ``` (<http://www.dbasupport.com/forums/showthread.php?t=5342>).
I found this quote: > In Oracle9i, you can even: > > alter table old\_table modify ( c clob > ); > > to convert it. See here: <http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1037232794454> **Edit** The max length of a varchar2 column is 4000. Is that too short?
Converting small-ish Oracle long raw values to other types
[ "", "sql", "oracle", "" ]
Using Eclipse I want to view the source code for a core Java class (E.g. `java.util.concurrent.ConcurrentHashMap`) but when I navigate to the source using 'Open Declaration' it says 'Source not found' and gives me the option to attach the source. My question is; how do i attach the source? Where do i get the source .jar from for the `java.util.concurrent` library?
You need to have the JDK installed. Then you can look in `JDK_INSTALL_DIR\src.zip` For me it is `C:\Program Files\java\jdk1.6.0_11\` (depends on your current version) You don't need to get a special open source version.
When you are coding in Eclipse, press `CTRL` and click on any core Java class name in your source. Eclipse will now show a screen saying you don't have the sources installed. However, in this screen there is a link saying "Attach source...". Click that link and import the src.zip file from your JDK installation directory (src.zip). This should do the trick
How do I view JRE's source code in Eclipse?
[ "", "java", "eclipse", "" ]
I declared a private variable ``` vector<SomeClass> theVector; ``` someplace inside my SomeClass class. Why can't I say: `delete theVector` inside my SomeClass destructor? The compiler error says: ``` type `class Vector<SomeClass>' argument given to `delete', expected pointer ``` What expected pointer?
If new and delete go hand in hand. To delete something you need to create it via new (which gives you a pointer). You can then delete the pointer. The way you are declaring the vector it is being created on the stack (not the heap) and will be deallocated when it goes out of scope. ``` int main() { vector<SomeClass> theVector; vector<SomeClass>* ptrVctor = new vector<SomeClass>(); delete ptrVctor; // ptrVctor must be deleted manually // theVector destroyed automatically here } ```
In C++ (unlike Java), you can create objects either on the stack or the heap. An example of creating it on the stack is, as you have done: ``` vector<SomeClass> theVector; ``` This object goes out of scope when the stack frame disappears (normally when you return from the function that created the object. Creating objects on the heap allows them to outlive the function that created them and you do that by performing: ``` vector<SomeClass> *theVectorPtr = new vector<SomeClass>(); ``` You can then pass the `theVectorPtr` pointer back to the caller of the function (or store it globally, whatever you want). In order to get rid of the object on the heap, you explicitly delete it: ``` delete theVectorPtr; ``` somewhere in your code. Deleting an object on the heap ends the scope of that object, the same way returning from a function ends the scope of variables created on the stack.
Destructor C++: type '***' argument given to 'delete', expected pointer
[ "", "c++", "destructor", "" ]
In C# is there a way to detect if a string is all caps? Most of the strings will be short(ie under 100 characters)
No need to create a new string: ``` bool IsAllUpper(string input) { for (int i = 0; i < input.Length; i++) { if (!Char.IsUpper(input[i])) return false; } return true; } ``` **Edit:** If you want to skip non-alphabetic characters (*The OP's original implementation does not, but his/her comments indicate that they might want to*) : ``` bool IsAllUpper(string input) { for (int i = 0; i < input.Length; i++) { if (Char.IsLetter(input[i]) && !Char.IsUpper(input[i])) return false; } return true; } ```
I like the LINQ approach. If you want to restrict it to *all upper case letters* (i.e. no spaces etc): ``` return input.All(c => char.IsUpper(c)); ``` or using a method group conversion: ``` return input.All(char.IsUpper); ``` If you want to just forbid lower case letters: ``` return !input.Any(c => char.IsLower(c)); ``` or ``` return !input.Any(char.IsLower); ```
Detecting if a string is all CAPS
[ "", "c#", "string", "" ]
I need to set up a test environment on my XPSP3 machine that runs Apache, MySQL, and PHP. My original test environment was an old box that ran those three under Win2k. That box died. Running on Windows was never optimal because the ultimate hosting environment is CentOS Linux. What is the most straightforward way to set up a virtual machine on XP these days? I don't want to spend all my time tinkering with the test environment when I could be coding. As a follow-up question, how important is it to use the same distro on my test environment as my deployment? I don't know CentOS at all, but I'm comfortable with Fedora or Ubuntu.
Download free [VMWare player](http://www.vmware.com/products/player/) and install one of the pre-made Open Source LAMP VMs from the [VMWare appliance marketplace](http://www.vmware.com/appliances/directory/). VMs are also available in many places other than the appliance marketplace.
VM's are great - I love them. But if you're in a real hurry to get started, take a look at WAMPserver for Windows: <http://www.wampserver.com/en/>
Easiest way to create a virtual LAMP machine on Windows XP?
[ "", "php", "mysql", "linux", "apache", "virtual-machine", "" ]
I know you can't rely on equality between double or decimal type values normally, but I'm wondering if 0 is a special case. While I can understand imprecisions between 0.00000000000001 and 0.00000000000002, 0 itself seems pretty hard to mess up since it's just nothing. If you're imprecise on nothing, it's not nothing anymore. But I don't know much about this topic so it's not for me to say. ``` double x = 0.0; return (x == 0.0) ? true : false; ``` Will that always return true?
It is **safe** to expect that the comparison will return `true` if and only if the double variable has a value of exactly `0.0` (which in your original code snippet is, of course, the case). This is consistent with the semantics of the `==` operator. `a == b` means "`a` is equal to `b`". It is **not safe** (because it is **not correct**) to expect that the result of some calculation will be zero in double (or more generally, floating point) arithmetics whenever the result of the same calculation in pure Mathematics is zero. This is because when calculations come into the ground, floating point precision error appears - a concept which does not exist in Real number arithmetics in Mathematics.
If you need to do a lot of "equality" comparisons it might be a good idea to write a little helper function or extension method in .NET 3.5 for comparing: ``` public static bool AlmostEquals(this double double1, double double2, double precision) { return (Math.Abs(double1 - double2) <= precision); } ``` This could be used the following way: ``` double d1 = 10.0 * .1; bool equals = d1.AlmostEquals(0.0, 0.0000001); ```
Is it safe to check floating point values for equality to 0?
[ "", "c#", ".net", "floating-point", "precision", "zero", "" ]
I have a solid understanding of most `OOP` theory but the one thing that confuses me a lot is virtual destructors. I thought that the destructor always gets called no matter what and for every object in the chain. When are you meant to make them virtual and why?
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class: ``` class Base { // some virtual methods }; class Derived : public Base { ~Derived() { // Do some important cleanup } }; ``` Here, you'll notice that I didn't declare Base's destructor to be `virtual`. Now, let's have a look at the following snippet: ``` Base *b = new Derived(); // use b delete b; // Here's the problem! ``` Since Base's destructor is not `virtual` and `b` is a `Base*` pointing to a `Derived` object, `delete b` has [undefined behaviour](https://stackoverflow.com/q/2397984/20984): > [In `delete b`], if the static type of the > object to be deleted is different from its dynamic type, the static > type shall be a base class of the dynamic type of the object to be > deleted and **the static type shall have a virtual destructor or the > behavior is undefined**. In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak. To sum up, always make base classes' destructors `virtual` when they're meant to be manipulated polymorphically. If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call `delete` on a base class pointer. You can learn more about virtuality and virtual base class destructor in [this article from Herb Sutter](http://www.gotw.ca/publications/mill18.htm).
A virtual constructor is not possible but virtual destructor is possible. Let us experiment....... ``` #include <iostream> using namespace std; class Base { public: Base(){ cout << "Base Constructor Called\n"; } ~Base(){ cout << "Base Destructor called\n"; } }; class Derived1: public Base { public: Derived1(){ cout << "Derived constructor called\n"; } ~Derived1(){ cout << "Derived destructor called\n"; } }; int main() { Base *b = new Derived1(); delete b; } ``` The above code output the following: ``` Base Constructor Called Derived constructor called Base Destructor called ``` The construction of derived object follow the construction rule but when we delete the "b" pointer(base pointer) we have found that only the base destructor is called. But this must not happen. To do the appropriate thing, we have to make the base destructor virtual. Now let see what happens in the following: ``` #include <iostream> using namespace std; class Base { public: Base(){ cout << "Base Constructor Called\n"; } virtual ~Base(){ cout << "Base Destructor called\n"; } }; class Derived1: public Base { public: Derived1(){ cout << "Derived constructor called\n"; } ~Derived1(){ cout << "Derived destructor called\n"; } }; int main() { Base *b = new Derived1(); delete b; } ``` The output changed as following: ``` Base Constructor Called Derived Constructor called Derived destructor called Base destructor called ``` So the destruction of the base pointer (which takes an allocation on derived object!) follows the destruction rule, i.e first the Derived, then the Base. On the other hand, there is nothing like a virtual constructor.
When to use virtual destructors?
[ "", "c++", "polymorphism", "shared-ptr", "virtual-destructor", "" ]
I'm trying to compile the following simple DL library example code from [Program-Library-HOWTO](http://tldp.org/HOWTO/Program-Library-HOWTO/dl-libraries.html) with g++. This is just an example so I can learn how to use and write shared libraries. The real code for the library I'm developing will be written in C++. ``` #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*cosine)(double); char *error; handle = dlopen ("/lib/libm.so.6", RTLD_LAZY); if (!handle) { fputs (dlerror(), stderr); exit(1); } cosine = dlsym(handle, "cos"); if ((error = dlerror()) != NULL) { fputs(error, stderr); exit(1); } printf ("%f\n", (*cosine)(2.0)); dlclose(handle); } ``` If I compile the program with gcc it works fine. ``` gcc -o foo foo.c -ldl ``` When I change the filename and compiler to the following ``` g++ -o foo foo.cpp -ldl ``` I get the following error: > foo.cpp:16: error: invalid conversion from 'void\*' to 'double (\*)(double)' I understand (I *think* I understand, correct me if this is wrong) that I can't do an implicit cast from a void pointer in C++, but C lets me, and this is why the above code will compile using gcc but not using g++. So I tried an explicit cast by changing line 16 above to: ``` cosine = (double *)dlsym(handle, "cos"); ``` With this in place, I get the following error: > foo.cpp:16: error: cannot convert 'double\*' to 'double (\*)(double)' in assignment These problems probably have more to do with my own general ignorance of proper C++ coding standards than anything else. Can anyone point me to a good tutorial on developing dynamic libraries for Linux that uses C++ example code?
C allows implicit casts from `void *` to any pointer type (including function pointers); C++ requires explicit casting. As leiflundgren says, you need to cast the return value of `dlsym()` to the function pointer type you need. Many people find C's function pointer syntax awkward. One common pattern is to typedef the function pointer: ``` typedef double (*cosine_func_ptr)(double); ``` You can define your function pointer variable `cosine` as a member of your type: ``` cosine_func_ptr cosine; ``` And cast using the type instead of the awkward function pointer syntax: ``` cosine = (cosine_func_ptr)dlsym(handle, "cos"); ```
`dlsym` returns a pointer to the symbol. (As `void*` to be generic.) In your case you should cast it to a function-pointer. ``` double (*mycosine)(double); // declare function pointer mycosine = (double (*)(double)) dlsym(handle, "cos"); // cast to function pointer and assign double one = mycosine(0.0); // cos(0) ``` So this one of these rare cases where the compiler error is a good clue. ;)
Dynamic Shared Library compilation with g++
[ "", "c++", "linux", "g++", "shared-libraries", "" ]
Is there a way to bind the child properties of an object to datagridview? Here's my code: ``` public class Person { private string id; private string name; private Address homeAddr; public string ID { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public Address HomeAddr { get { return homeAddr; } set { homeAddr = value; } } } public class Address { private string cityname; private string postcode; public string CityName { get { return cityname; } set { cityname = value; } } public string PostCode { get { return postcode; } set { postcode = value; } } } ``` And I want to show ID, Name, CityName when an object of the type Person is binded to datagridview. Note that CityName is a property of HomeAddr.
Hmm, [I've found a way to do this, in FarPoint](http://itscommonsensestupid.blogspot.com/2009/01/how-to-use-customtypedescriptor-to-show.html). But you *can* do this in DataGridView, if your object doesn't have a list type property.
IF you have the DataGridView to AutoGenerateColumns = true, there's really no simple way to do this. Your best bet is to set up the DataGridView ahead of time, and manually populate the DataGridView. Alternatively, you can implement the [ITypedList](http://msdn.microsoft.com/en-us/library/system.componentmodel.itypedlist.aspx) but that's a bit of a pain if you ask me.
Bind child Properties to DataGridView
[ "", "c#", "data-binding", "datagridview", "" ]