Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
My understanding of Linq to Sql is it will take my Linq statement and convert it into an equivalent SQL statement.
So
```
var products = from p in db.Products
where p.Category.CategoryName == "Beverages"
select p
```
Just turns into
```
Select * from Products where CategoryName = 'Beve... | Sprocs are another tool in the box. You might use your fancy automatically-adjusting wrench for 90% of your tasks, but you can't use that shiny thing on stripped nuts. For that a good ol' monkey wrench is your best friend. Unless you break the bolt, in which case you're stuck with assembly. | if that's all you ever did in sql, you didn't need sprocs before! | Why do I need Stored Procedures when I have LINQ to SQL | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
"stored-procedures",
""
] |
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft. I've also been reading books on OOP. I'm coding a web-based database application at work. While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project. ... | Learning about interfaces did it for me. Coming from a scripting background and switching to OO, I didn't see how creating all these classes was any more efficient. Then I read [Head First Design Patterns](http://oreilly.com/catalog/9780596007126/), and suddenly I saw the why. It's not the most detailed book, but it's ... | The majority of posters on SO are not exceptionally intelligent. There are a couple things that may skew you to think that is the case. First, only people who happen to know or think they know an answer will bother to respond. Second, incorrect/bad questions and answers are not visible. Third, it's natural that collect... | That A-Ha Moment for Understanding OO Design in C# | [
"",
"c#",
"oop",
""
] |
Ok, have a bunch of questions that I have been thinking about the past few days. Currently I have a site that is just a bunch of PHP files with MySQL statements mixed in with PHP, HTML and CSS, basically a huge mess. I have been tasked with cleaning up the site and have made for myself, the following requirements:
* T... | Here's an article about how to organize your PHP project, from Rasmus Lerdorf, the architect who created the language:
<http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html>
Despite the popularity of OO frameworks for PHP, Rasmus advocates a less OO approach. He knows more than anyone about PHP... | I highly recommend the [Smarty](http://www.smarty.net/) templating engine for all PHP projects. It gives you an easy way to separate the logic from the presentation. | PHP best design practices | [
"",
"php",
"oop",
"templates",
""
] |
The environment is plain-old win32 under C/C++ without any fancy MFC or similar mumbo-jumbo. I have a window, which has several children and grandchildren. Some children are oddly-shaped icons, and I need them to have transparent background (oddly-shaped icons). Consider a this pseudo-structure:
* Parent1
+ Child1 (... | GWES will not paint the rectangle of any child window with contents of the parent window. Ever. Period. That's by design.
You can either paint in the child rectangle in response to `WM_CTL...` in the parent, or subclass the child and override its `WM_PAINT` completely. That will be really tough for certain windows, su... | In the oddly shaped windows, how are you handling WM\_PAINT? Are you erasing the background? Maybe a better solution would be to use a non-rectangular clipping region?
EDIT
[SetWindowRgn is documented here](http://msdn.microsoft.com/en-us/library/aa930600.aspx) - I was incorrect to say "clipping region", I was really ... | How to force parent window to draw "under" children windows? | [
"",
"c++",
"c",
"user-interface",
"winapi",
"windows-mobile",
""
] |
I have a JSON result that contains numerous records. I'd like to show the first one, but have a next button to view the second, and so on. I don't want the page to refresh which is why I'm hoping a combination of JavaScript, jQuery, and even a third party AJAX library can help.
Any suggestions? | Hope this helps:
```
var noName = {
data: null
,currentIndex : 0
,init: function(data) {
this.data = data;
this.show(this.data.length - 1); // show last
}
,show: function(index) {
var jsonObj = this.data[index];
if(!jsonObj) {
alert("No more data");
... | I use jqgrid for just this purpose. Works like a charm.
<http://www.trirand.com/blog/> | Paging Through Records Using jQuery | [
"",
"javascript",
"jquery",
"ajax",
"json",
"paging",
""
] |
I have a standalone enum type defined, something like this:
```
package my.pkg.types;
public enum MyEnumType {
TYPE1,
TYPE2
}
```
Now, I want to inject a value of that type into a bean property:
```
<bean name="someName" class="my.pkg.classes">
<property name="type" value="my.pkg.types.MyEnumType.TYPE1" ... | Have you tried just "TYPE1"? I suppose Spring uses reflection to determine the type of "type" anyway, so the fully qualified name is redundant. Spring generally doesn't subscribe to redundancy! | Use the value child element instead of the value attribute and specify the Enum class name:
```
<property name="residence">
<value type="SocialSecurity$Residence">ALIEN</value>
</property>
```
The advantage of this approach over just writing `value="ALIEN"` is that it also works if Spring can't infer the actual t... | How to assign bean's property an Enum value in Spring config file? | [
"",
"java",
"spring",
""
] |
Given a function, I'm trying to find out the names of the nested functions in it (only one level deep).
A simple regex against `toString()` worked until I started using functions with comments in them. It turns out that some browsers store parts of the raw source while others reconstruct the source from what's compile... | **Cosmetic changes and bugfix**
The regular expression **must** read `\bfunction\b` to avoid false positives!
Functions defined in blocks (e.g. in the bodies of loops) will be ignored if `nested` does not evaluate to `true`.
```
function tokenize(code) {
var code = code.split(/\\./).join(''),
regex = /\b... | The academically correct way to handle this would be creating a lexer and parser for a subset of Javascript (the function definition), generated by a formal grammar (see [this link](http://en.wikipedia.org/wiki/Parsing_expression_grammar) on the subject, for example).
Take a look at [JS/CC](http://jscc.jmksf.com/)... | Extracting nested function names from a JavaScript function | [
"",
"javascript",
"regex",
"parsing",
"function",
""
] |
Currently I have my Facebook profile automatically republish blog posts from a WordPress instance.
What I would like to be able to do, however, is to also have comments posted to either the blog of Facebook show up on the other in the appropriate location.
Is there a way to do this with the Facebook API? | There's a bunch of facebook-connect enabled WordPress plugins that might help you achieve this.
Here's a couple:
* [Sociable Facebook Connect](http://www.sociable.es/facebook-connect/)
* [WP-Facebook-Connect](http://wordpress.org/extend/plugins/wp-facebookconnect/) | yoavf answer is good. A list including those plugins is maintained in Facebook's wiki:
<http://wiki.developers.facebook.com/index.php/Facebook_Connect_Plugin_Directory>
<http://dentedreality.com.au/2008/12/implementing-facebook-connect-on-wordpress-in-reality> has a novel approach that isn't on that list. | Facebook-WordPress comment/feedback integration | [
"",
"php",
"wordpress",
"facebook",
""
] |
Is `null` is a keyword in Java? | No.It is not a keyword. | Not according to the [Java Language Specification list of keywords](http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.9). On the other hand,
this doesn't compile:
```
int null = 10;
```
The [rules for identifiers](http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8) specify that:
> An... | Is null a Java keyword? | [
"",
"java",
"null",
"keyword",
""
] |
I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to `yield` these pieces ?
I would love to have a **lazy method**. | To write a lazy function, just use [`yield`](http://docs.python.org/tutorial/classes.html#generators):
```
def read_in_chunks(file_object, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = file_object.read(chunk_size)
... | `file.readlines()` takes in an optional size argument which approximates the number of lines read in the lines returned.
```
bigfile = open('bigfilename','r')
tmp_lines = bigfile.readlines(BUF_SIZE)
while tmp_lines:
process([line for line in tmp_lines])
tmp_lines = bigfile.readlines(BUF_SIZE)
``` | Lazy Method for Reading Big File in Python? | [
"",
"python",
"file-io",
"generator",
""
] |
I was thinking the other day on normalization, and it occurred to me, I cannot think of a time where there should be a 1:1 relationship in a database.
* `Name:SSN`? I'd have them in the same table.
* `PersonID:AddressID`? Again, same table.
I can come up with a zillion examples of 1:many or many:many (with appropriat... | A 1:1 relationship typically indicates that you have partitioned a larger entity for some reason. Often it is because of performance reasons in the physical schema, but it can happen in the logic side as well if a large chunk of the data is expected to be "unknown" at the same time (in which case you have a 1:0 or 1:1,... | One reason is database efficiency. Having a 1:1 relationship allows you to split up the fields which will be affected during a row/table lock. If table A has a ton of updates and table b has a ton of reads (or has a ton of updates from another application), then table A's locking won't affect what's going on in table B... | Is there ever a time where using a database 1:1 relationship makes sense? | [
"",
"sql",
"database-design",
"one-to-one",
"database-normalization",
""
] |
I am new to ADO.net. I actually created a sample database and a sample stored procedure. I am very new to this concept. I am not sure of how to make the connection to the database from a C# windows application. Please guide me with some help or sample to do the same. | Something like this... (assuming you'll be passing in a Person object)
```
public int Insert(Person person)
{
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand dCmd = new SqlCommand("InsertData", conn);
dCmd.CommandType = CommandType.StoredProcedure;
try
{
dCmd.Parameters.AddWithValue("@firstNam... | It sounds like you are looking for a tutorial on ADO.NET.
[Here is one about straight ADO.NET.](http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx)
[Here is another one about LINQ to SQL.](http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx) | How to run a sp from a C# code? | [
"",
"c#",
"ado.net",
"odbc",
""
] |
I have a simple HTML (as HTA) application that shows strange behavior on Windows XP x64 machine. I getting periodically (not every time) error message "Access is denied." when I start the application. The same application on Windows XP 32bit runs just fine...
Does somebody has any idea or explanation?
Error message:
... | Try adding a try catch around the startup code
```
try
{
window.resizeTo(500, 300);
} catch(e) { }
```
Alternatively try setTimeout:-
```
setTimeout(function() {
window.resizeTo(500, 300);
}, 100);
``` | Just a quick word for anyone who passes here I've run into a similar problem (mine is when the document is already loaded) and it is due to the browser not being ready to perform the resize/move actions whether it is due to not finishing loading or (like in my case) when it is still handling a previous resize request. | "Access is denied" by executing .hta file with JScript on Windows XP x64 | [
"",
"javascript",
"html",
"windows",
"scripting",
"64-bit",
""
] |
Looking to dabble with GAE and python, and I'd like to know what are some of the best tools for this - thanks! | I would spend the time and learn something like ***emacs***. The learning curve is a bit higher, but once you get used to it, you can develop from any terminal. It has fantastic support for python and many other libraries.
You have to remember that Python is a dynamically typed language so the traditional IDE is not r... | Netbeans has some very nice tools for Python development | Best opensource IDE for building applications on Google App Engine? | [
"",
"python",
"google-app-engine",
"ide",
""
] |
I've inherited a (Microsoft?) SQL database that wasn't very pristine in its original state. There are still some very strange things in it that I'm trying to fix - one of them is inconsistent ID entries.
In the accounts table, each entry has a number called accountID, which is referenced in several other tables (notes... | For surrogate keys, they are meant to be meaningless, so unless you actually had a database integrity issue (like there were no foreign key contraints properly defined) or your identity was approaching the maximum for its datatype, I would leave them alone and go after some other low hanging fruit that would have more ... | In this instance, it sounds like "why" is a better question than "how". The OP notes that there is a strange problem that needs to be fixed but doesn't say why it is a problem. Is it causing problems? What positive impact would changing these numbers have? Unless you originally programmed the system and understand prec... | Fixing DB Inconsistencies - ID Fields | [
"",
"sql",
"sql-server",
"database",
"coldfusion",
""
] |
I have a data object with three fields, A, B and C. The problem is that the user can set any of them because:
A \* B = C
So if a user starts off by setting A & B, C will be calculated. but then if a user set C, A gets recalculated, so there is an implicit anchoring that is happening based off the last field that the ... | So your rules are:
```
A = C / B
B = C / A
C = A * B
```
What you'd need to do is remember the last **two** fields that the user entered, and from that, calculate the third. Therefore if they entered A and then B, then you calculate C. If they then change C, then recalculate A, and so on.
If you want to code it with... | You state that your properties have the relationship "A \* B = C". So, your class should express this. A and B are independent variables, so they have simple setters and getters that merely get and set a filed. C is a Dependant variable and so it should only have a getter and perform the calculation based on A and B:
... | 3 way calculation | [
"",
"c#",
""
] |
We have 2 tables called **TableToUpdate** and **Dates**.
We need to update **TableToUpdate**'s EndTimeKey column by looking from other table **Dates**. We run sql below to do this, but it takes to long to finish.
Table **TableToUpdate** has 6M records.
Table **Dates** has 5000 records.
How can we optimize it ?
Thank... | You are updating potentially 6 million records, this is not going to be terribly speedy in any event. However, look at your execution plan and see if it using indexes.
Also run this in batches, that is generally faster when updating large numbers of records. Do the update during off hours when there is little load on ... | With this volume of data you might be best creating a SELECT query which produces a resultset, complete with updated values, as you would like to see the new table. Next, SELECT these into new table (perhaps 'NewTableToUpdate') , either by creating a the table and using INSERT INTO or by changing your SELECT adding an ... | Optimize sql update | [
"",
"sql",
"sql-server",
"performance",
"sql-update",
""
] |
We have a warehouse database that contains a year of data up to now. I want to create report database that represents the last 3 months of data for reporting purposes. I want to be able to keep the two databases in sync. Right now, every 10 minutes I execute a package that will grab the most recent rows from the wareho... | If you are using SQL 2000 or below, replication is your best bet. Since you are doing this every ten minutes, you should definitely look at transactional replication.
If you are using SQL 2005 or greater, you have more options available to you. Database snapshots, log shipping, and mirroring as SQLMenace suggested abo... | look into replication, mirroring or log shipping | SQL Server - Syncing two database | [
"",
"sql",
"sql-server",
"database",
"database-design",
""
] |
I'm using jQuery with the validators plugin. I would like to replace the "required" validator with one of my own. This is easy:
```
jQuery.validator.addMethod("required", function(value, element, param) {
return myRequired(value, element, param);
}, jQuery.validator.messages.required);
```
So far, so good. This w... | > Storing a reference to the function
> externally before calling addMethod
> and calling the default validator via
> that reference makes no difference.
That's exactly what *should work*.
```
jQuery.validator.methods.oldRequired = jQuery.validator.methods.required;
jQuery.validator.addMethod("required", function(va... | ```
Function.prototype.clone = function() {
var fct = this;
var clone = function() {
return fct.apply(this, arguments);
};
clone.prototype = fct.prototype;
for (property in fct) {
if (fct.hasOwnProperty(property) && property !== 'prototype') {
clone[property] = fct[proper... | Can I copy/clone a function in JavaScript? | [
"",
"javascript",
"jquery",
"validation",
"jquery-validate",
""
] |
I'm writing a Swing application, and further to [my previous question](https://stackoverflow.com/questions/496233/what-are-your-best-swing-design-patterns-and-tips), have settled on using the [Model-View-Presenter](http://en.wikipedia.org/wiki/Model_View_Presenter) pattern to separate the user interface from the busine... | Although it is not uncommon to have "nested" design patterns it is not necessary in your case. Drawing on the other answers:
**Model**
- Contains all the real data, variables, objects
- knows how to set its stored data values to the new values
- responds to orders (method calls)
- has method setPreferences... | My advice would be to think about what these 'preferences' fundamentally are. Are they part of the underlying business logic? If so then they should be part of the model structre. Are they specifying the user's preferred way of interacting with the business data? Then they should be part of the view. That may seem theo... | Applying the MVP pattern to JDialogs | [
"",
"java",
"swing",
"design-patterns",
"mvp",
""
] |
[This question](https://stackoverflow.com/questions/352130/sql-reporting-services-restrict-export-formats) asks how to restrict for a whole server. I just want to do so for a single report. I found a code snippet but it doesn't provide any clues on how to implement:
```
foreach (RenderingExtension extension in this.r... | Incidentally I found [this blog entry](http://mikemason.ca/blog/?p=4) which clarifies the above code a little. Turns out we're talking about using a reportviewer component to limit the export options. Apparently this requires a dirty, dirty hack and besides it's not how we want to run our reporting function.
So unless... | Does it matter?
Once they've downloaded the data and taken it offsite, you've lost it anyway. | How to restrict download options on a single report in SSRS? | [
"",
"c#",
"reporting-services",
""
] |
I have the following interface:
```
public interface Result<T extends Serializable> extends Serializable{
T getResult();
}
```
With that interface, I can not define a variable of type
```
Result<List<Integer>>
```
because List is not serializable.
However, if I change the interface to this:
```
public interfa... | You need to declare your variable type as `Result<? extends List<Integer>>`.
The type checking knows that `List` isn't `serializable`, but a subtype of `List` can be `serializable`.
Here is some sample code. The interface implementation was just done with anonymous inner classes. You can see that the `getResult` will... | Although the List interface doesn't implement Serializable, all of the built-in Collection implementations do. This is discussed in the Collections [Implementations tutorial](http://java.sun.com/docs/books/tutorial/collections/implementations/index.html).
The Collections Design FAQ has a question ["Why doesn't Collect... | How to generically specify a Serializable List | [
"",
"java",
"generics",
"serialization",
""
] |
Is there a way to use the same session on different user-agents. I have a flash app that is generating a new session id on posting data to myHandler.ashx ( same happens on aspx ). Am i missing a trick here? | Take a look at [swfupload](http://swfupload.org/) and their implementation in ASP.Net - they use a `Global.asax` hack in order to keep the same session. | I have no experience from c# or anything like that, but when doing remoting using amfphp you will sometimes need to supply the session\_id variable in your call manually, as the server will for some reason consider you two different users even though it's all going through the same browser.
Often, the simplest way to ... | Keeping same session with different user-agents | [
"",
"c#",
"flash",
"session",
"user-agent",
"ashx",
""
] |
In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a `params` so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.
I'm fairly sure Java supports... | In Java it's called [varargs](http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html), and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:
```
public void foo(Object... bar) {
for (Object baz : bar) {
System.out.println(baz.toString());
}
}
```
The vara... | This will do the trick in Java
`public void foo(String parameter, Object... arguments);`
You have to add three points `...` and the `varagr` parameter must be the last in the method's signature. | Java "params" in method signature? | [
"",
"java",
"variadic-functions",
"parameters",
"method-declaration",
""
] |
I have two Apache servers running PHP. One accepts forward-slashes in the query string and passes it along to PHP in the expected way, for example:
```
http://server/index.php?url=http://foo.bar
```
works and in PHP this expression is true:
```
$_REQUEST['url'] == "http://foo.bar"
```
However, in the *other* Apache... | `http://server/index.php?url=http://foo.bar` is not a valid url. You have to encode the slashes. I think browsers do this automagically, so maybe you were testing with different browsers?
Or perhaps it's the [AllowEncodedSlashes](http://httpd.apache.org/docs/2.2/mod/core.html#allowencodedslashes) setting? | A few posts here suggest the OP's usage is wrong, which is false.
Expanding on Sam152's comment, query strings are allowed to contain both ? and / characters, see section 3.4 of <http://www.ietf.org/rfc/rfc3986.txt>, which is basically the spec written by Tim Berners-Lee and friends governing how the web should operat... | How do you configure Apache/PHP to accept slashes in query strings? | [
"",
"php",
"apache",
"apache2",
"query-string",
""
] |
I'm doing a peer review and I've found people using window.location.search to check what paremetes have been sent to a given (search) page.
Is it safe to do so? I was thinking that we could probably print the parameters in the HTML output inside a script block and verify the printed variables instead of querying windo... | One thing to note about this approach. `window.location` is set statically on page load and will not detect changes that the user has made to the address bar after that time. This should not be a concern but it is important to know.
Save the following code as an html file and fire it up in a browser:
```
<!DOCTYPE ht... | If javascript is enabled, `window.location.search` is safe to use.
And just as some useless piece of further information: The property was as far as I know introduced in Netscape Navigator 2 / MS Internet Explorer 3, so I'd say it's pretty safe to use, even if it's not part of any standard (yet). | IS it safe to use window.location to query the GET params of a page? | [
"",
"javascript",
"dom",
""
] |
I'm looking for the perfect Linux C++ debugger. I don't expect success, but the search should be informative.
I am a quite capable gdb user but STL and Boost easily crush my debugging skills. It not that I can't get into the internals of a data structure, it's that it takes so long I usually find another way( "when in... | A development branch of gdb (part of gdb's [Project Archer](http://sourceware.org/gdb/wiki/ProjectArcher)) adds Python support to gdb (to replace gdb's macros). There's a series of blog postings [starting here](http://tromey.com/blog/?p=494) that extensively covers getting started with Python-enabled gdb and offers sev... | UndoDB is amazing if you don't mind paying for it. The reversible capability is much much faster than GDB's. <http://www.undo-software.com/> | Linux C++ Debugger | [
"",
"c++",
"linux",
"gdb",
"debugging",
""
] |
I have a table *Resource* with a field *Type*. *Type* is a lookup into the table *ResourceType*.
So for instance ResourceType might have:
1: Books
2: Candy
3: Both
And Resource might have
1: Tom's Grocery, 2
2: Freds News, 3
It would display as: Tom's Grocery Candy
Now lets say I am using a databound combobox for t... | Simply adding a deleted column was not enough - there had to be a way to see a deleted record in the text portion of a combo box while at the same time filtering out deleted records in the drop down.
In the end, I wrote a custom user control to handle this. | Add a bit Deleted column to the lookup table. When you delete a type, set Deleted = 1. When you pull back ResourceTypes, only pull out ResourceTypes where Deleted = 0 and then bind to the dropdown.
**Edit:**
How are you getting the dataset that you're binding to the dropdownlist? Are you using drag and drop datasets? ... | handling lookup tables with deleted records and databound controls | [
"",
"c#",
"database",
""
] |
I have a form which has a lot of SELECTs. For various reasons, I'd like to only pass to the form the ones that are selected by the user. In other words, each SELECT is something like this:
```
<SELECT name=field001>
<option value=-1>Please pick a value</option>
<option value=1>1</option>
<option value=2>2</optio... | When you post a form it will send the values of every single control to the server. If you need to prevent this I think your best option is to overwrite the onSubmit action and redirect to a new instance of the same page placing only the information you want on the querystring.
Take in mind that this will increase you... | This is not common.
If you really need it, then you can either do what @Sergio suggested or, actually remove the items you want to skip from the dom, or possibly mark them as disabled when you submit (though some browsers my do different things with `disabled` controls--you'd have to check).
This really isn't common.... | How to only pass certain form values | [
"",
"javascript",
"html",
""
] |
How to read data from Bar Code Scanner in .net windows application?
Can some one give the sequence of steps to be followed? I am very new to that. | Look at the scanner jack.
If it looks like this:

, then it's a `keyboard wedge` scanner. It acts like a keyboard: just types your barcode into an edit field.
If it looks like this:
... | I now use the Wasp USB WCS3905 barcode scanners attached to several of my winform (and 1 console) applications although have not noticed differences with other brands of USB scanner.
The way I always test when a new one comes along is to fire up notepad and scan a load of codes off everything that comes to hand; books... | Read data from Bar Code Scanner in .net (C#) windows application! | [
"",
"c#",
"barcode",
""
] |
Here's my custom filter:
```
from django import template
register = template.Library()
@register.filter
def replace(value, cherche, remplacement):
return value.replace(cherche, remplacement)
```
And, here are the ways I tried using it in my template file that resulted in an error:
```
{{ attr.name|replace:"_",... | It is possible and fairly simple.
Django only allows one argument to your filter, but there's no reason you can't put all your arguments into a single string using a comma to separate them.
So for example, if you want a filter that checks if variable X is in the list [1,2,3,4] you will want a template filter that loo... | **It is more simple than you think**
You can use ***simple\_tag*** for this.
```
from django import template
register = template.Library()
@register.simple_tag
def multiple_args_tag(a, b, c, d):
#do your stuff
return
```
**In Template**:
```
{% multiple_args_tag 'arg1' 'arg2' 'arg3' 'arg4' %}
```
> NOT... | How to add multiple arguments to my custom template filter in a django template? | [
"",
"python",
"django",
"replace",
"django-templates",
"django-template-filters",
""
] |
Can anyone explain the use of ^ operator in java with some examples? | This is the same as ^ in most languages, just an XOR.
```
false ^ false == false
true ^ false == true
false ^ true == true
true ^ true == false
``` | Some of the other answers only say it is a bitwise XOR, but note that it can also be a logical XOR if the operands are of boolean type, according to [this source](http://java.operator-precedence.com/). | ^ operator in java | [
"",
"java",
"operators",
""
] |
I have a file with a little over a million lines.
```
{<uri::rdfserver#null> <uri::d41d8cd98f00b204e9800998ecf8427e> <uri::TickerDailyPriceVolume> "693702"^^<xsd:long>}
{<uri::rdfserver#null> <uri::d41d8cd98f00b204e9800998ecf8427e> <uri::TickerDailyPriceId> <uri::20fb8f7d-30ef-dd11-a78d-001f29e570a8>}
```
Each line... | The fastest (as shown below) is a simple string split:
```
line.Split(new char[] { '{', '<', '>', '}', ' ', '^', '"' },
StringSplitOptions.RemoveEmptyEntries);
```
The next fastest is an anchored regular expression (ugly):
```
Regex lineParse
= new Regex(@"^\{(<([^>]+)>\s*){3,4}(""([^""]+)""\^\^<([^>]... | Sometimes a state machine is significantly faster than a Regex. | A more efficient Regex or alternative? | [
"",
"c#",
".net",
"regex",
""
] |
I am a web developer that is very conscious of security and try and make my web applications as secure as possible.
How ever I have started writing my own windows applications in C# and when it comes testing the security of my C# application, I am really only a novice.
Just wondering if anyone has any good tutorials/... | The books by Michael Howard are a good starting point;
* [19 Deadly Sins of software security](http://www.amazon.co.uk/Deadly-Sins-Software-Security-Programming/dp/0072260858/ref=sr_1_1?ie=UTF8&qid=1233915797&sr=8-1) (with examples in several
languages)
* [Writing Secure Code](http://www.amazon.co.uk/Writing-Secure-... | Apart from all the obvious answers to prevent buffer overflows, code injection, session highjacking et. al. you should find somebody else to check your code/software because you can only think about ways to hack your software that you know how to prevent. Only because you can’t find a way to hack your own software that... | Hacking your own application | [
"",
"c#",
"security",
"testing",
"cracking",
""
] |
I have to develop software for a USB scale that, when you press a button on it, sends serial communications over USB. I can see the values in HyperTerminal.
I am going to use the .NET classes for Serial communication to trap the data.
The problem is, I don't have the scale. The scale is connected to a remote computer... | 1) Abstract away your communications code. In test mode, feed your logic function from a data file stream rather than the serial stream.
or
2) If you have 2 serial ports (or two pcs), then setup a scale emulator app that talks out thru one port, and plug that into the other port where your software is running. | If you take the serial port emulation route, take a look at [com0com](http://com0com.sourceforge.net/). I use it all the time to fake communications with laboratory instruments and it works nicely. Very useful when you laptop lacks serial ports. | How to test serial / Hyperterminal integration with C#? | [
"",
"c#",
".net",
"serial-port",
"hyperterminal",
""
] |
An enum in Java implements the `Comparable` interface. It would have been nice to override `Comparable`'s `compareTo` method, but here it's marked as final. The default natural order on `Enum`'s `compareTo` is the listed order.
Does anyone know why a Java enums have this restriction? | For consistency I guess... when you see an `enum` type, you know *for a fact* that its natural ordering is the order in which the constants are declared.
To workaround this, you can easily create your own `Comparator<MyEnum>` and use it whenever you need a different ordering:
```
enum MyEnum
{
DOG("woof"),
CA... | Providing a default implementation of compareTo that uses the source-code ordering is fine; making it final was a misstep on Sun's part. The ordinal already accounts for declaration order. I agree that in most situations a developer can just logically order their elements, but sometimes one wants the source code organi... | Why is compareTo on an Enum final in Java? | [
"",
"java",
"enums",
"comparable",
"compareto",
""
] |
Hi,
My menu has the colour `#006699`, when hover I want it to **gradually**
go over to the colour `#4796E9`.
Is that possible? | Yes, you can do this using [jQuery](http://www.jquery.com). CSS Tricks has a tutorial called *Color Fading Menu with jQuery* [here](http://css-tricks.com/color-fading-menu-with-jquery/). | You can also achieve it with CSS3 (it will work on all browsers except IE9 and lower, though). Here is an example:
```
-webkit-transition: color 0.2s ease-out;
-moz-transition: color 0.2s ease-out;
-ms-transition: color 0.2s ease-out;
-o-transition: color 0.2s ease-out;
transition: color 0.2s ease-out;
``` | How to make a a:hover gradually have other colour | [
"",
"javascript",
"html",
"css",
"colors",
""
] |
I've looked at the [Python Time module](http://docs.python.org/library/time.html) and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time().
Am I simply missing something here or is there a common way to do this that's simply not listed there? | ```
import time
print int(time.time())
``` | [time.time()](http://docs.python.org/library/time.html#time.time) does it, but it might be float instead of int which i assume you expect. that is, precision can be higher than 1 sec on some systems. | Python's version of PHP's time() function | [
"",
"python",
"time",
""
] |
How can I call a constructor on a memory region that is already allocated? | You can use the placement new constructor, which takes an address.
```
Foo* foo = new (your_memory_address_here) Foo ();
```
Take a look at a more detailed explanation at the [C++ FAQ lite](https://isocpp.org/wiki/faq/dtors#placement-new) or the [MSDN](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx). The only ... | Notice that before invoking placement `new`, you need to call the destructor on the memory – at least if the object either has a nontrivial destructor or contains members which have.
For an object pointer `obj` of class `Foo` the destructor can explicitly be called as follows:
```
obj->~Foo();
``` | How to call a constructor on an already allocated memory? | [
"",
"c++",
"constructor",
""
] |
I'm new to C#, and am curious about best practice for using namespaces.
I have a solution that contains a single class library project, along with several, small console app projects. All the console app projects do is parse command-line arguments and call different classes within the library project. The library proj... | You are correct. It is unnecessary. The only reason you would want to be using a namespace is if you are creating libraries for re-use in many programs. | No, you dont need to. I find it's easier for maintainability to keep the entry points of an app (console, web, or windows) without namespaces. | Should I be using a C# namespace for simple console apps? | [
"",
"c#",
"namespaces",
"projects-and-solutions",
""
] |
Can someone give me 1 good reason why in C# the chained constructor is always called before any of the constructor body?
.NET allows you to call the chained constructor at any point within the constructor, so why does C# force you to do it before your constructor body executes?
I once wrote to Anders H and asked him ... | If there were a genuine reason why this ability should not be provided then it wouldn't be supported by the CLR or other .NET languages. I can only conclude that the answer is one of those "Because it's always been this way" ones, and the restriction was probably just copied from C++ or something. | Making the chained constructor execute first guarantees that all base class elements are at least as available in the derived class as they are in the base. Allowing the chained constructor to be executed at an arbitrary point would be a trade-off with little discernible benefit.
Allowing an arbitrary entry point for ... | 1 good reason why chained constructors are called first? | [
"",
"c#",
""
] |
I've got a Java web application (using Spring), deployed with Jetty. If I try to run it on a Windows machine everything works as expected, but if I try to run the same code on my Linux machine, it fails like this:
```
[normal startup output]
11:16:39.657 INFO [main] org.mortbay.jetty.servlet.ServletHandler$Context.l... | You must understand that a classloader can't see everything; they can only see what a parent classloader has loaded or what they have loaded themselves. So if you have two classloaders, say one for Jetty and another for your webapp, your webapp can see log4j (since the JAR is the WEB-INF/lib) but Jetty's classloader ca... | This seems like a classic classloader problem. It could be due to another web app being loaded first which also uses log4j but a version that is different to the one used by the app you are testing. The classloader uses the first version of the class it finds. The server class loading policy can usually be changed in t... | Why would Java classloading fail on Linux, but succeed on Windows? | [
"",
"java",
"cross-platform",
"classloader",
""
] |
How can I create in a Swing interface a toggle image button?
I have two images, imageon.jpg and imageoff.jpg,and I basically want a clickable element that toggles the images and fires an event.
Update: Is there a way to override the usual 'chrome' around the image? I would prefer a simple image to a button with an ima... | Load the images with `ImageIcon`. Create a `JToggleButton`. Then apply the icons with `AbstractButton.setIcon/setPressedIcon/setSelectedIcon`. Remove the border with `AbstractButton.setBorderPainted(false)`. | How about [`JToggleButton`](http://java.sun.com/javase/6/docs/api/javax/swing/JToggleButton.html)? You can subclass it and override `paint()` to paint the correct image based on whether it is selected or not.
Another way would be to subclass `JPanel` and catch mouse clicks, overriding `paintComponent()` to draw the co... | Java: Image as toggle button | [
"",
"java",
"swing",
""
] |
Suppose I have a variable "counter", and there are several threads accessing and setting the value of "counter" by using Interlocked, i.e.:
```
int value = Interlocked.Increment(ref counter);
```
and
```
int value = Interlocked.Decrement(ref counter);
```
Can I assume that, the change made by Interlocked will be vi... | InterlockedIncrement/Decrement on x86 CPUs (x86's lock add/dec) are automatically creating *memory barrier* which gives visibility to all threads (i.e., all threads can see its update as in-order, like sequential memory consistency). Memory barrier makes all pending memory loads/stores to be completed. `volatile` is no... | > Can I assume that, the change made by Interlocked will be visible in all threads?
This depends on how you read the value. If you "just" read it, then no, this won't always be visible in other threads unless you mark it as volatile. That causes an annoying warning though.
As an alternative (and much preferred IMO), ... | Does Interlocked provide visibility in all threads? | [
"",
"c#",
"multithreading",
"visibility",
"interlocked",
""
] |
I'm using Linq2Entity for most of my database operations. However for database creation, table creation and initial data insertion I use plain SQL files. Therefore I need both an SqlConnection and an EntityConnection. Unfortunately the Entity Framework starts complaining that the Sql Server is not listening on the othe... | Have you tried creating a SqlConnection which you then pass to the constructor for your EntityConnection? One of the overloads for EntityConnection takes a MetadataWorkspace and a DbConnection (from which SqlConnection derives.) The slight drawback of this is that you must create your MetadataWorkspace manually, which ... | I don't agree that you need a plain SQL connection and Entity connection for this task, at least as you've described it. You can execute SQL using the Entity connection. Look at [EntityConnection.CreateDbCommand](http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.createdbcommand.aspx). Naturally, t... | concurrent SqlConnection and EntityConnection to a local Sql Express Server | [
"",
"c#",
"sql-server-2005",
"linq-to-entities",
""
] |
Any succinct explanations?
Also Answered in:
[Difference between ref and out parameters in .NET](https://stackoverflow.com/questions/135234/difference-between-ref-and-out-parameters-in-net) | For the caller:
* For a ref parameter, the variable has to be definitely assigned already
* For an out parameter, the variable doesn't have to be definitely assigned, but will be after the method returns
For the method:
* A ref parameter starts off definitely assigned, and you don't *have* to assign any value to it
... | Most succinct way of viewing it:
ref = inout
out = out | What is the difference between ref and out? (C#) | [
"",
"c#",
""
] |
I've got an interface:
```
IRepository<T> where T : IEntity
```
while im knocking up my UI im using some fake repository implementations that just return any old data.
They look like this:
```
public class FakeClientRepository : IRepository<Client>
```
At the moment im doing this:
```
ForRequestedType<IRepository... | There is an easier way to do this. Please see this blog posting for details: [Advanced StructureMap: connecting implementations to open generic types](http://lostechies.com/jimmybogard/2009/12/18/advanced-structuremap-connecting-implementations-to-open-generic-types/)
```
public class HandlerRegistry : Registry
{
... | Thanks [Chris](https://stackoverflow.com/a/516955), thats exactly what I needed. For clarity, heres what I did from your link:
```
Scan(x =>
{
x.TheCallingAssembly();
x.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>();
x.With<FakeRepositoryScanner>();
});
private class FakeRep... | StructureMap Auto registration for generic types using Scan | [
"",
"c#",
"structuremap",
""
] |
I'm trying to figure out how to best lay this out. I'll explain what I have now, but I'm wondering if there is a better way to do this.
I have a class Section that has basic properties: Name, Description, et.al. I use a list of Sections for the users to choose from. They can add a Section as many times as they want to... | It sounds like the group isn't an intrinsic property of a section. It's only meaningful when relating sections to parents. Given this, I wouldn't add a group property. Maybe make a section container class that exposes the group:
```
interface IGroupedSection
{
ISection Section { get; }
string Group { get; }
}
... | When possible in object hierarchies, you want to avoid child to parent links. It makes for very tight coupling and awkward relationships.
Assuming I understand your problem, I would create a Group object to insert between the parents and the sections. A parent would have a list of groups, and each group would have a l... | Object Architecture Design Question | [
"",
"c#",
"architecture",
"oop",
"object",
""
] |
So I have a `UserControl` with some cascading `DropDownList`s on it. Selecting from list 1 enables list 2, which in turn enables list 3. Once you've made a selection in all three lists, you can move to the next page.
The `DropDownList`s are all inside an `UpdatePanel`. But the "Next Page" button is outside the `Update... | Could you not add a update panel around the "next page" and then add a trigger to the dropdownlist updatepanel for triggering the next page update panel?
Just throwing out ideas, without actually having tried it :) | Place an UpdatePanel around the next button and create a trigger for each of the dropdowns so that it fires an async postback. Ex:
```
<Triggers>
<asp:AsyncPostBackTrigger ControlID="dropDownList1" />
<asp:AsyncPostBackTrigger ControlID="dropDownList2" />
<asp:AsyncPostBackTrigger ControlID="dropDownList3"... | Updating a control outside the UpdatePanel | [
"",
"c#",
"asp.net",
"ajax",
"asp.net-ajax",
"updatepanel",
""
] |
While designing an interface for a class I normally get caught in two minds whether should I provide member functions which can be calculated / derived by using combinations of other member functions. For example:
```
class DocContainer
{
public:
Doc* getDoc(int index) const;
bool isDocSelected(Doc*) const;
... | In general, you should probably prefer free functions. Think about it from an OOP perspective.
If the function does not need access to any private members, then why should it be *given* access to them? That's not good for encapsulation. It means more code that may potentially fail when the internals of the class is mo... | I think its fine to have getSelectedDocs as a member function. It's a perfectly reasonable operation for a DocContainer, so makes sense as a member. Member functions should be there to make the class useful. They don't need to satisfy some sort of minimality requirement.
One disadvantage to moving it outside the class... | Member functions for derived information in a class | [
"",
"c++",
"oop",
""
] |
I have a TSQL script that is used to set up a database as part of my product's installation. It takes a number of steps which all together take five minutes or so. Sometimes this script fails on the last step because the user running the script does not have sufficient rights to the database. In this case I would like ... | ```
select * from fn_my_permissions(NULL, 'SERVER')
```
This gives you a list of permissions the current session has on the server
```
select * from fn_my_permissions(NULL, 'DATABASE')
```
This gives you a list of permissions for the current session on the current database.
[See here for more information](http://ms... | I assume it is failing on an update or insert after a long series of selects.
Just try a *simple* update or insert inside a transaction. Hard-code the row id, or whatever to make it simple and fast.
Don't commit the transaction--instead roll it back.
If you don't have rights to do the insert or update, this should f... | How can a SQL Sever TSQL script tell what security permissions it has? | [
"",
"sql",
"sql-server",
"security",
"t-sql",
""
] |
I try to write a simple Markdown parser in JavaScript. Therefore I want to check for the `[link content][link id]` syntax. I use the following code:
```
data = data.replace( /\[(.*?)\][ ]*\[([0-9]+)\]/g, '<a href="$2">$1</a>' );
```
It works well, but now I want to do this with a RegExp object. So I set up the follow... | Because the first argument of the RegExp constructor is a string, not a pattern literal, you have to escape the backslashes, since you want literal backslashes in the pattern:
```
var r = new RegExp( '\\[(.*?)\\][ ]*\\[([0-9]+)\\]', 'g' );
``` | In addition to the pattern's backslash problem, this:
```
data = data.replace( r, '<a href="$2">$1</a>' );
```
could be dangerous. I'll assume you've already taken care of the HTML-escaping, so I won't be able to do this:
```
[<script>stealCookies()</script>][http://oops.example.com/]
[hover me][http://hello" onmous... | JavaScript RegExp objects | [
"",
"javascript",
"regex",
""
] |
I'm writing a SQL query in SQL Server in which I need to replace multiple string values with a single string value. For example
```
Product Quantity
------- --------
Apple 2
Orange 3
Banana 1
Vegetable 7
Dairy 6
```
would become
```
Product Quantity
------- --------
Fruit ... | BradC has the best answer so far, but in case you are for some reason unable to create the additional table I wanted to post an adaption of Kibbee's answer:
```
SELECT
CASE WHEN Product IN ('Banana', 'Apple', 'Orange') Then 'Fruit'
ELSE Product END
FROM [Table]
``` | Make a new "category" table that has a list of your products, along with the "category" to which they belong.
Then just do an inner join. | Replace Multiple Strings in SQL Query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a little tray application that wants to write to its own folder under the Program Files directory. I know this is not an ultimate design and I will fix it, but first I want to understand how this works.
Running this on a 32-bit Vista machine it writes the files to the VirtualStore and it works just like it shou... | So I actually got this working by compiling all projects to target platform x86. So x64 does not work with VirtualStore on Vista 64 and neither does compiling to "Any CPU". And I had to set it for the entire solution (in the Configuration Manager), just setting it for each individual project didn't work.
Time to rewri... | Have more info about error ?
Do you use sysinternals tools for monitor execution/access errors ?
Take a look Event viewer for error too. | VirtualStore not working on Vista x64 | [
"",
"c#",
"visual-studio-2008",
"win64",
"virtualstore",
""
] |
What is the root cause of this issue? CSharpOptParse, XslTransform.Transform(...), or NUnit? What other equivalent library could I use instead, if this problem is unfixable, that is being actively supported?
I'm using version 1.0.1 of [CSharpOptParse](http://sourceforge.net/projects/csharpoptparse) which was last modi... | I know this is an old question. But..
The exception is caused because the `ToText()` method tries to determine the width of the console and it fails when you're writing to anything that is not a real console.
The fix is simple: Set a fixed width.
Change the call to ToText to:
```
try
{
usage.ToText(Console.Out,... | Why don't you attach a debugger to NUnit, turn on First-Chance exceptions, and find out what's going on? | Why is CSharpOptParse UsageBuilder failing due to an XPathException only when used in an NUnit test? | [
"",
"c#",
"xslt",
"nunit",
"csharpoptparse",
""
] |
I'm currently translating an API from C# to Java which has a network component.
The C# version seems to keep the input and output streams and the socket open for the duration of its classes being used.
Is this correct?
Bearing in mind that the application is sending commands and receiving events based on user input,... | There is a trade off between the cost of keeping the connections open and the cost of creating those connections.
**Creating connections** costs time and bandwidth. You have to do the 3-way TCP handshake, launch a new server thread, ...
**Keeping connections open** costs mainly memory and connections. Network connect... | If you've only got a single socket on the client and the server, you should keep it open for as long as possible. | Network Programming: to maintain sockets or not? | [
"",
"java",
"network-programming",
""
] |
When embedding JavaScript in an HTML document, where is the proper place to put the `<script>` tags and included JavaScript? I seem to recall that you are not supposed to place these in the `<head>` section, but placing at the beginning of the `<body>` section is bad, too, since the JavaScript will have to be parsed be... | Here's what happens when a browser loads a website with a `<script>` tag on it:
1. Fetch the HTML page (e.g. *index.html*)
2. Begin parsing the HTML
3. The parser encounters a `<script>` tag referencing an external script file.
4. The browser requests the script file. Meanwhile, the parser blocks and stops parsing the... | Just before the closing body tag, as stated on *[Put Scripts at the Bottom](http://developer.yahoo.com/performance/rules.html#js_bottom)*:
> Put Scripts at the Bottom
>
> The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two com... | Where should I put <script> tags in HTML markup? | [
"",
"javascript",
"html",
""
] |
I need to create a stored procedure that upon exceution checks if any new rows have been added to a table within the past 12 hours. If not, an warning email must be sent to a recipient.
I have the procedures for sending the email, but the problem is the query itself. I imagine I'd have to make an sql command that uses... | Say your date field in the table is 'CreateDate' and it's of type DateTime.
Your time to compare with is: GETDATE()
(which returns date + time)
To get the datetime value of 12 hours before that, is done using DATEADD:
DATEADD(hour, -12, GETDATE())
so if we want the # of rows added in the last 12 hours, we'll do:
```
... | Something like this should do what you wish.
```
Select ID
from TableName
where CreatedDate >= dateadd(hour,-12,getDate())
```
Hope this is clear but please feel free to pose further questions.
Cheers, John | SQL - how to check table for new data? | [
"",
"sql",
"sql-server-2005",
"stored-procedures",
""
] |
I have a web part that uses [PortalSiteMapProvider](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.publishing.navigation.portalsitemapprovider.aspx) to query the Sharepoint navigation hierarchy, but unit tests written for that code fail, because the code is being run outside the Sharepoint context and thu... | The Microsoft Patterns and Practices dudes recommend TypeMock to help unit test Sharepoint
<http://msdn.microsoft.com/en-us/library/dd203468.aspx>
<http://www.typemock.com/sharepointpage.php>
Not a free solution unfortunately. | You will not be able to mock the SPRequest class, which is an internal class. I am facing the same issues.
One approach is to try to isolate your code from the SharePoint API, and this is not so nice. | Unit testing code that uses PortalSiteMapProvider | [
"",
"c#",
"visual-studio-2008",
"sharepoint",
"unit-testing",
""
] |
I have a control that I'm writing where I want to turn off .NET's inbuilt request validation that prevents XSS attacks and similiar sort of nasties.
The control allows the owner of a web-site to adjust the content on that page. They can potentially enter markup if they want to. Since it's their site to edit, they must... | In the System.Web.Configuration
```
PagesSection pageSection = new PagesSection();
pageSection.ValidateRequest = false;
```
[Reference](http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.validaterequest.aspx) | None of the answers outlined here go far enough. Since the configuration items are read only, you first need to modify them so that they can be written to. Additionally, since the release of .NET 4, you also need to modify the `HttpRuntime.RequestValidationMode` property before this `Pages.ValidateRequest` property wil... | Turn off request validation programmatically | [
"",
"c#",
"asp.net",
"security",
""
] |
In my last job, we worked on a very database-heavy application, and I developed some formatting standards so that we would all write SQL with a common layout. We also developed coding standards, but these are more platform-specific so I'll not go into them here.
I'm interested to know what other people use for SQL for... | I am of the opinion that so long as you can read the source code easily, the formatting is secondary. So long as this objective is achieved, there are a number of good layout styles that can be adopted.
The only other aspect that is important to me is that whatever coding layout/style you choose to adopt in your shop,... | *Late answer, but hopefully useful.*
My experience working as part of the larger development team is that you can go ahead and define any standards you like, but the problem is actually enforcing these or making it very easy for developers to implement.
As developers we sometimes create something that works and then ... | SQL formatting standards | [
"",
"sql",
"sql-server",
"formatting",
"standards",
"coding-style",
""
] |
As an example:
```
public class Foo {
private Foo() {}
}
public class Bar extends Foo {
private Bar() {}
static public doSomething() {
}
}
```
That's a compilation error right there. A class needs to, at least, implicitly call its superclass's default constructor, which in this case is isn't visible... | You can't. You need to make Foo's constructor package private at the very least (Though I'd probably just make it protected.
(Edit - Comments in this post make a good point) | This is actually a symptom of a bad form of inheritance, called implementation inheritance. Either the original class wasn't designed to be inherited, and thus chose to use a private constructor, or that the entire API is poorly designed.
The fix for this isn't to figure out a way to inherit, but to see if you can com... | In java, how do I make a class with a private constructor whose superclass also has a private constructor? | [
"",
"java",
"constructor",
""
] |
I have a 'complex item' that is in XML, Then a 'workitem' (in xml) that contains lots of other info, and i would like this to contain a string that contains the complex item in xml.
for example:
```
<inouts name="ClaimType" type="complex" value="<xml string here>"/>
```
However, trying SAX and other java parsers I c... | I think you'll find that the XML you're dealing with won't parse with a lot of parsers since it's invalid. If you have control over the XML, you'll at a bare minimum need to escape the attribute so it's something like:
```
<inouts name="ClaimType" type="complex" value="<xml string here>" />
```
Then, once you'v... | Possibly the easiest solution would be to use a [CDATA](http://www.w3schools.com/XML/xml_cdata.asp) section. You could convert your example to look like this:
```
<inouts name="ClaimType" type="complex">
<![CDATA[
<xml string here>
]]>
</inouts>
```
If you have more than one attribute you want to store comple... | parsing XML that contain XML in elements, Can this be done | [
"",
"java",
"xml",
""
] |
I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook.
It's been given a python interface using the Win32Com library. Ot... | I don't know a thing about Python, unfortunately, but if it works through COM, Excel is not a Single-Instance application, so you should be able to create as many instances of Excel as memory permits.
Using C# you can create multiple Excel Application instances via:
```
Excel.Application xlApp1 = new Excel.Applicatio... | See ["Starting a new instance of a COM application" by Tim Golden](http://timgolden.me.uk/python/win32_how_do_i/start-a-new-com-instance.html), also referenced [here](http://www.thalesians.com/finance/index.php/Knowledge_Base/Python/General#Starting_a_new_instance_of_a_COM_application), which give the hint to use
```
... | Control 2 separate Excel instances by COM independently... can it be done? | [
"",
"python",
"windows",
"excel",
"com",
""
] |
I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*?
I know you can do something like this for both:
```
if something in dict_of_stuff:
pass
```
and
```
if something in list_of_stuff:
pass
```
My thought is the ... | # Speed
Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.
# Memory
Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchl... | A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part.
---
EDIT: for your new question, YES, a set would be better. Just create 2 sets, one ... | Python: List vs Dict for look up table | [
"",
"python",
"performance",
""
] |
I have a list of objects and I would like to access the objects in a random order continuously.
I was wondering if there was a way of ensuring that the random value were not always similar.
Example.
My list is a list of Queues, and I am trying to interleave the values to produce a real-world scenario for testing.
I... | Well, it isn't entire clear what the scenario is, but the thing with random is *you never can tell ;-p*. Anything you try to do to "guarantee" thins will probably reduce the randomness.
How are you doing it? Personally I'd do something like:
```
static IEnumerable<T> GetItems<T>(IEnumerable<Queue<T>> queues)
{
in... | It depends on what you really want...
If the "random" values are truly random then you **will** get uniform distribution with enough iterations.
If you're talking about *controlling* or *manipulating* the distribution then the values will no longer be truly random!
So, you can either have:
* Truly random values *wi... | Ensure uniform (ish) distribution with random number generation | [
"",
"c#",
".net",
"list",
"queue",
"random",
""
] |
We have an application written in C#, using .NET Framework 3.0 or 3.5 or something like that. As storage we use SQL Server, and we use Linq 2 SQL to talk with it.
Currently most (if not all) text columns in the database, are set to the varchar type (of different lengths of course).
But I started thinking... according... | Unless you've got text which is guaranteed to be representable in the code page of your database (or you're specifying the collation explicitly) I'd use nvarchar.
There are some cases where you can guarantee that the contents will be ASCII, in which case you could indeed use varchar - but I don't know how significant ... | There's a lot of perspective from the .net side of things. Here's a thought from the database side of things:
A varchar is half the size of an nvarchar. While this is not significant for many purposes, it is highly significant for indexes. An index that is half as wide, is twice as fast. This is because twice as many ... | C#: Should a standard .Net string be stored in varchar or nvarchar? | [
"",
"c#",
"sql-server",
"unicode",
"types",
""
] |
What would be a nice algorithm to remove dupes on an array like below...
```
var allwords = [
['3-hidroxitiramina', '3-hidroxitiramina'],
['3-hidroxitiramina', '3-hidroxitiramina'],
['3-in-1 block', 'bloqueo 3 en 1'],
['abacterial', 'abacteriano'],
['abacteriano', 'abacteriano'],
['ab... | [edit]: misread, after reading your clarification I'd suggest:
```
var i = allwords.length-1, prev='';
do {
if (allwords[i].join('/') === prev) {
allwords.splice(i,1);
}
prev = allwords[i].join('/');
} while (i-- && i>-1);
```
(reversing the loop is a optimization step) | You could use an object as an associative array/hash (If you mean dups in the first dimension)
```
var allWordsObj = {};
for( var i = 0; i < allWords.length; i++ ) {
allWordsObj[allWords[i][0]] = allWords[i][1];
}
alert( allWordsObj['3-hidroxitiramina'] );
``` | Removing duplicates from 2d array in Javascript | [
"",
"javascript",
"algorithm",
"sorting",
""
] |
I am not sure, whether I should use for -loop. Perhaps, like
```
for i in range(145):
by 6: //mistake here?
print i
``` | ```
for i in range(0,150,6):
print i
```
if you are stepping by a constant | I would prefer:
```
for i in xrange(25): # from 0 to 24
print 6*i
```
You can easily build a list containing the same numbers with a similar construct named *list comprehension*:
```
numbers = [6*i for i in xrange(25)]
print numbers
```
If you already have a list of (unknown) numbers, say `someNumbers`, but ... | How can I make a list in Python like (0,6,12, .. 144)? | [
"",
"python",
"list",
""
] |
In java, is there ever a case for allowing a non-abstract class to be extended?
It always seems to indicate bad code when there are class hierarchies. Do you agree, and why/ why not? | I agree with Jon and Kent but, like Scott Myers (in Effective C++), I go much further. I believe that *every class should be either `abstract`, or `final`*. That is, only leaf classes in any hierarchy are really apt for direct instantiation. All other classes (i.e. inner nodes in the inheritance) are “unfinished” and s... | There are certainly times when it makes sense to have non-final concrete classes. However, I agree with Kent - I believe that classes should be final (sealed in C#) by default, and that Java methods should be final by default (as they are in C#).
As Kent says, inheritance requires careful design and documentation - it... | Why avoid the final keyword? | [
"",
"java",
"inheritance",
"final",
"extends",
""
] |
is there any sort of XY-Layout to Java?
So I can set a Button at the X and Y cordinate and that it is suppose to be that big etc.... Because this border layout and grid and panel thing is driven me crazy. :)
They are flowing every were and getting strecht up. And to make them small you have to put panel in panel in p... | When setting the container's layout to null (no LayoutManager), you can set the component's bounds individually with component.setBounds(x,y,w,h).
**Fixed layouts are** in 99% of all cases **bad UI design** (if your labels, for example, don't get their preferred size you run into mayor problems when your application s... | The reason components resize is so stuff looks nice whatever size the window is, so Swing discourages straight X-Y position. You might want to have a look at GroupLayout <http://java.sun.com/docs/books/tutorial/uiswing/layout/group.html> which is designed for GUI builders, and the page mentioned above describes using i... | XY Layout JAVA | [
"",
"java",
"layout",
""
] |
I am writing a little program that creates an index of all files on my directories. It basically iterates over each file on the disk and stores it into a searchable database, much like Unix's locate. The problem is, that index generation is quite slow since I have about a million files.
Once I have generated an index,... | I've done this in my tool MetaMake. Here is the recipe:
1. If the index is empty, add the root directory to the index with a timestamp == dir.lastModified()-1.
2. Find all directories in the index
3. Compare the timestamp of the directory in the index with the one from the filesystem. This is a fast operation since yo... | Can you jump out of java.
You could simply use
```
dir /b /s /on M:\tests\
```
the /on sorts by name
if you pipe that out to out.txt
Then do a diff to the last time you ran this file either in Java or in a batch file. Something like this in Dos. You'd need to get a diff tool, either diff in cygwin or the excellent... | How to quickly find added / removed files? | [
"",
"java",
"file",
"filesystems",
""
] |
This situation arises from someone wanting to create their own "pages" in their web site without having to get into creating the corresponding actions.
So say they have a URL like mysite.com/index/books... they want to be able to create mysite.com/index/booksmore or mysite.com/index/pancakes but not have to create any... | You have to play with the router
<http://framework.zend.com/manual/en/zend.controller.router.html>
I think you can specify a wildcard to catch every action on a specific module (the default one to reduce the url) and define an action that will take care of render the view according to the url (or even action called)
... | Using the magic `__call` method works fine, all you have to do is check if the view file exists and throw the right exception (or do enything else) if not.
```
public function __call($methodName, $params)
{
// An action method is called
if ('Action' == substr($methodName, -6)) {
$action = substr($metho... | A Generic, catch-all action in Zend Framework... can it be done? | [
"",
"php",
"zend-framework",
"zend-framework-mvc",
""
] |
How to screen scrape a particular website. I need to log in to a website and then scrape the inner information.
How could this be done?
Please guide me.
**Duplicate: [How to implement a web scraper in PHP?](https://stackoverflow.com/questions/26947/how-to-implement-a-web-scraper-in-php)** | You want to look at the [**curl**](http://www.php.net/curl) functions - they will let you get a page from another website. You can use cookies or HTTP authentication to log in first then get the page you want, depending on the site you're logging in to.
Once you have the page, you're probably best off using [**regular... | ```
Zend_Http_Client and Zend_Dom_Query
``` | screen scraping technique using php | [
"",
"php",
"screen-scraping",
""
] |
All members are camel case, right? Why True/False but not true/false, which is more relaxed? | From [Pep 285](http://www.python.org/dev/peps/pep-0285/):
> Should the constants be called 'True'
> and 'False' (similar to
> None) or 'true' and 'false' (as in C++, Java and C99)?
>
> => True and False.
>
> Most reviewers agree that consistency within Python is more
> important than consistency with other languages.
... | All of python's [built-in constants](http://docs.python.org/library/constants.html) are capitalized or [upper] CamelCase: | Why True/False is capitalized in Python? | [
"",
"python",
"camelcasing",
""
] |
I want to hide the selected item from the opened WPF combo box, basically to show instead of this:
```
item2
item1
item2
item3
```
this:
```
item2
item1
item3
```
How can this be done? | Why don't you change the selected item's visibility instead? | Since the combobox's item's view is automatically generated from the collection of items it contains,
what you need to do is either remove the selected item from the combobox's items and set IsEditable="True" so that the selection will be valid.
You can place a label above the combobox which contains the selection ... | How can I hide the selected item in a WPF combo box? | [
"",
"c#",
"wpf",
"combobox",
"selecteditem",
""
] |
I'm trying to find out some matrix multiplication/inversion benchmarks online. My C++ implementation can currently invert a 100 x 100 matrix in 38 seconds, but compared to [this](http://www.google.com/url?sa=t&source=web&ct=res&cd=3&url=http%3A%2F%2Fwww.bluebit.gr%2Fmatrix%2Fbenchmarks.htm&ei=QyWLSdHaNoz40QWsl4ihBw&usg... | This sort of operation is extremely cache sensitive. You want to be doing most of your work on variables that are in your L1 & L2 cache. Check out section 6 of this doc:
<http://people.redhat.com/drepper/cpumemory.pdf>
He walks you through optimizing a matrix multiply in a cache-optimized way and gets some big perf i... | Check if you are passing huge matrix objects by value (As this could be costly if copying the whole matrix).
If possable pass by reference.
The thing about matricies and C++ is that you want to avoid copying as much as possable.
So your main object should probably not conatain the "matrix data" but rather contain ... | Matrix implementation benchmarks, should I whip myself? | [
"",
"c++",
"matrix",
"benchmarking",
"multiplication",
"inversion",
""
] |
I want to turn off PHP's magic quotes. I don't have access to php.ini.
When I tried to add `php_flag magic_quotes_gpc off` to my .htaccess file, I get a 500 internal server error. This is what my .htaccess file looks like:
```
AddType x-mapp-php5 .php
php_flag magic_quotes_gpc off
```
Then I tried to use `ini_set('m... | As per [the manual](http://php.net/manual/security.magicquotes.disabling.php#82777) you can often install a custom php.ini on shared hosting, where mod\_php isn't used and the `php_value` directive thus leads to an error. For suexec/FastCGI setups it is quite common to have a per-webspace `php.ini` in any case.
--
I ... | While I can't say why php\_flag is giving you `500 Internal Server Error`s, I will point out that the [PHP manual](http://us.php.net/manual/en/security.magicquotes.disabling.php) has an example of detecting if magic quotes is on and stripping it from the superglobals at runtime. Unlike the others posted, this one is re... | How to turn off magic quotes on shared hosting? | [
"",
"php",
"magic-quotes-gpc",
""
] |
On my Windows machine, my main hard drive has the letter C: and the name "Local disk".
To list the drive letters in Java on Windows, the File object has the static listRoots() method. But I can't find a way to acquire the drive names (as opposed to the drive letters) on Windows.
Has anyone tried this before? | Ah yes, you need to get the FileSystemView object and use [getSystemDisplayName](http://java.sun.com/javase/6/docs/api/javax/swing/filechooser/FileSystemView.html#getSystemDisplayName(java.io.File)). (I once implemented a Filesystem browser in Java).
It's not perfect though but it will get you the name. From the docum... | Actually to get the drive name (ex. Local Disk) you need to use getSystemTypeDescription. getSystemDisplayName returns the volume name.
```
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.swing.filechooser.FileSystemView;
public class Test2 {
public static void main(String args[]... | Acquiring drive names (as opposed to drive letters) in Java | [
"",
"java",
"windows",
""
] |
I'm using jQuery and I want to check the existence of an element in my page. I have written following code, but it's not working:
```
if($("#btext" + i) != null) {
//alert($("#btext" + i).text());
$("#btext" + i).text("Branch " + i);
}
```
How do I check the existence of the element? | Check the [jQuery FAQ](http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/)...
You can use the length property of the jQuery collection returned by your selector:
```
if ( $('#myDiv').length ){}
``` | (Since I don't seem to have enough reputation to vote down the answer...)
**Wolf** wrote:
> Calling length property on undefined
> or a null object will cause IE and
> webkit browsers to fail!
>
> Instead try this:
>
> ```
> // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram
> if($("#something") !== null)... | How to check null objects in jQuery | [
"",
"javascript",
"jquery",
"dom",
"object",
"null",
""
] |
I have a 2D bitmap-like array of let's say 500\*500 values. I'm trying to create a linear gradient on the array, so the resulting bitmap would look something like this (in grayscale):
[](https://i.stack.imgur.com/Zdn9Q.jpg)
(source: [showandtell-graphics.com](ht... | In your example image, it looks like you have a radial gradient. Here's my impromtu math explanation for the steps you'll need. Sorry for the math, the other answers are better in terms of implementation.
1. Define a linear function (like y = x + 1) with the domain (i.e. x) being from the colour you want to start with... | This is really a math question, so it might be debatable whether it really "belongs" on Stack Overflow, but anyway: you need to project the coordinates of each point in the image onto the axis of your gradient and use that coordinate to determine the color.
Mathematically, what I mean is:
1. Say your starting point i... | Creating a linear gradient in 2D array | [
"",
"c++",
"algorithm",
"graphics",
""
] |
I want to avoid calling a lot of `isinstance()` functions, so I'm looking for a way to get the concrete class name for an instance variable as a string.
Any ideas? | ```
instance.__class__.__name__
```
example:
```
>>> class A():
pass
>>> a = A()
>>> a.__class__.__name__
'A'
``` | ```
<object>.__class__.__name__
``` | How to get the concrete class name as a string? | [
"",
"python",
""
] |
Why is the integrated vs debugger so... barely functional? I cannot see the contents of an object in memory. For example, I am working with bitmaps and I would like to see them in memory. Do I need a better debugger for this? If so I am interested in recommendations. Nothing too powerful like a disassembler, just the d... | I've never found it to be "barely functional". VS gives you disassembly by default when it can't find source, and it's pretty easy to get to the memory view. Debug-> Windows -> Memory. Type "this" into the Address: box to get the memory of your current object. To view a specific member type '&this->member\_name'. It'll... | Debug | Windows | Memory | Memory1-4. Put the address of the block of memory you want to look at in the Address. It's probably the most difficult menu option you'll ever attempt to execute with your mouse (you'll see...).
In older versions of VS, if you wanted to look at the contents of a variable, you needed to deter... | Visual Studio C++ Debugger: No hex dump? | [
"",
"c++",
"visual-studio",
"debugging",
""
] |
How can I compute the minimum **bipartite** vertex cover in C#? Is there a code snippet to do so?
EDIT: while the problem *is NP-complete* for **general graphs**, it **is solvable in polynomial time** for bipartite graphs. I know that it's somehow related to maximum matching in **bipartite** graphs (by Konig's theorem... | I could figure it out:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class VertexCover
{
static void Main(string[] args)
{
var v = new VertexCover();
v.ParseInput();
v.FindVertexCover();
v.PrintResults();
}
private void Print... | Its probably best to just go ahead and pick a node at random. For each node, either it goes in the vertex cover, or all of its neighbors do (since you need to include that edge). The end-result of the whole thing will be a set of vertex covers, and you pick the smallest one. I"m not going to sit here and code it out, t... | How can I compute the minimum bipartite vertex cover? | [
"",
"c#",
"graph-theory",
""
] |
In other words, what's the sprintf equivalent for `pprint`? | The [pprint](http://docs.python.org/library/pprint.html) module has a function named [pformat](http://docs.python.org/library/pprint.html#pprint.pformat), for just that purpose.
From the documentation:
> Return the formatted representation of object as a string. indent,
> width and depth will be passed to the PrettyP... | Assuming you really do mean `pprint` from the [pretty-print library](http://docs.python.org/library/pprint.html), then you want
the `pprint.pformat` function.
If you just mean `print`, then you want `str()` | How do I get Python's pprint to return a string instead of printing? | [
"",
"python",
"pretty-print",
"pprint",
""
] |
Here's the proxy method that was created for the web service I'm trying to access. How would I go about modifying it to get the raw XML from the web service call?
```
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("CallOptionsValue")]
[System.Web.Services.Protocols.SoapHeaderAttribut... | Fortunately there is a nice way to do it, just modify the generated proxy class so it inherits from different base. The alternative implementation comes from Web Services Enhancements 3.0 pack:
[Microsoft.Web.Services3.WebServicesClientProtocol](http://www.microsoft.com/downloads/details.aspx?familyid=018a09fd-3a74-43... | If you want just make a dump using the [Fiddler Web Debugging tools](http://www.fiddlertool.com/fiddler/).
If you want to really retrive/process raw XML then proxy method will not help you. Create System.Net.HttpWebRequest for the web service, call it, and retrive pure XML response. Format/structure can be found at .A... | How to modify webservice proxy to get Raw XML | [
"",
"c#",
".net",
"xml",
"web-services",
""
] |
Is there any tool that lists which and when some classes are effectively used by an app or, even-better, automatically trims JAR libraries to only provide classes that are both referenced and used? | Bear in mind that, as proven by the [halting problem](http://en.wikipedia.org/wiki/Halting_problem), you can't definitely say that a particular class is or isn't used. At least on any moderately complex application. That's because classes aren't just bound at compile-time but can be loaded:
* based on XML config (eg S... | Yes, you want [ProGuard](http://proguard.sourceforge.net). It's a completely free Java code shrinker and obfuscator. It's easy to configure, fast and effective. | How to determine which classes are used by a Java program? | [
"",
"java",
"optimization",
"jar",
"dependencies",
""
] |
I have a field object and I create a list of fields:
```
class Field {
string objectName;
string objectType;
string fieldName;
string fieldValue;
//constructor...
}
List<Field> fieldList = new List<Field>();
```
Suppose I wanted to query this list to return a collection of distinct object names (to then be inse... | The expression should return a List of distinct object names from the list as defined. I converted it to a list since the docs for the CheckedListBox DataSource property indicated that it needs to implement IList or IListSource, not merely IEnumerable.
```
((ListControl)cbListBox).DataSource = fieldList.Select( f => f... | ```
var q = from Field f in fileldList select f.objectName;
chkBoxList.DataSource = q.Distinct();
``` | C# .NET 3.5 - Performing list like operations on members of a list | [
"",
"c#",
"list",
""
] |
Suppose I have some application A with a database. Now I want to add another application B, which should keep track of the database changes of application A. Application B should do some calculations, when data has changed. There is no direct communication between both applications. Both can only see the database.
The... | I'd go with #1. It's not actually as much traffic as you might think. If your data doesn't change frequently, you can be pessimistic about it and only fetch something that gives you a yay or nay about table changes.
If you design your schema with polling in mind you may not really incur that much of a hit per poll.
*... | I would go with solution #1 (polling), because avoiding dependencies and direct connections between separate apps can help reduce complexity and problems. | Some data changes in the database. How can I trigger some C# code doing some work upon these changes? | [
"",
"c#",
"database",
"ado.net",
"odp.net",
""
] |
What is the simplest way to suppress any output a function might produce? Say I have this:
```
function testFunc() {
echo 'Testing';
return true;
}
```
And I want to call testFunc() and get its return value without "Testing" showing up in the page. Assuming this would be in the context of other code that *doe... | Yes, messing with the [Output Buffer](http://php.net/outcontrol) is exactly the answer. Just turn it on before you call your method that would output (not the function itself, but where you call it, you could wrap it around your whole script or the script flow, but you can make it as "tight" as possible by just wrappin... | Here you go:
```
ob_start();
testFunc();
ob_end_clean();
```
"ob" stands for "output buffering", take a look at the manual pages here: <http://www.php.net/outcontrol> | PHP: Suppress output within a function? | [
"",
"php",
"function",
"output-buffering",
""
] |
I found the following behavior at least *weird*:
```
def errors():
try:
ErrorErrorError
finally:
return 10
print errors()
# prints: 10
# It should raise: NameError: name 'ErrorErrorError' is not defined
```
The exception disappears when you use `return` inside a `finally` clause. Is that a bu... | You asked about the Python developers' reasoning. I can't speak for them, but no other behavior makes sense. A function can either return a value, or it can raise an exception; it can't do both. The purpose of a "finally" clause is to provide cleanup code that is "guaranteed" to be run, regardless of exceptions. By put... | > The exception disappears when you use `return` inside a `finally` clause. .. Is that documented anywhere?
[It is:](http://docs.python.org/reference/compound_stmts.html#the-try-statement)
> If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If ... | return eats exception | [
"",
"python",
"exception",
"return",
"finally",
""
] |
Can I get an object's name in run time (like getting an object's type via RTTI)? I want the object to be able to print its name. | Its not possible. For on thing, an object doesn't have a unique name.
```
A a;
A& ar = a; // both a and ar refer to the same object
new A; // the object created doesn't have a name
A* ap = new A[100]; // either all 100 objects share the same name, or need to
// know that they are part of an ... | Since objects in C++ don't have any names, you cannot get them. The only thing you can get to identify an object is its address.
Otherwise, you can implement your naming scheme (which means the objects would have some `char*` or `std::string` member with their name). You can inspire yourself in Qt with their QObject h... | How to get C++ object name in run time? | [
"",
"c++",
"runtime",
""
] |
I have a Data Grid View inside a control that is displayed in a certain area in an application.
I'd like this activity grid to refresh when F5 is pressed.
It's easy enough to do this when the Activity Grid View is the currently focused element on the screen by handling the Key Up event, but this obviously doesn't wor... | No.
If you don't have access to the other controls that may have focus at the time, there's no way to pass the key up message from them to your control. | You can do some global keyboard event handling on the Form the controls are on.
If you add this to your form you can get the global key events before they are send to the control.
```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.F5:
//... | Can I handle a key up event even when grid view isn't focused? | [
"",
"c#",
".net-3.5",
"event-handling",
""
] |
I am developing my stuff in python. In this process I encountered a situation where I have a string called "import django". And I want to validate this string. Which means, I want to check whether the module mentioned('django' in this case) is in the python-path. How can I do it? | My previous answer was wrong -- i didn't think to test my code. This actually works, though: look at the [imp](http://docs.python.org/library/imp.html) module.
To just check for the module's importability in the current sys.path:
```
try:
imp.find_module('django', sys.path)
except ImportError:
print "Boo! no ... | I doub't that it's safe, but it's the most naïve solution:
```
try:
exec('import django')
except ImportError:
print('no django')
``` | Execute a string as a command in python | [
"",
"python",
"django",
"path",
""
] |
which is better ???
```
public class Order
{
private double _price;
private double _quantity;
public double TotalCash
{
get
{
return _price * _quantity;
}
}
```
or
```
public class Order
{
private double _totalCash;
private double _price;
private double _quantity;
private v... | There are tradeoffs. If the calculations simple and does not take a long time, then put it in the get. It makes your life easier, because you don't have to worry about doing the check in every set that total price is dependant on, which could lead to mistakes.
If the calculation takes a lot of time, then you could als... | Typically I try to put them on set since the value they generate will be stored internally and only need to be calculated once. You should only put calculations on get if the value is likely to change every time its queried.
In your price/quantity example, you could actually have a single separate method that recalcul... | do you put your calculations on your sets or your gets . | [
"",
"c#",
"language-agnostic",
"class",
"methods",
"oop",
""
] |
This question is very similar to [SQL Server 2005: T-SQL to temporarily disable a trigger](https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger)
However I do not want to disable all triggers and not even for a batch of commands, but just for one single INSERT.
I have to de... | You can disable triggers on a table using:
```
ALTER TABLE MyTable DISABLE TRIGGER ALL
```
But that would do it for all sessions, not just your current connection.. which is obviously a very bad thing to do :-)
The best way would be to alter the trigger itself so it makes the decision if it needs to run, whether tha... | You may find this helpful:
[Disabling a Trigger for a Specific SQL Statement or Session](http://www.mssqltips.com/tip.asp?tip=1591)
But there is another problem that you may face as well.
If I understand the situation you are in correctly, your system by default inserts product code automatically(by generating the va... | MSSQL: Disable triggers for one INSERT | [
"",
"sql",
"sql-server",
"insert",
"triggers",
""
] |
When in Windows XP, if I open the properties window for the file and click the second tab, I will find a window where to add attributes or remove them.
While developing things, I noticed there was actually something I wanted to know about the file. How to retrieve this data? It's a string with name 'DESCRIPTION'.
The... | I think the custom tab is only available for Office documents, and display custom properties (In Word, File -> Properties, Custom tab).
The best way to get the information would be by using MS Office hooks. Last time I did anything like this, it was using OLE Automation, so good luck!
**Edit:**
Since you added a me... | Not on an XP machine, but I think this might work
```
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo("path.txt");
string desc = myFileVersionInfo.FileDescription;
``` | Retrieve file properties | [
"",
"c#",
".net",
"windows",
""
] |
Why does the jvm require around 10 MB of memory for a simple hello world but the clr doesn't. What is the trade-off here, i.e. what does the jvm gain by doing this?
Let me clarify a bit because I'm not conveying the question that is in my head. There is clearly an architectural difference between the jvm and clr runti... | I guess one reason is that Java has to do everything itself (another aspect of platform independence). For instance, Swing draws it's own components from scratch, it doesn't rely on the OS to draw them. That's all got to take place in memory. Lots of stuff that windows may do, but linux does not (or does differently) h... | Seems like java is just using more *virtual* memory.
```
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
amwise 20598 0.0 0.5 22052 5624 pts/3 Sl+ 14:59 0:00 mono Test.exe
amwise 20601 0.0 0.7 214312 7284 pts/2 Sl+ 15:00 0:00 java Program
```
I made a test program in C#... | jvm design decision | [
"",
"java",
".net",
"clr",
"jvm",
""
] |
How do you add Javascript file programmatically to the user control?
I want the user control to be a complete package - ie I don't want to have to add javascript that's related to the user control on the page where it's used, when I can do it inside the control itself.
Since there is no Page object in the user contro... | In the Page\_Load method of control.ascx.cs file:
```
LiteralControl jsResource = new LiteralControl();
jsResource.Text = "<script type=\"text/javascript\" src=\"js/mini-template-control.js\"></script>";
Page.Header.Controls.Add(jsResource);
HtmlLink stylesLink = new HtmlLink();
stylesLink.Attributes["rel"] = "styles... | You can register client script includes using the ClientScriptManager.
Page is accessible through the Control.Page property.
```
Page.ClientScript.RegisterClientScriptInclude (
typeof ( MyControl ), "includeme.js", "js/includeme.js" );
```
EDIT: Sorry, for a total "complete package", its possible using scripts as ... | Programmatically adding Javascript File to User Control in .net | [
"",
"asp.net",
"javascript",
"user-controls",
""
] |
I have this method:
```
private delegate void watcherReader(StreamReader sr);
private void watchProc(StreamReader sr) {
while (true) {
string line = sr.ReadLine();
while (line != null) {
if (stop) {
return;
}
//... | Whenever you have a `while(true)` loop in your code you're going to peg your cpu (or at least one core) at 100%, unless you also have a way to break out of the loop. In your case, you do have a `return` statement, but at no point in the loop do you ever do anything to the `stop` variable guarding it. | I would change:
```
while(true)
```
to:
```
while(!sr.EOS) {
}
```
It is a better way to check to end the loop. | Why does my loop use 100% CPU and never end? | [
"",
"c#",
"delegates",
"readline",
"streamreader",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.