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 answe...
**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 `...
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 ent...
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: ``` in...
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 wri...
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 ...
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...
``` 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...
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 ...
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 in...
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 w...
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(); } privat...
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 d...
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 possibl...
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_conten...
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 ma...
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...
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 li...
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 ...
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 pag...
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 someth...
**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'); ...
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 bookm...
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 loa...
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 ...
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 ...
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 ...
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 str...
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 ...
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...
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 _ ...
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...
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 us...
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 H...
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 detec...
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 s...
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 ...
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 w...
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 t...
``` 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 assig...
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); <...
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 characte...
`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...
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 ...
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 */ ``` ...
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 -> A...
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. ...
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(datD...
``` 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" Header...
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 Quest...
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=...
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 verticall...
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 librar...
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\...
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 ne...
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 in...
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...
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): ...
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.fie...
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)`: ``` ...
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 som...
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 refer...
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...
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...
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>(); ...
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> MyLi...
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. ...
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 ``` ...
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 ...
``` 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 publ...
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 `...
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...
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...
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...
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 pageflak...
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...
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.co...
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 `t...
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, handle...
# 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...
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 q...
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 onl...
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: / \ \* ? [ ] H...
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 i...
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 wa...
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...
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 ex...
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 c...
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 = ...
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(...
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 fileNa...
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. Pro...
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()....
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 d...
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 Northwi...
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 wan...
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) even...
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("cleve...
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 se...
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 ...
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, pro...
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 = tru...
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 ca...
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...
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...
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...
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,...
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 intende...
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;<',$...
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.ti...
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(so...
``` 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,...
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...
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...
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 signatur...
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 possibl...
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 NO...
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 `...
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?..............
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 loo...
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] <...
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 cod...
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 c...
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 AllFr...
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 ...
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()...
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-incrom...
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 ...
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: <h...
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"); ...
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 s...
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-t...
``` 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 quer...
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...
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 == withou...
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 :...
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 MyCleverEnu...
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 des...
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 won...
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#fu...
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 ...
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 perf...
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 a...
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')...
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 sh...
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 e...
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...
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 ...
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...
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 db...
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 ...
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 May...
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 propert...
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 ...
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....
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 ...
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 d...
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 app...
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(...
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 appear...
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 3...
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 subtr...
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 ...
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 interpre...
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 Rob...
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 behi...
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.innerHT...
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 some...
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 m...
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...
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 O...
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...
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 t...
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. F...
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 b...
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 ...
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 navigatio...
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.getEl...
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. **...
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 = ...
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 ...
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 pe...
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 fou...
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...
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 enclos...
<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 h...
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.d...
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.j...
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.SetCompatibl...
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 a...
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 retu...
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: "...
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 d...
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...
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 .j...
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 directo...
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<SomeCla...
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 o...
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 hi...
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(...
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 s...
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 ...
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...
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 coul...
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 decl...
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...
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++. ```...
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 ...
`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) ...
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 { ...
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.itypedl...
Bind child Properties to DataGridView
[ "", "c#", "data-binding", "datagridview", "" ]