Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I was just reading this [thread](https://stackoverflow.com/questions/243082/c-casting-programmatically-can-it-be-done) and it occurred to me that there is one seemingly-valid use of that pattern the OP is asking about. I know I've used it before to implement dynamic creation of objects. As far as I know, there is no be...
I think what you are asking is how to keep the object creation code with the objects themselves. This is usually what I do. It assumes that there is some key that gives you a type (int tag, string, etc). I make a class that has a map of key to factory functions, and a registration function that takes a key and factory...
What you're describing here is termed the [factory](http://en.wikipedia.org/wiki/Factory_method_pattern) pattern. A variant is the [builder](http://en.wikipedia.org/wiki/Builder_pattern) pattern.
creating objects dynamically in C++
[ "", "c++", "serialization", "" ]
Disclaimer: I'm fairly new to python! If I want all the lines of a file until (edit: and including) the line containing some string `stopterm`, is there a way of using the list syntax for it? I was hoping there would be something like: ``` usefullines = [line for line in file until stopterm in line] ``` For now, I'v...
``` from itertools import takewhile usefullines = takewhile(lambda x: not re.search(stopterm, x), lines) from itertools import takewhile usefullines = takewhile(lambda x: stopterm not in x, lines) ``` Here's a way that keeps the stopterm line: ``` def useful_lines(lines, stopterm): for line in lines: if ...
" I was hoping for a 1 thought->1 Python line mapping." Wouldn't we all love a programming language that somehow mirrored our natural language? You can achieve that, you just need to define your unique thoughts once. Then you have the 1:1 mapping you were hoping for. ``` def usefulLines( aFile ): for line in aFil...
Python: item for item until stopterm in item?
[ "", "python", "" ]
I added a `get_absolute_url` function to one of my models. ``` def get_absolute_url(self): return '/foo/bar' ``` The admin site picks it up and adds a "view on site" link to the detail page for that object (when I put a real URL there instead of "/foo/bar"). The problem is instead of going to `http://localhost:8...
You have to change [default site](http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites) domain value.
The funniest thing is that "example.com" appears in an obvious place. Yet, I was looking for in in an hour or so. Just use your admin interface -> Sites -> ... there it is :)
Django Admin's "view on site" points to example.com instead of my domain
[ "", "python", "django", "django-admin", "" ]
I have a form action that needs to have its value set from a variable. I need to set the variable once and it will be reflected many times throughout the DOM. So: variable = "somthing.html"; ...
This will cause all FORMs to get the variable action: ``` <script src="jquery-1.2.6.pack.js"></script> <script> $(document).ready(function() { var variable = "something.html"; $('form').attr("action", variable); }); </script> ```
You can then change the form action to be equal to the variable name. Something like the following. ``` var variableName = "myform.htm"; this.form.action = variableName; ``` Edit, you can also do this with other elements, just like you would with any other piece of javascript, using things such as "getElementById()"...
print or echo a javascript variable, not to the document, but to be the value, or part of the value, to a DOM element, specifically a form action
[ "", "javascript", "html", "dom", "" ]
I have this SQL query: ``` SELECT * FROM IMAGES WHERE IMAGENAME in ('IMG1', 'IMG2', 'IMG3', 'IMG4', 'IMG5', 'IMG6') ORDER BY CASE IMAGENAME WHEN 'IMG1' THEN 1 WHEN 'IMG2' THEN 2 WHEN 'IMG3' THEN 3 WHEN 'IMG4' THEN 4 WHEN 'IMG5' THEN 5 WHEN 'IMG6' THEN 6 ELSE 7 END ``` I cannot guarantee that the list of...
I'm not sure if this is available in your target databases, but it might hopefully work at least as inspiration for a better approach. In MySQL, you would do what you want with the FIELD() function like this: ``` SELECT * FROM IMAGES WHERE IMAGENAME IN ('IMG1', 'IMG2', 'IMG3', 'IMG4', 'IMG5', 'IMG6') ORDER BY FIEL...
``` SELECT * FROM IMAGES WHERE IMAGENAME in ('IMG1', 'IMG2', 'IMG3', 'IMG4', 'IMG5', 'IMG6') ORDER BY IMAGENAME ASC ``` You don't need to strip the imagename; you're only selecting the few cases noted above, and order by can order string well enough. Also, the 'else' condition makes no sense, because it would never be...
Is there a more efficient way to do this SQL Select?
[ "", "sql", "sorting", "performance", "" ]
I am currently working in C#, and I need to insert a new record into one table, get the new primary key value, and then use that as a foreign key reference in inserting several more records. The Database is MS SQL Server 2003. All help is appreciated!
The way to get the identity of the inserted row is with the `SCOPE_IDENTITY()` function. If you're using stored procedures then this would look something like the following to return the row identity as an output parameter. ``` CREATE PROCEDURE dbo.MyProcedure ( @RowId INT = NULL OUTPUT ) AS INSERT INTO MyTable (...
The best way of doing this is the use SCOPE\_IDENTITY() function in TSQL. This should be executed as part of the insert i.e. ``` SqlCommand cmd = new SqlCommand(@" INSERT INTO T (Name) VALUES(@Name) SELECT SCOPE_IDENTITY() As TheId", conn); cmd.AddParameter("@Name", SqlDbType.VarChar, 50).Value = "Test"; int t...
Getting autonumber primary key from MS SQL Server
[ "", "c#", "sql-server", "autonumber", "" ]
I want to validate a set of credentials against the domain controller. e.g.: ``` Username: STACKOVERFLOW\joel Password: splotchy ``` ## Method 1. Query Active Directory with Impersonation A lot of people suggest querying the Active Directory for something. If an exception is thrown, then you know the credentials are...
C# in .NET 3.5 using [System.DirectoryServices.AccountManagement](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx). ``` bool valid = false; using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { valid = context.ValidateCredentials( username, passwo...
Install `System.DirectoryServices.AccountManagement` from NuGet Package Manager and then: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security; using System.DirectoryServices.AccountManagement; public struct Credentials { public string Username; publi...
How to validate domain credentials?
[ "", "c#", "windows", "security", "authentication", "" ]
I know that you cannot return anonymous types from methods but I am wondering how the Select extension method returns an anonymous type. Is it just a compiler trick? Edit Suppose L is a List. How does this work? ``` L.Select(s => new { Name = s }) ``` The return type is IEnumerable<'a> where 'a = new {String Name}
The type is actually defined by *the caller*, so it's in the scope of the calling function - neatly avoiding the issue of "returning" an anonymous type. This is accomplished by generic type inference. The signature for [Select](http://msdn.microsoft.com/en-us/library/bb548891.aspx) is `Select<Tsource, TResult>(IEnumer...
Well, it's normal type inference for generic method type arguments. For instance: ``` List<string> x = new List<string>(); // The compiler converts this: x.Select(y => y.Length); // Into this, using type inference: Enumerable.Select<string, int>(x, y => y.Length); ``` The same would be true if `x` were a list of so...
Methods and Anonymous Types
[ "", "c#", "extension-methods", "anonymous-types", "anonymous-methods", "" ]
I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness). Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness wit...
If you're using autoconf, you can use the `AC_C_BIGENDIAN` macro, which is fairly guaranteed to work (setting the `WORDS_BIGENDIAN` define by default) alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branc...
There is no portable way to do this at compile time, your best bet is probably to use the [Boost](http://www.boost.org/) [endian macros](http://www.boost.org/doc/libs/1_36_0/boost/detail/endian.hpp) or emulate the methods they use.
Is there a way to do a C++ style compile-time assertion to determine machine's endianness?
[ "", "c++", "templates", "metaprogramming", "endianness", "" ]
Why are there not more opensource easy to use charting libraries for Java?. The only successful opensource project in this area seems to be jfreechart, and it doesn't even have any documentation or examples available.
There is [charts4j](https://github.com/julienchastang/charts4j) which is a charts and graphs API. It enables developers to programmatically create the charts available in the [Google Chart API](http://code.google.com/apis/chart/) through a straightforward and intuitive Java API. Disclaimer: I wrote [charts4j](https://...
There aren't a lot of them because they would be in competition with [JFreeChart](http://www.jfree.org/jfreechart/), and it's awesome. You can get documentation and examples by downloading the [developer's guide](http://www.object-refinery.com/jfreechart/guide.html). There are also tons of free online tutorials if you ...
What is the best open-source java charting library? (other than jfreechart)
[ "", "java", "charts", "plot", "" ]
If I'm using ConcurrentHashMap (where the put is thread safe) , and I supply a public function myPut that uses the ConcurrentHashMap put - do I need to synchronize my function? meaning : should this be synchronized? ``` ConcurrentHashMap map; public void myPut(int something) { this.map.put(something); } ```
Concurrency utilities such as ConcurrentHashMap are designed so that you don't need to synchronize: they'll handle thread-safe access internally. What Tom says is true, that you need to think about the potential of the map reference to change. If the reference actually *doesn't* change, then in practice you'll get awa...
Because the `map` reference is not declared `final` it may be changed. Therefore, there is a potential threading bug here. If `map` is supposed to be a mutable reference then you will need to do some more work. Otherwise use `final`. Indeed, use `final` whenever you can, even if it is "easier" not to. "`final` is the ...
Does a call to a threadsafe function need to be syncronized too?
[ "", "java", "synchronization", "concurrenthashmap", "" ]
Is it possible (by using the stock c# TreeView) to have Multiline TreeNodes? Also, is it possible to add control characters to TreeNode's text e.g. '\t'? This same effect could also be achieved by adding columns to the TreeNode. is this possible?
I do not believe this is possible using WinForms, at least without drawing your own nodes. You may be able to use an "owner-drawn" treenode to accomplish this in WinForms, though, I don't know. This is natively supported with WPF, though.
It isn't very clear from your question whether you are on ASP.NET or WinForms. If you're in ASP.NET you could try using the PRE tag to get formatting...? What that's said the Ra-Ajax TreeView which you can see an example of [here](http://ra-ajax.org/samples/Viewport-RSS-Starter-Kit.aspx) can have any arbitrage amount ...
c# Treeview Node with formatted text e.g. tabs & new lines
[ "", "c#", "treeview", "format", "treenode", "" ]
I am trying to use the range property of the jQuery slider so that the slider control displays two handles from which the user can select a price range for real estate. The code I have is: ``` $("#price").slider({ range: true, minValue: 0, maxValue: 2000000, change: function(e, ui) { var range = (Math.round(ui...
To access the slider handle values in a double handled slider you need to access them from the [slider( "value", index )](http://docs.jquery.com/UI/Slider/slider#slider.28.C2.A0.22value.22.2C.C2.A0index_.29) function. Try the following code: ``` $(document).ready(function(){ $("#price").slider( { range: true...
``` <script type="text/javascript"> var str; $(function() { $("#slider-range").slider({ range: true, min: 250, max: 2500, values: [500, 1000], slide: function(event, ui) { $("#amount").val('Rs' + ui.values[0] + ' - Rs' + ui.values[1]); ...
jQuery slider range
[ "", "javascript", "jquery", "slider", "" ]
I have a binary field in my database that is hard to describe in a UI using a single "Is XXXX?"-type checkbox. I'd rather use a pair of radio buttons (e.g. "Do it the Foo way" and "Do it the Bar way"), but right now all the other fields on my form are data-bound to a business object. I'd like to data-bind the pair of r...
I have found a way of doing this using DataSet/DataTable. I make a calculated column in the DataTable with the expression `IIF(Foo=true, false, true)`. Let's call that column `Bar`. `Bar` is of type Boolean. Now you can bind one `RadioButton.Checked` to `Foo` and one to `Bar`. To get `Bar` checking/unchecking to pro...
1. Bind the `RadioButton` that is directly linked to your boolean value (ie is checked when the value is `true`). 2. Add an event handler to the `CheckedChanged` event on this `RadioButton` that looks like the following : ``` private void radioButton_CheckedChanged(object sender, EventArgs e) { foreach...
How do I use databinding with Windows Forms radio buttons?
[ "", "c#", "winforms", "data-binding", "radio-button", "" ]
I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from `as_p()`, `as_ul()`, etc does not reflect the updated Meta exclude. I assume then that the html is generated when the ModelForm is created not when the ...
The Meta class is used to dynamically construct the form definition - so by the time you've created the ModelForm instance, the fields not in the exclude have already been added as the new object's attributes. The normal way to do it would be to just have multiple class definitions for each possible exclude list. But ...
Another way: ``` class PassengerInfoForm(ModelForm): def __init__(self, *args, **kwargs): exclude_list=kwargs.pop('exclude_list', '') super(PassengerInfoForm, self).__init__(*args, **kwargs) for field in exclude_list: del self.fields[field] class Meta: model = Pas...
Dynamically update ModelForm's Meta class
[ "", "python", "django", "django-forms", "metaprogramming", "modelform", "" ]
In C#, if I declare an auto-implemented property, why do I have to declare BOTH the get and set part? i.e. ``` public string ThisWorks { get; set; } public string ThisDoesnt { get; } ``` Isn't this just syntactic sugar - i.e. the compiler inserts a private field for the property? So why the problem? Curious.
If you didn't have a setter - then how would you ever set the property? Incidentally, you can specify the accessibility, eg: ``` public string Foo { get; private set; } ```
Without a setter, you would never be able to provide a value - as you don't have any way of specifying the backing variable's name. I've requested a readonly automatic property, declared like this: ``` public string ReadonlyProperty { get; readonly set; } ``` which would create a readonly backing variable, a propert...
Why do automatic properties require both getters AND setters?
[ "", "c#", ".net", "automatic-properties", "" ]
Whats this syntax useful for : ``` function(String... args) ``` Is this same as writing ``` function(String[] args) ``` with difference only while invoking this method or is there any other feature involved with it ?
The only difference between the two is the way you call the function. With String var args you can omit the array creation. ``` public static void main(String[] args) { callMe1(new String[] {"a", "b", "c"}); callMe2("a", "b", "c"); // You can also do this // callMe2(new String[] {"a", "b", "c"}); } pub...
The difference is only when invoking the method. The second form must be invoked with an array, the first form can be invoked with an array (just like the second one, yes, this is valid according to Java standard) or with a list of strings (multiple strings separated by comma) or with no arguments at all (the second on...
difference fn(String... args) vs fn(String[] args)
[ "", "java", "variadic-functions", "" ]
I need to read data added to the end of an executable from within that executable . On win32 I have a problem that I cannot open the .exe for reading. I have tried CreateFile and std::ifstream. Is there a way of specifying non-exclusive read access to a file that wasn't initially opened with sharing. EDIT- Great t...
Why not just use resources which are designed for this functionality. It won't be at the end, but it will be in the executable. If you are adding to the .exe after it is built -- you don't have to add to the end, you can update resources on a built .exe <http://msdn.microsoft.com/en-us/library/ms648049(VS.85).aspx>
We do this in one of our projects. What's the problem with it? If the EXE is running, then it's already held open for reading, and you can continue to open it read-only multiple times. I just checked our code, we just use: ``` HANDLE file=CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); ```...
Executable reading itself
[ "", "c++", "winapi", "file", "" ]
I know that new-ing something in one module and delete-ing it in another can often cause problems in VC++. Problems with different runtimes. Mixing modules with staticly linked runtimes and/or dynamically linked versioning mismatches both can screw stuff up if I recall correctly. **However, is it safe to use VC++ 2008...
Freeing the memory is safe, so long as it all came from the same *memory management* context. You've identified the most common issue (different C++ runtimes); having separate heaps is another less-common issue you can run into. Another issue which you didn't mention, but which can be exascerbated by shared pointers, ...
You're beginning to see how incredibly amazing `shared_ptr` is :) Being safe across DLL boundaries is exactly what `shared_ptr` was designed to be (among other things, of course). Contrary to what others have said, you don't even need to pass a custom deleter when constructing the `shared_ptr`, as the default is alre...
Is it safe to use STL (TR1) shared_ptr's between modules (exes and dlls)
[ "", "c++", "visual-c++", "memory-management", "stl", "shared-ptr", "" ]
I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code: ``` <img src="image.py?text=xxxxxxxxxxxxxx"> ``` The problem is that I expect in the future the "text" field will get very long and the URL will become too large. From Goog...
Store the text somewhere (e.g. a database) and then pass through the primary key.
This will get you an Image as the result of a POST -- you may not like it 1. Put an iFrame where you want the image and size it and remove scrollbars 2. Set the src to a form with hidden inputs set to your post parameters and the action set to the URL that will generate the image 3. submit the form automatically with ...
Including a dynamic image in a web page using POST?
[ "", "python", "html", "django", "cgi", "image", "" ]
Is there anything I should know before converting a large C++ program from VS2005 to VS2008?
I'm working on this very problem right now. *Running WinMerge to see what I've changed...* OK, here is what I had to fix in an huge Win32/MFC client application: Some MFC functions have become virtual (which were not in the past - CWnd::GetMenu for one, if I recall correctly). Also something related to our legacy mo...
If you have to support older platforms, beware: VC2008 is the first version that [can't target Win9x or NT4](https://stackoverflow.com/questions/213711/does-visual-studio-2008-support-windows-98). My company has to stick to VC2005 for that very reason.
Anything I should know before converting a large C++ program from VS2005 to VS2008?
[ "", "c++", "visual-studio", "visual-c++", "" ]
If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. `SELECT * FROM table WHERE column LIKE %news%`), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a ...
``` select substring(column, CHARINDEX ('news',lower(column))-10, 20) FROM table WHERE column LIKE %news% ``` basically substring the column starting 10 characters before where the word 'news' is and continuing for 20. Edit: You'll need to make sure that 'news' isn't in the first 10...
You can use substring function in a SELECT part. Something like: ``` SELECT SUBSTRING(column, 1,20) FROM table WHERE column LIKE %news% ``` This will return the first 20 characters from column *column*
Is it possible to get the matching string from an SQL query?
[ "", "sql", "" ]
What's the difference between these two? Which is better/faster/reliable?
SCGI is a language-neutral means of connecting a front-end web server and a web application. WSGI is a Python-specific interface standard for web applications. Though they both have roots in CGI, they're rather different in scope and you could indeed quite reasonably use both at once, for example having a mod\_scgi on...
SCGI (like FastCGI) is a (serialized) protocol suitable for inter-process communication between a web-server and a web-application. WSGI is a Python API, connecting two (or more) Python WSGI-compatible modules inside the same process (Python interpreter). One module represents the web-server (being either a Python in-...
What's the difference between scgi and wsgi?
[ "", "python", "wsgi", "scgi", "" ]
I'm revisiting som old code of mine and have stumbled upon a method for getting the title of a website based on its url. It's not really what you would call a stable method as it often fails to produce a result and sometimes even produces incorrect results. Also, sometimes it fails to show some of the characters from t...
A simpler way to get the content: ``` WebClient x = new WebClient(); string source = x.DownloadString("http://www.singingeels.com/"); ``` A simpler, more reliable way to get the title: ``` string title = Regex.Match(source, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Titl...
Perhaps with this suggestion a new world opens up for you I also had this question and came to this Download "Html Agility Pack" from <http://html-agility-pack.net/?z=codeplex> Or go to nuget: <https://www.nuget.org/packages/HtmlAgilityPack/> And add in this reference. Add folow using in the code file: ``` using Ht...
How to get website title from c#
[ "", "c#", "webrequest", "" ]
I'm preferably looking for a SQL query to accomplish this, but other options might be useful too.
``` SELECT LAST_DDL_TIME, TIMESTAMP FROM USER_OBJECTS WHERE OBJECT_TYPE = 'PROCEDURE' AND OBJECT_NAME = 'MY_PROC'; ``` **`LAST_DDL_TIME`** is the last time it was compiled. **`TIMESTAMP`** is the last time it was changed. Procedures may need to be recompiled even if they have not changed when a dependency changes.
``` SELECT name, create_date, modify_date FROM sys.procedures order by modify_date desc ```
How do I find out when a stored procedure was last modified or compiled in Oracle?
[ "", "sql", "oracle", "stored-procedures", "plsql", "oracle10g", "" ]
I have an XML document looking similar to this: ``` <items> <item cat="1" owner="14">bla</item> <item cat="1" owner="9">bla</item> <item cat="1" owner="14">bla</item> <item cat="2" owner="12">bla</item> <item cat="2" owner="12">bla</item> </items> ``` Now I'd like to get all unique owners (I actually only need t...
Presuming the fragment is in itemsElement: ``` var distinctOwners = (from item in itemsElement.Element("item") where itemElements.Attribute("cat") == 1 select item.Attribute("owner")).Distinct(); ``` Apologies for formatting and indentation!
Try this function:- ``` static IEnumerable<int> GetOwners(XDocument doc, string cat) { return from item in doc.Descendants("item") where item.Attribute("cat").Value == cat select (int)item.Attribute("owner")).Distinct(); } ```
Select unique XElements (by attribute) with a filter using LinqToXml
[ "", "c#", "xml", "linq-to-xml", "unique", "" ]
I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?
jQuery doesn't have a convenient function for this. You need to combine `contents()`, which will give just child nodes but includes text nodes, with `find()`, which gives all descendant elements but no text nodes. Here's what I've come up with: ``` var getTextNodesIn = function(el) { return $(el).find(":not(iframe...
Jauco posted a good solution in a comment, so I'm copying it here: ``` $(elem) .contents() .filter(function() { return this.nodeType === 3; //Node.TEXT_NODE }); ```
How do I select text nodes with jQuery?
[ "", "javascript", "jquery", "dom", "" ]
can i somehow compare two numbers in regex? i want regex that is correct for 10-12, but incorrect for 12-10. I mean that 10 must be smaller than 12. I want to do it in Javascript.
If the input is always of the form X-Y, then why not use the split() function with '-' as the delimiter and then compare the two parts with > You can't compare numerical values using RegExps.
I wouldn't use regex for this. I'd split the string on the operator, then compare the two resulting numbers based on what operator I found (I'm assuming `10+12` and `12+10` would both be legal).
regex compare two numbers
[ "", "javascript", "regex", "numbers", "compare", "" ]
I'm new to using LINQ to Entities (or Entity Framework whatever they're calling it) and I'm writing a lot of code like this: ``` var item = (from InventoryItem item in db.Inventory where item.ID == id select item).First<InventoryItem>(); ``` and then calling methods on that object like this: ...
You want to use the .Include(string) method references in this ["Shaping query results"](http://msdn.microsoft.com/en-us/library/bb896272.aspx) article. ``` var item = from InventoryItem item in db.Inventory.Include("ItemTypeReference").Include("OrderLineItems") where item.ID == id ...
In addition to Robert's answer, you might like to check out this question for options for an extension method that that allows you to .Include() using an expression instead of a string, so you get compile time checking: [Entity Framework .Include() with compile time checking?](https://stackoverflow.com/questions/29211...
How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()
[ "", "c#", "linq", "linq-to-entities", "" ]
I have a C++ DLL including bitmap resources created by Visual Studio. Though I can load the DLL in VB6 using LoadLibrary, I cannot load the image resources either by using LoadImage or by using LoadBitmap. When I try to get the error using GetLastError(), it doesnot return any errors. I have tried using LoadImage and...
Since you are using the numeric ID of the bitmap as a string, you have to add a "#" in front of it: ``` DLLHandle = LoadLibrary("Mydll.dll") myimage = LoadBitmap(DLLHandle, "#101") ' note the "#" ``` In C++ you could also use the MAKEINTRESOURCE macro, which is simply a cast to LPCTSTR: ``` imagehandle = LoadBitmap...
You've got the right idea. You probably have the call wrong. Perhaps you could show a bit of code as I can't guess as to what you're passing.
accessing bitmap resources in a C++ DLL from VB6
[ "", "c++", "dll", "vb6", "bitmap", "resources", "" ]
A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be "reset" on each iteration. ...
**Most** of the time, it does not matter whether you declare a variable inside or outside the loop; the rules of definite assignment ensure that it doesn't matter. In the debugger you might occasionally see old values (i.e. if you look at a variable in a breakpoint before it is assigned), but static-analysis proves tha...
**Summary** Comparing the generated IL for declaring variables inside the loop to the generated IL for declaring variables outside the loop proves that there is no performance difference between the two styles of variable declaration. (The generated IL is virtually identical.) --- Here is the original source, suppos...
Declaring variables within FOR loops
[ "", "c#", "scope", "" ]
I'm working on a script in PHP that needs to get some info from a SQL Server database. However, I am having trouble connecting to the database. When i use the mssql\_connect() function, it gives me an error and says it cannot connect to the database. However, it gives no reason why. Is there any way to find out why it ...
Try to use pdo (<http://php.net/pdo>). the mssql-extension is a mess. Instead of '' it returns ' ' for empty strings. It seems to be a bug in ntwdblib that has never been fixed. When I experienced the problem i nearly went crazy... To get the client connected: Have you activated tcp/ip on the sql-server? On MSSQL 200...
Have you tried looking in the Windows Event Log? I am not sure if there will be enough info there, but it may help.
PHP and SQL Server debugging
[ "", "php", "sql-server", "" ]
I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. How do i do this? I am using sqlAlchemy.
This always works and requires little thinking -- only patience. 1. Make a backup. 2. Actually make a backup. Everyone skips step 1 thinking that they have a backup, but they can never find it or work with it. Don't trust any backup that you can't recover from. 3. Create a new database schema. 4. Define your new struc...
The simplest approach is to simply write some sql update scripts and use those to update the database. Obviously that's a fairly low-level (as it were) approach. If you think you will be doing this a lot and want to stick in Python you might want to look at [sqlalchemy-migrate](http://code.google.com/p/sqlalchemy-migr...
How to update turbogears application production database
[ "", "python", "database", "postgresql", "data-migration", "turbogears", "" ]
Has anybody seen such a thing? Small self-sufficient modules are preferred.
The [fractions module](http://docs.python.org/library/fractions.html) from 2.6 can be ripped out if necessary. Grab fractions.py, numbers.py, and abc.py; all pure python modules. You can get the single files from here (2.6 branch, 2.7 does not work): <http://hg.python.org/cpython/branches>
[SymPy](http://code.google.com/p/sympy/) is a symbolic maths library written entirely in Python and has full support for rational numbers. From the [tutorial](http://docs.sympy.org/tutorial.html): ``` >>> from sympy import * >>> a = Rational(1,2) >>> a 1/2 >>> a*2 1 >>> Rational(2)**50/Rational(10)**50 1/8881784197...
Pure Python rational numbers module for 2.5
[ "", "python", "rational-numbers", "" ]
I am interested if there is a port for the server implementation.
Windows Server ports: * [memcached for Win32](http://www.splinedancer.com/memcached-win32/) * [Jellycan Code - memcached](http://code.jellycan.com/memcached/) Memcached .NET Client ports: * [memcacheddotnet](http://sourceforge.net/projects/memcacheddotnet/) * [enyim.com Memcached Client](https://github.com/enyim/Eny...
There is no official support for windows builds. Check this link: <https://github.com/memcached/memcached/wiki/Install> For the clients, check this link: <https://github.com/memcached/memcached/wiki/Clients> Hope that helps.
Is there a port of memcache to .Net?
[ "", "c#", "asp.net", "windows", "memcached", "" ]
Using `MySQL`, I can do something like: ``` SELECT hobbies FROM peoples_hobbies WHERE person_id = 5; ``` **My Output:** ``` shopping fishing coding ``` but instead I just want 1 row, 1 col: **Expected Output:** ``` shopping, fishing, coding ``` The reason is that I'm selecting multiple values from multiple table...
You can use [`GROUP_CONCAT`](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat): ``` SELECT person_id, GROUP_CONCAT(hobbies SEPARATOR ', ') FROM peoples_hobbies GROUP BY person_id; ``` As Ludwig stated in [his comment,](https://stackoverflow.com/questions/276927/can-i-concatena...
Have a look at `GROUP_CONCAT` if your MySQL version (4.1) supports it. See [the documentation](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) for more details. It would look something like: ``` SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') FROM peoples_hobbies WHERE person...
Can I concatenate multiple MySQL rows into one field?
[ "", "mysql", "sql", "concatenation", "group-concat", "" ]
Is there any way I can specify a standard or custom numeric format string to always output the sign, be it +ve or -ve (although what it should do for zero, I'm not sure!)
Yes, you can. There is conditional formatting. See [Conditional formatting in MSDN](http://msdn.microsoft.com/en-us/library/0c899ak8.aspx) eg: ``` string MyString = number.ToString("+0;-#"); ``` Where each section separated by a semicolon represents positive and negative numbers or: ``` string MyString = number.To...
Beware, when using conditional formatting the negative value doesn't automatically get a sign. You need to do ``` string MyString = number.ToString("+#;-#;0"); ```
Custom numeric format string to always display the sign
[ "", "c#", ".net", "formatting", "string-formatting", "" ]
I have a project built and packaged with a specific version of jsp-apiand servlet-api jar files. Now I want these jars to be loaded when deploying the web project on any application server for example tomcat, WAS, Weblogic etc. The behaviour I have seen on tomcat is that it gives messages that the packaged version of ...
1. If you have control over the server where you want to install this webapp you can replace the core jars with yours. 2. Additionally you can prepend the jars in the startup of the app server. **Update:** As for the second part, you'll need to modify the startup file of the application server it self. I don't have ...
*I've split the answer in two for clarity* Tushu, I have two news for you. The good one is I've managed to replace the servlet api from 2.5 to 2.3 in my tomcat using the steps I've described you in my previous post( screeshots below ) The bad new ( and I should've guessed this before ) The tomcat won't start.That's ...
Overriding application server behaviour for loading jsp-api and servlet-api jars in a packaged web application
[ "", "java", "web-applications", "jakarta-ee", "classloader", "" ]
We have an advanced webpage (ASP.NET, C#), and a application which needs to be installed on the client computer in order to utilize the webpage to its fullest. The application is a tray app, and has primarily two tasks. Detect when certain events happen on the webserver (for instance invited to a meeting, or notify of ...
If you want to detect with javascript inside the browser, you can probably use the collection "navigator.plugins". It works with Firefox, Opera and Chrome but unfortunately not with IE. Update: In FF, Opera and Chrome you can test it easily like this: ``` if (navigator.plugins["Adobe Acrobat"]) { // do some stuff if ...
When installing your client-side app you could modify the browser configuration to include another request header in HTTP requests and then have the server code look for that header, for example as a supported mime type using the following registry key (for Internet explorer) ``` HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\...
Detect from browser if specific application is installed
[ "", "asp.net", "javascript", "ajax", "web-applications", "" ]
we're dealing with a very slow update statement in an Oracle project. Here's a little script to replciate the issue: ``` drop table j_test; CREATE TABLE J_TEST ( ID NUMBER(10) PRIMARY KEY, C1 VARCHAR2(50 BYTE), C2 VARCHAR2(250 BYTE), C3 NUMBER(5), C4 NUMBER(10) ); -- just insert a bunch of rows i...
One possible cause of poor performance is row chaining. All your rows initially have columns C3 and C4 null, and then you update them all to have a value. The new data won't fit into the existing blocks, so Oracle has to chain the rows to new blocks. If you know in advance that you will be doing this you can pre-alloc...
Try this: ``` insert into j_test (id, C3, C4) select rownum, 1, 'NEU' from <dummy_table> where rownum < 100000; ```
Slow Update Statement
[ "", "sql", "oracle", "" ]
I have the following Python code: ``` import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] ``` which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, ...
See [this question](https://stackoverflow.com/questions/15798/how-do-i-validate-xml-against-a-dtd-file-in-python) - the accepted answer is to use [lxml validation](http://codespeak.net/lxml/validation.html).
Just by way of explanation: Python xml.dom.minidom and xml.sax use the expat parser by default, which is a non-validating parser. It may read the DTD in order to do entity replacement, but it won't validate against the DTD. [gimel](/users/6491/gimel) and [Tim](/users/20670/tim) recommend lxml, which is a nicely python...
Python xml.dom.minidom.parse() function ignores DTDs
[ "", "python", "xml", "" ]
I have two tables. Club and Coach. Between them is 0,1 - 0,1 relationship (coach can have zero or one club. club can have zero or one coach). When I want to change the coach of the given club, i have to update the club table. So i have to change idCoach of that club. Lets consider a new coach (the newly assigned coach ...
I suggest this might not be an appropriate use for triggers, which are very difficult to debug, and often surprise people by the way they don't support single-record operations as you would expect. Break it down into simple SQL statements and wrap a transaction around it instead.
Is it OK to have a 3rd table, which can hold relations? I think that will be a simple approach to work with. Just delete the record from the new table, if the coach resigns from a club. Insert a record, for a coach joining a new club. Hope that helps.
MS SQL Trigger update call dead lock?
[ "", "sql", "sql-server", "triggers", "" ]
I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. What I think I want the program to do is to find the size of a file, divide that number i...
Check out `os.stat()` for file size and `file.readlines([sizehint])`. Those two functions should be all you need for the reading part, and hopefully you know how to do the writing :)
linux has a split command ``` split -l 100000 file.txt ``` would split into files of equal 100,000 line size
How do I split a huge text file in python
[ "", "python", "text-files", "" ]
I had telephone interview question yesterday. The interviewer asked me if I had faced any challenging debugging issue? I told him I once faced a problem debugging someone else's code and it took me 3-4 days to solve that. I used Windbg, symbols and a crash dump to solve the problem. Now is this enough to tell? What is...
The general rule for interviews is to use the STAR model (my co-op coordinator is going to be proud here...): **S** - Describe the situation you were in **T** - Explain the task, providing enough info so that the interviewer understands the problem. **A** - Describe the action you took to solve the problem. **R*...
One of the main reason deadlock can occur in a multi-threaded application is circular wait where two different threads holding two resources and each of them wait for the other resource. The other conditions deadlock to occur is no preemption, hold-and-wait and mutual-exclusion. The best way to avoid deadlock is to ma...
Interview question about debugging, multithreading
[ "", "c++", "debugging", "" ]
There are a few things that I almost always do when I put a class together in C++. 1) Virtual Destructor 2) Copy constructor and assignment operator (I either implement them in terms of a private function called Copy(), or declare them private and thus explicitly disallow the compiler to auto generate them). What thi...
I find turning on the gcc flags `-Wall`, `-Werror`, and (this is the fun one) `-Weffc++` help catch a lot of potential problems. From the gcc man page: > ``` > -Weffc++ (C++ only) > Warn about violations of the following style guidelines from Scott > Meyers’ Effective C++ book: > > · Item 11: De...
Oddly, most of the suggestions here are things I specifically don't do. * I don't make dtors virtual unless I am designing it specifically to be inherited. It adds a lot of overhead and prevents automatic inlining, which is bad since most dtors are empty anyways (and few classes benefit from inheritance) * I don't mak...
In C++, what do you do nearly all the time?
[ "", "c++", "" ]
I'm writing a basic sprite engine for my own amusement and to get better aquainted with Java's 2d API. Currently I am making use of large numbers of separate .png files with transparent backgrounds to represent the various sprites and different frames of animation that I need. Most 'real world' game development project...
I currently use XML files generated by a simple sprite editor that store the sprite as a collection of (optionally animated) poses, which are in turn a collection of frames or cells. Frames store per-frame information like the x and y offset of the frame in sheet, cell width and height, and any transformation (resize/r...
Make your sprite sheet knowing the size and number of each sequence. Grab a buffered image of your sheet and use something like this: ``` currentframe=spritesheet.getSubimage(x, y, w, h); ``` Your x and y will change based on the frame you are on. Keep the width and height the same to make things easy on yourself. ...
What's the best way of reading a sprite sheet in Java?
[ "", "java", "io", "2d", "sprite-sheet", "" ]
I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page: > Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++. Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers? ...
There is an interesting thread on [Lambda the Ultimate](http://lambda-the-ultimate.org/) that discusses the [LALR grammar for C++](http://lambda-the-ultimate.org/node/2158#comment-27800). It includes a link to a [PhD thesis](http://www.computing.surrey.ac.uk/research/dsrg/fog/FogThesis.pdf) that includes a discussion ...
LR parsers can't handle ambiguous grammar rules, by design. (Made the theory easier back in the 1970s when the ideas were being worked out). C and C++ both allow the following statement: ``` x * y ; ``` It has two different parses: 1. It can be the declaration of y, as pointer to type x 2. It can be a multiply of x...
Why can't C++ be parsed with a LR(1) parser?
[ "", "c++", "parsing", "grammar", "formal-languages", "" ]
I'm reviewing some code for a friend and say that he was using a return statement inside of a try-finally block. Does the code in the Finally section still fire even though the rest of the try block doesn't? Example: ``` public bool someMethod() { try { return true; throw new Exception("test"); // doesn't...
Simple answer: Yes.
Normally, yes. The finally section is guaranteed to execute whatever happens including exceptions or return statement. An exception to this rule is an asynchronous exception happening on the thread (`OutOfMemoryException`, `StackOverflowException`). To learn more about async exceptions and reliable code in that situat...
Will code in a Finally statement fire if I return a value in a Try block?
[ "", "c#", ".net", "exception", "try-catch", "" ]
I'm working on an AJAXy project (Dojo and Rails, if the particulars matter). There are several places where the user should be able to sort, group, and filter results. There are also places where a user fills out a short form and the resulting item gets added to a list on the same page. The non-AJAXy implementation wo...
Number 5 in my [list of five AJAX styles](https://stackoverflow.com/questions/429005/how-dangerous-is-it-send-html-in-ajax-as-opposed-to-sending-json-and-building-the#429072) tends to work pretty well.
Well, every time you generate HTML snippets on the client and on the server you may end up with duplicated code. There is no good way around it generally. But you can do two things: 1. Generate everything on the server. Use [AHAH](http://en.wikipedia.org/wiki/Ahah) when you need to generate HTML snippets dynamically. ...
How do I reduce view duplication between client and server?
[ "", "javascript", "ruby-on-rails", "ajax", "model-view-controller", "" ]
In C# is it guaranteed that expressions are evaluated left to right? For example: ``` myClass = GetClass(); if (myClass == null || myClass.Property > 0) continue; ``` Are there any languages that do not comply?
You actually refer to a language feature called "short-circuiting logical expressions": What this means is this: When the outcome of a logical expression cannot change anymore, e.g. when it is clear that the expression will evaluate to "true" or "false" no matter what, remaining parts of the expression will not be eva...
Short-circuiting is described in section 7.11 of the C# 3.0 spec: > The operation x || y corresponds to > the operation x | y, except that y is > evaluated only if x is not true. So yes, you're fine. As for other languages - I never like to speak for *all* languages. In VB.NET, you can use OrElse and AndAlso which a...
Left to right expression evaluation
[ "", "c#", "language-agnostic", "compiler-construction", "expression", "expression-evaluation", "" ]
I want to develop Java apps, real quick, what IDE should I choose?
I think CodeGear [jbuilder](http://www.codegear.com/products/jbuilder) is a very good start.
[IntelliJ IDEA.](http://www.jetbrains.com/idea/) from JetBrains.
Which Java IDE is the most RAD in a Delphi-like way?
[ "", "java", "ide", "rad", "" ]
I need to be able to determine when `ContainsFocus` changes on a `Control` (specifically a windows form). Overriding `OnGotFocus` is not the answer. When I bring the form to the foreground, `ContainsFocus` is true and `Focused` is false. So is there an `OnGotFocus` equivalent for `ContainsFocus`? Or any other way?
Note: GotFocus events of the child controls are fired if you have a child control. Otherwise OnGotFocus of the form is called. If I understood the question correctly, then this should work: ``` bool lastNotificationWasGotFocus = false; protected override void OnControlAdded(ControlEventArgs e) { ...
One way to solve this is to use a Timer. It's definitely brute force, but it gets the job done: ``` private Timer m_checkContainsFocusTimer = new Timer(); private bool m_containsFocus = true; m_checkContainsFocusTimer.Interval = 1000; // every second is good enough m_checkContainsFocusTimer.Tick += new EventHandler(C...
Is there a way to catch when ContainsFocus changes?
[ "", "c#", "winforms", "events", "" ]
I am curious to know how the Loader maps DLL into Process Address Space. How does the loader do that magic?
What level of detail are you looking for? On the basic level, all dynamic linkers work pretty much the same way: 1. Dynamic libraries are compiled to relocatable code (using relative jumps instead of absolute, for example). 2. The linker finds an appropriately-sized empty space in the memory map of the application, an...
Okay, I'm assuming the Windows side of things here. What happens when you load a PE file is that the loader (contained in NTDLL) will do the following: 1. Locate each of the DLLs using the DLL search semantics (system and patch-level specific), well-known DLLs are kind of exempt from this 2. Map the file into memory (...
How loader maps DLL into Process Address Space
[ "", "c++", "c", "dll", "loader", "" ]
Check out this test: ``` [TestFixture] public class Quick_test { [Test] public void Test() { Assert.AreEqual(0, GetByYield().Count()); Assert.AreEqual(0, GetByEnumerable().Count()); } private IEnumerable<string> GetByYield() { yield break; } private IEnumerable<string> GetBy...
I would prefer any method that delivers the clearest meaning to the developer. Personally, I don't even know what the ***yield break;*** line is does, so returning 'Enumerable.Empty();` would be preferred in any of my code bases.
[Enumerable.Empty](http://msdn.microsoft.com/en-us/library/bb341042.aspx) : the documentation claims that it "caches an empty sequence". Reflector confirms. If caching behavior matters to you, there's one advantage for Enumerable.Empty
Returning empty collections
[ "", "c#", "linq", "" ]
I need to watch when certain processes are started or stopped on a Windows machine. I'm currently tapped into the WMI system and querying it every 5 seconds, but this causes a CPU spike every 5 seconds because WMI is WMI. Is there a better way of doing this? I could just make a list of running processes and attach an E...
This is not exactly how you'd do it in the real world but should help. This seems not to drive my CPU much at all. ``` static void Main(string[] args) { // Getting all instances of notepad // (this is only done once here so start up some notepad instances first) // you may want use GetP...
If you are only looking for PID/Name of your processes, you may instead wish to pick up on Win32\_ProcessTrace events, using a WQL query such as "SELECT \* FROM Win32\_ProcessTrace WHERE TargetInstance.ProcessName = 'name'" **if applicable\***. The pitfall of using "SELECT \* FROM \_\_InstanceModificationEvent WITHIN ...
WMI Process Watching uses too much CPU! Any better method?
[ "", "c#", "wmi", "wmi-query", "" ]
Is there an easy way to parse the user's HTTP\_ACCEPT\_LANGUAGE and set the locale in PHP? I know the Zend framework has a method to do this, but I'd rather not install the whole framework just to use that one bit of functionality. The PEAR I18Nv2 package is in beta and hasn't been changed for almost three years, so ...
Nice solution is [on its way](http://php.net/manual/en/locale.acceptfromhttp.php). Without that you'll need to parse that header. It's a comma-separated list of semicolon-separated locales and attributes. It can look like this: ``` en_US, en;q=0.8, fr_CA;q=0.2, *;q=0.1 ``` and then try each locale until `setlocale(...
It's not as easy as it should be (in my humble opinion). First of all you have to extract the locales from the `$_SERVER['HTTP_ACCEPT_LANGUAGE']` and sort them by their `q` values. Afterwards you have to retrieve the appropriate system locale for each of the given locales, which should be no problem on a \*nix machine ...
How do I automatically set a user's locale in PHP?
[ "", "php", "internationalization", "locale", "" ]
Continuing [my investigation](https://stackoverflow.com/questions/308481/writing-the-f-recursive-folder-visitor-in-c-seq-vs-ienumerable) of expressing F# ideas in C#, I wanted a pipe forward operator. For anything wrapped in a IEnumerable, we already have it, as you can .NextFunc() to your heart's content. But for exam...
I haven't bothered with a raw pipe, but I have tried making all references into the Maybe monad: ``` public static class ReferenceExtensions { public static TOut IfNotNull<TIn, TOut>(this TIn v, Func<TIn, TOut> f) where TIn : class where TOut...
So for Piping I don't think there is expectation to check for null and not call the piped function. The function argument in many cases could easy take a null and have it handled by the function. Here is my implementation. I have `Pipe` and `PipeR`. Be forewarned, the `PipeR` is not pipe right, but just for the cases ...
Pipe forwards in C#
[ "", "c#", "f#", "functional-programming", "" ]
I'm using JPA (Hibernate's implementation) to annotate entity classes to persist to a relational database (MySQL or SQL Server). Is there an easy way to auto generate the database schema (table creation scripts) from the annotated classes? I'm still in the prototyping phase and anticipate frequent schema changes. I wo...
You can use [hbm2ddl](https://blog.eyallupu.com/2007/05/hibernates-hbm2ddl-tool.html) from Hibernate. The docs are [here](https://web.archive.org/web/20120606064202/http://docs.jboss.org/tools/2.1.0.Beta1/hibernatetools/html/ant.html#d0e2726).
**Generate create and drop script for given JPA entities** We use this code to generate the drop and create statements: Just construct this class with all entity classes and call create/dropTableScript. If needed you can use a persitence.xml and persitance unit name instead. Just say something and I post the code too...
Auto generate data schema from JPA annotated entity classes
[ "", "java", "database", "hibernate", "jpa", "jakarta-ee", "" ]
How does the SQL Server JDBC Trusted Connection Authentication work? (ie how does the trusted connection authenticate the logged in AD user in such a transparent and elegant fashion and how can I implement a similar authentication solution for my client-server applications in Java without a database connection or any u...
It depends on the client. For example if you have a Web Browser, it can use the NTLM Authentication to pass the domain authentication of your current client to the server. In this case the browser like IE or FF supports this, and you web server needs the support for NTLM. For example here for Tomcat: <http://jcifs.samb...
jTDS and Microsoft JDBC Driver both offer native Windows Authentication.
How does the SQL Server JDBC Trusted Connection Authentication work?
[ "", "java", "sql-server", "jdbc", "jna", "trustedconnection", "" ]
The number is bigger than `int` & `long` but can be accomodated in `Decimal`. But the normal `ToString` or `Convert` methods don't work on `Decimal`.
I believe this will produce the right results where it returns anything, but may reject valid integers. I dare say that can be worked around with a bit of effort though... (Oh, and it will also fail for negative numbers at the moment.) ``` static string ConvertToHex(decimal d) { int[] bits = decimal.GetBits(d); ...
Do it manually! <http://www.permadi.com/tutorial/numDecToHex/>
How can I Convert a Big decimal number to Hex in C# (Eg : 588063595292424954445828)
[ "", "c#", "decimal", "hex", "type-conversion", "" ]
I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that...
The Python convention is to name "private" functions and methods with a leading underscore. When you see a leading underscore, you know not to try and use it. Remember, [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html).
inner doesn't exist until outer makes it. You should either move inner up to a toplevel function for testability, or have the outer test test all the possible execution paths of itself and inner. Do note that the inner function isn't a simple function, it's a closure. Consider this case: ``` def outer(a): b = com...
Running unit tests on nested functions
[ "", "python", "testing", "closures", "" ]
I currently have a list view which has several rows of data and I have a contextmenustrip in C# .NET. What I am having problems with is when you click on the menu strip item I want to know which row has been selected.
To get selected rows as sindre says you do like this: ``` foreach (ListViewItem item in lvFiles.SelectedItems) { .................................... } ``` lvFiles is the ListView.
To get the selected item of list view, try this: int index = 0; if (this.myListView.SelectedItem.Count > 0) index = this.myListView.SelectedIndices[0] This will give you the index of selected item in listview. You may also refer this: <http://www.neowin.net/forum/index.php?showtopic=358458>
Finding the selected item of list view
[ "", "c#", "listview", "contextmenustrip", "" ]
I have a row of buttons, which all create a pdf file which I want to open in a new tab. This way the button page stays on top, and the pdf's open to get printed. To prevent clicking a button twice I disable the button, like this (I use python): ``` <input type='submit' value='Factureren' name='submitbutton' id='%s' on...
It is easy: a disabled submit button do not submit a form in IE. Consider to restructure your code: * Use a regular button, disable it, and call form.submit() from its handler. * Do not disable the button in its "onclick", but save it, and do it in form's onsubmit.
It is easier to do: ``` <input type='submit' value='Factureren' name='submitbutton' id='%s' onclick="this.disabled=true; this.className='button_disabled';"> % ((but_id,) *3) ``` I don't know if this solves your problem but it is what I would do in a case like this. I think you don't need "javascript:" anyway.
Disabling button with javascript: FF vs IE
[ "", "javascript", "html", "internet-explorer", "" ]
How can I read a Chinese text file using C#, my current code can't display the correct characters: ``` try { using (StreamReader sr = new StreamReader(path,System.Text.Encoding.UTF8)) { // This is an arbitrary size for this example. string c = null; while (sr.Peek() >= 0) {...
You need to use the right encoding for the file. Do you know what that encoding is? It might be UTF-16, aka Encoding.Unicode, or possibly something like Big5. Really you should try to find out for sure instead of guessing though. As leppie's answer mentioned, the problem might also be the capabilities of the console. ...
If it is simplified chinese usually it is gb2312 and for the traditionnal chinese it is usually the Big5 : ``` // gb2312 (codepage 936) : System.Text.Encoding.GetEncoding(936) // Big5 (codepage 950) : System.Text.Encoding.GetEncoding(950) ```
How to read a Chinese text file from C#?
[ "", "c#", "text-files", "" ]
I wonder if there is something like a standalone version of Visual Studio's "Immediate Window"? Sometimes I just want to test some simple stuff, like `DateTime.Parse("blah")` to see if that works. But everytime I have to create a new console application, put in my code and test it. The Immediate Window sadly only work...
Linqpad - I use it like this all the time. <http://www.linqpad.net/> Don't be misled by the name - that just describes the original motivation for it, not its functionality. Just recently he released a version with proper statement completion - that's a chargeable add-on (the core tool is free), but a minute amount o...
*C# Interactive* window and *csi.exe* REPL were added to **Visual Studio 2015 Update 1**: > # Introducing Interactive > > The Interactive Window is back! The C# Interactive Window returns in Visual Studio 2015 Update 1 along with a couple other interactive treats: > > * **C# Interactive**. The C# Interactive window is...
C# Console/CLI Interpreter?
[ "", "c#", ".net", "read-eval-print-loop", "" ]
I have a control that is basically functioning as a client-side timer countdown control. I want to fire a server-side event when the count down has reached a certain time. Does anyone have an idea how this could be done? So, when timer counts down to 0, a server-side event is fired.
You would probably want to use AJAX to make your server side call.
When you render the page create a client-side button that would do the action you want on postback. Then use [ClientScriptManager.GetPostBackEventReference](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.getpostbackeventreference.aspx) passing in the control as reference and add a client-side...
How do you raise a server-side event from javascript?
[ "", ".net", "asp.net", "javascript", "event-handling", "" ]
What is [`java.awt.Component.getName()`](http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html#getName%28%29) used for? It always seems to be `null` in the applications I build with NetBeans. I'm thinking of storing some help text per component in it -- I don't want to use the tooltip, I have another panel w...
Component.setName(..) is used in the JDK mostly by the look and feel implementation classes to set ID-like strings for each component, e.g. BasicOptionPaneUI might call it on a button component to set its name to "OptionPane.button". The getName() is used in toString() methods, when setting the names of child componen...
I haven't seen it used for anything by the framework. Its useful if you have components being passed in to a method so you can ask their name to decide how to handle them. Also, many UI testing frameworks use this to allow you to refer to the components by name in the testing scripts. I don't see any reason you can't u...
What is java.awt.Component.getName() and setName() used for?
[ "", "java", "awt", "" ]
Here's my problem: I have to call a web service with a secure header from a classic ASP page that returns a complex data type. For various reasons concerning a 3rd party tool it has to be classic ASP. We decided that I should create an external dll to do this - which I did (in c#) so it returns a dataset (Something ASP...
No, that (static/no ctor) isn't true. Quite the opposite, in fact, since COM will need to create an instance! You simply need to make the class COM visible. Mainly, this is just adding some attributes, and registering it as a COM dll (regasm). <http://msdn.microsoft.com/en-us/library/zsfww439.aspx>
Creating a class that returns a DataSet is not so difficult: ``` using System; using System.Data; using System.Runtime.InteropServices; namespace COMTest { [Guid("AC4C4347-27EA-4735-B9F2-CF672B4CBB4A")] [ComVisible(true)] public interface ICOMTest { [ComVisible(true)] DataSet GetDataSet(); ...
Converting a fairly simple C# Class library into a COM object?
[ "", "c#", "web-services", "com", "asp-classic", "" ]
I'm looking for a *free* JavaScript obfuscator. Would compression be enough? What tools would you recommend? Of course, I don't need military-style obfuscation, I need a *simple* way to prevent kiddies from stealing my javascript by looking at the source or by using something simple such as unescape(). Thanks, Tom
Your problem is that no matter how much you compress it or hide it, eventually the browser has to interpret it. The best you can do is renaming all variables to meaningless random vars, and removing all comments and whitespace. **A few good tools:** * <http://www.dev411.com/dojo/javascript_compressor/> * <http://java...
You can use /packer/ <http://dean.edwards.name/packer/>
Free JavaScript obfuscators?
[ "", "javascript", "compression", "obfuscation", "" ]
I am writing a Firefox extension. I would like to search the current webpage for a set of words, and count how many times each occurs. This activity is only performed when the user asks, but it must still happen reasonably quickly. I am currently using indexOf on the BODY tag's innerHTML element, but am finding it too...
I'm not sure if it is the fastest but the following worked pretty quickly for me. ``` var words = document.body.innerHTML.replace(/<.*?>/g,'').split(/\s+/); var i = words.length; var keywordCounts = {'keyword': 0, 'javascript': 0, 'today': 0}; var keywords = []; var keywordMatcher = ''; var word; for (word in keywordC...
I could not find hasItem, setItem or getItem in prototypes Hash like tvanfosson suggested, but used set and get and wrote a hasItem based on get. But profiling showed that it is slower to use prototypes Hash compared to javascripts native object. If you have an array with keywords, convert it to an hash object with th...
Fastest javascript page search
[ "", "javascript", "firefox", "search", "performance", "" ]
I'm astonished that the [Apache Commons Collections](http://commons.apache.org/collections/) project still hasn't got around to making their library generics-aware. I really like the features provided by this library, but the lack of support for generics is a big turn-off. There is a [Lavalabs fork of Commons Collectio...
There are contributions. Checkout the [jira](https://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&mode=hide&sorter/order=DESC&sorter/field=priority&resolution=-1&pid=12310465&fixfor=12312131)'s There is also a [JDK5 branch](http://svn.apache.org/repos/asf/commons/proper/collections/branches/collections...
Consider [Google Collections](http://code.google.com/p/google-collections/). From their [Javalobby interview](http://www.javalobby.org/articles/google-collections/): > [Google Collections is] built with Java 5 features: generics, enums, covariant return types, etc. When writing Java 5 code, you want a collections libr...
Genericized commons collection
[ "", "java", "collections", "upgrade", "apache-commons", "binary-compatibility", "" ]
I have a (varchar) field Foo which can only be specified if (bit) Bar is *not* true. I would like the textbox in which Foo is displayed to be *disabled* when Bar is true -- essentially, `FooBox.Enabled = !isBar`. I'm trying to do something like ``` FooBox.DataBindings.Add(new Binding("Enabled", source, "!isBar")); ```...
I tried doing something like this a while ago and the best I could come up with was either a) Changing the source class to also have a NotBar property and bind to that b) Make a dumb wrapper class around source that has a NotBar property and bind to that.
As far as I can tell, Databind uses reflection to find the member passed as the 3rd string argument. You cannot pass an expression there, just the member name.
How do I data bind Control.Enabled to !(field)?
[ "", "c#", "winforms", "data-binding", "" ]
I am using a specific command in in my C# code, which works well. However, it is said to misbehave in "unmanaged" code. What is managed or unmanaged code?
Here is some text from MSDN about [unmanaged code](http://msdn.microsoft.com/en-us/library/0e91td57.aspx). > Some library code needs to call into unmanaged code (for example, native code APIs, such as Win32). Because this means going outside the security perimeter for managed code, due caution is required. Here is so...
[This](http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm) is a good article about the subject. To summarize, 1. **Managed code** is not compiled to machine code but to an intermediate language which is interpreted and executed by some service on a machine an...
What is managed or unmanaged code in programming?
[ "", "c#", ".net", "unmanaged", "definition", "managed", "" ]
I'm working on something that requires traversing through the file system and for any given path, I need to know how 'deep' I am in the folder structure. Here's what I'm currently using: ``` int folderDepth = 0; string tmpPath = startPath; while (Directory.GetParent(tmpPath) != null) { folderDepth++; tmpPath...
Off the top of my head: ``` Directory.GetFullPath().Split("\\").Length; ```
I'm more than late on this but I wanted to point out Paul Sonier's answer is probably the shortest but should be: ``` Path.GetFullPath(tmpPath).Split(Path.DirectorySeparatorChar).Length; ```
C# Best way to get folder depth for a given path?
[ "", "c#", ".net", "directory", "" ]
I have created a windows installer for a windows forms app as an MSI. I have published this and put it in a zip file and sent it to the client. When they try to run the installer they get the message 'The publisher could not be verified. Are you sure you want to run this software?’ Is there a setting or something i ne...
I have spoken to some of the guys here and someone has used Orca to edit some of the msi content. Apparently before this happened the installer was fine.
Is this a certificate issue? I haven't had to do this with msi (I usually use ClickOnce, which makes this very easy), but a quick search shows things like [this](http://www.advancedinstaller.com/digital-signatures.html) or on MSDN [here](http://msdn.microsoft.com/en-us/library/aa371854(VS.85).aspx). Note that your cer...
MSI produces question for installers
[ "", "c#", "winforms", "windows-installer", "deployment", "" ]
What is the difference between using `#include<filename> and #include<filename.h`> in [C++](http://en.wikipedia.org/wiki/C%2B%2B)? Which of the two is used and why is it is used?
C++ only include-files not found in the C standard never used `filename.h` . Since the very first C++ Standard came out (1998) they have used `filename` for their own headers. Files inherited by the C Standard became `cfilename` instead of `filename.h`. The C files inherited used like `filename.h` are deprecated, but ...
The `#include <foo.h>` was common in C++ code prior to the C++ standard. The standard changed it to `#include <foo>` with everything from the header placed in the `std` namespace. (Thanks to litb for pointing out that the standard has never allowed .h headers.) There is no magic going on, the first looks for a file ca...
Difference between using #include<filename> and #include<filename.h> in C++
[ "", "c++", "include", "namespaces", "" ]
I myself am convinced that in a project I'm working on signed integers are the best choice in the majority of cases, even though the value contained within can never be negative. (Simpler reverse for loops, less chance for bugs, etc., in particular for integers which can only hold values between 0 and, say, 20, anyway....
## I made this community wiki... Please edit it. I don't agree with the advice against "int" anymore. I now see it as not bad. Yes, i agree with Richard. You should never use `'int'` as the counting variable in a loop like those. The following is how you might want to do various loops using indices (althought there is...
Don't derive publicly from STL containers. They have nonvirtual destructors which invokes undefined behaviour if anyone deletes one of your objects through a pointer-to base. If you must derive e.g. from a vector, do it privately and expose the parts you need to expose with `using` declarations. Here, I'd just use a `...
acceptable fix for majority of signed/unsigned warnings?
[ "", "c++", "stl", "coding-style", "unsigned", "" ]
I have a custom attribute which can be assigned to a class, `[FooAttribute]`. What I would like to do, from within the attribute, is determine which type has actually used me. e.g. If I have: ``` [FooAttribute] public class Bar { } ``` In the code for FooAttribute, how can I determine it was Bar class that added me? ...
First off, you might consider the existing `[DisplayName]` for keeping friendly names. As has already been covered, you simply can't get this information inside the attribute. You can look up the attribute from Bar, but in general, the only way to do it from the attribute would be to pass the type *into* the attribute ...
To elaborat. A attribute, built in or custom, is just meta data for a class, or class member, and the attribute itself nas no notation that it's being associated with something. * The type knows of it's own metadata * The meta data (in this case, the attribute) does not know to whom it belongs
How to determine the attached type from within a custom attribute?
[ "", "c#", ".net", "reflection", "custom-attributes", "" ]
I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER. Currently, I have somethin...
You could try something like this: (code off the top of my head) ``` Criteria crit = session.createCriteria(MyClass.class); crit.add(Restrictions.eq("id", myClassId)); crit.setFetchMode("myProperty", FetchMode.EAGER); MyClass myThingy = (MyClass)crit.uniqueResult(); ``` I believe that FetchMode.JOIN or FetchMode.SELE...
If you're not using Criteria there's also the `JOIN FETCH` keyword that will eagerly load the association specified by the join. ``` session.createQuery("select p from Parent p join fetch p.children c") ```
Setting FetchMode in native Hibernate
[ "", "java", "hibernate", "" ]
I wrote a PHP code like this ``` $site="http://www.google.com"; $content = file_get_content($site); echo $content; ``` But when I remove "http://" from `$site` I get the following warning: > Warning: > file\_get\_contents(www.google.com) > [function.file-get-contents]: failed > to open stream: I tried `try` and `ca...
Step 1: check the return code: `if($content === FALSE) { // handle error here... }` Step 2: suppress the warning by putting an [error control operator](http://php.net/manual/en/language.operators.errorcontrol.php) (i.e. `@`) in front of the call to *file\_get\_contents()*: `$content = @file_get_contents($site);`
You can also [set your error handler](https://www.php.net/set_error_handler) as an [anonymous function](http://php.net/manual/en/functions.anonymous.php) that calls an [Exception](http://us.php.net/manual/en/class.errorexception.php) and use a try / catch on that exception. ``` set_error_handler( function ($severi...
How can I handle the warning of file_get_contents() function in PHP?
[ "", "php", "function", "exception", "warnings", "file-get-contents", "" ]
We are using Google Charts for render the chart images, but 500 requests/day became not enough. What PHP classes/frameworks are worth looking at?
[JpGraph](http://jpgraph.net/) and [GraPHPite](http://graphpite.sourceforge.net/) are the most developed open-source packages available. I recommend GraPHPite in particular, it has a somewhat better API and produces better looking graphs. **Edit:** I recently developed a small [graphing library](http://www.binpress.co...
The Google Chart API no longer has a 500 request/day limit. I recall this changed a couple of months ago.
Rendering eye-candy bar charts with PHP: tools / best practices
[ "", "php", "charts", "" ]
What is the 'correct' way to store a native pointer inside a Java object? I could treat the pointer as a Java `int`, if I happen to know that native pointers are <= 32 bits in size, or a Java `long` if I happen to know that native pointers are <= 64 bits in size. But is there a better or cleaner way to do this? **Edi...
IIRC, both `java.util.zip` and `java.nio` just use `long`.
`java.nio.DirectByteBuffer` does what you want. Internally it uses a `private long address` to store pointer value. *Dah !* Use JNI function `env->NewDirectByteBuffer((void*) data, sizeof(MyNativeStruct))` to create a DirectByteBuffer on C/C++ side and return it to Java side as a ByteBuffer. **Note:** It's your job t...
What is the 'correct' way to store a native pointer inside a Java object?
[ "", "java", "java-native-interface", "" ]
If I have a method with a parameter that's an interface, whats the fasts way to see if the interface's reference is of a specific generic type? More specifically, if I have: ``` interface IVehicle{} class Car<T> : IVehicle {} CheckType(IVehicle param) { // How do I check that param is Car<int>? } ``` I'm also ...
To check if param is a `Car<int>` you can use "is" and "as" as normal: ``` CheckType(IVehicle param) { Car<int> car = param as Car<int>; if (car != null) { ... } } ```
Or, you can just do: ``` if(param is Car<int>) { // Hey, I'm a Car<int>! } ```
Whats a fast way to check that reference is a specific generic type?
[ "", "c#", "reflection", "" ]
In a html page we use the head tag to add reference to our external .js files .. we can also include script tags in the body .. But how do we include our external .js file in a web user control? After little googling I got this. It works but is this the only way? ``` ScriptManager.RegisterStartupScript(this.Page, Pag...
You can also use ``` Page.ClientScript.RegisterClientScriptInclude("key", "path/to/script.js"); ``` That's the way I always do it anyway
> Yes this works too .. but why does all > the script gets dumped in the body and > not in the head?? There's a potential workaround for that [here](http://www.codeproject.com/KB/aspnet/scriptregister.aspx)
External JS file in web user control?
[ "", "asp.net", "javascript", "webusercontrol", "" ]
I am extremely new to python, having started to learn it less than a month ago, but experienced with some other programming languages (primarily C# and SQL). But now that Python 3.0 has been released and is not backwards compatible, what would be the advantages and disadvantages of deciding to focus on Python 3.0 or Py...
I would say begin with 2.6 since the vast, vast majority of documentation regarding Python will be applicable to 2.6 as well most open source projects you may want to contribute to will be in 2.6 for awhile. Then, once you have a good foundation in 2.6, you can learn 3.0. That way you can kind of appreciate how the lan...
Go with 2.6 since that's what most libraries(pygame, wxpython, django, etc) target. The differences in 3.0 aren't that huge, so transitioning to it later shouldn't be much of a problem.
Python Version for a Newbie
[ "", "python", "python-3.x", "" ]
Here's my problem.I have 2 xmlfiles with identical structure, with the second xml containing only few node compared to first. File1 ``` <root> <alpha>111</alpha> <beta>22</beta> <gamma></gamma> <delta></delta> </root> ``` **File2** ``` <root> <beta>XX</beta> <delta>XX</delta> </root> `...
Here is a little bit simpler and more efficient solution that that proposed by Alastair (see my comment to his solution). This transformation: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:variable name="vFile2"...
In XSLT you can use the `document()` function to retrieve nodes from File2 if you encounter an empty node in File1. Something like: ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="root/*[.='']"> <xsl:variable name="f...
Comparing 2 XML docs and applying the changes to source document
[ "", "c#", "xml", "xslt", "merge", "" ]
I'm working on a site with multiple subdomains, some of which should get their own session. I think I've got it worked out, but have noticed something about cookie handling that I don't understand. I don't see anything in the docs that explains it, so thought I would see if anyone here has some light to shed on the qu...
PHP's cookie functions automatically prefix the $domain with a dot. If you don't want this behavior you could use the [header](https://www.php.net/header) function. For example: ``` header("Set-Cookie: cookiename=cookievalue; expires=Tue, 06-Jan-2009 23:39:49 GMT; path=/; domain=subdomain.example.net"); ```
If you run your PHP script under "<http://subdomain.example.net>", **don't use the domain parameter**: ``` setcookie('cookiename','cookievalue',time()+(3600*24),'/'); ``` You will get a cookie with "subdomain.example.net" (and not ".subdomain.example.net")
PHP: Cookie domain / subdomain control
[ "", "php", "cookies", "" ]
I'm completely new at C# and NUnit. In Boost.Test there is a family of `BOOST_*_THROW` macros. In Python's test module there is `TestCase.assertRaises` method. As far as I understand it, in C# with NUnit (2.4.8) the only method of doing exception test is to use `ExpectedExceptionAttribute`. Why should I prefer `Expe...
I'm surprised I haven't seen this pattern mentioned yet. David Arno's is very similar, but I prefer the simplicity of this: ``` try { obj.SetValueAt(-1, "foo"); Assert.Fail("Expected exception"); } catch (IndexOutOfRangeException) { // Expected } Assert.IsTrue(obj.IsValid()); ```
If you can use NUnit 2.5 there's some nice [helpers](http://nunit.com/blogs/?p=63) there. ``` Assert.That( delegate { ... }, Throws.Exception<ArgumentException>()) ```
Is NUnit's ExpectedExceptionAttribute only way to test if something raises an exception?
[ "", "c#", "exception", "nunit", "" ]
Is it possible to write a PL/SQL query to identify a complete list of a stored procedures dependencies? I'm only interested in identifying other stored procedures and I'd prefer not to limit the depth of nesting that it gets too either. For example, if A calls B, which calls C, which calls D, I'd want B, C and D report...
On [this page](http://www.oracle.com/technology/oramag/code/tips2004/091304.html), you will find the following query which uses the [PUBLIC\_DEPENDENCY](http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_5132.htm#REFRN29106) dictionary table: ``` SELECT lvl , u.object_id , u.object_typ...
I agree with EddieAwad. Its valuable to point out that Oracle only tracks the dependencies down to the object level. If you have your stored procedures in a package you can only track the dependencies if the package, not the individual functions/procedures within the package. If you're looking to track intra-package ...
How do you programatically identify a stored procedure's dependencies?
[ "", "sql", "oracle", "stored-procedures", "plsql", "oracle10g", "" ]
I am sure making a silly mistake but I can't figure what: In SQL Server 2005 I am trying select all customers except those who have made a reservation before 2 AM. When I run this query: ``` SELECT idCustomer FROM reservations WHERE idCustomer NOT IN (SELECT distinct idCustomer FROM reservations WHERE DATEPA...
``` SELECT distinct idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2 and idCustomer is not null ``` Make sure your list parameter does not contain null values. Here's an explanation: ``` WHERE field1 NOT IN (1, 2, 3, null) ``` is the same as: ``` WHERE NOT (field1 = 1 OR field1 = 2 OR field1 =...
It's always dangerous to have `NULL` in the `IN` list - it often behaves as expected for the `IN` but not for the `NOT IN`: ``` IF 1 NOT IN (1, 2, 3, NULL) PRINT '1 NOT IN (1, 2, 3, NULL)' IF 1 NOT IN (2, 3, NULL) PRINT '1 NOT IN (2, 3, NULL)' IF 1 NOT IN (2, 3) PRINT '1 NOT IN (2, 3)' -- Prints IF 1 IN (1, 2, 3, NULL...
SQL query question: SELECT ... NOT IN
[ "", "sql", "sql-server", "" ]
**Duplicate of:** [Use javascript to inject script references as needed?](https://stackoverflow.com/questions/203113/use-javascript-to-inject-script-references-as-needed) Javascript doesn't have any directive to "include" or "import" another js file. This means that if `script1.js` uses functions/objects defined in `s...
Use dynamic includes: [Use javascript to inject script references as needed?](https://stackoverflow.com/questions/203113/use-javascript-to-inject-script-references-as-needed)
Scriptaculous (and probably other frameworks) handle this by writing script tags for the included files to the document when they are loaded. Below is the relevant bit from the scriptaculous.js file that allows loading the other files in the framework. ``` var Scriptaculous = { Version: '1.8.2', require: functi...
javascript "include" strategies
[ "", "javascript", "" ]
In the past I wrote most of my unit tests using C# even when the actual software development was in another .NET language (VB.NET, C++.NET etc.) but I could use VB to get the same results. I guess the only reason I use C# is because most of the examples in the internet are written in C#. I you use unit tests as part o...
You should use what ever language is comfortable for your dev team. I don't see what you would write your unit tests in a language other than the language that the rest of the project is written in as it would have the possibility to cause confusion, or require devs know two different languages to work on the project....
C# because that is what all new code base is being written in. I would say it largely depends on what the companies preferred language is. If possible I think it best to fix on one if possible and this would also be what tests are written in too. And if only a few write in C++ then keep the more common languages still ...
What .NET language you use to write Unit Tests?
[ "", "c#", ".net", "unit-testing", "" ]
I want to make a transparent dialog. I capture the OnCtlColor message in a CDialog derived class...this is the code: ``` HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if(bSetBkTransparent_) { pDC->SetBkMode(TRANSPARENT); ...
You have two options. You can not use Common Controls v6 (the XP-Styled controls), which will make your app lose the fanciness of newer windows versions. However IIRC the groupbox will respect the CTLCOLOR issue. If you are not using that anyway, and it is still not respecting your color, then you only have one option...
Simply set the WS\_EX\_TRANSPARENT extended window style for the group box.
How to make the group-box text background transparent
[ "", "c++", "visual-studio-2005", "mfc", "" ]
I want to display from cache for a long time and I want a slightly different behavior on page render vs loading the page from cache. Is there an easy way I can determine this with JavaScript?
One way you could do it is to include the time the page was generated in the page and then use some javascript to compare the local time to the time the page was generated. If the time is different by a threshold then the page has come from a cache. The problem with that is if the client machine has its time set incorr...
I started with the answer "Daniel" gave above but I fear that over a slow connection I could run into some latency issues. Here is the solution that ultimately worked for me. On the server side I add a cookie refCount and set it's value to 0. On document load in javascript I first check refCount and then increment it....
How can I use JavaScript to detect if I am on a cached page
[ "", "javascript", "" ]
Could anyone suggest a good packet sniffer class for c++? Looking for a easy insertable class I can use in my c++ program, nothing complicated.
You will never be able to intercept network traffic just by inserting a class into your project. Packet capture functionality requires kernel mode support, hence you will at the very least need to have your application require or install libpcap/WinPcap, as Will Dean pointed out. Most modern Unix-like distributions in...
You'll need to say something about your platform, as this is a platform rather than a language thing. But assuming you're on something common, look into pcap or winpcap.
Could anyone suggest a good packet sniffer class for c++?
[ "", "c++", "packet-capture", "winpcap", "sniffing", "" ]
What is the best design decision for a 'top-level' class to attach to an event to a class that may be '5+ layers down in the callstack? For example, perhaps the MainForm has spawned an object, and that object has spawned a callstack of several other object calls. The most obvious way would be to chain the event up the...
If your application isn't based on Composite UI Application Blocks, the easiest solution is to put a "listener" class between Main form and your other components which both classes can easily access. Conceptually, the classes are laid out as follows: ``` ---------- ---------------- | MainForm | ...
My initial intention would be to try and avoid that, so that an object's scope has obvious boundaries. In the particular case of Forms, I would attempt to have the child's parent form manage all required communications withs its ancestors. Can you be more specific about your case?
Best way to attach to events far down in the callstack in C#?
[ "", "c#", "events", "" ]
I have pretty much finished my first working Symbian application, but in my hastened learning have paid little attention to memory management and pushing to and cleaning up the stack? Could somebody please point me in the direction of some of the best practises to use here, and maybe some of the best leak detection/me...
I have in the past used [HookLogger from Symbian](http://www.newlc.com/Hooklogger-Tracking-leaked-heap.html) to trace and investigate memory leaks. It is not the best, but it sure does help. Also, the heap markers raise ALLOC panics in case of memory leaks whenever your exit your application. The information those pani...
Things stored on the stack do not need to be stored on the cleanup stack (unless they need special handling (R Classes etc, see below) ) The cleanup stack is for deleting objects when a leave (think exception) occurs, which would otherwise leak memory. The actual use of the cleanup stack is through the static functio...
Memory management practices and tools for Symbian C++
[ "", "c++", "memory-management", "symbian", "s60", "" ]
I have a question about using `new[]`. Imagine this: ``` Object.SomeProperty = new[] {"string1", "string2"}; ``` Where SomeProperty expects an array of strings. I know this code snippet will work. But i want to know what it does under the hood. Does `new[]` makes an instance of the class `object` and in `SomeProper...
Okay, there's still a *little* bit of confusion here. The inference that's going on has nothing to with the type of Object.SomeProperty, but everything to do with the types of the expressions in the array initializer. In other words, you could do: ``` object o = new[] { "string1", "string2" }; ``` and o would still ...
This is just syntactical sugar. The compiler will infer the type actually necessary here and create code that is equivalent to the explicit construct: ``` Object.SomeProperty = new string[] {"string1", "string2"}; ``` There's no such thing as `new[]` that gets executed at runtime.
C# Using new[]
[ "", "c#", "new-operator", "" ]
I get an error when I compile this code: ``` using System; public struct Vector2 { public event EventHandler trigger; public float X; public float Y; public Vector2 func() { Vector2 vector; vector.X = 1; vector.Y = 2; return vector; // error CS0165: Use of unassi...
In C# you still need to 'new' a struct to call a constructor unless you are initializing **all** the fields. You left EventHandler member 'trigger' unassigned. Try either assigning to 'trigger' or using: ``` Vector2 vector = new Vector2() ``` The new object is **not** allocated on the heap, it is still allocated on ...
Others have explained ways round this, but I think it's worth mentioning the other big, big problem with your code: you have a mutable struct. Those are pretty much *always* a bad idea. This is bound to be just the first of many issues you'll run into if you keep it that way. I *strongly* recommend that you either mak...
Why do I get this error creating & returning a new struct?
[ "", "c#", "reference", "events", "struct", "compiler-errors", "" ]
this is the scenario: multiple web systems (mostly lampp/wampp) exist, most of them with separate login information, (some share it). We're considering the benefits/disadvantages of unifying them somehow, or at least making handling the user administration parts easier. Due to the nature of some systems (its a mixed b...
What we did was to centralise all login details in one repository (Active Directory for us), then wrote a c# library to authenticate with wrappers for all the languages we programmed in (PHP, C, .NET, etc). and then just wrote some glue code in the appropriate place for each application. Aside from our in-house apps, w...
There is a big industry around it and it is called IAM - Identity Access Management. The IAM solutions basically do what You want - manager users, user permissions and translate their internal state to the multitude of systems. Depending on possibility of integration, You might have a "SSO" - Single Sign On for some so...
Best Way to handle/consolidate multiple Logins?
[ "", "php", "security", "authentication", "" ]