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 = 'Beverages'
```
If that's the case, I don't see how stored procedures are useful anymore. | 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. I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends. But that was a very linear approach to coding.
All this being said, something is just not clicking with me. I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding. I have to study other people's code so much that it simply seems like I'm not doing anything on my own. I'm getting discouraged.
It's not like I'm not capable of it. I picked up t-sql really quickly. Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want. SQL is something that I get. This isn't happening for me with OOP or C#. Granted, C# is inherently more complex, but at some point it has to click. Right?
I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.
What was it for you that made it click?
**Edited to add:**
A lot of the answers here were outstanding. However, one in particular seemed to have risen to the top and that's the one I marked as the "answer". I also hate not marking my questions with the answer. | 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 a fantastic first step to explaining the "why" of OO programming, something that I struggled with immensely.
Hope this helps. | 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 collective knowledge will be much greater than individual knowledge.
The thing that you mistake for intelligence, is time spent in an arena. The more time and effort you devote to learning the better and more knowledgeable you will become. From what you are saying, you are not approaching things in an optimal way. Understand that a specific language just provides the rules of syntax and grammar. The key to becoming a good developer is to be being a good thinker. Don't focus or get hung up on a language.
Craig Larman and Bruce Eckols and the Head Start books are a great fit for this model of learning. However, I do have to warn you that reading the books and doing the exercises is not enough. You've got to immerse yourself in discussion and feedback with other developers (unless of course, you are an exceptionally intelligent person - in which case you'll simply get it...).
You've demonstrated a trait that is more important than intelligence. You've got humility. If you have humility and perseverence, you'll be much more effective and knowledgeable than the vast majority of the posters on SO.
Humility is also important because it will help you cope with the fact that no matter how hard you work and how much you study, you'll never know more than Jon Skeet. | 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:
* The site needs to be efficient and well laid out (the source code), I would like to be able to write as little code as possible.
* There has to be good separation between structure, presentation and logic.
* For whatever reason, I can't use a framework and need to keep the code maintainable and "simple" as there will be future developers working with it.
* There needs to be an admin section for at least a few pages.
Saying that, this is what I know about the site as it is now:
* Consists of 10-12 pages, a few are completely static, most are dynamically driven via a database and there is a huge form for users to fill out (20-30 fields) that need to be validated and checked.
* The hierarchy of the site is basically 5-6 main pages and then sub-pages within those.
So, knowing those things I wanted to know if anyone had any tips/suggestions as to how to go about doing this with the least amount of headaches.
* Would an OO approach be best in this situation?
* Since there are many static pages and the dynamic pages just need the content filled in would it be best to use some kind of basic template?
**EDIT:** Thanks for the answers, when I said no frameworks I basically meant anything that would require new syntax other than PHP, as whoever gets hired to work on this site after me will probably only know PHP. | 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 intended usage, and how to take advantage of its architecture for high-performance websites.
**edit:** In response to the comment by @theman, I'll concede the article isn't a fine work of writing, but I think the content is important. Using PHP as it was intended to be used is better than struggling against its weaknesses to make it fit an OO mold. | 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 (normal)
+ Child2 (oddly-shaped icon)
+ Child3 (normal) / Parent2
- Grandchild1 (normal)
- Grandchild2 (oddly-shaped icon)
Above, Child2 and Grandchild2 are supposed to have transparent background (WM\_ERASEBKGND does nothing, or (WNDCLASS)->hbrBackground = NULL). Right now the background for these icons is transparent, but transparent to extreme -- I see stuff under Parent1 -- desktop, etc.
This all happens under Windows Mobile.
Is there any extra flag I have to set for Parent1 and Parent2? Any good tricks you might offer?
I would be surprised if noone had similar problems, since many applications now have to display icons, all shapes and sizes.
EDIT: The oddly-shaped window is icon with transparencies. It would be nice if parent window would not do clipping for these particular windows, but invalidate them every time parent draws itself. CS\_PARENTDC looks very promising, but not promising enough. Any ideas? | 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, such as edit controls, but it's mostly doable. | 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 thinking of this method. You set up an irregular region which is the shape of your icon and then draw to that. I think this is probably a common technique for drawing windows with odd shapes. | 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");
return;
}
this.currentIndex = index;
var title = jsonObj.title;
var text = jsonObj.text;
var next = $("<a>").attr("href","#").click(this.nextHandler).text("next");
var previous = $("<a>").attr("href","#").click(this.previousHandler).text("previous");
$("body").html("<h2>"+title+"</h2><p>"+text+"</p>");
$("body").append(previous);
$("body").append(document.createTextNode(" "));
$("body").append(next);
}
,nextHandler: function() {
noName.show(noName.currentIndex + 1);
}
,previousHandler: function() {
noName.show(noName.currentIndex - 1);
}
};
window.onload = function() {
var data = [
{"title": "Hello there", "text": "Some text"},
{"title": "Another title", "text": "Other"}
];
noName.init(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" />
</bean>
```
...and that didn't work :(
How should I Inject an Enum into a spring bean? | 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 type of the enum from the property (e.g. the property's declared type is an interface).*Adapted from araqnid's comment.* | 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 compiled; The output of `toString()` may contain the original code comments in some browsers. As an aside, here are my findings:
## Test subject
```
function/*post-keyword*/fn/*post-name*/()/*post-parens*/{
/*inside*/
}
document.write(fn.toString());
```
## Results
```
Browser post-keyword post-name post-parens inside
----------- ------------ --------- ----------- --------
Firefox No No No No
Safari No No No No
Chrome No No Yes Yes
IE Yes Yes Yes Yes
Opera Yes Yes Yes Yes
```
I'm looking for a cross-browser way of extracting the nested function names from a given function. The solution should be able to extract "fn1" and "fn2" out of the following function:
```
function someFn() {
/**
* Some comment
*/
function fn1() {
alert("/*This is not a comment, it's a string literal*/");
}
function // keyword
fn2 // name
(x, y) // arguments
{
/*
body
*/
}
var f = function () { // anonymous, ignore
};
}
```
The solution doesn't have to be pure regex.
**Update:** You can assume that we're always dealing with valid, properly nested code with all string literals, comments and blocks terminated properly. This is because I'm parsing a function that has already been compiled as a valid function.
**Update2:** If you're wondering about the motivation behind this: I'm working on a new JavaScript unit testing framework that's called [jsUnity](http://jsunity.com). There are several different formats in which you can write tests & test suites. One of them is a function:
```
function myTests() {
function setUp() {
}
function tearDown() {
}
function testSomething() {
}
function testSomethingElse() {
}
}
```
Since the functions are hidden inside a closure, there's no way for me invoke them from outside the function. I therefore convert the outer function to a string, extract the function names, append a "now run the given inner function" statement at the bottom and recompile it as a function with new `Function()`. If the test function have comments in them, it gets tricky to extract the function names and to avoid false positives. Hence I'm soliciting the help of the SO community...
**Update3:** I've come up with [a new solution](https://stackoverflow.com/questions/517411/extracting-nested-function-names-from-a-javascript-function/546984#546984) that doesn't require a lot of semantic fiddling with code. I use the original source itself to probe for first-level functions. | **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 = /\bfunction\b|\(|\)|\{|\}|\/\*|\*\/|\/\/|"|'|\n|\s+/mg,
tokens = [],
pos = 0;
for(var matches; matches = regex.exec(code); pos = regex.lastIndex) {
var match = matches[0],
matchStart = regex.lastIndex - match.length;
if(pos < matchStart)
tokens.push(code.substring(pos, matchStart));
tokens.push(match);
}
if(pos < code.length)
tokens.push(code.substring(pos));
return tokens;
}
var separators = {
'/*' : '*/',
'//' : '\n',
'"' : '"',
'\'' : '\''
};
function extractInnerFunctionNames(func, nested) {
var names = [],
tokens = tokenize(func.toString()),
level = 0;
for(var i = 0; i < tokens.length; ++i) {
var token = tokens[i];
switch(token) {
case '{':
++level;
break;
case '}':
--level;
break;
case '/*':
case '//':
case '"':
case '\'':
var sep = separators[token];
while(++i < tokens.length && tokens[i] !== sep);
break;
case 'function':
if(level === 1 || (nested && level)) {
while(++i < tokens.length) {
token = tokens[i];
if(token === '(')
break;
if(/^\s+$/.test(token))
continue;
if(token === '/*' || token === '//') {
var sep = separators[token];
while(++i < tokens.length && tokens[i] !== sep);
continue;
}
names.push(token);
break;
}
}
break;
}
}
return names;
}
``` | 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/), for a Javascript parser generator.
Other solutions are just regex hacks, that lead to unmaintainable/unreadable code and probably to hidden parsing errors in particular cases.
As a side note, I'm not sure to understand why you aren't specifying the list of unit test functions in your product in a different way (an array of functions?). | 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 identifier is an unlimited-length
> sequence of Java letters and Java
> digits, the first of which must be a
> Java letter. An identifier cannot have
> the same spelling (Unicode character
> sequence) as a keyword (§3.9), boolean
> literal (§3.10.3), or the null literal
> (§3.10.7).
I'm not sure what the benefit of making it not-a-keyword is, to be honest. | 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)
if not data:
break
yield data
with open('really_big_file.dat') as f:
for piece in read_in_chunks(f):
process_data(piece)
```
---
Another option would be to use [`iter`](http://docs.python.org/library/functions.html#iter) and a helper function:
```
f = open('really_big_file.dat')
def read1k():
return f.read(1024)
for piece in iter(read1k, ''):
process_data(piece)
```
---
If the file is line-based, the file object is already a lazy generator of lines:
```
for line in open('really_big_file.dat'):
process_data(line)
``` | `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 appropriate intermediate tables), but never a 1:1.
Am I missing something obvious? | 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, but no more).
As an example of a logical partition: you have data about an employee, but there is a larger set of data that needs to be collected, if and only if they select to have health coverage. I would keep the demographic data regarding health coverage in a different table to both give easier security partitioning and to avoid hauling that data around in queries unrelated to insurance.
An example of a physical partition would be the same data being hosted on multiple servers. I may keep the health coverage demographic data in another state (where the HR office is, for example) and the primary database may only link to it via a linked server... avoiding replicating sensitive data to other locations, yet making it available for (assuming here rare) queries that need it.
Physical partitioning can be useful **whenever** you have queries that need consistent subsets of a larger entity. | 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.
Others bring up a good point. Security can also be a good reason depending on how applications etc. are hitting the system. I would tend to take a different approach, but it can be an easy way of restricting access to certain data. It's really easy to just deny access to a certain table in a pinch.
[My blog entry about it.](http://structuredsight.com/2015/01/12/its-o-k-that-its-just-the-two-of-us-when-a-1x1-table-relationship-makes-sense/) | 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("@firstName", person.FirstName);
dCmd.Parameters.AddWithValue("@lastName", person.LastName);
dCmd.Parameters.AddWithValue("@age", person.Age);
return dCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
``` | 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:
```
Line: 18
Char: 6
Error: Access is denied.
Code: 0
URL: file:///D:/test_j.hta
```
Here is the code of my "test\_j.hta":
```
<html>
<head>
<title>Test J</title>
<HTA:APPLICATION
ID="objTestJ"
APPLICATIONNAME="TestJ"
SCROLL="no"
SINGLEINSTANCE="yes"
WINDOWSTATE="normal"
>
<script language="JScript">
function main()
{
//window.alert("test");
window.resizeTo(500, 300);
}
function OnExit()
{
window.close();
}
</script>
</head>
<body onload="main()">
<input type="button" value="Exit" name="Exit" onClick="OnExit()" title="Exit">
</body>
</html>
``` | 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 really the answer since those are mostly designed for statically typed languages. Basically you want something that has syntax highlighting, compilation and maybe some shortcuts and macros to make life easier for you... emacs has all of this :)
I would Google "Emacs Python" to get started.
If you really don't want to use emacs, I would look at [PyDev](http://pydev.sourceforge.net/). It's an extension to the eclipse IDE that let's you write python code. Some of my friends that do Django work have had good luck with that one.
Hope this helps.
Good luck with GAE. | 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, equipment, etc. ). The problem is that the numbers (for some random reason) - range from about -100000 to +2000000 when there are about only 7000 entries.
Is there any good way to re-number them while changing corresponding numbers in the other tables? At my disposal I also have ColdFusion, so any thing that works with SQL and/or that I'll accept. | 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 impact. | 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 precisely why the number is in its current state, you are taking quite a risky making changes like this. | 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 user set.
i want to avoid a solution with a lot of flag member variables. Any best practices on how i can code this class up without having a lot of stuff like this below
```
public class Object
{
private double _A;
private double _B;
private double _C;
private bool _enteredA;
private bool _enteredB;
private bool _enteredC;
public double A
{
get
{
if (_enteredC)
{
return _C / _B;
}
else
{
return _A;
}
}
}
```
should the logic of setting A, B, and C always be on the "get" or the "set".
Is there any cleaner way to doing this? | 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 without using boolean flags, there's a couple of different ways you could do that. A queue, or just a simple array/map would work:
```
editOrder = {A : 0, B : 0, C : 0 } // (or just use 0, 1, 2)
editCount = 0;
every time any field is edited :
editCount = editCount + 1
editOrder[field] = editCount
if two fields have an editOrder > 0
recalculate the field with the lowest editOrder
```
Example usage:
```
Field changed editOrder recalculate field
A 1,0,0 -
A 2,0,0 -
B 2,3,0 C
C 2,3,4 A
C 2,3,5 A
B 2,6,5 A
A 7,6,5 C
``` | 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:
```
class Foo
{
private double m_a;
public double A
{
get { return m_a; }
set { m_a = value; }
}
private double m_b;
public double B
{
get { return m_b; }
set { m_b = value; }
}
public double C
{
get { return A * B; }
}
}
```
An editor can be written that allows A and B to edited trivially. It can also allow the user to edit C if (and only if) the user has edited A or B already. The view would store some state to indicate which (if any) field was last edited and can therefore apply the appropriate change to A or B when the conceptual C is edited.
Now, if the View is unaware of the calculation of C, you can add methods to the Foo class to "SetAGivenC()" and "SetBGivenC()":
```
class Foo
{
... as above ...
public void SetAGivenC( double newC )
{
A = newC/B;
}
public void SetBGivenC( double newC )
{
B = newC/A;
}
}
```
Now your GUI just calls one of these methods when "C" is edited.
I am confused as to what "last field that the user set" means. Imagine that there are two editors up on the screen (both bound to the same Foo instance) and the user edits A in the first editor, then B in the second, then C in the first. What gets adjusted when C is set? A or B? If you can answer this question, you will know which class should track the "last field that the user set" - should it be the model or the view? I expect that A would be adjusted in this case and the view tracks the last edited field. But that's an issue for another day!
Edit:
Jeepers - I even stuffed up my own pathological case!
I'll try that last paragraph again:
I am confused as to what "last field that the user set" means. Imagine that there are two editors up on the screen (both bound to the same Foo instance) and the user edits A then B in the first editor, the user then edits B then A in the second, the user then edits C in the first. What gets adjusted when C is set? A or B? If you can answer this question, you will know which class should track the "last field that the user set" - should it be the model or the view? I expect that A would be adjusted in this case and the view tracks the last edited field. But that's an issue for another day! | 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 ?
Thanks for replies !
```
update TableToUpdate set
EndTimeKey = DATE_NO
from Dates where EndTime = DATE
``` | 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 the database, this will reduce potential locking issues. Make sure your datatypes are the same between the two tables so you aren't having to do any implicit conversions.
Look at the table you are updating, are there any triggers on it? Depending on how the trigger is written, this could seriously slow down an update of that many records (especially if someone who wasn't too bright decided to put a cursor or a loop in the trigger instead of writing set-based code).
Also here is some thing I would add (I also changed it show explicitly show the join)
```
update t
set EndTimeKey = DATE_NO
from TableToUpdate t
Join Dates D on t.EndTime = d.DATE
where EndTimeKey <> DATE_NO
```
No point in updating records that already match. | 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 INTO to create the new table.
Next use sp\_rename to rename 'TableToUpdate' to 'OLDTableToUpdate' and 'NEWTableToUpdate' to 'TableToUpdate' and then create the indexes as you had them on the original table.
In my experience I've found this to be the quickest means of acheiving big changes like this. HTH.
Extra thought... if you have a clustered index on your table then add an ORDER BY to your SELECT statement to ensure it is inserted into your new table in the same sequence as the clustered index. That'll speed up the index creation in a significant way. | 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 warehouse and adds them to the report db. The problem is that I only get new rows but not new updates.
I would like to know what are the various ways of solving this scenario.
Thanks | 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 above. The suitability of these vary depending on your hardware. You will have to do some research to pick the optimal one for your needs. | 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 works just fine. But what I *really* want to do is call my function in some cases, and the default validator for the rest. Unfortunately, this turns out to be recursive:
```
jQuery.validator.addMethod("required", function(value, element, param) {
// handle comboboxes with empty guids
if (someTest(element)) {
return myRequired(value, element, param);
}
return jQuery.validator.methods.required(value, element, param);
}, jQuery.validator.messages.required);
```
I looked at the source code for the validators, and the default implementation of "required" is defined as an anonymous method at jQuery.validator.messages.required. So there is no other (non-anonymous) reference to the function that I can use.
Storing a reference to the function externally before calling addMethod and calling the default validator via that reference makes no difference.
What I really need to do is to be able to copy the default required validator function by value instead of by reference. But after quite a bit of searching, I can't figure out how to do that. Is it possible?
If it's impossible, then I can copy the source for the original function. But that creates a maintenance problem, and I would rather not do that unless there is no "better way." | > 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(value, element, param) {
// handle comboboxes with empty guids
if (someTest(element)) {
return myRequired(value, element, param);
}
return jQuery.validator.methods.oldRequired(value, element, param);
}, jQuery.validator.messages.required);
```
This should work too: (And the problem with `this` is solved)
```
var oldRequired = jQuery.validator.methods.required;
jQuery.validator.addMethod("required", function(value, element, param) {
// handle comboboxes with empty guids
if (someTest(element)) {
return myRequired(value, element, param);
}
return oldRequired.call(this, value, element, param);
// return jQuery.oldRequired.apply(this, arguments);
}, jQuery.validator.messages.required);
``` | ```
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[property];
}
}
return clone;
};
```
The only bad thing with that is that the prototype isn't cloned so you can't really change it...
I'm working on a way to clone any type of objects and I just have RegExp left to do.
So I'll probably edit tomorrow and put the entire code (which is kind of long and isn't optimised if you only use it for functions and objects.
And to comment other answers, using eval() is totaly stupid and is way too long and the Function constructor is kind of the same. Literrals are much better.
And including JQuery just for that, moreover if it doesn't work properly (and I don't think it does) isn't the brightest thing you can do. | 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 business logic.
When my application starts up, it executes the following code:
```
Model model = new BasicModel();
Presenter presenter = new Presenter(model);
View view = new SwingView(presenter);
presenter.setView(view);
presenter.init();
```
which creates the user interface. Events are generated by the `View`, and delegated to the `Presenter`. The `Presenter` then manipulates the `Model` and updates the `View` accordingly.
In order to handle some events, I need to obtain further information from the user. In the case of these events, I believe it is appropriate for the Swing view to spawn a new `JDialog` window.
One line of thinking makes me feel this might be appropriate code in the orignal `Presenter`:
```
public void handlePreferences() {
Preferences prefs = view.getPreferences();
model.setPreferences(prefs);
}
```
That is, the contents of each `JDialog` should represent a distinct object that should be retrieved from the `View` and updated in the `Model`. However, this leaves the question: do I create a new `Model` to represent the `Preferences` object and a new `Presenter` for event handling in that `JDialog`?
It seems to me that creating a new `Presenter` and `Model` internal to the original `View` forces me to do a lot of work that would be harder to port if I wanted to change the UI to use JSF, for example.
Please feel free to add comments for clarification. | 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(value1,value2,value3...);
**View**
- is the IO for the application, just output and input
- it can only work on its self, on its state
- it maintains local variables and objects, eg. it has JButtons, JMenus, int counters ...
- it is knows how to inform the Presenter of State Change
- its state is visible to the Presenter, or revealed by method call
- responds to orders (method calls)
- knows how to get preferences from the user
- has method askForPrefs();
- has method getPrefState();
**Presenter**
- Responds to state changes
- does all the deciding, it tells the other objects what to do (not how to do it)
- knows when preferences are needed
- knows where to get new preferences and where to put them
- has method newPrefsAvailable();
> ... to obtain further information from the user. In the case of these events, I believe it is appropriate for the Swing view to spawn a new JDialog window.
Presenter - checks the Model, determines new preferences are required
Presenter - this.myView.askForPrefs(); //tells view to ask user for pref values
View.askForPrefs - pops up a JDialog box, retVals stored in the view as a state change
View - this.myPresenter.newPrefsAvailable();
Presenter - responds with this.myModel.setPreferences (this.myView.getPrefState());
Model.setPreferences - changes the stored values to View.getPrefState()
Presenter - checks the Model - determines preferences are good
Presenter - continues on
The JDialog is treated as just an extension of the View,it is a member of the View just like a JButton would be.
The model has the authoritative actual preference values, and the view has local variables that represent the state of the JDialog. | 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 theoretical, but in my experience it saves a lot of headaches in the end.
If you can't work that out then where the preferences are saved gives you another clue. if they need to be saved with the data being manipulated then they are probably part of the business logic. If they are saved in the user's personal preference file then they are not, and should be considered view. | 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.reportViewer.LocalReport.ListRenderingExtensions()) {
if (extension.Name == "PDF") {
((Extension)(extension.GetType().GetField("m_serverExtension", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(extension))).Visible = false;
}
```
I can't see how to make the report reference this code upon loading. Does anyone know how I am supposed to make the report execute this code?
EDIT: Incidentally report access is through the SSRS Report Manager web app. We are, in the main, delighted with this product so wouldn't consider reinventing the wheel in order to implement a hack to produce what is, essentially a "would be nice" feature.
It still boggles the mind slightly that the report's available rendering options are not controllable at the report level. Ho hum. | 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 anyone has a better idea than this within the next fortnight I'll mark this as the answer which basically sums up to:
You can only restrict functionality like this under certain conditions and by no means easily even when you do.
This seems like a clear failure in the wider fitness of SSRS for purpose as we have users who require Excel export functionality and users who need to be limited to PDF only. Oh well. | 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 interface Result<T> extends Serializable{
T getResult();
}
```
It now becomes impossible to implement, with compile time checking, because there is no guarantee that T is serializable, and the whole point of the class is to store the result so that I can get it back later, possibly after a transfer over the internet.
My question is this, is there a way to declare a variable so that it is of two types, or is there some other way to do this that I am not seeing? So, maybe something like:
```
(List<Integer> extends Serializable) value = new ArrayList();
```
I am trying to put as much of the burden of this problem on the implementation, so that future consumers of this interface are unaware of the problem.
Thanks for your help!
Here is a more detailed example of what I am trying to do:
I am calling a server, The result of which I want to store in a result object, but I do not want to have to deal with casting. So, each method that can be called on the server will define the type of the result by using generics. This result object will also store other meta-data about the result, for example maybe there was too much information to return. In many cases I want to use a list, but the List interface is not serializable, although many of the implementations are.
So, how to I specify that the type used must be Serializable, but still allow for a List(and not a specific implementation of List) to be used? | 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 return a `List<Integer>` on the 2nd object
```
Result<Integer> res = new Result<Integer>() {
Integer myInteger;
private static final long serialVersionUID = 1L;
@Override
public Integer getResult() {
return myInteger;
}
@Override
public void addResult(Integer input) {
this.myInteger = input;
}
};
Integer check = res.getResult();
Result<? extends List<Integer>> res2 = new Result<ArrayList<Integer>>() {
ArrayList<Integer> myList;
private static final long serialVersionUID = 1L;
@Override
public ArrayList<Integer> getResult() {
return myList;
}
@Override
public void addResult(ArrayList<Integer> input) {
this.myList = input;
}
};
List<Integer> check2 = res2.getResult();
```
Edit: Made the example more complete by implementing a `void addResult(T input)` interface method | 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 Collection extend Cloneable and Serializable?"](http://java.sun.com/javase/6/docs/technotes/guides/collections/designfaq.html#5) which talks about why Sun designed it without extending Serializable. | 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 do this is to supply your swf with the id in a flashvar when loading it. This will require you to print the session\_id in the html source, which isn't ideal, but it's not that big of a deal since it can be sniffed very easily anyway. | 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 similar behaviour, but I cant find out how to do it. | 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 vararg parameter must *always* be the **last** parameter in the method signature, and is accessed as if you received an array of that type (e.g. `Object[]` in this case). | 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 server, the same URL results in a `403 Forbidden` error! Note that if the query string is properly URL-escaped (i.e. with `%2F` instead of forward-slash), then everything works.
Clearly there's some difference in the Apache or PHP configuration that causes this, but I can't figure out what!
I want to *accept* this form of URL in both cases, not reject it. | `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 operate.
The problem is that poorly written (or poorly configured, or misused) parsers interpret query string slashes as separating path components.
I have seen examples of PHP's pathinfo function being used to parse URL's. Pathinfo wasn't written to parse a URL. You can however extract the path using parse\_url then use fileinfo to retrieve details from the path. You will see that parse\_url handles / and ? in query strings just fine.
In any case, the overall problem is that this area is poorly understood all-round, even among experienced developers, and most people (myself included until recently) just assume that anything after the filename has to be urlencoded, which is patently false if you take the standards into consideration.
tl;dr Read the spec :) | 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 window.location. | 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 html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test</title>
</head>
<body>
<a href="javascript:void(0);"
onclick="alert(window.location);">click me</a>
</body>
</html>
```
The "click me" anchor will display the current window location `onclick`. However if you add anything to the address bar and click the link again it will report the same thing it did the first time.
Hopefully this is not a concern and I cannot imagine that it would affect you in any way but it is good to know. | 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 doubt, print it out" ).
The macro language for gdb is weird and not very adaptive. Just look at the code for the stanford gdb utils to print out stl structures.
In short I'm unhappy with what I've got.
I recently stumbled upon [Zero Bugs](http://zero-bugs.com). It looks like a silver bullet. What do the current Zero Bugs users think of it?
Has anyone found other good solutions to the Linux C++ Debugger problem? | 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 several tutorials on using Python for defining new gdb commands and pretty printing of C++ data structures. | 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 the resource type and the third record is deleted from ResourceType, we of course get an error when *Fred's News* is displayed. I could simply put a marker in (perhaps an asterisk), indicating that it has been deleted, rather than actually delete it. It shows up as \*\*Both\* in the textbox portion of the combo and I am content.
However, I would not want it to show up as an *option* in the dropdown. Is this too much to ask from databound fields? Must I write my own code to load the drop down? | 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? I really haven't worked with datasets like that in years, but I'm pretty sure you can change the Get sql to what you need it to be. | 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</option>
<option value=3>3</option>
</SELECT>
```
Usually, only one or two will be selected at a time, and I'd like to only pass the selected ones to the form. I'm guessing I'd need to unset the inputs that are -1 in JavaScript, but I'm not sure how to do that, and also wonder if there might be a standard approach to this kind of thing. | 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 your code complexity a LOT and will make it harder to maintain. My opinion is that you simply wont gain enough performance that will make your effort worth while, but that's up to 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. If you have so many selects that sending them is causing problems, you have too many selects.
The normal way to handle this is to use your magic value, "-1", to know when to ignore certain values on the server side. | 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:

, it's a `serial port` scanner.
You need to create an instance of [`System.IO.Ports.SerialPort`](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport?redirectedfrom=MSDN&view=netframework-4.8) and use it to communicate with the scanner.
If it looks like this:
[](https://i.stack.imgur.com/ZepI7.gif)
(source: [datapro.net](https://www.datapro.net/connectors/USB-A.gif))
, it's a `USB` scanner. From programmer's point of view, it can be either a `keyboard wedge` or a `serial port` scanner. You need to look at the manual, find out which is it and use one of the approaches above.
P.S. It will be easier if you post your scanner's model here, really. | 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, DVD, asset tags, but most importantly the stock I need to track. This will allow you visualise how the data is captured.
In my experience they all act like a user typing each character succesively on a keyboard followed by an "Enter" keypress.
For each character (NOTE: not complete bar-code) scanned in a textbox control then at least following events fire:
KeyDown
KeyPress
TextChanged
KeyUp
The Enter keystroke at the end of a scan can be used to push a form's AcceptButton
It should probably be noted that I've only used these on UK-English & US-English configured windows systems.
G- | 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:"_"," " }}
{{ attr.name|replace:"_" " " }}
{{ attr.name|replace:"_":" " }}
{{ attr.name|replace:"cherche='_', remplacement=' '" }}
```
I looked into [django's docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) and [book](http://www.djangobook.com/en/beta/chapter10/) but only found example using a single argument... is it even possible? | 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 looks like this:
```
{% if X|is_in:"1,2,3,4" %}
```
Now we can create your templatetag like this:
```
from django.template import Library
register = Library()
def is_in(var, args):
if args is None:
return False
arg_list = [arg.strip() for arg in args.split(',')]
return var in arg_list
register.filter(is_in)
```
The line that creates arg\_list is a generator expression that splits the args string on all the commas and calls .strip() to remove any leading and trailing spaces.
If, for example, the 3rd argument is an int then just do:
```
arg_list[2] = int(arg_list[2])
```
Or if all of them are ints do:
```
arg_list = [int(arg) for arg in args.split(',')]
```
EDIT: now to specifically answer your question by using key,value pairs as parameters, you can use the same class Django uses to parse query strings out of URL's, which then also has the benefit of handling character encoding properly according to your settings.py.
So, as with query strings, each parameter is separated by '&':
```
{{ attr.name|replace:"cherche=_&remplacement= " }}
```
Then your replace function will now look like this:
```
from django import template
from django.http import QueryDict
register = template.Library()
@register.filter
def replace(value, args):
qs = QueryDict(args)
if qs.has_key('cherche') and qs.has_key('remplacement'):
return value.replace(qs['cherche'], qs['remplacement'])
else:
return value
```
You could speed this up some at the risk of doing some incorrect replacements:
```
qs = QueryDict(args)
return value.replace(qs.get('cherche',''), qs.get('remplacement',''))
``` | **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' %}
```
> NOTE: Don't forget to re-run the server. | 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 is a statement.
```
struct Statement
string C;
string S;
string P;
string O;
string T;
```
Currently I'm using a TextReader in a while loop and parsing each line with a regular expression:
```
Regex lineParse = new Regex(@"[^<|\""]*\w[^>\""]*", RegexOptions.Singleline | RegexOptions.Compiled);
```
It takes quite awhile to do this parsing and I'm hoping someone can point me to a more efficient parsing strategy.
Some lines have 5 matchs and some 4. Here is how each line is parsed:
```
{<uri::rdfserver#null> <uri::d41d8cd98f00b204e9800998ecf8427e> <uri::TickerDailyPriceVolume> "693702"^^<xsd:long>}
Statement()
C = uri::rdfserver#null
S = uri::d41d8cd98f00b204e9800998ecf8427e
P = uri::TickerDailyPriceVolume
O = 693702
T = xsd:long
{<uri::rdfserver#null> <uri::d41d8cd98f00b204e9800998ecf8427e> <uri::TickerDailyPriceId> <uri::20fb8f7d-30ef-dd11-a78d-001f29e570a8>}
Statement()
C = uri::rdfserver#null
S = uri::d41d8cd98f00b204e9800998ecf8427e
P = uri::TickerDailyPriceId
O = uri::20fb8f7d-30ef-dd11-a78d-001f29e570a8
```
Additional information from the comments: "The poor performance I was seeing is actually due to a conditional break-point that I had set in the code. Without that break-point everything is pretty fast. Still if anyone has any improvement ideas I would be interested" -Eric Schoonover | 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}(""([^""]+)""\^\^<([^>]+)>\s*)?\}$",
RegexOptions.Compiled);
Match m = lineParse.Match(line);
if (m.Groups[2].Captures.Count == 3)
{
Data data = new Data { C = m.Groups[2].Captures[0].Value,
S = m.Groups[2].Captures[1].Value, P = m.Groups[2].Captures[2].Value,
O = m.Groups[4].Value, T = m.Groups[5].Value };
} else {
Data data = new Data { C = m.Groups[2].Captures[0].Value,
S = m.Groups[2].Captures[1].Value, P = m.Groups[2].Captures[2].Value,
O = m.Groups[2].Captures[3].Value, T = String.Empty };
}
```
Timings for 1M lines of random data (String.Split as the baseline):
```
Method #1 Wall (Diff) #2 Wall (Diff)
------------------------------------------------------------
line.Split 3.6s (1.00x) 3.1s (1.00x)
myRegex.Match 5.1s (1.43x) 3.3s (1.10x)
itDependsRegex.Matches 6.8s (1.88x) 4.4s (1.44x)
stateMachine 8.4s (2.34x) 5.6s (1.82x)
alanM.Matches 9.1s (2.52x) 7.8s (2.52x)
yourRegex.Matches 18.3s (5.06x) 12.1s (3.90x)
```
**Updated to include @AlanM and @itdepends regular expressions.** It appears that Regex.Matches is slower than Regex.Match, however, the more context clues you give the parser, the better it performs. The single negative character class used by @AlanM is the simplest to read, yet slower than the most cryptic (mine). Hats off to @itdepends for the simplest regex that produces the fastest time. Ok, and while I thought it would be crazy to write a state machine to parse the line, it actually doesn't perform poorly at all...kudos to @RexM for the suggestion. I've also added times from my Q6600 at home (#2) v. an older Xeon at work (#1). | 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/readme's on how to hack your own windows application and writing secure code. | 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-Second-Michael-LeBlanc/dp/0735617228/ref=sr_1_1?ie=UTF8&s=books&qid=1233915846&sr=1-1)
There's loads of links and interesting articles from Michael Howard's blog [here](http://blogs.msdn.com/michael_howard/default.aspx)
There's an interesting powerpoint presentation from Microsoft about threat assessment, risks and ASP [here](http://download.microsoft.com/download/d/9/a/d9abfa8d-2207-4827-9e15.../Writing%20Secure%20Code%20--%20Best%20Practices.ppt). | 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 doesn’t mean that nobody else can. | 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 I can RDP into. When I want to test, I can ask the client to press the button on the scale.
I can't ask the client to press the button 100 times a day, I need to have a way to develop with a reasonably good idea of what the scale will report, and only test when I think I have a solution.
I'm looking for something locally, that can mimic the scale and send to my .NET Serial classes, the same output as the scale. Ideally, if I could record the scale's data, and then play it back on another machine, it would be perfect.
How would I do this? | 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"),
CAT("meow");
String sound;
MyEnum(String s) { sound = s; }
}
class MyEnumComparator implements Comparator<MyEnum>
{
public int compare(MyEnum o1, MyEnum o2)
{
return -o1.compareTo(o2); // this flips the order
return o1.sound.length() - o2.sound.length(); // this compares length
}
}
```
You can use the `Comparator` directly:
```
MyEnumComparator comparator = new MyEnumComparator();
int order = comparator.compare(MyEnum.CAT, MyEnum.DOG);
```
or use it in collections or arrays:
```
NavigableSet<MyEnum> set = new TreeSet<MyEnum>(comparator);
MyEnum[] array = MyEnum.values();
Arrays.sort(array, comparator);
```
Further information:
* [The Java Tutorial on Enum Types](http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html)
* [Sun's Guide to Enums](http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html)
* [Class Enum API](http://java.sun.com/javase/6/docs/api/java/lang/Enum.html) | 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 organized in a way that makes readability and maintenance to be paramount. For example:
```
//===== SI BYTES (10^n) =====//
/** 1,000 bytes. */ KILOBYTE (false, true, 3, "kB"),
/** 106 bytes. */ MEGABYTE (false, true, 6, "MB"),
/** 109 bytes. */ GIGABYTE (false, true, 9, "GB"),
/** 1012 bytes. */ TERABYTE (false, true, 12, "TB"),
/** 1015 bytes. */ PETABYTE (false, true, 15, "PB"),
/** 1018 bytes. */ EXABYTE (false, true, 18, "EB"),
/** 1021 bytes. */ ZETTABYTE(false, true, 21, "ZB"),
/** 1024 bytes. */ YOTTABYTE(false, true, 24, "YB"),
//===== IEC BYTES (2^n) =====//
/** 1,024 bytes. */ KIBIBYTE(false, false, 10, "KiB"),
/** 220 bytes. */ MEBIBYTE(false, false, 20, "MiB"),
/** 230 bytes. */ GIBIBYTE(false, false, 30, "GiB"),
/** 240 bytes. */ TEBIBYTE(false, false, 40, "TiB"),
/** 250 bytes. */ PEBIBYTE(false, false, 50, "PiB"),
/** 260 bytes. */ EXBIBYTE(false, false, 60, "EiB"),
/** 270 bytes. */ ZEBIBYTE(false, false, 70, "ZiB"),
/** 280 bytes. */ YOBIBYTE(false, false, 80, "YiB");
```
The above ordering looks good in source code, but is not how the author believes the compareTo should work. The desired compareTo behavior is to have ordering be by number of bytes. The source-code ordering that would make that happen degrades the organization of the code.
As a client of an enumeration i could not care less how the author organized their source code. I do want their comparison algorithm to make some kind of sense, though. Sun has unnecessarily put source code writers in a bind. | 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 thing you need to make sure that the memory is properly aligned (`malloc` is supposed to return memory that is properly aligned for anything, but beware of things like SSE which may need alignment to 16 bytes boundaries or so). | 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 project uses the standard CompanyName.Tool convention.
My question is, since the only purpose of a given console app is to a class in the library project, and will never itself be called from another project or class, do I need to put it inside a namespace? It seems unnecessary. | 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 this and he was kind enough to spend the time replying despite how busy he must be. Unfortunately he managed to answer a question I didn't actually ask (about named constructors.)
So, just out of curiosity I thought I would ask here because personally I don't think there is a single good reason for this limitation, so hopefully I will be reeducated :-)
Just to clarify. The .NET CLR rule is that 1 constructor must be called, only 1 constructor, and only once. So in the CLR these are valid
```
public class Meh
{
public Meh()
{
Console.WriteLine("Meh()");
this("Hello");
}
public Meh(string message)
{
Console.WriteLine("Meh {0}", message);
base();
}
}
```
But not in C# | 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 the chained constructor also precludes lazy creation of the base class since such a feature would potentially run the chained constructor twice. | 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.log>(ServletHandler.java:1145) >16> Set web app root system property: 'webapp.root' = [/path/to/working/dir]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.mortbay.start.Main.invokeMain(Main.java:151)
at org.mortbay.start.Main.start(Main.java:476)
at org.mortbay.start.Main.main(Main.java:94)
Caused by: java.lang.ExceptionInInitializerError
at org.springframework.web.util.Log4jWebConfigurer.initLogging(Log4jWebConfigurer.java:129)
at org.springframework.web.util.Log4jConfigListener.contextInitialized(Log4jConfigListener.java:51)
at org.mortbay.jetty.servlet.WebApplicationContext.doStart(WebApplicationContext.java:495)
at org.mortbay.util.Container.start(Container.java:72)
at org.mortbay.http.HttpServer.doStart(HttpServer.java:708)
at org.mortbay.util.Container.start(Container.java:72)
at org.mortbay.jetty.Server.main(Server.java:460)
... 7 more
Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: No suitable Log constructor [Ljava.lang.Class;@15311bd for org.apache.commons.logging.impl.Log4JLogger (Caused by java.lang.NoClassDefFoundError: org/apache/log4j/Category) (Caused by org.apache.commons.logging.LogConfigurationException: No suitable Log constructor [Ljava.lang.Class;@15311bd for org.apache.commons.logging.impl.Log4JLogger (Caused by java.lang.NoClassDefFoundError: org/apache/log4j/Category))
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:543)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:235)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:209)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:351)
at org.springframework.util.SystemPropertyUtils.(SystemPropertyUtils.java:42)
... 14 more
Caused by: org.apache.commons.logging.LogConfigurationException: No suitable Log constructor [Ljava.lang.Class;@15311bd for org.apache.commons.logging.impl.Log4JLogger (Caused by java.lang.NoClassDefFoundError: org/apache/log4j/Category)
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:413)
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:529)
... 18 more
Caused by: java.lang.NoClassDefFoundError: org/apache/log4j/Category
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.getConstructor(Class.java:1657)
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:410)
... 19 more
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Category
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 24 more
[shutdown output]
```
I've run the app with `java -verbose:class`, and according to that output, org.apache.log4j.Category is loaded from the log4j JAR in my /WEB-INF/lib, just before the first exception is thrown.
Now, the Java versions on the two machines are slightly different. Both the machines have Sun's java, the Linux machine has 1.6.0\_10, while the Windows machine has 1.6.0\_08, or maybe 07 or 06, I can't remember the exact number right now, and don't have the machine at hand. But even though the minor versions of the Javas are slightly different, the code shouldn't break like this. Does anyone understand what's wrong here? | 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 can't.
If you manage to make a class available to Jetty (for example something in the DB layer) which uses log4j but which ends up running in the context (and classloader) of Jetty, you will get an error.
To debug this, set a breakpoint in org.springframework.web.util.Log4jWebConfigurer.initLogging(). If you can, copy the source of this class into your project (don't forget to delete it afterwards) and add this line:
```
ClassLoader cl = Thread.currentThread().getContextClassLoader();
```
Have a look at the cl object in your debugger. That should give you some information who created it. My guess is that this is the classloader from Jetty.
[EDIT] Note that you get in a different mess if you have log4j in both classloaders: In this case, you will have *two* classes with the *same* name which create objects which are not assignment compatible! So make sure there is only a single instance of this jar or that instances of log4j will never be passed between the two contexts (which is usually not possible). | 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 the config files. Sorry I am a bit rusty on this but maybe it can point you in the correct direction.
1. Make sure there are no other installed apps on the web server,
2. Make sure the log4j being loaded is the correct version,
3. Make sure you don't have a log4j lurking somewhere in the classpath of the server.
HTH | 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 image inside. | 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 correct image. This way the only thing that gets drawn is the actual image (unlike the `JToggleButton` option). | 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 visible in all threads?
If not, what should I do to make all threads synchronize the variable?
EDIT: someone suggested me to use volatile. But when I set the "counter" as volatile, there is compiler warning "reference to volatile field will not be treated as volatile".
When I read online help, it said, "A volatile field should not normally be passed using a ref or out parameter". | 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 not related to this question although C# and Java (and some C/C++ compilers) enforce `volatile` to make memory barrier. But, interlocked operation already has memory barrier by CPU.
Please also take a look [my another answer](https://stackoverflow.com/questions/1581718/does-interlocked-compareexchange-use-a-memory-barrier/1716587#1716587) in stackoverflow.
Note that I have assume that C#'s InterlockedIncrement/Decrement are intrinsic mapping to x86's lock add/dec. | > 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), read it using another Interlocked instruction. This will always see the updated value on all threads:
```
int readvalue = Interlocked.CompareExchange(ref counter, 0, 0);
```
which returns the value read, and if it was 0 swaps it with 0.
Motivation: the warning hints that something isn't right; combining the two techniques (volatile & interlocked) wasn't the intended way to do this.
Update: it seems that another approach to reliable 32-bit reads without using "volatile" is by using `Thread.VolatileRead` as suggested in [this answer](https://stackoverflow.com/a/6139812/33080). There is also some evidence that I am completely wrong about using `Interlocked` for 32-bit reads, for example [this Connect issue](http://connect.microsoft.com/VisualStudio/feedback/details/256490/interlocked-read-only-does-long-data-type), though I wonder if the distinction is a bit pedantic in nature.
What I really mean is: don't use this answer as your only source; I'm having my doubts about this. | 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 other end of the pipe.
I'm not sure what the problem is here, it could be due to user instancing. Clearing the pool of the SqlConnection or disposing the connection instance does not help.
The connection string I'm using is the following:
"Data Source=.\SQLEXPRESS; Initial Catalog=dbname; Integrated Security=SSPI;"
update:
I have tried to use the EntityConnection for database maintenance purposes but I'm running into troubles. I can't use the EntityConnection to create databases and drop databases. The following syntax is unsupported for an EntityConnection but works fine for an SqlConnection to ms SQL express.
```
CREATE DATABASE silverfit ON ( NAME = silverfit, FILENAME = 'c:\silverfit\silverfit.mdf' );
```
Also for some reason the EntityConnection does not allow me to change databases which is necessary to drop a database. I'm afraid I still need the SqlConnection to create the database and tables..
Is there a way for SqlConnections and EntityConnections to coexist for local ms SQL express databases?
Thanks,
Wouter | 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 gathers up the .csdl, .ssdl, and .msl files that define your workspace. However, in the long run, you should be able to share a single connection for both executing DML queries, and using Entity Framework. | 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, there's a danger here that you are doing DB-server-specific things on a non-DB-server-specific instance like a EntityConnection. But it probably beats having a separate connection, in this case. | 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
* An out parameter *doesn't* start off definitely assigned, and you have to make sure that any time you return (without an exception) it *will* be definitely assigned
So:
```
int x;
Foo(ref x); // Invalid: x isn't definitely assigned
Bar(out x); // Valid even though x isn't definitely assigned
Console.WriteLine(x); // Valid - x is now definitely assigned
...
public void Foo(ref int y)
{
Console.WriteLine(y); // Valid
// No need to assign value to y
}
public void Bar(out int y)
{
Console.WriteLine(y); // Invalid: y isn't definitely assigned
if (someCondition)
{
// Invalid - must assign value to y before returning
return;
}
else if (someOtherCondition)
{
// Valid - don't need to assign value to y if we're throwing
throw new Exception();
}
else
{
y = 10;
// Valid - we can return once we've definitely assigned to y
return;
}
}
``` | 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<Client>>()
.TheDefaultIsConcreteType<FakeRepositories.FakeClientRepository>();
```
but loads of times for all my IEntities. Is it possible to use Scan to auto register all my fake repositories for its respective IRepository?
Edit: this is as far as I got, but i get errors saying the requested type isnt registered :(
```
Scan(x =>
{
x.TheCallingAssembly();
x.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>();
x.AddAllTypesOf(typeof(IRepository<>));
x.WithDefaultConventions();
});
```
Thanks
Andrew | 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
{
public HandlerRegistry()
{
Scan(cfg =>
{
cfg.TheCallingAssembly();
cfg.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>();
cfg.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
});
}
}
```
Doing it this way avoids having to create your own `ITypeScanner` or conventions. | 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 FakeRepositoryScanner : ITypeScanner
{
public void Process(Type type, PluginGraph graph)
{
Type interfaceType = type.FindInterfaceThatCloses(typeof(IRepository<>));
if (interfaceType != null)
{
graph.AddType(interfaceType, type);
}
}
}
``` | 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 a Parent object and any number of Sections.
When they add a Section to the parent, they have to assign what group it belongs to (lets say group1, group2, group3) and in what order it will be displayed. This Group property is not on the table, there is no group needed when I list out the Sections for the user to choose from, it wouldn't make sense. Think of this Section they are adding as a clone with extra properties.
I have another table that has a foreign key to the Parent and to the Section. Many sections can be added to 1 Parent. On this link table is also the Grouping and DisplayOrder columns (as well as a few others) for each section that they add.
So when I create the Parent object and query a collection of its Sections, do I want to try and use the same Section class and add a Grouping property?
```
Section 1
Section 2
Section 3
Parent 1
Section 1 - Group = g1, DisplayOrder = 1
Section 1 - Group = g2, DisplayOrder = 2
Section 2 - Group = g2, DisplayOrder = 3
Section 3 - Group = g3, DisplayOrder = 4
Parent 2
Section 4 - Group = g3, DisplayOrder = 1
Section 1 - Group = g2, DisplayOrder = 2
Section 2 - Group = g3, DisplayOrder = 3
```
Tell me if you have no idea what I'm saying and I'll try to explain it better...or I'll delete it and pretend like I never asked. =P | 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; }
}
```
or make grouping a property of parent, e.g.
```
interface IParent
{
void AddSection(string group, ISection section);
IEnumerable<ISection> GetSectionsInGroup(string group);
}
```
You may need more than one section grouping strategy, after all, so it's best not to couple your section design to the types of collection it can be contained within. | 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 list of sections.
**Edit in response to DisplayOrder:**
Display order is actually a property of the parent, not the sections. A parent contains a list of sections, and that list has a particular order associated with it. | 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 `UpdatePanel`. That button should be disabled until all three lists have a selection, and then it should be enabled again. But since the button is outside the `UpdatePanel`, it doesn't update when I make selections. (**Edit**: The "Next Page" button is on a page that also contains the `UserControl`.)
I know one way to resolve this:
```
var scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(dropDownList1);
scriptManager.RegisterPostBackControl(dropDownList2);
scriptManager.RegisterPostBackControl(dropDownList3);
```
This ensures a postback when any dropdown list is changed, so that the button can update. But if I do this, I might as simplify by getting rid of the `UpdatePanel` in the first place.
Is there another way, through some clever JavaScript or something, that I can update a control outside an `UpdatePanel` without having to give up Ajax? | 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" />
</Triggers>
``` | 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;
int getDocCount() const;
//Should this method be here???
//This method returns the selected documents in the contrainer (in selectedDocs_out)
void getSelectedDocs(std::vector<Doc*>& selectedDocs_out) const;
};
```
Should I provide this as a class member function or probably a namespace where I can define this method? Which one is preferred? | 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 modified.
It also limits the possible amount of code reuse.
If you wrote the function as something like this:
```
template <typename T>
bool getSelectedDocs(T& container, std::vector<Doc*>&);
```
Then the same implementation of getSelectedDocs will work for *any* class that exposes the required functions, not just your DocContainer.
Of course, if you don't like templates, an interface could be used, and then it'd still work for any class that implemented this interface.
On the other hand, if it is a member function, then it'll only work for this particular class (and possibly derived classes).
The C++ standard library follows the same approach. Consider `std::find`, for example, which is made a free function for this precise reason. It doesn't need to know the internals of the class it's searching in. It just needs *some* implementation that fulfills its requirements. Which means that the same `find()` implementation can work on any container, in the standard library or elsewhere.
Scott Meyers argues for the [same thing](http://www.ddj.com/cpp/184401197).
If you don't like it cluttering up your main namespace, you can of course put it into a separate namespace with functionality for this particular class. | 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 is that people will have to look in two places when the try to figure out how to use a DocContainer: they need to look in the class and also in the utility namespace. | 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 the script to fail strait away. To do this I want the script to test what rights it has up front. Can anyone point me at a general purpose way of testing if the script is running with a particular security permission?
**Edit:** In the particular case I am looking at it is trying to do a backup, but I have had other things go wrong and was hoping for a general purpose solution. | ```
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://msdn.microsoft.com/en-us/library/ms176097%28SQL.90%29.aspx). | 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 fail. If you DO, it will roll back and not cause a permanent change. | 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 following bit of code:
```
var r = new RegExp( '\[(.*?)\][ ]*\[([0-9]+)\]', 'g' );
data = data.replace( r, '<a href="$2">$1</a>' );
```
But it doesn't work. It even says that my regular expression (which works since the first example does a good job) is invalid:
> unmatched ) in regular expression
I think it must have to do with some RegExp-object peculiarities I am not aware of.
What am I doing wrong and how can the problem be solved? | 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" onmouseover="stealCookies()]
```
but you'll still need to check the URL is a known-good scheme so I can't do this:
```
[click me][javascript:stealCookies()]
```
You'll probably want to use the String.replace(r, func) variant of the method, and include validation in your replacement-making 'func'. | 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 2
Fruit 3
Fruit 1
Vegetable 7
Dairy 6
```
The only way I know how to do this is to use a nested REPLACE in the SELECT clause.
```
SELECT
REPLACE('Banana', REPLACE('Orange', REPLACE('Banana', Product, 'Fruit'),
'Fruit'), 'Fruit') AS Product
FROM
Table
```
Is there an easier way?
EDIT: There may be other values in the Product category. See edited example above. | 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 should.
But when installing this on a Vista 64-bit machine I immediately get hit with an UnauthorizedAccessException for trying to write to the directory within Program Files (and Program Files (x86)).
The VirtualStore redirect does not seem to work on Vista 64-bit. Any ideas?
It's a C# app written in Visual Studio 2008 and I use a FileStream obj to persist the stream to disk. | 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 rewrite it using AppData folder or IsolatedStorage. Thanks for all the help! | 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 modified in Feb 2005.
I've have the following class (simplified for this example of course) to use along with CSharpOptParse:
```
public enum CommandType
{
Usage
}
public class Options
{
[OptDef(OptValType.Flag)]
[LongOptionName("help")]
[Description("Displays this help")]
public bool Help { get; set; }
public CommandType CommandType
{
get { return CommandType.Usage; }
}
}
```
Here is a bit of unit test code that replicates the issue:
```
TextWriter output = Console.Out;
Options options = new Options { Help = true };
Parser p = ParserFactory.BuildParser(options);
p.Parse();
output.WriteLine("Usage: Console [--a]");
UsageBuilder builder = new UsageBuilder();
builder.BeginSection("Arguments:");
builder.AddOptions(p.GetOptionDefinitions()); //could the issue be created here?
builder.EndSection();
builder.ToText(output, OptStyle.Unix, true); //The problem occurs here
```
Is it possible that I'm causing the problem by not setting up the UsageBuilder with the correct sections? Possibly this might be causing problems in the xslt file???
When I run that code I get the following exception:
```
System.Xml.XPath.XPathException : Function 'ext:FormatText()' has failed.
----> System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
----> System.ArgumentOutOfRangeException : Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: startIndex
at MS.Internal.Xml.XPath.FunctionQuery.Evaluate(XPathNodeIterator nodeIterator)
at System.Xml.Xsl.XsltOld.Processor.ValueOf(ActionFrame context, Int32 key)
at System.Xml.Xsl.XsltOld.ValueOfAction.Execute(Processor processor, ActionFrame frame)
at System.Xml.Xsl.XsltOld.ActionFrame.Execute(Processor processor)
at System.Xml.Xsl.XsltOld.Processor.Execute()
at System.Xml.Xsl.XsltOld.Processor.Execute(TextWriter writer)
at System.Xml.Xsl.XslTransform.Transform(XPathNavigator input, XsltArgumentList args, TextWriter output, XmlResolver resolver)
at System.Xml.Xsl.XslTransform.Transform(IXPathNavigable input, XsltArgumentList args, TextWriter output, XmlResolver resolver)
at CommandLine.OptParse.UsageBuilder.ToText(TextWriter writer, OptStyle optStyle, Boolean includeDefaultValues, Int32 maxColumns)
--TargetInvocationException
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Xml.Xsl.XsltOld.XsltCompileContext.FuncExtension.Invoke(XsltContext xsltContext, Object[] args, XPathNavigator docContext)
at MS.Internal.Xml.XPath.FunctionQuery.Evaluate(XPathNodeIterator nodeIterator)
--ArgumentOutOfRangeException
at System.String.LastIndexOfAny(Char[] anyOf, Int32 startIndex, Int32 count)
```
I have no idea what is causing this problem....and the weirdest part is that is only occurs within my NUnit test. When this code is called via "Console.exe --help" it runs fine with no exceptions. I can't see anything wrong with CSharpOptParse so could this be a problem in .NET's XslTransform class or in NUnit?
Has anyone else experienced this issue? Does anyone have any advice on how to track down the issue or switch to a better library? | 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, OptStyle.Unix, true);
}
catch
{
usage.ToText(Console.Out, OptStyle.Unix, true, 90);
}
```
Now if the normal call fails, it will try a fail-safe one. | 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, is it more sensible to open a new socket stream for each "message"?
I'm maintaining a ServerSocket for listening to the server throwing events but I'm not so sure that maintaining a Socket and output stream for outbound comms is such a good idea.
I'm not really used to Socket programming. As with many developers I usually work at the application layer when I need to do networking and not at the socket layer, and it's been 5 or 6 years since I did this stuff at university.
Cheers for the help. I guess this is more asking for advice than for a definitive answer. | 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 connections are a resource limited by the OS. If you have too many clients connected, you might run out of available connections. It will cost memory as you will have one thread open for each connection, with its associated state.
The right balanced will be different based on the usage you expect. If you have a lot of clients connecting for short period of times, it's probably gonna be more efficient to close the connections. If you have few clients connecting for long period of time, you should probably keep the connections open ... | 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 before the page is rendered completely (or something like that). This seems to leave the *end* of the `<body>` section as a logical place for `<script>` tags.
So, where *is* the right place to put the `<script>` tags?
(This question references [this question](https://stackoverflow.com/questions/436154/why-does-the-call-to-this-jquery-function-fail-in-firefox), in which it was suggested that JavaScript function calls should be moved from `<a>` tags to `<script>` tags. I'm specifically using jQuery, but more general answers are also appropriate.) | 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 other HTML on your page.
5. After some time the script is downloaded and subsequently executed.
6. The parser continues parsing the rest of the HTML document.
Step #4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.
## Why does this even happen?
Any script can insert its own HTML via `document.write()` or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document. After all, the script *could* have inserted its own HTML in the document.
However, most JavaScript developers no longer manipulate the DOM *while* the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:
```
<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>
```
JavaScript:
```
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});
```
Because your browser does not know *my-script.js* isn't going to modify the document until it has been downloaded and executed, the parser stops parsing.
## Antiquated recommendation
The old approach to solving this problem was to put `<script>` tags at the bottom of your `<body>`, because this ensures the parser isn't blocked until the very end.
This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts and stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.
In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.
## The modern approach
Today, browsers support the `async` and `defer` attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.
### async
```
<script src="path/to/script1.js" async></script>
<script src="path/to/script2.js" async></script>
```
Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible that script 2 is downloaded and executed before script 1.
According to <http://caniuse.com/#feat=script-async>, 97.78% of all browsers support this.
### defer
```
<script src="path/to/script1.js" defer></script>
<script src="path/to/script2.js" defer></script>
```
Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.
Unlike async scripts, defer scripts are only executed after the entire document has been loaded.
*(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer)*
# Conclusion
The current state-of-the-art is to put scripts in the `<head>` tag and use the `async` or `defer` attributes. This allows your scripts to be downloaded ASAP without blocking your browser.
The good thing is that your website should still load correctly on the 2% of browsers that do not support these attributes while speeding up the other 98%.
## References
* [async vs defer attributes](https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html)
* [Efficiently load JavaScript with defer and async](https://flaviocopes.com/javascript-async-defer/)
* [Remove Render-Blocking JavaScript](https://developers.google.com/speed/docs/insights/v5/get-started)
* [Async, Defer, Modules: A Visual Cheatsheet](https://gist.github.com/jakub-g/385ee6b41085303a53ad92c7c8afd7a6#visual-representation) | 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 components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. | 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 current date and compares that to the dates in the rows. But I'm a complete beginner in SQL so I can't even use the right words to find anything on google.
Short version:
Using MS SQL Server 2005, how can I check against the dates, then return a result based on whether new rows were created within the last 12 hours, and use that result to decide whether or not to send email? | 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:
```
SELECT COUNT(*)
FROM Table
WHERE CreateDate >= DATEADD(hour, -12, GETDATE())
```
in your proc, you've to store the result of this query into a variable and check if it's > 0, so:
```
DECLARE @amount int
SELECT @amount=COUNT(*)
FROM Table
WHERE CreateDate >= DATEADD(hour, -12, GETDATE())
```
and then you'll check the @amount variable if it's > 0. | 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 thus no site map providers are available.
I've identified two alternate ways of solving this dilemma:
* Because Sharepoint is basically an elaborate ASP.Net application, it should be possible to run tests inside the Sharepoint context with the HostType and UrlToTest test attributes
* Use a mock instead of PortalSiteMapProvider
Are either of these viable or is there a better third option? | 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 be able to stick whatever they want on there.
I'm wondering if it is possible to disable this validation programmatically?
The only way I can find to do it is either by shutting off request validation completely in the web.config or by using a page directive. For various reasons, I can't have this control in another page - so that option is out. | 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 will get recognised.
```
public void ModifiyValidation(bool validate) {
var pagesSection = System.Configuration.ConfigurationManager.GetSection("system.web/pages") as PagesSection;
var httpRuntime = System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (pagesSection != null && httpRuntime != null && pagesSection.ValidateRequest != validate)
{
var fi = typeof (ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(pagesSection, false);
fi.SetValue(httpRuntime, false);
pagesSection.ValidateRequest = validate;
httpRuntime.RequestValidationMode = new Version(validate ? "4.0" : "2.0");
fi.SetValue(pagesSection, true);
fi.SetValue(httpRuntime, true);
}
}
```
You should also be aware that the will only be activated on the **following** request. | 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 formatting standards. Unlike most other coding environments, I haven't found much of a consensus online for them.
To cover the main query types:
```
select
ST.ColumnName1,
JT.ColumnName2,
SJT.ColumnName3
from
SourceTable ST
inner join JoinTable JT
on JT.SourceTableID = ST.SourceTableID
inner join SecondJoinTable SJT
on ST.SourceTableID = SJT.SourceTableID
and JT.Column3 = SJT.Column4
where
ST.SourceTableID = X
and JT.ColumnName3 = Y
```
There was some disagreement about line feeds after `select`, `from` and `where`. The intention on the select line is to allow other operators such as "top X" without altering the layout. Following on from that, simply keeping a consistent line feed after the key query elements seemed to result in a good level of readability.
Dropping the linefeed after the `from` and `where` would be an understandable revision. However, in queries such as the `update` below, we see that the line feed after the `where` gives us good column alignment. Similarly, a linefeed after `group by` or `order by` keeps our column layouts clear and easy to read.
```
update
TargetTable
set
ColumnName1 = @value,
ColumnName2 = @value2
where
Condition1 = @test
```
Finally, an `insert`:
```
insert into TargetTable (
ColumnName1,
ColumnName2,
ColumnName3
) values (
@value1,
@value2,
@value3
)
```
For the most part, these don't deviate that far from the way MS [SQL Server Managements Studio](http://en.wikipedia.org/wiki/SQL_Server_Management_Studio) / query analyser write out SQL, however they *do* differ.
I look forward to seeing whether there is any consensus in the Stack Overflow community on this topic. I'm constantly amazed how many developers can follow standard formatting for other languages and suddenly go so random when hitting SQL. | 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, ensure that it is consistently used by all coders.
Just for your reference, here is how I would present the example you provided, just my layout preference. Of particular note, the `ON` clause is on the same line as the `join`, only the primary join condition is listed in the join (i.e. the key match) and other conditions are moved to the `where` clause.
```
select
ST.ColumnName1,
JT.ColumnName2,
SJT.ColumnName3
from
SourceTable ST
inner join JoinTable JT on
JT.SourceTableID = ST.SourceTableID
inner join SecondJoinTable SJT on
ST.SourceTableID = SJT.SourceTableID
where
ST.SourceTableID = X
and JT.ColumnName3 = Y
and JT.Column3 = SJT.Column4
```
One tip, get yourself a copy of [SQL Prompt](https://www.red-gate.com/products/sql-development/sql-prompt/index) from [Red Gate](https://www.red-gate.com/?gclid=CjwKCAjwyrvaBRACEiwAcyuzRC-M2uV3xNsyFPxojXgbZDRXkWihn1iL9dC0E471Pc7IGs3asu09khoCyVsQAvD_BwE). You can customise the tool to use your desired layout preferences, and then the coders in your shop can all use it to ensure the same coding standards are being adopted by everyone. | *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 say “I’ll format it later”, but that later never comes.
Initially, we used SQL Prompt (it was great) for this, but then switched to [ApexSQL Refactor](http://www.apexsql.com/sql_tools_refactor.aspx), because it’s a free tool. | 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 in *Foo*.
Can I call *Object*'s constructor from *Bar* instead? | 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 compose the object instead of inheriting, and do so via interfaces. I.e., class Foo is now interface Foo, with a FooImpl. Then interface bar can extend Foo, with a BarImpl, which has no relation to FooImpl.
Inside BarImpl, you could if you wish to do some code reuse, have a FooImpl inside as a member, but that's entirely up to the implementation, and will not be exposed. | 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 cannot get it to process this line, it doesn't like the < or the "'s in the string, I have tried escaping, and converting the " to '.
Is there anyway around this at all?? Or will I have to come up with another solution?
Thanks | 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've extracted the attribute you can possibly re-parse it to treat it as XML.
Alternatively, you can take one of the approaches above (using CDATA sections) with some re-factoring of your XML.
If you don't have control over your XML, you could try using the [TagSoup library](http://www.ccil.org/~cowan/XML/tagsoup/) to parse it to see how you go. (Disclaimer: I've only used TagSoup for HTML, I have no idea how it'd go with non-HTML content)
(The tag soup site actually appears down ATM, but you should be able to find enough doco on the web, and downloads via the [maven repository](http://repo1.maven.org/maven2/org/ccil/cowan/tagsoup/tagsoup/)) | 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 complex strings for, you could use multiple child elements with different names:
```
<inouts name="ClaimType" type="complex">
<value1>
<![CDATA[
<xml string here>
]]>
</value1>
<value2>
<![CDATA[
<xml string here>
]]>
</value2>
</inouts>
```
Or multiple value elements with an identifying id:
```
<inouts name="ClaimType" type="complex">
<value id="complexString1">
<![CDATA[
<xml string here>
]]>
</value>
<value id="complexString2">
<![CDATA[
<xml string here>
]]>
</value>
</inouts>
``` | 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. Other processes can call functions in my python package which in turn invokes the functions I need via Win32Com.
Unfortunately COM does not allow me to specify a particular COM process, so at the moment no matter how powerful my server I can only control one instance of Excel at a time on the computer. If I were to try to run more than one instance of excel there would be no way of ensuring that the python layer is bound to a specific Excel instance.
I'd like to be able to run more than 1 of my excel applications on my Windows server concurrently. Is there a way to do this? For example, could I compartmentalize my environment so that I could run as many Excel \_ Python combinations as my application will support? | 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.Application();
Excel.Application xlApp2 = new Excel.Application();
Excel.Application xlApp3 = new Excel.Application();
```
Using late binding in C# you can use:
```
object objXL1 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
object objXL2 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
object objXL3 = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
```
If using VB.NET, VB6 or VBA you can use CreateObject as follows:
```
Dim objXL1 As Object = CreateObject("Excel.Application")
Dim objXL2 As Object = CreateObject("Excel.Application")
Dim objXL3 As Object = CreateObject("Excel.Application")
```
Unfortunately, in Python, I don't have a clue. But unless there is some limitation to Python (which I can't imagine?) then I would think that it's very do-able.
That said, the idea of having multiple instances of Excel acting as some kind of server for other operations sounds pretty dicy... I'd be careful to test what you are doing, especially with respect to how many instances you can have open at once without running out of memory and what happens to the calling program if Excel crashed for some reason. | 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
```
xl_app = DispatchEx("Excel.Application")
```
rather than
```
xl_app = Dispatch("Excel.Application")
```
to start a separate process. So you should be able to do:
```
xl_app_1 = DispatchEx("Excel.Application")
xl_app_2 = DispatchEx("Excel.Application")
xl_app_3 = DispatchEx("Excel.Application")
```
**Note** that when you're done, to close the app, I've found it's necessary to do:
```
xl_app.Quit()
xl_app = None
```
I found the process won't shut down until `xl_app = None`, that is, the Python COM object's reference count goes to zero.
**Note** I'm having one remaining problem: while my Python program is running, if I double-click an Excel file in Explorer (at least, on Win2k), it ends up opening the file in the existing Excel process that Python started (which is running hidden), which disrupts the Python program. I haven't yet found a resolution for this. | 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 dict will be faster and more efficient.
Thanks for your help.
**EDIT 1**
Little more info on what I'm trying to do. [Euler Problem 92](http://projecteuler.net/index.php?section=problems&id=92). I'm making a look up table to see if a value calculated has all ready been calculated.
**EDIT 2**
Efficiency for look up.
**EDIT 3**
There are no values assosiated with the value...so would a *set* be better? | # 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. Kuchling in *Beautiful Code*, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.
If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering. | 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 for sequences ended in 1 and other for the sequences ended in 89. I have sucessfully solved this problem using sets. | 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 don't particularly want all of the items in Queues 1 and 2 before any other item.
Is there a guaruanteed way to do this?
Thanks
EDIT ::
The List of Queues I have is a basically a list of files that i am transmitting to a webservice. Files need to be in a certain order hence the Queues.
So I have
Queue1 = "set1\_1.xml", set1\_2.xml", ... "set1\_n.xml"
Queue2 ...
...
QueueN
While each file needs to be transmitted in order in terms of the other files in its queue, I would like to simulate a real world simulation where files would be received from different sources at different times and so have them interleaved.
At the moment I am just using a simple rand on 0 to (number of Queues) to determine which file to dequeue next. This works but I was asking if there might have been away to get some more uniformity rather than having 50 files from Queue 1 and 2 and then 5 files from Queue 3.
I do realise though that altering the randomness no longer makes it random.
Thank you for all your answers. | 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)
{
int remaining = queues.Sum(q => q.Count);
Random rand = new Random();
while (remaining > 0)
{
int index = rand.Next(remaining);
foreach (Queue<T> q in queues)
{
if (index < q.Count)
{
yield return q.Dequeue();
remaining--;
break;
}
else
{
index -= q.Count;
}
}
}
}
```
This should be fairly uniform over the entire set. The trick here is that by treating the queues as a single large queue, the tendency is that the queue's with lots of items will get dequeued more quickly (since there is more chance of getting an index in their range). This means that it should automatically balance consumption between the queues so that they all run dry at (roughly) the same time. If you don't have LINQ, just change the first line:
```
int remaining = 0;
foreach(Queue<T> q in queues) {remaining += q.Count;}
```
Example usage:
```
static void Main()
{
List<Queue<int>> queues = new List<Queue<int>> {
Build(1,2,3,4,5), Build(6,7,8), Build(9,10,11,12,13)
};
foreach (int i in GetItems(queues))
{
Console.WriteLine(i);
}
}
static Queue<T> Build<T>(params T[] items)
{
Queue<T> queue = new Queue<T>();
foreach (T item in items)
{
queue.Enqueue(item);
}
return queue;
}
``` | 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 *with* uniform distribution, or
* *Controlled* distribution, but no longer truly random | 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 to MSDN "The string type represents a sequence of zero or more Unicode characters." Does that mean that we should really change those columns to nvarchar for things to be stored correctly? Or how does that work? Their reasoning for setting them to varchar originally was because nvarchar requires twice as much space (if I have understood correctly). And as far as I have seen so far, it works with varchar, but we haven't done very much testing with unusal foreign characters...
Could someone shed some light on this? | 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 the benefits of that will be compared with the hassles of making *absolutely* sure that not only will the contents be ASCII, but you're *never* going to want anything other than ASCII (or within the specific code page). | 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 values can be stored on a datapage (the unit of database IO).
There are certain strings that you (from the app) control the construction of and would like to use to access important records. Alphanumeric identifiers (such as a customer number) fall into this category. Since you control the construction, you can force these to be safely varchar (and frequently do anyway). Why not gain the benefit of a half-sized double-fast index for this effort you're already doing? | 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'],
['abciximab', 'abciximab'],
...
```
Just to clarify, I would want one of the
```
['3-hidroxitiramina', '3-hidroxitiramina'],
```
To be removed, so there is just one | [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 you want to print only those which are multiples of 6:
```
for i in someNumbers:
if i%6 == 0:
print i
``` | 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 should consequently be `abstract`.
It simply makes no sense for usual classes to be further extended. If an aspect of the class is worth extending and/or modifying, the cleaner way would be to take that one class and separate it into one `abstract` base class and one concrete interchangeable implementation. | 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's very easy to think you can just override a single method, but not know the situations in which that method may be called from the base class as part of the rest of the implementation.
See ["How do you design a class for inheritance"](https://stackoverflow.com/questions/453879/how-do-you-design-a-class-for-inheritance) for more discussion on this. | 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 panel in panel ^^, | 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 supports multiple languages), so **my advice for you is to rather write a specialized layout manager for your specific needs**.
Writing your custom layout manager is quite easy, all you have to do is to be able to calculate the preferred size for a container with given components and your layout, and to do the layout by setting the (calculated) bounds of your components.
I got rid of the GridBagLayout and started coding my own layouts long ago, and layouting has never been easier.
Here's an example of a custom layout, that layouts pairs of key and value components:
```
public class KeyValueLayout implements LayoutManager {
public static enum KeyAlignment {
LEFT, RIGHT;
}
private KeyAlignment keyAlignment = KeyAlignment.LEFT;
private int hgap;
private int vgap;
public KeyValueLayout () {
this(KeyAlignment.LEFT);
}
public KeyValueLayout (KeyAlignment keyAlignment) {
this(keyAlignment, 5, 5);
}
public KeyValueLayout (int hgap, int vgap) {
this(KeyAlignment.LEFT, hgap, vgap);
}
public KeyValueLayout (KeyAlignment keyAlignment, int hgap, int vgap) {
this.keyAlignment = keyAlignment != null ? keyAlignment : KeyAlignment.LEFT;
this.hgap = hgap;
this.vgap = vgap;
}
public void addLayoutComponent (String name, Component comp) {
}
public void addLayoutComponent (Component comp, Object constraints) {
}
public void removeLayoutComponent (Component comp) {
}
public void layoutContainer (Container parent) {
Rectangle canvas = getLayoutCanvas(parent);
int ypos = canvas.y;
int preferredKeyWidth = getPreferredKeyWidth(parent);
for (Iterator<Component> iter = new ComponentIterator(parent); iter.hasNext();) {
Component key = (Component) iter.next();
Component value = iter.hasNext() ? (Component) iter.next() : null;
int xpos = canvas.x;
int preferredHeight = Math.max(key.getPreferredSize().height, value != null ? value.getPreferredSize().height : 0);
if (keyAlignment == KeyAlignment.LEFT)
key.setBounds(xpos, ypos, key.getPreferredSize().width, key.getPreferredSize().height);
else
key.setBounds(xpos + preferredKeyWidth - key.getPreferredSize().width, ypos, key.getPreferredSize().width,
key.getPreferredSize().height);
xpos += preferredKeyWidth + hgap;
if (value != null)
value.setBounds(xpos, ypos, canvas.x + canvas.width - xpos, preferredHeight);
ypos += preferredHeight + vgap;
}
}
public Dimension minimumLayoutSize (Container parent) {
int preferredKeyWidth = getPreferredKeyWidth(parent);
int minimumValueWidth = 0;
int minimumHeight = 0;
int lines = 0;
for (Iterator<Component> iter = new ComponentIterator(parent); iter.hasNext();) {
lines++;
Component key = (Component) iter.next();
Component value = iter.hasNext() ? (Component) iter.next() : null;
minimumHeight += Math.max(key.getPreferredSize().height, value != null ? value.getMinimumSize().height : 0);
minimumValueWidth = Math.max(minimumValueWidth, value != null ? value.getMinimumSize().width : 0);
}
Insets insets = parent.getInsets();
int minimumWidth = insets.left + preferredKeyWidth + hgap + minimumValueWidth + insets.right;
minimumHeight += insets.top + insets.bottom;
if (lines > 0)
minimumHeight += (lines - 1) * vgap;
return new Dimension(minimumWidth, minimumHeight);
}
public Dimension preferredLayoutSize (Container parent) {
int preferredKeyWidth = getPreferredKeyWidth(parent);
int preferredValueWidth = 0;
int preferredHeight = 0;
int lines = 0;
for (Iterator<Component> iter = new ComponentIterator(parent); iter.hasNext();) {
lines++;
Component key = (Component) iter.next();
Component value = iter.hasNext() ? (Component) iter.next() : null;
preferredHeight += Math.max(key.getPreferredSize().height, value != null ? value.getPreferredSize().height : 0);
preferredValueWidth = Math.max(preferredValueWidth, value != null ? value.getPreferredSize().width : 0);
}
Insets insets = parent.getInsets();
int preferredWidth = insets.left + preferredKeyWidth + hgap + preferredValueWidth + insets.right;
preferredHeight += insets.top + insets.bottom;
if (lines > 0)
preferredHeight += (lines - 1) * vgap;
return new Dimension(preferredWidth, preferredHeight);
}
public Dimension maximumLayoutSize (Container target) {
return preferredLayoutSize(target);
}
private int getPreferredKeyWidth (Container parent) {
int preferredWidth = 0;
for (Iterator<Component> iter = new ComponentIterator(parent); iter.hasNext();) {
Component key = (Component) iter.next();
if (iter.hasNext())
iter.next();
preferredWidth = Math.max(preferredWidth, key.getPreferredSize().width);
}
return preferredWidth;
}
private Rectangle getLayoutCanvas (Container parent) {
Insets insets = parent.getInsets();
int x = insets.left;
int y = insets.top;
int width = parent.getSize().width - insets.left - insets.right;
int height = parent.getSize().height - insets.top - insets.bottom;
return new Rectangle(x, y, width, height);
}
private class ComponentIterator implements Iterator<Component> {
private Container container;
private int index = 0;
public ComponentIterator (Container container) {
this.container = container;
}
public boolean hasNext () {
return index < container.getComponentCount();
}
public Component next () {
return container.getComponent(index++);
}
public void remove () {
}
}
}
```
Just set the layout and add alternatingly labels and value components. It's easy to use, especially compared to GridBagLayout or nested panels with custom layouts. | 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 invisible components to absorb the stretches. eg:`layout.setAutoCreateGaps(true);`
SpringLayout might also be useful - see the [visual guide](http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html)
If you really want X and Y then set the layout manager to null, and use setLocation() or setBounds(). I REALLY REALLY wouldn't recommend this, but it does work. Have a read of [this tutorial](http://mindprod.com/jgloss/layout.html) | 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, is there a quick way to find out which files have been added or removed on the disk since the last run?
**EDIT**: I do not want to monitor the file system events. I think the risk is too high to get out of sync, I would much prefer to have something like a quick re-scan that quickly finds where files have been added / removed. Maybe with directory last modified date or something?
## A Little Benchmark
I just made a little benchmark. Running
```
dir /b /s M:\tests\ >c:\out.txt
```
Takes 0.9 seconds and gives me all the information I need. When I use a Java implementation ([much like this](https://stackoverflow.com/questions/189094/how-to-scan-a-folder-in-java)), it takes about 4.5 seconds. Any ideas how to improve at least this brute force approach?
Related posts: [How to see if a subfile of a directory has changed](https://stackoverflow.com/questions/56682/how-to-see-if-a-subfile-of-a-directory-has-changed) | 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 you have the full path (no scanning of all files/dirs in the tree involved).
4. If the timestamp has changed, you have a change in this directory. Rescan it and update the index.
5. If you encounter missing directories in this step, delete the subtree from the index
6. If you encounter an existing directory, ignore it (will be checked in step 2)
7. If you encounter a new directory, add it with timestamp == dir.lastModified()-1. Make sure it gets considered in step 2.
This will allow you to notice new and deleted files in an effective manner. Since you scan only for known paths in step #2, this will be very effective. File systems are bad at enumerating all the entries in a directory but they are fast when you know the exact name.
Drawback: You will not notice changed files. So if you edit a file, this will *not* reflect in a change of the directory. If you need this information, too, you will have to repeat the algorithm above for the file nodes in your index. This time, you can ignore new/deleted files because they have already been updated during the run over the directories.
[EDIT] Zach mentioned that timestamps are not enough. My reply is: There simply is no other way to do this. The notion of "size" is completely undefined for directories and changes from implementation to implementation. There is no API where you can register "I want to be notified of any change being made to something in the file system". There are APIs which work while your application is alive but if it stops or misses an event, then you're out of sync.
If the file system is remote, things get worse because all kinds of network problems can cause you to get out of sync. So while my solution might not be 100% perfect and water tight, it will work for all but the most constructed exceptional case. And it's the only solution which even gets this far.
Now there is a single kind application which would want to preserve the timestamp of a directory after making a modification: A virus or worm. This will clearly break my algorithm but then, it's not meant to protect against a virus infection. If you want to protect against this, you must a completely different approach.
The only other way to achieve what Zach wants is to build a new filesystem which logs this information permanently somewhere, sell it to Microsoft and wait a few years (probably 10 or more) until everyone uses it. | 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 <http://gnuwin32.sourceforge.net/packages/diffutils.htm>
```
dir /b /s /on m:\tests >new.txt
diff new.txt archive.txt >diffoutput.txt
del archive.txt
ren new.txt archive.txt
```
Obviously you could use a java diff class as well but I think the thing to accept is that a shell command is nearly always going to beat Java at a file list operation. | 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 actions in the index controller. They (a non-technical person who can do simple html) basically want to create a simple, static page without having to use an action.
Like there would be some generic action in the index controller that handles requests for a non-existent action. How do you do this or is it even possible?
**edit:** One problem with using \_\_call is the lack of a view file. The lack of an action becomes moot but now you have to deal with the missing view file. The framework will throw an exception if it cannot find one (though if there were a way to get it to redirect to a 404 on a missing view file \_\_call would be doable.) | 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)
```
new Zend_Controller_Router_Route('index/*',
array('controller' => 'index', 'action' => 'custom', 'module'=>'index')
```
in you customAction function just retrieve the params and display the right block.
I haven't tried so you might have to hack the code a little bit | 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($methodName, 0, -6);
// We want to render scripts in the index directory, right?
$script = 'index/' . $action . '.' . $this->viewSuffix;
// Script file does not exist, throw exception that will render /error/error.phtml in 404 context
if (false === $this->view->getScriptPath($script)) {
require_once 'Zend/Controller/Action/Exception.php';
throw new Zend_Controller_Action_Exception(
sprintf('Page "%s" does not exist.', $action), 404);
}
$this->renderScript($script);
}
// no action is called? Let the parent __call handle things.
else {
parent::__call($methodName, $params);
}
}
``` | 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 expressions**](http://www.php.net/preg_match) to scrape the data you want. | ```
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.
This, as Andrew points out, is probably because [all (most)? built-in constants are capitalized](http://docs.python.org/library/constants.html). | 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 to prevent the user from typing within the combobox.
Another solution would to be use 2 combobox, one with all the items and one with all the items but the item selected in the first combobox.
Then prevent the first combobox from expanding and place it above the second combobox. | 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=AFQjCNES3btcbbWo9HSXChrywHTMvZwuNA&sig2=fXBRffm_thJZidEUBXrbSQ) benchmark I found, my implementation's performances really suck. I don't know if it's a super-optimized something or if really you can easily invert a 200 x 200 matrix in about 0.11 seconds, so I'm looking for more benchmarks to compare the results. Have you god some good link?
**UPDATE**
I spotted a bug in my multiplication code, that didn't affect the result but was causing useless cycle waste. Now my inversion executes in 20 seconds. It's still a lot of time, and any idea is welcome.
Thank you folks | 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 improvements. | 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 meta data about the matrix and a pointer (wrapped in by somthing smart) to the data portion. Thus when copying an object you only copy a small chunk of data not the whole thing (see string implementation for an example). | 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('magic_quotes_gpc', 'O')`, but that had no effect.
How do I turn magic quotes off? | 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 don't think O (uppercase letter o) is a valid value to set an ini flag. You need to use a true/false, 1/0, or "on"/"off" value.
```
ini_set( 'magic_quotes_gpc', 0 ); // doesn't work
```
**EDIT**
After checking the [list of ini settings](http://php.net/manual/ini.list.php), I see that magic\_quotes\_gpc is a `PHP_INI_PERDIR` setting (after 4.2.3), which means you can't change it with `ini_set()` (only `PHP_INI_ALL` settings can be changed with `ini_set()`)
What this means is you have to use an .htaccess file to do this - OR - implement a script to reverse the effects of magic quotes. Something like this
```
if ( in_array( strtolower( ini_get( 'magic_quotes_gpc' ) ), array( '1', 'on' ) ) )
{
$_POST = array_map( 'stripslashes', $_POST );
$_GET = array_map( 'stripslashes', $_GET );
$_COOKIE = array_map( 'stripslashes', $_COOKIE );
}
``` | 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 recursive and will correctly strip quotes from arrays:
Update: I noticed today that there's a new version of the following code on the PHP manual that uses references to the super-globals instead.
Old version:
```
<?php
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
?>
```
New version:
```
<?php
if (get_magic_quotes_gpc()) {
$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
while (list($key, $val) = each($process)) {
foreach ($val as $k => $v) {
unset($process[$key][$k]);
if (is_array($v)) {
$process[$key][stripslashes($k)] = $v;
$process[] = &$process[$key][stripslashes($k)];
} else {
$process[$key][stripslashes($k)] = stripslashes($v);
}
}
}
unset($process);
}
?>
``` | 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 documentation:
> Name of a file, directory, or folder as it would be displayed in a system file browser. Example from Windows: the "M:\" directory displays as "CD-ROM (M:)" The default implementation gets information from the ShellFolder class. | 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[]){
List <File>files = Arrays.asList(File.listRoots());
for (File f : files) {
String s1 = FileSystemView.getFileSystemView().getSystemDisplayName (f);
String s2 = FileSystemView.getFileSystemView().getSystemTypeDescription(f);
System.out.println("getSystemDisplayName : " + s1);
System.out.println("getSystemTypeDescription : " + s2);
}
/* output (French WinXP)
getSystemDisplayName :
getSystemTypeDescription : Disquette 3½ pouces
getSystemDisplayName : REGA1 (C:)
getSystemTypeDescription : Disque local
getSystemDisplayName :
getSystemTypeDescription : Lecteur CD
getSystemDisplayName : My Book (F:)
getSystemTypeDescription : Disque local
*/
}
}
``` | 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){
> // do something
> }
> ```
>
> or
>
> ```
> // NOTE!! THE FOLLOWING IS WRONG; DO NOT USE! -- EleotleCram
> if($("#something") === null){
> // don't do something
> }
> ```
While it is true that calling the length property on an undefined or null object will cause browsers to fail, the result of jQuery's selectors (the $('...')) will *never* be null or undefined. Thus the code suggestions make no sense. Use one of the other answers, they make more sense.
---
(Update 2012) Because people look at code and this answer is pretty high up the list: For the last couple of years, I have been using this small plugin:
```
jQuery.fn['any'] = function() {
return (this.length > 0);
};
```
I think **$('div').any()** reads better than **$('div').length**, plus you won't suffer as much from typos: **$('div').ayn()** will give a runtime error, **$('div').lenght** will silently most likely always be falsy.
\_\_
Edits november 2012:
1) Because people tend to look at code and not read what is said around the code, I added two big caveat lector notes to the quoted code of Wolf.
2) I added code of the small plugin I use for this situation. | 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](http://showandtell-graphics.com/images/gradient/gradient_12.jpg))
The input would be the array to fill, two points (like the starting and ending point for the Gradient tool in Photoshop/GIMP) and the range of values which would be used.
My current best result is this:
[alt text http://img222.imageshack.us/img222/1733/gradientfe3.png](http://img222.imageshack.us/img222/1733/gradientfe3.png)
...which is nowhere near what I would like to achieve. It looks more like a radial gradient.
What is the simplest way to create such a gradient? I'm going to implement it in C++, but I would like some general algorithm. | 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 to the colour your want to end with. You can think of this in terms of a range the within Ox0 to OxFFFFFF (for 24 bit colour). If you want to handle things like brightness, you'll have to do some tricks with the range (i.e. the y value).
2. Next you need to map a vector across the matrix you have, as this defines the direction that the colours will change in. Also, the colour values defined by your linear function will be assigned at each point along the vector. The start and end point of the vector also define the min and max of the domain in 1. You can think of the vector as one line of your gradient.
3. For each cell in the matrix, colours can be assigned a value from the vector where a perpendicular line from the cell intersects the vector. See the diagram below where c is the position of the cell and . is the the point of intersection. If you pretend that the colour at . is Red, then that's what you'll assign to the cell.
```
|
c
|
|
Vect:____.______________
|
|
``` | 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 is (x1, y1) and your ending point is (x2, y2)
2. Compute `A = (x2 - x1)` and `B = (y2 - y1)`
3. Calculate `C1 = A * x1 + B * y1` for the starting point and `C2 = A * x2 + B * y2` for the ending point (`C2` should be larger than `C1`)
4. For each point in the image, calculate `C = A * x + B * y`
5. If `C <= C1`, use the starting color; if `C >= C2`, use the ending color; otherwise, use a weighted average:
`(start_color * (C2 - C) + end_color * (C - C1))/(C2 - C1)`
I did some quick tests to check that this basically worked. | 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 debugger. | 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 jump right to the first byte. | 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 determine the address of the variable, I usually used the watch window.
However, in newer versions, you often can just type in the name of the variable as the Address, just like you would in a watch window. | 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) but I can't understand the theorem correctly to be able to convert the result of maximum bipartite matching to vertex cover. | 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 PrintResults()
{
Console.WriteLine(String.Join(" ", VertexCoverResult.Select(x => x.ToString()).ToArray()));
}
private void FindVertexCover()
{
FindBipartiteMatching();
var TreeSet = new HashSet<int>();
foreach (var v in LeftVertices)
if (Matching[v] < 0)
DepthFirstSearch(TreeSet, v, false);
VertexCoverResult = new HashSet<int>(LeftVertices.Except(TreeSet).Union(RightVertices.Intersect(TreeSet)));
}
private void DepthFirstSearch(HashSet<int> TreeSet, int v, bool left)
{
if (TreeSet.Contains(v))
return;
TreeSet.Add(v);
if (left) {
foreach (var u in Edges[v])
if (u != Matching[v])
DepthFirstSearch(TreeSet, u, true);
} else if (Matching[v] >= 0)
DepthFirstSearch(TreeSet, Matching[v], false);
}
private void FindBipartiteMatching()
{
Bicolorate();
Matching = Enumerable.Repeat(-1, VertexCount).ToArray();
var cnt = 0;
foreach (var i in LeftVertices) {
var seen = new bool[VertexCount];
if (BipartiteMatchingInternal(seen, i)) cnt++;
}
}
private bool BipartiteMatchingInternal(bool[] seen, int u)
{
foreach (var v in Edges[u]) {
if (seen[v]) continue;
seen[v] = true;
if (Matching[v] < 0 || BipartiteMatchingInternal(seen, Matching[v])) {
Matching[u] = v;
Matching[v] = u;
return true;
}
}
return false;
}
private void Bicolorate()
{
LeftVertices = new HashSet<int>();
RightVertices = new HashSet<int>();
var colors = new int[VertexCount];
for (int i = 0; i < VertexCount; ++i)
if (colors[i] == 0 && !BicolorateInternal(colors, i, 1))
throw new InvalidOperationException("Graph is NOT bipartite.");
}
private bool BicolorateInternal(int[] colors, int i, int color)
{
if (colors[i] == 0) {
if (color == 1) LeftVertices.Add(i);
else RightVertices.Add(i);
colors[i] = color;
} else if (colors[i] != color)
return false;
else
return true;
foreach (var j in Edges[i])
if (!BicolorateInternal(colors, j, 3 - color))
return false;
return true;
}
private int VertexCount;
private HashSet<int>[] Edges;
private HashSet<int> LeftVertices;
private HashSet<int> RightVertices;
private HashSet<int> VertexCoverResult;
private int[] Matching;
private void ReadIntegerPair(out int x, out int y)
{
var input = Console.ReadLine();
var splitted = input.Split(new char[] { ' ' }, 2);
x = int.Parse(splitted[0]);
y = int.Parse(splitted[1]);
}
private void ParseInput()
{
int EdgeCount;
ReadIntegerPair(out VertexCount, out EdgeCount);
Edges = new HashSet<int>[VertexCount];
for (int i = 0; i < Edges.Length; ++i)
Edges[i] = new HashSet<int>();
for (int i = 0; i < EdgeCount; i++) {
int x, y;
ReadIntegerPair(out x, out y);
Edges[x].Add(y);
Edges[y].Add(x);
}
}
}
```
As you can see, this code solves the problem in polynomial time. | 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, though, since if I remember correctly, its NP complete. | 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 PrettyPrinter constructor as
> formatting parameters.
Example:
```
>>> import pprint
>>> people = [
... {"first": "Brian", "last": "Kernighan"},
... {"first": "Dennis", "last": "Richie"},
... ]
>>> pprint.pformat(people, indent=4)
"[ { 'first': 'Brian', 'last': 'Kernighan'},\n { 'first': 'Dennis', 'last': 'Richie'}]"
``` | 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.SoapHeaderAttribute("MruHeaderValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("SessionHeaderValue")]
[System.Web.Services.Protocols.SoapHeaderAttribute("QueryOptionsValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace = "urn:partner.soap.sforce.com", ResponseNamespace = "urn:partner.soap.sforce.com", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("result")]
public QueryResult query(string queryString)
{
object[] results = this.Invoke("query", new object[] {
queryString});
return ((QueryResult)(results[0]));
}
```
Thanks for your help! | 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-43c5-8ec1-8d789091255d&displaylang=en)
in the class you'll have RequestSoapContext.Envelope.InnerXml and ResponseSoapContext.Envelope.InnerXml in the scope - that's exactly what you need. | 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 .ASPX page or web service documentation. | 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 Spring);
* loaded from properties files (eg JDBC driver name);
* added dynamically with annotations;
* loaded as a result of external input (eg user input, data from a database or remote procedure call);
* etc.
So just looking at source code isn't enough. That being said, any reasonable IDE will provide you with dependency analysis tools. IntelliJ certainly does.
What you really need is runtime instrumentation on what your application is doing but even that isn't guaranteed. After all, a particular code path might come up one in 10 million runs due to a weird combination of inputs so you can't be guaranteed that you're covered.
Tools like this do have some value though. You might want to look at something like [Emma](http://emma.sourceforge.net/). Profilers like [Yourkit](http://www.yourkit.com/) can give you a code dump that you can do an analysis on too (although that won't pick up transient objects terribly well).
Personally I find little value beyond what the IDE will tell you: removing unused JARs. Going more granular than that is just asking for trouble for little to no gain. | 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 inserted into a checkedlistbox. How would I go about doing that?
I imagine some LINQ magic can manage this? | 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.objectName )
.Distinct()
.ToList() );
```
If accessing the checkedListBox as a ListControl doesn't give access to the DataSource (sometimes the [docs](http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.aspx) lie), you could try:
```
cbListBox.Items.AddRange( fieldList.Select( f => f.objectName )
.Distinct()
.ToArray() );
``` | ```
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 basic problem is: Some data changes in the database. How can I trigger some C# code doing some work upon these changes?
---
To give some stimulus for answers, I mention some approaches, which I am currently considering:
1. Make application B polling for
changes in the tables of interest.
Advantage: Simple approach.
Disadvantage: Lots of traffic,
especially when many tables are
involved.
2. Introduce triggers, which will fire
on certain events. When they fire
they should write some entry into an
“event table”. Application B only
needs to poll that “event table”.
Advantage: Less traffic.
Disadvantage: Logic is placed into
the database in the form of triggers.
(It’s not a question of the
“evilness” of triggers. It’s a design
question, which makes it a
disadvantage.)
3. Get rid of the polling approach and
use SqlDependency class to get
notified for changes. Advantage:
(Maybe?) Less traffic than polling
approach. Disadvantage: Not database
independent. (I am aware of
OracleDependency in ODP.NET, but what
about the other databases?)
What approach is more favorable? Maybe I have missed some major (dis)advantage in the mentioned approaches? Maybe there are some other approaches I haven’t think of?
---
Edit 1: Database independency is a factor for the ... let's call them ... "sales people". I can use SqlDependency or OracleDependency. For DB2 or other databases I can fall back to the polling approach. It's just a question of cost and benefit, which I want to at least to think about so I can discuss it. | 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.
* If you're only adding records, not changing them, then checking the highest id might be enough on a particular table.
* If you're updating them all then you can store a timestamp column and index it, then look for the maximum timestamp.
* And you can send an ubber query that polls multiple talbes (efficiently) and returns the list of changed tables.
Nothing in this answer is particularly clever, I'm just trying to show that #1 may not be quite as bad as it at first seems. | 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 *does* output other things, is there a good method for doing this? Maybe messing with the output buffer? | 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 wrapping it around the call of the method):
```
function foo() {
echo "Flush!";
return true;
}
ob_start();
$a = foo();
ob_end_clean();
```
And no output is generated. | 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 bug? Is that documented anywhere?
But the real question (and the answer I will mark as correct) is:
What is the python developers' reason to allow that odd behavior? | 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 putting a return statement in a finally clause, you have declared that you want to return a value, no matter what, regardless of exceptions. If Python behaved as you are asking and raised the exception, it would be breaking the contract of the "finally" clause (because it would fail to return the value you told it to return). | > 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 an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. **If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.** | 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 array.
```
Your best bet is to add a string argument to the objects constructor, and give it a name when its created. | 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 hierarchy, which uses a similar approach. | 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 work when another element (e.g. the menu bar) was the last thing that was clicked on.
Is there a way to track key presses in this case as well? I don't have access to the code outside my data grid view/control.
The answer to this may be a clear no, but I wanted to make sure I wasn't missing something obvious in making this work. | 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:
// Send Refesh Event To Grid
return true; // Mark Key As Handled
// Add Any Extra Command Keys Here
}
return base.ProcessCmdKey(ref msg, keyData); // Resend To Base Function
}
``` | 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 django for you!"
``` | 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 void CalcCashTotal()
{
_totalCash = _price * _quantity
}
public double Price
{
set
{
_price = value;
CalcCashTotal();
}
}
public double Quantity
{
set
{
_price = value;
CalcCashTotal();
}
}
public double TotalCash
{
get
{
return _totalCash;
}
}
``` | 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 also take a hybrid approach. You could set a IsDirtyTotalPrice boolean in all the dependant sets, and then do the calculation on the fly in the get and cache it so that the get only calculates the variable when it needs to. You don't do the calculation in the sets because there could be a lot of them, and you wan to do the calculation as few times as possible.
```
public class Order
{
private double _totalCash;
private double _price;
private double _quantity;
private _IsDirtyTotalCash = true;
private void CalcCashTotal()
{
_totalCash = _price * _quantity
}
public double Price
{
set
{
_price = value;
_IsDirtyTotalCash = true;
}
}
public double Quantity
{
set
{
_price = value;
_IsDirtyTotalCash = true;
}
}
public double TotalCash
{
get
{
if(_IsDirtyTotalCash)
{
_totalCash = CalcTotalCost();
_isDirtyTotalCash = false;
}
return _totalCash;
}
}
}
``` | 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 recalculates the quantity when either price or quantity is set. | 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 deal with a shop system where the original author put some application logic into a trigger (bad idea!). That application logic works fine as long as you don't try to insert data in another way than the original "administration frontend". My job is to write an "import from staging system" tool, so I have all data ready. When I try to insert it, the trigger overwrites the existing Product Code (not the IDENTITY numeric ID!) with a generated one. To generate the Code it uses the autogenerated ID of an insert to another table, so that I can't even work with the @@IDENTITY to find my just inserted column and UPDATE the inserted row with the actual Product Code.
Any way that I can go to avoid extremly awkward code (INSERT some random characters into the product name and then try to find the row with the random characters to update it).
So: Is there a way to disable triggers (even just one) for **just one** INSERT? | 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 that be with an "insert type" flag on the table or some other means if you are already storing a type of some sort. | 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 value).
Now you need to insert a product that was created by some staging system, and for that product its product code was created by the staging system and you want to insert it to the live system manually.
If you really have to do it you need to make sure that the codes generated by you live application in the future are not going to conflict with the code that you inserted manually - I assume they musty be unique.
Other approach is to allow the system to generate the new code and overwrite any corresponding data if needed. | 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 actual tab is saying 'Custom'. I think it's called metadata what it shows.
I noticed that only the files I'm looking at have that tab. It seems to be specific only for the SLDLFP -file. | 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 mention of SLDLFP, I'm guessing that you are working with SolidWorks files.
There *may* be some standard APIs for this, but none that I have heard of.
Using SolidWorks via Automation is probably going to be your best bet.
I found a link describing how to read these kind of values with a Word 2003 and VB.Net, I would expect that it is similar to how to do this with SolidWorks.
[Reading and Writing Custom Document Properties in Microsoft Office Word 2003 with Microsoft Visual Basic .NET](http://msdn.microsoft.com/en-us/library/aa537163.aspx) | 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 runtimes. The jvm has a significantly higher memory footprint than the clr. I'm assuming there is some benefit to this overhead otherwise why would it exist. I'm asking what the trade-offs are in these two designs. What benefit does the jvm gain from it's memory overhead? | 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) has to be fully contained in Java so that it works the same on both.
Java also always insists that it's entire library is "Linked" and available. Since it doesn't use DLLs (they wouldn't be available on every platform), everything has to be loaded and tracked by java.
Java even does a lot of it's own floating point since the FPUs often give different results which has been deemed unacceptable.
So if you think about all the stuff C# can delegate to the OS it's tied to vs all the stuff Java has to do for the OS to compensate for others, the difference should be expected.
I've run java apps on 2 embedded platforms now. One was a spectrum analyzer where it actually drew the traces, the other is set-top cable boxes.
In both cases, this minimum memory footprint hasn't been an issue--there HAVE been Java specific issues, that just hasn't been one. The number of objects instantiated and Swing painting speed were bigger issues in these cases. | 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# and in Java that print the string "test" and waits for input. I believe that the resident set size (RSS) value more accurately shows the memory usage. The virtual memory useage (VSZ) is less meaningful.
As I understand it applications can reserve a ton of virtual memory without actually using any real memory. For example you can ask the [VirtualAlloc](http://msdn.microsoft.com/en-us/library/aa366887.aspx) function on Windows to either reserve or commit virtual memory.
EDIT:
Here is a pretty picture from my windows box:
[alt text http://awise.us/images/mem.png](http://awise.us/images/mem.png)
Each app was a simple printf followed by a getchar.
Lots of virtual memory usage by Java and CLR. The C version depends on just about nothing, so it's memory usage is tiny relatively.
I doubt it really matters either way. Just pick whichever platform you are more familiar with and then don't write terrible, memory-wasting code. I'm sure it will work out.
EDIT:
This [VMMap tool](http://technet.microsoft.com/en-us/sysinternals/dd535533.aspx) from Microsoft might be useful in figureing out where memory is going. | 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 control, how would you do it? | 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"] = "stylesheet";
stylesLink.Attributes["type"] = "text/css";
stylesLink.Href = "css/mini-template-control.css";
Page.Header.Controls.Add(stylesLink);
```
This will load css and Javascript into the head tag of the main page, just make sure that the head has runat="server". | 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 Embedded Resources,
and aquire dynamic URL's through the WebResource.axd handler.
If this is not considered totally complete, then i guess it could be put in App\_LocalResources, but it never gonna be just one file,
unless the code and script is inline. | 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;
}
//Console.WriteLine(line);
line = stripColors(line);
txtOut.Text += line + "\n";
line = sr.ReadLine();
}
}
}
```
And it reads the streams from a Process (cmd.exe). When the user closes the cmd.exe window, it causes the CPU usage to jump to 100%. When playing with the debugger I see that it stops on the sr.ReadLine() and never returns. Because this is watching both the StandardErrorStream and the StandardOutputStream it uses 100% on both cores.
Here's some more code of the project if you need it.
```
[DllImport("User32")]
private static extern int ShowWindow(int hwnd, int nCmdShow); //this will allow me to hide a window
public ConsoleForm(Process p) {
this.p = p;
p.Start();
ShowWindow((int)p.MainWindowHandle, 0); //0 means to hide the window.
this.inStream = p.StandardInput;
this.outStream = p.StandardOutput;
this.errorStream = p.StandardError;
InitializeComponent();
wr = new watcherReader(watchProc);
wr.BeginInvoke(this.outStream, null, null);
wr.BeginInvoke(this.errorStream, null, null);
}
public void start(string[] folders, string serverPath) {
this.inStream.WriteLine("chdir C:\\cygwin\\bin");
this.inStream.WriteLine("bash --login -i");
this.inStream.WriteLine("");
}
//code example from http://geekswithblogs.net/Waynerds/archive/2006/01/29/67506.aspx it is
//to make the textbox autoscroll I don't understand what it does, but it works.
#region autoscroll
[DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
const int WM_VSCROLL = 277;
const int SB_BOTTOM = 7;
private void txtOut_TextChanged(object sender, EventArgs e) {
IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
IntPtr ptrLparam = new IntPtr(0);
SendMessage(((RichTextBox)sender).Handle, WM_VSCROLL, ptrWparam, ptrLparam);
}
#endregion
private void ConsoleForm_FormClosed(object sender, FormClosedEventArgs e) {
this.stop = true;
try {
this.p.Kill();
} catch (InvalidOperationException) {
return;
}
}
```
Another interesting this is that it doesn't always hide the cmd window like it's supposed to. It hides it the first time, and then the second (or after) it won't hide it. This is when the user can close the cmd.exe window and cause the readline to act funny. It also never reads the last line outputted to cmd unless it exits.
Any suggestions on how to fix this? | 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.