Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Using C#, say you have a ComboBox that has a DropDownStyle set to DropDown (there are items in the drop down but the user can manually enter a value as well). How do you set a default value for the ComboBox that is **not** in the list of values in the drop down, but *begins with* text from a possible selection? Normally setting ComboBox.Text works fine, but if there is an item in the drop down that *begins with* the text you want as the default, it automatically selects the first item in the list that starts with the text. For example:
**Values in the drop down:**
`c:\program files\`
`c:\windows\`
`d:\media\`
**Default Value Assignment**
`myComboBox.Text = "C:\";`
**Result**
Initial value of ComboBox when the form opens is "`c:\program files\`".
So what am I doing wrong? How do I correctly set a default value of an item not in the drop down list that begins with a possible selection? | I couldn't repro the behavior you are describing. Adding the three values via the Items collection and then setting the initial value to "c:\" (you omitted an @ in your code sample, by the way) worked fine. My guess is that something else in your code is setting the value of the combo box after you set it. | Does the following code work?
```
myCombo.SelectedIndex = myCombo.FindString(@"c:\");
```
Note: I haven't tried it. Looked up for properties/methods that could help using reflector. | How do I set a ComboBox default *not in the drop down* when a list item begins with the same text as a drop down item? | [
"",
"c#",
".net",
"user-interface",
"combobox",
""
] |
I'm running this code:
```
RESTORE DATABASE [MyDB_2009May11]
FROM DISK = N'C:\DB Copy\MyDB_2009May11.bak'
WITH
MOVE N'Archive_Data'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.mdf',
MOVE N'Data'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.mdf',
MOVE N'Log'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.ldf',
NOUNLOAD,
STATS = 10
GO
```
I'm getting this error:
Msg 3176, Level 16, State 1, Line 1
File 'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB\_2009May11.mdf' is claimed by 'Archive\_Data'(3) and 'Data'(1). The WITH MOVE clause can be used to relocate one or more files.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
How the crap do I migrate from sql server 2000 to 2008 when all I have is the backup file?
:) Any help is appreciated. | do a select \* from sysaltfiles and look at the correct filenames and then change the names in the move to part accordingly
This will give you the names of all the filegroups currently
```
select filename from master..sysaltfiles
where name = 'MyDB_2009May11'
```
if you don't have the databse scripted yet then do this first. make sure the folders exists, you might also want to change the filesizes
```
CREATE DATABASE [MyDB_2009May11] ON (NAME = N'Data',
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.mdf'
, SIZE = 12, FILEGROWTH = 10%),
(NAME = N'Archive_Data',
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.ndf'
, SIZE = 12, FILEGROWTH = 10%)
LOG ON (NAME = N'Log',
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.ldf'
, SIZE = 21, FILEGROWTH = 10%)
COLLATE SQL_Latin1_General_CP1_CI_AS
```
Now the restore should be this, notice the ndf extension for the archive filegroup
```
RESTORE DATABASE [MyDB_2009May11]
FROM DISK = N'C:\DB Copy\MyDB_2009May11.bak'
WITH
MOVE N'Archive_Data'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.mdf',
MOVE N'Data'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.ndf',
MOVE N'Log'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\MyDB_2009May11.ldf',
NOUNLOAD,
STATS = 10
GO
``` | You're trying to move Archive\_Data and Data to the same file - change the file name and you should be fine :) | how to migrate from sql 2000 to sql 2008 via restore? | [
"",
"sql",
"sql-server-2008",
"migrate",
""
] |
Let's say I have a class A which can fire an event called X. Now I have a class B and in a method I get an instance to A and bind the event to a handler in B:
```
public void BindEvent(A a)
{
a.X += AEventHandler;
}
```
I have three questions about this.
* Is it true that when I now set the reference to the B instance to null, it won't be garbage collected since the garbage collector thinks it's still in use (thus keeping a useless and potentially interfering copy of B in memory).
* What about when I have another object c (of class C) in which I have a reference to A called a ("this.a = new A()"). Then I call "b.BindEvent(this.a)", and in c I set the reference to a to null ("this.a = null"). Will this keep the copy of A in memory because it's referenced through the event in b?
* If either or both are true of the above, how can I best circumvent these issues? If I have a whole list of event handlers (say 10 lines like "a.SomeEvent += SomeMethod") should I clean them all up again ("a.SomeEvent -= SomeMethod"). At which time or place in the code should I do these things?
Well it's gotten a bit fuzzy but I'm not sure how to explain in a better way. Please leave a comment if I need to explain something more detailed. | so: `A` is the publisher and `B` is the subscriber?
first bullet: if `B` is the instance with `AEventHandler` - then it **is** still in use, so no, it won't get collected unless the `a` instance is unreachable.
second bullet: huh? (will read again...) If the `A` and `B` instances are both unreachable, they will be garbage collected; the event doesn't matter. If `A` is reachable, then `B` will stay alive. However, the event subscription **never** keeps `A` alive; it is one way... `A` can keep `B` alive, but `B` doesn't keep `A` alive. Does that cover it?
third bullet: in most cases, the two things have similar life expentency, so it isn't an issue. It only becomes an issue if the thing publishing the event lives a lot longer than the things with the handlers. In which case, you simply need to religiously clean up after yourself - for example: `a.X -= AEventHandler`. In particular, `static` events are **evil** for this reason. | You should really unbind the event handler before destroying the class instance that it relates to. (Using your code as an exmaple.)
```
public void UnbindEvent(A a)
{
a.X -= AEventHandler;
}
```
I would also ask, why are you setting class variables to null? | How to get rid of event handlers safely? | [
"",
"c#",
"events",
""
] |
I'm looking for an example of an open-source project that was engineered using Test Driven Development (TDD) in C# on the .NET Framework. Does anyone know of one? | If you are interested in web development in ASP.NET MVC (C#) check [KIGG Project](http://www.codeplex.com/Kigg) and [Kona](http://mvcsamples.codeplex.com/) [Project](http://www.asp.net/learn/mvc-videos/#MVCStorefrontStarterKit) | Just doing Unit tests not means you are doing TDD.
TDD is writing test before the solution. | Open Source Projects Engineered using TDD and C#? | [
"",
"c#",
"open-source",
"tdd",
""
] |
I have a table in Oracle 10 with following structure
```
Create Table Bookmarks(
BOOKMARKID NUMBER(10,0) NOT NULL PRIMARY KEY,
URL VARCHAR2(4000 CHAR) NOT NULL UNIQUE
)
```
URL has a unique constraint set thus a unique index. There are about 1 million records in this table. I have to frequently check if a bookmark already exists in the table. I am issuing the following query
```
Select bookmarkid from Bookmarks where URL='<some url>'
```
The problem is that as the number of records have grown so has the performance gone down. Now It takes significantly longer to return the bookmark id specially when the query URL is long. In the Explain Plan the query does use Unique index on URL column. Any suggestions for improving response time? | You would typically use a hash index for this. In mssql I would create a persisted computed column that did like CRC(url). Then when you want to check for existance, you look up WHERE crc('some url') = PersistedCrcColumn AND URL='some url'
You have to include the original check with the crc check since you can occassionally get CRC collisions.
EDIT - changing my description above from 'hash lookup' to 'hash index' to avoid confusion. Some dbs have hash indexes as a first class index, I don't believe oracle does (and I know mssql doesn't). If it is not supported intrinsically, the above approach is how you implement it manually. | Make index that includes bookmarkid column also.
Like this:
```
create IX on bookmarks (url, bookmarkid);
``` | Optimizing SELECT Query on Oracle 10 Dense Unique Index | [
"",
"sql",
"oracle",
"optimization",
""
] |
I have a new problem that bugs me ...
I am making a web page that I want to be fixed with no scrolling and most important I want my main Div to fill aaaaaaaaall my available space...
I made this code
```
<!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" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<title>There is a @#!¤*-ing blank !</title>
<style type='text/css'>
html {margin:0px;padding:0px;height:100%;overflow:hidden;border: 3px solid green}
div {margin:0px;padding:0px;}
</style>
</head>
```
<body onload="document.getElementById('mydiv').style.height=document.getElementsByTagName('html')[0].offsetHeight+'px'"><div id="mydiv" style="margin:0px;padding:0px;width:100%;border: 2px solid red"></div></body>
</html>
As you can see I get a white space between my body element border and my div element border even though my body padding and div margin are set to 0...
I had once read "More Eric Meyer on CSS" that contains a solution to this issue but it was a long time ago and I don't remember ...
Any help would be greatly appreciated ^^. | You didn't set the body's style:
```
body {margin: 0px; padding: 0px; height: 100%;}
``` | Your body margin isn't set to 0px, just that of html. | HTML blank I want to erase | [
"",
"javascript",
"html",
"css",
"padding",
"margin",
""
] |
I was browsing the source code of some website, and noticed a dll file being used as the `src` of a `<script>`.
(`view-source:http://www.yellowbridge.com/onlinelit/baijiaxing.php`)
It was something like: `<script src="some-dll-file.dll"></script>`
Several questions:
* I didn't know a `<script>` could be anything besides js. What else can it be used for?
* Can you point me in the direction of some more information on this topic? I've tried ggoogling around, but realized that I don't know what I should be googling exactly.
* Is this cross-platform? I mean if I were to try this on epiphany on an ubuntu box, would it function and serve its purpose?
I'm on a windows box right now and won't have access to anything else for a while, so I can't test it myself. | Only JavaScript can be used as the client-side scripting language (and VBScript too, in IE). The `src` attribute just specifies some URL, and that URL will return the JavaScript.
So, the URL <http://www.yellowbridge.com/lib/yellowbridge.dll> actually does return JavaScript. If you save its contents as a local text file, you can read the script.
Without knowing anything about the site or its JavaScript, I would guess they are dynamically generating some part of the script file from the DLL.
Edit: actually, looking at generated JS, I guess it's dynamically compressing the script on its way to the client. | Actually the file you are referring to '***yellowbridge.dll***' is a javascript file itself. You can view the source of this file.
It might be the dll that generates javascript code. | DLL as `src` of `<script>` | [
"",
"javascript",
"html",
"dll",
"scripting",
"client-side",
""
] |
I'm trying to store a complex object here and am doing that by serialising the object running a `mysql_real_escape_string` on it and inserting it into a mysql database.
However when I retrieve it running a sql query - I'm using `Zend` frameworks `Zend_DB_Table` here but anyway - and when I try to stripslashes and unserialize I dont get my object back. I've tried to just unserialize without stripping slashes and all but nothings working.
---
**UPDATE**
This is weird. I made a simple page which just unserializes a serialised object. If I take the serialized string as it is retrieved from the database and unserialize it via this other page which just has an `unserialize()` on it - it works perfectly and I get my object back. However in the code where ironically I'm retriving the string and I run the exact same unserialize option there ,its not working!
So basically there is nothing wrong with the serialized string - for some weird reason it won't unserialize it in my application but it unserializes somewhere else, it makes no sense. | You probably need to run it through base64 encoding first:
```
$safe_string_to_store = base64_encode(serialize($data));
```
Then to get it back out:
```
$date = unserialize(base64_decode($safe_string_to_store));
```
Try that and let us know if it works.
(and dont run stripslashes on it - there is no need to) | You shouldn't run `stripslashes` on it - the database will give you back the right string to put into `unserialize`.
Make sure you have notices turned on and echo the string before you unserialize it - does it look right? | Cannot unserialize object after storing it serialized in database | [
"",
"php",
"mysql",
"zend-framework",
"serialization",
""
] |
I'm designing a new system to store short text messages [sic].
I'm going to identify each message by a unique identifier in the database, and use an AUTO\_INCREMENT column to generate these identifiers.
Conventional wisdom says that it's okay to start with 0 and number my messages from there, but I'm concerned about the longevity of my service. If I make an external API, and make it to 2^31 messages, some people who use the API may have improperly stored my identifier in a signed 32-bit integer. At this point, they would overflow or crash or something horrible would happen. I'd like to avoid this kind of foo-pocalypse if possible.
Should I "UPDATE message SET id=2^32+1;" before I launch my service, forcing everyone to store my identifiers as signed 64-bit numbers from the start? | If you wanted to achieve your goal and avoid the problems that cletus mentioned, the solution is to set your starting value to 2^32+1. There's still plenty of IDs to go and it won't fit in a 32 bit value, signed or otherwise.
Of course, documenting the value's range and providing guidance to your API or data customers is the only right solution. Someone's always going to try and stick a long into a char and wonder why it doesn't work (always) | Actually 0 can be problematic with many persistence libraries. That's because they use it as some sort of sentinel value (a substitute for NULL). Rightly or wrongly, I would avoid using 0 as a primary key value. Convention is to start at 1 and go up. With negative numbers you're likely just to confuse people for no good reason. | Should I initialize my AUTO_INCREMENT id column to 2^32+1 instead of 0? | [
"",
"sql",
"twitter",
"64-bit",
"primary-key",
""
] |
I'm having an SQL query (MSSQLSERVER) where I add columns to the resultset using subselects:
```
SELECT P.name,
(select count(*) from cars C where C.type = 'sports') AS sportscars,
(select count(*) from cars C where C.type = 'family') AS familycars,
(select count(*) from cars C where C.type = 'business') AS businesscars
FROM people P
WHERE P.id = 1;
```
The query above is just from a test setup that's a bit nonsense, but it serves well enough as example I think. The query I'm actually working on spans a number of complex tables which only distracts from the issue at hand.
In the example above, each record in the table "people" also has three additional columns: "wantsSportscar", "wantsFamilycar" and "wantsBusinesscar". Now what I want to do is only do the subselect of each additional column if the respective "wants....." field in the people table is set to "true". In other words, I only want to do the first subselect if P.wantsSportscar is set to true for that specific person. The second and third subselects should work in a similar manner.
So the way this query should work is that it shows the name of a specific person and the number of models available for the types of cars he wants to own. It might be worth noting that my final resultset will always only contain a single record, namely that of one specific user.
It's important that if a person is not interested in a certain type of cars, that the column for that type will not be included in the final resultset. An example to be sure this is clear:
If person A wants a sportscar and a familycar, the result would include the columns "name", "sportscars" and "familycars".
If person B wants a businesscar, the result would include the columns "name" and "businesscar".
I've been trying to use various combinations with IF, CASE and EXISTS statements, but so far I've not been able to get a syntactically correct solution. Does anyone know if this is even possible? Note that the query will be stored in a Stored Procedure. | In your case, there are `8` column layouts possible and to do this, you will need `8` separate queries (or build your query dynamically).
It's not possible to change the resultset layout within a single query.
Instead, you may design your query as follows:
```
SELECT P.name,
CASE WHEN wantssport = 1 THEN (select count(*) from cars C where C.type = 'sports') ELSE NULL END AS sportscars,
CASE WHEN wantsfamily = 1 THEN (select count(*) from cars C where C.type = 'family') ELSE NULL END AS familycars,
CASE WHEN wantsbusiness = 1 THEN (select count(*) from cars C where C.type = 'business') ELSE NULL END AS businesscars
FROM people P
WHERE P.id = 1
```
which will select `NULL` in appropriate column if a person doesn't want it, and parse these `NULL`'s on client side.
Note that relational model answers the queries in terms of `relations`.
In your case, the relation is as follows: "this person needs are satisifed with this many sport cars, this many business cars and this many family cars".
Relational model always answers this specific question with a quaternary relation.
It doesn't omit any of the relation members: instead, it just sets them to `NULL` which is the `SQL`'s way to show that the member of a relation is not defined, applicable or meaningful. | I'm mostly an Oracle guy but there's a high chance the same applies. Unless I've misunderstood, what you want is not possible at that level - you will always have a static number of columns. Your query can control if the column is empty but since in the outer-most part of the query you have specified X number of columns, you are guaranteed to get X columns in your resultset.
As I said, I am unfamiliar with MS SQL Server but I'm guessing there will be some way of executing dynamic SQL, in which case you should research that since it should allow you to build a more flexible query. | SQL: selective subqueries | [
"",
"sql",
"conditional-statements",
"subquery",
""
] |
```
Set<Type> union = new HashSet<Type>(s1);
```
And
```
Set<Type> union = new HashSet<Type>();
Set<Type> s1 = new HashSet<Type>();
union.addAll(s1);
``` | Assuming that `Set` `s1` contains the same contents in the first and second examples, the end results should come out to be the same.
(However, the second example will not compile because a `Set` is an interface rather than a concrete class.)
One advantage of using the [`HashSet(Collection)`](http://java.sun.com/javase/6/docs/api/java/util/HashSet.html#HashSet(java.util.Collection)) constructor is that it will have an initial capacity that is enough to hold the `Collection` (in this case, the `Set` `s1`) that is passed into the constructor:
> Constructs a new set containing the
> elements in the specified collection.
> The `HashMap` is created with default
> load factor (0.75) and an initial
> capacity sufficient to contain the
> elements in the specified collection.
However, using the [`HashSet()`](http://java.sun.com/javase/6/docs/api/java/util/HashSet.html#HashSet()) constructor, the initial size is 16, so if the `Set` that was added via the [`Collection.addAll`](http://java.sun.com/javase/6/docs/api/java/util/AbstractCollection.html#addAll(java.util.Collection)) is larger than 16, there would have to be a resizing of the data structure:
> Constructs a new, empty set; the
> backing `HashMap` instance has default
> initial capacity (16) and load factor
> (0.75).
Therefore, using the [`HashSet(Collection)`](http://java.sun.com/javase/6/docs/api/java/util/HashSet.html#HashSet(java.util.Collection)) constructor to create the `HashSet` would probably be a better option in terms of performance and efficiency.
However, from the standpoint of readability of the code, the variable name `union` seems to imply that the newly created `Set` is an union of another `Set`, so probably the one using the `addAll` method would be more understandable code.
If the idea is just to make a new `Set` from an existing one, then the newly created `Set` should probably be named differently, such as `newSet`, `copyOfS1` or something to that effect. | The **first will be more efficient** because the second `Set` will be created with the correct amount of space in the backing data structure where in the second piece of code, the `Set` will have to resize to make room for the new elements.
**As far as end results go, they are the same.** | What is the exact difference between these two groups of statements? | [
"",
"java",
"collections",
""
] |
Has anyone seen JavaMail not sending proper MimeMessages to an SMTP server, depending on how the JVM in started? At the end of the day, I can't send JavaMail SMTP messages with Subject: or From: fields, and it appears other headers are missing, only when running the app as a war.
The web project is built with Maven and I'm testing sending JavaMail using a browser and a simple mail.jsp to debug and see different behavior when launching the app with:
> 1) mvn jetty:run (mail sends fine, with proper Subject and From fields)
>
> 2) mvn jetty:run-war (mail sends fine, but missing Subject, From, and other fields)
I've meticulously run diff on the (verbose) Maven debug output (-X), and there are zero differences in the runtime dependencies between the two. I've also compared System properties, and they are identical. Something else is happening the jetty:run-war case that changes the way JavaMail behaves. What other stones need turning?
Curiously, I've tried a debugger in both situations and found that the javax.mail.internet.MimeMessage instance is getting created differently. The webapp is using Spring to send email picked off of an Apache ActiveMQ queue. When running the app as `mvn jetty:run` the MimeMessage.contentStream variable is used for message content. When running as `mvn jetty:run-war`, the MimeMessage.content variable is used for the message contents, and the
content = ASCIIUtility.getBytes(is);
call removes all of the header data from the parsed content. Since this seemed very odd, and debugging Spring/ActiveMQ is a deep dive, I created a simplified test without any of that infrastructure: just a JSP using mail-1.4.2.jar, yet the same headers are missing.
Also of note, these headers are missing when running the WAR file under Tomcat 5.5.27. Tomcat behaves just like Jetty when running the WAR, with the same missing headers.
With JavaMail debugging turned on, I clearly see different output.
GOOD CASE: In the jetty:run (non-WAR) the log output is:
```
DEBUG: JavaMail version 1.4.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "mail.authsmtp.com", port 465, isSSL false
220 mail.authsmtp.com ESMTP Sendmail 8.14.2/8.14.2/Kp; Thu, 18 Jun 2009 01:35:24 +0100 (BST)
DEBUG SMTP: connected to host "mail.authsmtp.com", port: 465
EHLO jmac.local
250-mail.authsmtp.com Hello sul-pubs-3a.Stanford.EDU [171.66.201.2], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE 52428800
250-AUTH CRAM-MD5 DIGEST-MD5 LOGIN PLAIN
250-DELIVERBY
250 HELP
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "52428800"
DEBUG SMTP: Found extension "AUTH", arg "CRAM-MD5 DIGEST-MD5 LOGIN PLAIN"
DEBUG SMTP: Found extension "DELIVERBY", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5
AUTH LOGIN
334 VXNlcm5hjbt7
YWM0MDkwhi==
334 UGFzc3dvjbt7
YXV0aHNtdHAydog3
235 2.0.0 OK Authenticated
DEBUG SMTP: use8bit false
MAIL FROM:<webmaster@mydomain.org>
250 2.1.0 <webmaster@mydomain.org>... Sender ok
RCPT TO:<jason@mydomain.org>
250 2.1.5 <jason@mydomain.org>... Recipient ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP: Jason Thrasher <jason@mydomain.org>
DATA
354 Enter mail, end with "." on a line by itself
From: Webmaster <webmaster@mydomain.org>
To: Jason Thrasher <jason@mydomain.org>
Message-ID: <5158456.0.1245285323633.JavaMail.jason@mail.authsmtp.com>
Subject: non-Spring: Hello World
MIME-Version: 1.0
Content-Type: text/plain;charset=UTF-8
Content-Transfer-Encoding: 7bit
Hello World: message body here
.
250 2.0.0 n5I0ZOkD085654 Message accepted for delivery
QUIT
221 2.0.0 mail.authsmtp.com closing connection
```
BAD CASE: The log output when running as a WAR, with missing headers, is quite different:
```
Loading javamail.default.providers from jar:file:/Users/jason/.m2/repository/javax/mail/mail/1.4.2/mail-1.4.2.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
Loading javamail.default.providers from jar:file:/Users/jason/Documents/dev/subscribeatron/software/trunk/web/struts/target/work/webapp/WEB-INF/lib/mail-1.4.2.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@98203f; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "mail.authsmtp.com", port 465, isSSL false
220 mail.authsmtp.com ESMTP Sendmail 8.14.2/8.14.2/Kp; Thu, 18 Jun 2009 01:51:46 +0100 (BST)
DEBUG SMTP: connected to host "mail.authsmtp.com", port: 465
EHLO jmac.local
250-mail.authsmtp.com Hello sul-pubs-3a.Stanford.EDU [171.66.201.2], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE 52428800
250-AUTH CRAM-MD5 DIGEST-MD5 LOGIN PLAIN
250-DELIVERBY
250 HELP
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg "52428800"
DEBUG SMTP: Found extension "AUTH", arg "CRAM-MD5 DIGEST-MD5 LOGIN PLAIN"
DEBUG SMTP: Found extension "DELIVERBY", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5
AUTH LOGIN
334 VXNlcm5hjbt7
YWM0MDkwhi==
334 UGFzc3dvjbt7
YXV0aHNtdHAydog3
235 2.0.0 OK Authenticated
DEBUG SMTP: use8bit false
MAIL FROM:<webmaster@mydomain.org>
250 2.1.0 <webmaster@mydomain.org>... Sender ok
RCPT TO:<jason@mydomain.org>
250 2.1.5 <jason@mydomain.org>... Recipient ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP: Jason Thrasher <jason@mydomain.org>
DATA
354 Enter mail, end with "." on a line by itself
Hello World: message body here
.
250 2.0.0 n5I0pkSc090137 Message accepted for delivery
QUIT
221 2.0.0 mail.authsmtp.com closing connection
```
Here's the actual mail.jsp that I'm testing war/non-war with.
```
<%@page import="java.util.*"%>
<%@page import="javax.mail.internet.*"%>
<%@page import="javax.mail.*"%>
<%
InternetAddress from = new InternetAddress("webmaster@mydomain.org", "Webmaster");
InternetAddress to = new InternetAddress("jason@mydomain.org", "Jason Thrasher");
String subject = "non-Spring: Hello World";
String content = "Hello World: message body here";
final Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "mail.authsmtp.com");
props.setProperty("mail.port", "465");
props.setProperty("mail.username", "myusername");
props.setProperty("mail.password", "secret");
props.setProperty("mail.debug", "true");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
Session mailSession = Session.getDefaultInstance(props);
Message message = new MimeMessage(mailSession);
message.setFrom(from);
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(content, "text/plain;charset=UTF-8");
Transport trans = mailSession.getTransport();
trans.connect(props.getProperty("mail.host"), Integer
.parseInt(props.getProperty("mail.port")), props
.getProperty("mail.username"), props
.getProperty("mail.password"));
trans.sendMessage(message, message
.getRecipients(Message.RecipientType.TO));
trans.close();
%>
email was sent
```
SOLUTION:
Yes, the problem was transitive dependencies of Apache CXF 2. I had to exclude geronimo-javamail\_1.4\_spec from the build, and just rely on javax's mail-1.4.jar.
```
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>2.2.6</version>
<exclusions>
<exclusion>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-javamail_1.4_spec</artifactId>
</exclusion>
</exclusions>
</dependency>
```
Thanks for all of the answers. | Is it possible that when you build it as a WAR that other dependencies are being pulled in? It seems others have encountered this problem, and the cause was a bug in geronimo (for more information, see <http://mail-archives.apache.org/mod_mbox/geronimo-user/200902.mbox/%3C21943498.post@talk.nabble.com%3E> ).
We also had geronimo-javamail\_1.4\_spec-1.2 included in our product and that package has a bug with headers. We excluded this (along with geronimo-activation\_1.1\_spec) from our dependencies and it corrected the problem. | It'ss the dependency which creates this problem, make sure you load mail.jar before other jar's which contains javax.mail.Transport class. In my case the culprit was javaee-api-5.0-1.jar | JavaMail not sending Subject or From under jetty:run-war | [
"",
"java",
"smtp",
"jakarta-mail",
"war",
""
] |
I'm looking for either a best practise or library for processing string into an object tree..
here is the example:
"[age] = '37' And [gender] Is Not Null And [optindate] > '2003/01/01' And [idnumber] Is Null And ([saresident] = '52' Or [citizenship] Like 'abc%')"
I should be able to objectize this into a tree something like this:
```
{attribute='age', operator='=', value='37', opperand='And'}
{attribute='gender', operator='Is Not Null', value='', opperand='And'}
{attribute='optindate', operator='>', value='2003/01/01', opperand='And'}
```
etc....
any suggestions would be great! | If you need to store the operations in a tree structure, you should use the postfix or prefix notation.
e.g. age = 37 and gender is not null
should be stored as
and = age 37 != gender null
so the tree should be like
```
and
= !=
age 37 gender null
```
You can use these links for more details: [Notation Used for Operations](http://www.cs.cas.cz/portal/AlgoMath/AlgebraicStructures/AlgebraicOperations/NotationForOperations.htm) and [Expressions, Conversion and Evaluation with C (All you need to know about Expressions)](http://www.programmersheaven.com/2/Art_Expressions_p1) | How about the [dynamic LINQ library](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx)? You could either use "as is", or look at how it builds an `Expression<Func<T,bool>>` predicate (which is the tree). | C# Advanced query statement String Processing | [
"",
"c#",
".net",
"oop",
"string",
""
] |
I have a series of checkboxes on a form.
I want to be able to select these from a context menu as well as the form itself. The context menu is linked to the system tray icon of the application.
My question is, is it possible to link the context menu to these checkboxes?
Or even possible to add checkboxes to the context menu?
Or even a combination?! | The menu items have a `Checked` property ([`MenuItem.Checked`](http://msdn.microsoft.com/en-us/library/system.windows.forms.menuitem.checked.aspx), [`ToolStripMenuItem.Checked`](http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripmenuitem.checked.aspx)) that you can use for this purpose.
Regarding the possibility to link the context menu items to the check boxes, if you use a `ContextMenuStrip` and set `CheckOnClick` property to `true`, you can hook up the `CheckedChanged` events to the same event handler for the `ToolStripMenuItem` and `CheckBox` controls that should be "linked", and inside that event handler make sure to synchronize the `Checked` property of the controls and perform any other needed actions. | Well, a menu item has the "Checked" property, which can make it behave like a checkbox. When you click a menu item, you can programmatically toggle the state of the corresponding checkbox on your form.
You can also use the Opening event of the context menu to set the Checked state of the menu items based on the checked state of the checkboxes. | C# Add Checkbox To WinForms Context Menu | [
"",
"c#",
"checkbox",
""
] |
I've installed pear using this guide <http://t-machine.org/index.php/2008/12/28/how-to-install-pear-on-os-x-105/>
In **/etc/php.ini** my **include\_path = ".:/usr/local/PEAR"**
PHPUnit is installed under **/usr/local/PEAR/PHPUnit** using **sudo pear install phpunit/PHPUnit**(I get an error otherwise)
Yet when I try execute phpunit I'm getting this error
```
Warning: require_once(PHPUnit/Util/Filter.php): failed to open stream: Not a directory in /usr/local/bin/phpunit on line 44
Fatal error: require_once(): Failed opening required 'PHPUnit/Util/Filter.php' (include_path='.:') in /usr/local/bin/phpunit on line 44
```
I'm just wondering has anyone got an idea of what the problem is or a complete(and correct guide) on installing pear osx.
Thanks! | Just a quick guess, that could be wrong, but perhaps you may need to add a trailing slash to the path like this: `include_path = ".:/usr/local/PEAR/"`
Edit: somehow /usr/local/PEAR is *not* in your include path as `(include_path='.:')` in your error message shows. | Solved the problem I had a stupid ; before the include\_path statement!
I am aware I'm an idiot, many thanks. :) | Install PHPUnit and Pear correctly on OSX Leopard | [
"",
"php",
"macos",
"phpunit",
"pear",
""
] |
I have found various code and libraries for editing [Exif](http://en.wikipedia.org/wiki/Exchangeable_image_file_format).
But they are only lossless when the image width and height is multiple of 16.
I am looking for a library (or even a way to do it myself) to edit just the Exif portion in a JPEG file (or add Exif data if it doesn't exist yet), leaving the other data unmodified. Isn't that possible?
So far I could only locate the Exif portion (starts with 0xFFE1) but I don't understand how to read the data. | Here are the specifications for the Exif interchange format, if you plan to code your own library for editing tags.
<http://www.exif.org/specifications.html>
Here's a library written in Perl that meets your needs that you may be able to learn from:
<http://www.sno.phy.queensu.ca/~phil/exiftool/>
Here's a decent .NET library for Exif evaluation from [The Code Project](http://en.wikipedia.org/wiki/The_Code_Project):
<http://www.codeproject.com/KB/graphics/exiftagcol.aspx> | You can do this without any external lib:
```
// Create image.
Image image1 = Image.FromFile("c:\\Photo1.jpg");
// Get a PropertyItem from image1. Because PropertyItem does not
// have public constructor, you first need to get existing PropertyItem
PropertyItem propItem = image1.GetPropertyItem(20624);
// Change the ID of the PropertyItem.
propItem.Id = 20625;
// Set the new PropertyItem for image1.
image1.SetPropertyItem(propItem);
// Save the image.
image1.Save("c:\\Photo1.jpg", ImageFormat.Jpg);
```
List of all possible PropertyItem ids (including exif) you can found [here](http://msdn.microsoft.com/en-us/library/ms534413(VS.85).aspx).
**Update:** Agreed, this method will re-encode image on save. But I have remembered another method, in WinXP SP2 and later there is new imaging components added - WIC, and you can use them to lossless write metadate - [How-to: Re-encode a JPEG Image with Metadata](http://msdn.microsoft.com/en-us/library/bb531153(VS.85).aspx). | .NET C# library for lossless Exif rewriting? | [
"",
"c#",
".net",
"jpeg",
"exif",
""
] |
I have a java app that uses about 15G on a machine with 16G. I don't know if I should set the max heap size.
If set will the jvm eat all the ram up to the limit and then start garbage collecting and stop everything while it churns through 15G of heap objects?
If not will the jvm hurt performance by not using all of the available ram on the machine.
My specific vm is: Java HotSpot(TM) 64-Bit Server VM (build 1.6.0\_03-b05, mixed mode).
Thanks | `-Xmx15G` will set the maximum heap size to 15 gig. Java will only allocate what it needs as it runs. If you don't set it, it will only use the default. For info on the default, see [this post](https://stackoverflow.com/questions/4667483/how-is-the-default-java-heap-size-determined).
`-Xms15G` sets the minimum heap to 15 gig. This forces java to allocate 15 gig of heap space before it starts executing, whether it needs it or not.
Usually you can set them both to appropriate values depending on how you're tuning the JVM. | In Java 6, the default maximum heap size is determined by the amount of system memory present.
According to the [Garbage Collector Ergonomics](http://java.sun.com/javase/6/docs/technotes/guides/vm/gc-ergonomics.html) page, the maximum heap size is:
> Smaller of 1/4th of the physical
> memory or 1GB. Before J2SE 5.0, the
> default maximum heap size was 64MB.
By using the `-Xmx` switch can be used to change the maximum heap size. See the [`java` - the Java application launcher](http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html) documentation for usage details. | Java app that uses a lot of memory. Use -Xmx? | [
"",
"java",
"performance",
"memory-management",
"jvm",
""
] |
I have following string
adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0
I need only the value of adId,siteId and userId.
means
4028cb901dd9720a011e1160afbc01a3
8a8ee4f720e6beb70120e6d8e08b0002
5082a05c-015e-4266-9874-5dc6262da3e0
all the 3 in different variable or in a array so that i can use all three | You could do something like this:
```
input='adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0'
result={}
for pair in input.split(';'):
(key,value) = pair.split(':')
result[key] = value
print result['adId']
print result['siteId']
print result['userId']
``` | You can split them to a dictionary if you don't need any fancy parsing:
```
In [2]: dict(kvpair.split(':') for kvpair in s.split(';'))
Out[2]:
{'adId': '4028cb901dd9720a011e1160afbc01a3',
'siteId': '8a8ee4f720e6beb70120e6d8e08b0002',
'userId': '5082a05c-015e-4266-9874-5dc6262da3e0'}
``` | parsing in python | [
"",
"python",
""
] |
I'm trying to draw a text on a panel(The panel has a background picture).
It works brilliant,but when I minimize and then maximize the application the text is gone.
My code:
```
using (Graphics gfx = Panel1.CreateGraphics())
{
gfx.DrawString("a", new Font("Tahoma", 5), Brushes.White, new PointF(1, 1));
}
```
How do I keep it static so it doesn't get lost? | If you don't use a `Paint` event, you are just drawing on the screen where the control happens to be. The control is not aware of this, so it has no idea that you intended for the text to stay there...
If you put the value that you want drawn on the panel in it's `Tag` property, you can use the same paint event handler for all the panels.
Also, you need to dispose of the Font object properly, or you will be having a lot of them waiting to be finalized before they return their resources to the system.
```
private void panel1_Paint(object sender, PaintEventArgs e) {
Control c = sender as Control;
using (Font f = new Font("Tahoma", 5)) {
e.Graphics.DrawString(c.Tag.ToString(), f, Brushes.White, new PointF(1, 1));
}
}
``` | Inherit from Panel, add a property that represents the text you need to write, and override the OnPaintMethod():
```
public class MyPanel : Panel
{
public string TextToRender
{
get;
set;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawString(this.TextToRender, new Font("Tahoma", 5), Brushes.White, new PointF(1, 1));
}
}
```
This way, each Panel will know what it needs to render, and will know how to paint itself. | Why does text drawn on a panel disappear? | [
"",
"c#",
"winforms",
""
] |
I have two action methods that are conflicting. Basically, I want to be able to get to the same view using two different routes, either by an item's ID or by the item's name and its parent's (items can have the same name across different parents). A search term can be used to filter the list.
For example...
```
Items/{action}/ParentName/ItemName
Items/{action}/1234-4321-1234-4321
```
Here are my action methods (there are also `Remove` action methods)...
```
// Method #1
public ActionResult Assign(string parentName, string itemName) {
// Logic to retrieve item's ID here...
string itemId = ...;
return RedirectToAction("Assign", "Items", new { itemId });
}
// Method #2
public ActionResult Assign(string itemId, string searchTerm, int? page) { ... }
```
And here are the routes...
```
routes.MapRoute("AssignRemove",
"Items/{action}/{itemId}",
new { controller = "Items" }
);
routes.MapRoute("AssignRemovePretty",
"Items/{action}/{parentName}/{itemName}",
new { controller = "Items" }
);
```
I understand why the error is occurring, since the `page` parameter can be null, but I can't figure out the best way to resolve it. Is my design poor to begin with? I've thought about extending `Method #1`'s signature to include the search parameters and moving the logic in `Method #2` out to a private method they would both call, but I don't believe that will actually resolve the ambiguity.
Any help would be greatly appreciated.
---
**Actual Solution** (based on Levi's answer)
I added the following class...
```
public class RequireRouteValuesAttribute : ActionMethodSelectorAttribute {
public RequireRouteValuesAttribute(string[] valueNames) {
ValueNames = valueNames;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
bool contains = false;
foreach (var value in ValueNames) {
contains = controllerContext.RequestContext.RouteData.Values.ContainsKey(value);
if (!contains) break;
}
return contains;
}
public string[] ValueNames { get; private set; }
}
```
And then decorated the action methods...
```
[RequireRouteValues(new[] { "parentName", "itemName" })]
public ActionResult Assign(string parentName, string itemName) { ... }
[RequireRouteValues(new[] { "itemId" })]
public ActionResult Assign(string itemId) { ... }
``` | MVC doesn't support method overloading based solely on signature, so this will fail:
```
public ActionResult MyMethod(int someInt) { /* ... */ }
public ActionResult MyMethod(string someString) { /* ... */ }
```
However, it *does* support method overloading based on attribute:
```
[RequireRequestValue("someInt")]
public ActionResult MyMethod(int someInt) { /* ... */ }
[RequireRequestValue("someString")]
public ActionResult MyMethod(string someString) { /* ... */ }
public class RequireRequestValueAttribute : ActionMethodSelectorAttribute {
public RequireRequestValueAttribute(string valueName) {
ValueName = valueName;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
return (controllerContext.HttpContext.Request[ValueName] != null);
}
public string ValueName { get; private set; }
}
```
In the above example, the attribute simply says "this method matches if the key *xxx* was present in the request." You can also filter by information contained within the route (controllerContext.RequestContext) if that better suits your purposes. | The parameters in your routes `{roleId}`, `{applicationName}` and `{roleName}` don't match the parameter names in your action methods. I don't know if that matters, but it makes it tougher to figure out what your intention is.
Do your itemId's conform to a pattern that could be matched via regex? If so, then you can add a restraint to your route so that only url's that match the pattern are identified as containing an itemId.
If your itemId only contained digits, then this would work:
```
routes.MapRoute("AssignRemove",
"Items/{action}/{itemId}",
new { controller = "Items" },
new { itemId = "\d+" }
);
```
Edit: You could also add a constraint to the `AssignRemovePretty` route so that both `{parentName}` and `{itemName}` are required.
Edit 2: Also, since your first action is just redirecting to your 2nd action, you could remove some ambiguity by renaming the first one.
```
// Method #1
public ActionResult AssignRemovePretty(string parentName, string itemName) {
// Logic to retrieve item's ID here...
string itemId = ...;
return RedirectToAction("Assign", itemId);
}
// Method #2
public ActionResult Assign(string itemId, string searchTerm, int? page) { ... }
```
Then specify the Action names in your routes to force the proper method to be called:
```
routes.MapRoute("AssignRemove",
"Items/Assign/{itemId}",
new { controller = "Items", action = "Assign" },
new { itemId = "\d+" }
);
routes.MapRoute("AssignRemovePretty",
"Items/Assign/{parentName}/{itemName}",
new { controller = "Items", action = "AssignRemovePretty" },
new { parentName = "\w+", itemName = "\w+" }
);
``` | ASP.NET MVC ambiguous action methods | [
"",
"c#",
"asp.net-mvc",
"asp.net-mvc-routing",
""
] |
working on my paypal integration and its going great - I was wondering that in the case a refund needs to be made is there a way to have a refund made programmatically? | From my understanding, you should use the Refund API.
* [Refund using SOAP](https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_soap_r_RefundTransaction)
* [Refund using NVP](https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_r_RefundTransaction) | Doing a refund in PayPal is straight forward if you follow the API documentation mentioned by Machine.
You may also find, if you prefer to save money, that you can Void a transaction in PayPal, before it is captured (usually before midnight on the day of the transaction), which is free.
I have found that always sending a void first, then if the void fails, sending the refund works well without much overhead. | How do I programmatically refund using paypal? | [
"",
"php",
"paypal",
""
] |
In light of the ["Hidden features of..."](https://stackoverflow.com/search?q=hidden+features) series of questions, what little-known features of PL/SQL have become useful to you?
**Edit:** Features specific to PL/SQL are preferred over features of Oracle's SQL syntax. However, because PL/SQL can use most of Oracle's SQL constructs, they may be included if they make programming in PL/SQL easier. | You can override variables, you can name anonymous blocks, and you can still refer to the overridden variables by name:
```
PROCEDURE myproc IS
n NUMBER;
BEGIN
n := 1;
<<anon>>
DECLARE
n NUMBER;
BEGIN
n := 2;
dbms_output.put_line('n=' || n);
dbms_output.put_line('anon.n=' || anon.n);
dbms_output.put_line('myproc.n=' || myproc.n);
END anon;
END myproc;
``` | You can index pl/sql tables by other types besides integers. This way you can create "dictionary" like structures, which can make your code much easier to read:
Example:
```
DECLARE
TYPE dictionary IS TABLE OF VARCHAR2(200) INDEX BY VARCHAR2(100);
dict dictionary;
BEGIN
dict('NAME') := 'John Doe';
dict('CITY') := 'New York';
dbms_output.put_line('Name:' || dict('NAME'));
END;
``` | Hidden features of PL/SQL | [
"",
"sql",
"oracle",
"plsql",
""
] |
I've got a simple query (postgresql if that matters) that **retrieves all items for some\_user excluding the ones she has on her wishlist**:
```
select i.*
from core_item i
left outer join core_item_in_basket b on (i.id=b.item_id and b.user_id=__some_user__)
where b.on_wishlist is null;
```
The above query runs in ~50000ms (yep, the number is correct).
If I remove the "b.on\_wishlist is null" condition or make it "b.on\_wishlist is not null", the query runs in some 50ms (quite a change).
The query has more joins and conditions but this is irrelevant as only this one slows it down.
Some info on the database size:
* core\_items has ~ 10.000 records
* core\_user has ~5.000 records
* core\_item\_in\_basket has ~2.000
* records (of which some 50% has
on\_wishlist = true, the rest is null)
I don't have any indexes (except for ids and foreign keys) on those two tables.
The question is: **what should I do to make this run faster?** I've got a few ideas myself to check out this evening, but I'd like you guys to help if possible, as well.
Thanks! | Sorry for adding 2nd answer, but stackoverflow doesn't let me format comments properly, and since formatting is essential, I have to post answer.
Couple of options:
1. CREATE INDEX q ON core\_item\_in\_basket (user\_id, item\_id) WHERE on\_wishlist is null;
2. same index, but change order of columns in it.
3. SELECT i.\* FROM core\_item i WHERE i.id not in (select item\_id FROM core\_item\_in\_basket WHERE on\_wishlist is null AND user\_id = \_\_some\_user\_\_); (this query can benefit from index from point #1, but will not benefit from index #2.
4. SELECT \* from core\_item where id in (select id from core\_item EXCEPT select item\_id FROM core\_item\_in\_basket WHERE on\_wishlist is null AND user\_id = \_\_some\_user\_\_);
Let us know the results :) | try using not exists:
```
select i.*
from core_item i
where not exists (select * from core_item_in_basket b where i.id=b.item_id and b.user_id=__some_user__)
``` | Slow query with left outer join and is null condition | [
"",
"sql",
"postgresql",
""
] |
Java Reflection provides a mechanism to introspect an Object at runtime. No second thoughts, this is a great feature, but it breaks all the Refactoring conventions!
There is no easy way (other than `File Search`) even in modern IDE's to know which attribute is referenced and where. This makes Refactorings much more complex (tiresome!) and error prone.
To be frank, it's not just the `Reflection API`; `Hibernate mapping files (hbm.xml)` and `JSP files` both refer to the attributes as String and when you refactor your attribute name, then you have to manually change in all these places.
Worse, the changes in Hibernate mapping files or JSP files result in runtime errors.
I am interested in knowing how other programmers handle this in Java. Are there some tools? I use Eclipse/IBM RAD as main development platform. Normally we use a `constant` to define the attribute and use it whenever possible but its not always possible.
I would also be interested how other languages handle this! | Java reflection causes many of the same problems you get with dynamically typed languages such as Python and Ruby. In fact, one way to think about dynamically typed languages is that everything is called using reflection, and the languages just provide a nice, clean syntax for reflection.
And yes, with dynamically typed languages (or heavy uses of reflection), refactoring is hard. You don't get the nice Eclipse refactoring capabilities. Instead, grep becomes your friend.
From my experience, the best thing you can do is build yourself a good safety net of unit tests. That way, if you break some dynamic code during refactoring, at least you'll catch it quickly when you run the tests.
If you're doing lots of statically typed code, you're in big trouble if you don't have a good base of unit tests. If you're doing lots of dynamically typed code (including code with lots of reflection), you don't have any hope of being successful without a good base of unit tests. | Modern IDE's have the feature that when renaming a class, they will search for the fully qualified name in, for example, your xml files to try and rename any references you might have in those. Don't think it solves the problem - very often you don't absolutely reference class names.
Also, that is why particular care and consideration must be exercised before you use it in your own code.
But this problem with reflection is why using annotations is becoming more popular. The problem is reduced when using annotations.
But let me say, as the previous post rightly points out, if you don't have a good safety net of unit tests, any kind of refactoring, whether you use a lot of reflection or not, is dangerous. | Java Reflection and the pain in Refactoring | [
"",
"java",
"language-agnostic",
"reflection",
"refactoring",
""
] |
I'm using ICEFaces. I have datatable with multiple columns. One I load the page I get the following exception; however, the page still loads and contiues correctly but after I start pagination the table it's slow, I'm not sure what this exception is about as the page still work and I'm not sure if it's related to the slowness of pagination.
Any ideas?
THanks,
Tam
The Excpetion:
```
15:27:49,254 ERROR [Digester] Parse Fatal Error at line 1 column 1: Content is not allowed in prolog.
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.commons.digester.Digester.parse(Digester.java:1765)
at com.icesoft.faces.webapp.parser.TagToComponentMap.addTags(TagToComponentMap.java:145)
at com.icesoft.faces.webapp.parser.JsfJspDigester.startPrefixMapping(JsfJspDigester.java:126)
at org.apache.xerces.parsers.AbstractSAXParser.startNamespaceMapping(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.commons.digester.Digester.parse(Digester.java:1785)
at com.icesoft.faces.webapp.parser.Parser.parse(Parser.java:130)
at com.icesoft.faces.application.D2DViewHandler.renderResponse(D2DViewHandler.java:464)
at com.icesoft.faces.application.D2DViewHandler.renderView(D2DViewHandler.java:153)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:110)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at com.icesoft.faces.webapp.http.core.JsfLifecycleExecutor.apply(JsfLifecycleExecutor.java:19)
at com.icesoft.faces.context.View$2$1.respond(View.java:48)
at com.icesoft.faces.webapp.http.servlet.ServletRequestResponse.respondWith(ServletRequestResponse.java:201)
at com.icesoft.faces.webapp.http.servlet.ThreadBlockingAdaptingServlet$ThreadBlockingRequestResponse.respondWith(ThreadBlockingAdaptingServlet.java:36)
at com.icesoft.faces.context.View$2.serve(View.java:76)
at com.icesoft.faces.context.View.servePage(View.java:139)
at com.icesoft.faces.webapp.http.core.SingleViewServer.service(SingleViewServer.java:52)
at com.icesoft.faces.webapp.http.common.ServerProxy.service(ServerProxy.java:11)
at com.icesoft.faces.webapp.http.servlet.MainSessionBoundServlet$4.service(MainSessionBoundServlet.java:114)
at com.icesoft.faces.webapp.http.common.standard.PathDispatcherServer.service(PathDispatcherServer.java:24)
at com.icesoft.faces.webapp.http.servlet.MainSessionBoundServlet.service(MainSessionBoundServlet.java:160)
at com.icesoft.faces.webapp.http.servlet.SessionDispatcher$1.service(SessionDispatcher.java:42)
at com.icesoft.faces.webapp.http.servlet.ThreadBlockingAdaptingServlet.service(ThreadBlockingAdaptingServlet.java:19)
at com.icesoft.faces.webapp.http.servlet.EnvironmentAdaptingServlet.service(EnvironmentAdaptingServlet.java:63)
at com.icesoft.faces.webapp.http.servlet.SessionDispatcher.service(SessionDispatcher.java:62)
at com.icesoft.faces.webapp.http.servlet.PathDispatcher.service(PathDispatcher.java:23)
at com.icesoft.faces.webapp.http.servlet.MainServlet.service(MainServlet.java:153)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:595)
``` | It's going to be difficult to diagnose anything without seeing any code, but it looks like this has been covered before in other places. Have you at least tried Google'ing that error? Here is a definition of the error you're seeing from [this](http://marc.info/?l=xerces-j-user&m=117066285728163&w=2) message board thread:
*This means you have something before the root element which is not permitted to appear there according to the XML spec. Make sure that NOTHING comes before the XML declaration except the
optional byte-order mark, and that NOTHING comes between the XML declaration and the outermost element except comments, processing instructions, and whitespace.*
Hope that helps. | Could be a simple syntax problem if you use Facelets. The XML parser (Xerces) tells you that there are parts in the page that are not allowed. This can be the cause for the behavior.
But, as mentioned above, we need a detailled look at the page markup. | Exception with ICEFaces | [
"",
"java",
"jsf",
"icefaces",
""
] |
I have two methods in C# 3.5 that are identical bar one function call,
in the snippet below, see clientController.GetClientUsername vs clientController.GetClientGraphicalUsername
```
private static bool TryGetLogonUserIdByUsername(IGetClientUsername clientController, string sClientId, out int? logonUserId)
{
string username;
if (clientController.GetClientUsername(sClientId, out username))
{
// ... snip common code ...
}
return false;
}
private static bool TryGetLogonUserIdByGraphicalUsername(IGetClientUsername clientController, string sClientId, out int? logonUserId)
{
string username;
if (clientController.GetClientGraphicalUsername(sClientId, out username))
{
// ... snip common code ...
}
return false;
}
```
Is there a way (delegates, lamda's ?) that I can pass in which method on clientController I want to call?
Thanks! | Sure. Just define a delegate like so:
```
public delegate bool GetUsername(string clientID, out string username);
```
And then pass it into your function and call it:
```
private static bool TryGetLogonUserId(IGetClientUsername clientController, string sClientId, out int? logonUserId, GetUsername func)
{
string username;
if (func.Invoke(sClientId, out username))
{
// ... snip common code ...
}
return false;
}
```
To call the function with the delegate, you'll do this:
```
TryGetLogonUserId(/* first params... */, clientController.GetClientUsername);
``` | While you can pass a delegate as a parameter, I suggest going with a different route. Encapsulate the body of the `if` statement which involves common code in another function and call that one in both functions.
Visual Studio has a "Refactor `->` Extract Method" feature in the context menu. You can just fill in one of the bodies, select the body and use that feature to extract a method out of it automatically. | In C# 3.5, How do you pass which method to call on an object as a parameter | [
"",
"c#",
".net-3.5",
"delegates",
"refactoring",
""
] |
i am implementing a log-in system, i am sure a lot of you know what it is, i use sessions to store the user's ID, and check it if he access a page that needs the user to be logged in.
But my problem is when the user clicks the log-out anchor, nothing happens i still can access the other pages as long as the current page is open.
here is the code is use:
```
<?
unset($_SESSION["ID"]);
session_destroy();
header('location: ../Home/index.php');
?>
```
so anyone can help. thanks in advance. | You need to do a `session_start()` before `session_destroy()`.
If you don't, PHP has no idea which session you're trying to destroy. | > But my problem is when the user clicks
> the log-out anchor, nothing happens
**A lot of things happens !**
1. Are you trying to go back with the previous button and then accessing to the login page which log you in back ?
2. Are you page really checking for a session when a user try to display ?
3. Are you sure you are NOT displaying a cached version of your page ?
4. Did you check PHP sessions files are well deleted ? (maybe permission problems can occurs)
5. Check the location header syntax, RFC2616 14.30 says:
> The Location response-header field is
> used to redirect the recipient to a
> location other than the Request-URI
> for completion of the request or
> identification of a new resource. For
> 201 (Created) responses, the Location
> is that of the new resource which was
> created by the request. For 3xx
> responses, the location SHOULD
> indicate the server's preferred URI
> for automatic redirection to the
> resource. The field value consists of
> a single absolute URI.
>
> ```
> Location = "Location" ":" absoluteURI
> ```
Try:
`var_dump($_SESSION);`
On each of your page, to see what, really happens. | log-out is not working in php for a login System | [
"",
"php",
""
] |
What's the best, complex math library in c++? (I'd like to use it in graphics engine)
EDIT: I should precise it a bit: it should have all 3d math, like planes, spheres, points, AABB, etc. and of course matrix, vector, quaternion support. | It dependes on What you are going to develop . as per my knowledge these are good libs .
[Geometric Tools](http://www.geometrictools.com/) (previously known as WildMagic)
OxMath 2D/3D Math Library 2.1
[MATHLIB3D](http://sourceforge.net/projects/mathlib3d/)
[Configurable Math Library (CML)](http://cmldev.net/)
[glmath](http://glmath.sourceforge.net/) | If you're working with OpenGL you could try the [OpenGL Mathematics (glm)](http://glm.g-truc.net/) library. It implements all of it's classes in terms of GLSL so it's easy to use between client side and server side. | C++ 3D Math Library | [
"",
"c++",
"math",
"3d",
""
] |
I'm having an issue with multiple markers on google maps - I currently have a MySQL database storing info (location info). In php I then extract this info and loop through each postcode to dynamically create the required javascript to place a marker for each place in my database.
This works successfully so I know that I'm passing the correct information to the js function - Now what I'm trying to achieve is adding additional information when the marker is clicked but its showing the same on every marker window.
This is the js I'm using (I initiate an icon at the top but excluded this from the code for now):
```
function usePointFromPostcode(postcode, callbackFunction, text) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0])
{
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point, text);
}else{
alert("Postcode not found!");
}
});
localSearch.execute(postcode + ", UK");
}
function placeMarkerAtPoint(point, html, icon)
{
var marker = new GMarker(point,{icon: icon});
GEvent.addListener(marker,"click",function() {
marker.openInfoWindowHtml(html);
});
map.addOverlay(marker);
}
```
The php code I have is:
```
$query = "SELECT * FROM hospitalInfo";
$result = mysql_query($query);
if($result) {
while ($row = mysql_fetch_assoc($result)) {
$code .= "usePointFromPostcode('".$row['Postcode']."', placeMarkerAtPoint,
'".$row['placeName']."');";
}
}
```
$code is then echo'ed.
Any advice on why this is occuring would be much appreciated! Thanks ! | As you mentioned in your comment, the problem is that you're sending several requests before you get any results, and the value of the marker text changes each time you send the request. I think you could greatly simplify your code by using the GClientGeocoder - unless it's absolutely necessary to use GLocalSearch, which isn't really part of the Maps API. Here's [Google's tutorial](http://code.google.com/apis/maps/documentation/services.html#Geocoding_Object) for the geocoder.
First create the geocoder like this:
```
var geocoder = new GClientGeocoder();
```
Next, here's your new **usePointFromPostcode()** function:
```
function usePointFromPostcode(postcode, text) {
geocoder.getLatLng(postcode, function(point) {
if (!point) {
//alert('address not found');
} else {
var marker = new GMarker(point, {icon: icon});
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(text);
});
map.addOverlay(marker);
}
});
}
```
This worked great for me. Try it out and let us know how it goes.
If you need more information about the returned point, like accuracy, use [getLocations()](http://code.google.com/apis/maps/documentation/reference.html#GClientGeocoder.getLocations) instead of getLatLng(). The tutorial explains how it works. | You may be having a scope/closure problem, similar to the issue discussed [here](https://stackoverflow.com/questions/1078309/google-maps-api-all-markers-opening-the-same-infowindow).
Try replacing this code:
```
GEvent.addListener(marker,"click",function() {
marker.openInfoWindowHtml(html);
});
```
with this:
```
marker.bindInfoWindowHtml(html);
```
If that doesn't work, I'd guess that the closure problem is coming from the setSearchCompleteCallback() function. It's difficult to guess without seeing the actual page. | Google Maps - Same text appears in info window when using multiple markers | [
"",
"javascript",
"google-maps",
""
] |
Is it at all possible to have a table valued function in MSSQL that takes an attribute and generates an associated SQL statement with Pivot function?
```
CREATE FUNCTION dbo.fnPivot (@EntityTypeID int)
RETURNS TABLE
AS
BEGIN
DECLARE @SQL varchar(MAX);
DECLARE @COLS varchar(MAX);
select @COLS=coalesce(@COLS+',','')+'['+Name+']'from c_EntityAttribute WHERE EntityTypeID = @EntityTypeID;
SET @SQL = 'SELECT * FROM (SELECT EntityInstanceID, AttributeName, Value FROM v_EntityElementData WHERE EntityTypeID = 1) as s';
SET @SQL = @SQL + 'PIVOT ( MIN(Value) FOR AttributeName IN (' + @COLS + ') ) AS p';
RETURN EXEC sp_ExecuteSQL @SQL ;
END
``` | Unfortunately not, with the exception of stored procedures SQL Server keeps track of the table definition of the output of all views, functions etc. Thus the columns and types can't change dynamically on the input.
For this reason I've never found the PIVOT operator to be useful. Generally the only way to get varying column data out is to treat it as XML.
For what reason are you pivoting it? This is usually a UI concern, and so I would recommend doing it at the UI, or SSRS etc. | A table valued function must always return a specified schema, so this isn't possible. | SQL Function that returns dynamically pivotted data | [
"",
"sql",
"dynamic",
"pivot",
""
] |
We are looking to host a Java Domain Model (written using DDD) inside a web application. Ideally I would like to support RESTful resources and requests, having a single site to support both users and a REST api.
Ideally the same url could be used for both end users and the RESTful API of a given feature (with HTTP content types / negotiation specifying the difference).
I have done similar apps in Ruby on Rails and Asp.mvc, but have no experience doing anything like this in Java. Anybody have an experience or advice on where to start ? (Googling suggests that Spring v3 might be an answer, anybody have any thoughts on Spring 3 ?) | For web services, [Jersey](http://jersey.java.net/) is nice and easy. Spring 3 sounds like it will be good, but it's not out yet, and Jersey is full featured and supports SOAP and JSON out of the box. It's all annotation based aside from adding the servlet to your web.xml file which makes it probably easier to configure than even Spring plug-ins, but to avoid getting yelled at, I'll say maybe not.
For (MVC) web pages (user UI), I use Spring MVC or Struts. | [Restlets Framework](http://www.restlet.org/) <http://www.restlet.org/>
I've used this framework extensively, easy to use, really flexible and supports loads of features and more you'd expect from file upload to gzipping responses.
This module has Spring support too, really easy. For example:
**web.xml**
```
<servlet>
<servlet-name>webapi</servlet-name>
<servlet-class>
com.noelios.restlet.ext.spring.RestletFrameworkServlet
</servlet-class>
</servlet>
```
**spring context**
```
<bean id="root" class="org.restlet.ext.spring.SpringRouter">
<property name="attachments">
<map>
<entry key="/{variable}/your/restful/call/{variable2}">
<bean class="org.restlet.ext.spring.SpringFinder">
<lookup-method name="createResource" bean="yourBean" />
</bean>
</entry>
</map>
</bean>
```
Framework also has a great [documentation](http://www.restlet.org/documentation/), [first steps for newbies](http://www.restlet.org/documentation/1.1/firstSteps) and a great [WIKI](http://wiki.restlet.org/about/2-restlet.html).
This framework is very mature and actively improved, checkout the up and coming [features](http://blog.noelios.com/2009/05/27/restlet-2-0-m3-released/).
It's also very easy to unit test your Restlet Resource endpoints using jmock.
Hope that helps. | Can anyone recommend a Java web framework that is based on MVC and supports REST? | [
"",
"java",
"model-view-controller",
"rest",
""
] |
I need to match an infinite number of figures in a web page.
I need to be able to match all of the following formats:
```
100 $
99$
$99
$ 8
$.99
$ .8
$ 99.8
.99$
.99 $
9.2 $
1.2$
```
And the equivalent using commas:
```
444,333
22,333
1,222
11,111,111
333,333,333,333.01132
```
Or spaces:
```
444 333
22 333
1 222
11 111 111
333 333 333 333.01132
```
This is a really hard one for me. I am used to playing with regexp but I have totally failed to write something bullet proof. Usually <http://www.regexlib.com> has the solution, but not for this one.
I can't think of another way other than using regexp since it's a plain text search/replace. | Here's a regular expression that will match all the number formats you've provided:
```
^(?:\$\s*)?(?:(?:\d{0,3}(?:[, ]\d{0,3})*[, ])+\d{3}|\d+)(?:\.\d*)?(?:\s*\$)?$
```
To break it down:
* `^(?:\$\s*)?` will look for an optional $ at the start of the string, followed by any amount of spaces
* `(?:(?:\d{0,3}(?:[, ]\d{0,3])*[, ])+\d{3}|\d*)` will match either a number broken down into groups separated by a comma or space (`\d{0,3}(?:[, ]\d{0,3})*[, ])+\d{3}`) or a string of numbers (`\d+`) -- so 123,456,789, 123 456 789 and 123456789 would be all matched. The regular expression will not accept numbers with improper grouping (so 123,45,6789 will not be matched)
* `(?:\.\d*)?` will match a number with an optional decimal and any number of numbers after
* `(?:\s*\$)?$` will match an optional $ at the end of the string, preceded by any amount of space. | Why write 1 regexp, when you can write several, and apply them in turn?
I'm assuming (?) that you can iterate through line-by-line. Why not try your comma-savvy regexp, followed by your space-savvy regexp etc.? If one matches, then don't bother trying the rest, and store your result and move on to the next line. | Hints for a complex currency regular expression for Javascript? | [
"",
"javascript",
"regex",
"currency",
""
] |
I'm using a SELECT statement in T-SQL on a table similar to this:
```
SELECT DISTINCT name, location_id, application_id FROM apps
WHERE ((application_id is null) or (application_id = '4'))
AND ((location_id is null) or (location_id = '3'))
```
This seems to work fine when searching for one application\_id or one location\_id, but what if I want to run the statement for multiple locations? I want to return all results for an unknown amount of location\_id's and application\_id's. For example, if I wanted to search for someone at the location\_id's 2, 3, 4, 5 but with only one application\_id. How would I do this?
Thank you in advance!
---
**EDIT:** I'm an idiot! I made it sound easy without giving you all the full details. All of these values are given from inside a table. The user will have to choose the id's from a column in the table instead of inserting them. After doing a bit of research on this problem I [came up with a page](http://www.sommarskog.se/arrays-in-sql-2005.html#CSV) that seemed to tout a viable solution.
```
CREATE FUNCTION iter$simple_intlist_to_tbl (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos int,
@nextpos int,
@valuelen int
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (number)
VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos
END
RETURN
END
```
Can anyone help me perfect this to meet my needs? Sorry if my question isn't very clear, as I'm struggling to get to grips with it myself.
---
**EDIT 2:** After doing a bit more reading on the subject it seems that I need a stored procedure to do this. The code up the top seems to be what I need, but I'm having trouble tailoring it to my needs. The table structure is as follows:
```
application_id name location_id
------------------------------------------------------
1 Joe Blogs 34
2 John Smith 55
```
According to the article I've just linked to:
> "The correct way of handling the
> situation is to use a function that
> unpacks the string into a table. Here
> is a very simple such function:"
So, it seems that I need to unpack these values into a string and pass them through using this stored procedure. Any idea on how I can get this to work?
**EDIT 3:** I've managed to solve it using charindex() and convert(), whilst setting them at the top. Thank you for all your help and I apologise again for being a pain. | Use IN as follows:
```
location_id IN ('2', '3', '4', '5')
``` | I'm not sure if I understood the "**EDIT**" part of your question right, but do you mean something like this?
```
SELECT DISTINCT name, location_id, application_id
FROM apps
WHERE location_id IN
(
SELECT id FROM other_table
)
```
**EDIT:**
Now that I read your second edit, I'm still not sure if I understand what you REALLY want to do.
Of course, we can help you with your stored procedure, but there's one thing which is not quite clear to me:
Do you want us to help you create the SP?
Or do you really want to do something else, but think you must do it by creating a SP because the link said so?
Can you specify how the expected result looks like? | SQL: Use multiple values in single SELECT statement | [
"",
"t-sql",
"sql",
""
] |
I've just discovered that when the remove() function is used, the matched elements are not removed from the jQuery object, just the DOM.
According to the [remove() documentation](http://docs.jquery.com/Manipulation/remove#expr):
> Removes all matched elements from the
> DOM. This does NOT remove them from
> the jQuery object, allowing you to use
> the matched elements further.
Surely if a web app keeps on adding and removing elements from the dom, this will keep using up more and more memory? Can someone confirm if this is the case? What can be done to avoid this? | I think that it would be garbage collected (eventually) once it falls out of scope. If you're having problems with excessive memory use, though you might try using the delete operator on the returned object. | I have tried to find the answer to my own question by doing a little test.
```
<script type="text/javascript">
$(document).ready(function() {
for ($i=1; $i<10000; $i++) {
$('table').append("<tr id=\"test_" + $i + "\"><td>test " + $i + "</td></tr>");
$('#test_'+($i-1)).remove();
}
});
</script>
<table>
<tr><td id="test_0">test 0</td></tr>
</table>
```
I did variations on the remove() by using:
```
var test = $('#test_'+($i-1)).remove();
```
and with the [delete operator](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator) (thanks to tvanfosson's suggestion):
```
var test = $('#test_'+($i-1)).remove();
delete test
```
Having done these tests I would still just use remove(). Its very hard to tell if there was a memory leak since the memory usage of the browser always increased after reloading the page. Perhaps someone else is able to provide a more conclusive answer by testing the code differently. | Possible jQuery memory issues with $('#foo').remove()? | [
"",
"javascript",
"jquery",
"dom",
""
] |
I have a java process running on a Linux box, but it cannot be started/re-started in debug mode. I read about the [jsadebugd](http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jsadebugd.html) command and started the daemon, but I want to connect to it from an IDE(possibly Eclipse) debugger or maybe YourKit or jconsole. How can I do this? The remote JVM is 1.6+. | I assume since you mentioned Yourkit and other tool that what you really want to do is look at object state inside your applications. There are a couple of options, though I don't think it gets you the ability to set break-points like Eclipse or another debugger would (though I'd be intersted in hearing what restricts you from starting the process in debug mode - technical? process?)
1. have you tried connecting with: [VisualVM](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/jmx_connections.html)? I don't believe you need to start in debug mode, and it *will* give you the ability to navigate the object graph, and inspect objects. You can even use it to take heapdumps and do some ad-hoc analysis through them using [OQL](http://www.javaworld.com/community/node/3115) queries.
2. If you're running on JDK6+ - have you tried instrumenting with btrace? Some [notes from the sailfin team](http://weblogs.java.net/blog/binod/archive/2008/06/sailfin_work_an.html) sounded promising, and like DTrace in Solaris, this seem like it would be useful in a variety of situations. | I am not sure if I understand your restrictions correctly but you can start JVM with debugging server (serving JDWP) enabled. See for example "Sun VM Invocation Options" in <http://java.sun.com/j2se/1.4.2/docs/guide/jpda/conninv.html>
Then you can connect your Eclipse debugger to running JVM. See "Remote debugging" section here <http://www.ibm.com/developerworks/library/os-ecbug/> | Can I connect to a jsadebugd process on a remote machine from Eclipse/IDE debugger? | [
"",
"java",
"eclipse",
"debugging",
""
] |
I'm learning Python and have been trying to understand more about the details of Python's `unittest` module. The documentation includes the following:
> For the ease of running tests, as we
> will see later, it is a good idea to
> provide in each test module a callable
> object that returns a pre-built test
> suite:
>
> ```
> def suite():
> suite = unittest.TestSuite()
> suite.addTest(WidgetTestCase('testDefaultSize'))
> suite.addTest(WidgetTestCase('testResize'))
> return suite
> ```
As far as I can tell, the purpose of doing this is not explained. In addition, I was unable to figure out how one would use such a method. I tried several things without success (aside from learning about the error messages I got):
```
import unittest
def average(values):
return sum(values) / len(values)
class MyTestCase(unittest.TestCase):
def testFoo(self):
self.assertEqual(average([10,100]),55)
def testBar(self):
self.assertEqual(average([11]),11)
def testBaz(self):
self.assertEqual(average([20,20]),20)
def suite():
suite = unittest.TestSuite()
suite.addTest(MyTestCase('testFoo'))
suite.addTest(MyTestCase('testBar'))
suite.addTest(MyTestCase('testBaz'))
return suite
if __name__ == '__main__':
# s = MyTestCase.suite()
# TypeError: unbound method suite() must be called
# with MyTestCase instance as first argument
# s = MyTestCase.suite(MyTestCase())
# ValueError: no such test method in <class '__main__.MyTestCase'>: runTest
# s = MyTestCase.suite(MyTestCase('testFoo'))
# TypeError: suite() takes no arguments (1 given)
```
The following "worked" but seems awkward and it required that I change the method signature of `suite()` to '`def suite(self):`'.
```
s = MyTestCase('testFoo').suite()
unittest.TextTestRunner().run(s)
``` | The very first error message you got is meaningful, and explains a lot.
```
print MyTestCase.suite # <unbound method MyTestCase.suite>
```
*Unbound*. It means that you cannot call it unless you bind it to an instance. It's actually the same for `MyTestCase.run`:
```
print MyTestCase.run # <unbound method MyTestCase.run>
```
Maybe for now you don't understand why you can't call `suite`, but please leave it aside for now. Would you try to call `run` on the class, like above? Something like:
```
MyTestCase.run() # ?
```
Probably not, right? It does not make sense to write this, and it will not work, because `run` is an instance method, and needs a `self` instance to work on. Well it appears that Python "understands" `suite` in the same way it understands `run`, as an unbound method.
Let's see why:
If you try to put the `suite` method out of the class scope, and define it as a global function, it just works:
```
import unittest
def average(values):
return sum(values) / len(values)
class MyTestCase(unittest.TestCase):
def testFoo(self):
self.assertEqual(average([10,100]),55)
def testBar(self):
self.assertEqual(average([11]),11)
def testBaz(self):
self.assertEqual(average([20,20]),20)
def suite():
suite = unittest.TestSuite()
suite.addTest(MyTestCase('testFoo'))
suite.addTest(MyTestCase('testBar'))
suite.addTest(MyTestCase('testBaz'))
return suite
print suite() # <unittest.TestSuite tests=[<__main__.MyTestCase testMethod=testFoo>, <__main__.MyTestCase testMethod=testBar>, <__main__.MyTestCase testMethod=testBaz>]>
```
But you don't want it out of the class scope, because you want to call `MyTestCase.suite()`
You probably thought that since `suite` was sort of "static", or instance-independent, it did not make sense to put a `self` argument, did you?
It's right.
But if you define a method inside a Python class, Python will expect that method to have a `self` argument as a first argument. Just omitting the `self` argument does not make your method `static` automatically. When you want to define a "static" method, you have to use the [staticmethod](http://docs.python.org/library/functions.html#staticmethod) decorator:
```
@staticmethod
def suite():
suite = unittest.TestSuite()
suite.addTest(MyTestCase('testFoo'))
suite.addTest(MyTestCase('testBar'))
suite.addTest(MyTestCase('testBaz'))
return suite
```
This way Python does not consider MyTestCase as an instance method but as a function:
```
print MyTestCase.suite # <function suite at 0x...>
```
And of course now you can call `MyTestCase.suite()`, and that will work as expected.
```
if __name__ == '__main__':
s = MyTestCase.suite()
unittest.TextTestRunner().run(s) # Ran 3 tests in 0.000s, OK
``` | The [documentation](http://docs.python.org/library/unittest.html) is saying `suite()` should be a function in the module, rather than a method in your class. It appears to be merely a convenience function so you can later aggregate test suites for many modules:
```
alltests = unittest.TestSuite([
my_module_1.suite(),
my_module_2.suite(),
])
```
Your problems with calling your function are all related to it being a method in the class, yet not written as a method. The `self` parameter is the "current object", and is required for instance methods. (E.g. `a.b(1, 2)` is conceptually the same as `b(a, 1, 2)`.) If the method operates on the class instead of instances, read about [`classmethod`](http://docs.python.org/library/functions.html#classmethod). If it is just grouped with the class for convenience but doesn't operate on the class nor instances, then read about [`staticmethod`](http://docs.python.org/library/functions.html#staticmethod). Neither of these will particularly help you use `unittest`, but they might help explain why you saw what you did. | With Python unittest, how do I create and use a "callable object that returns a test suite"? | [
"",
"python",
""
] |
I have a container with a lot of small images.
```
<div id="container">
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
...
<img src="100.jpg" />
</div>
```
I set opacity to 0. (not hidding)
Then I want to show(fadeIn) random image after half second. for example 5th, 1st, 55th ...
Any suggestions, thanx a lot | try this
```
<script type="text/javascript">
//generate random number
var randomnumber=Math.floor(Math.random()*$("#container").children().length);
$(function() {
//hide all the images (if not already done)
$("#container > img").hide();
//set timeout for image to appear (set at 500ms)
setTimeout(function(){
//fade in the random index of the image collection
$("#container > img:eq(" + randomnumber + ")").fadeIn();
}, 500);
});
</script>
``` | put an id to each image, with a number pattern, and then fade a image with a random generated id, using math.random from javascript
```
function getImage(minim,maxim) {
return "img" + Math.round(Math.random()*(maxim-minim)+minim);
}
``` | jQuery randomly fadeIn images | [
"",
"javascript",
"jquery",
"image",
"fade",
"setinterval",
""
] |
What strategy is good for migrating a hibernate class from a sequence based integer primary key to a GUID primary key while retaining the old keys for backward compatibility?
We have an extensive class hierarchy (using the joined-subclass model) where the base class has a Long primary key generated from a sequence in the DB.
We are working on transitioning to a GUID primary key, but wish to retain the old primary key (both in old and newly created content) for legacy apps. While the implementation seems fairly straightforward (change the primary key to GUID, add an interceptor to populate the content ID on new content), what pitfalls might I want to watch out for? | I can't think of a pretty solution but,
I would create another field to hold the GUIDs and auto generate IDs for any records that currently exist and go from there. It will smell a bit but it's better than trying to store incompatible types in the same field if you ask me. | Are you sure you want to do this?
I understand wanting GUIDs, but do you really want them to be your database PKs. Some informal testing I did showed that there was about a 10-15% hit in using a GUID PK for joins / searches vs an integer PK. I would suggest you try out some tests with GUIDs on your current population and see what the performance hit is. It may be better to just add a uniquely indexed GUID column to your tables and leave the PKs as they are. | migrating a hibernate class from a sequence based integer primary key to a GUID primary key while retaining the old keys for backward compatibility? | [
"",
"java",
"hibernate",
"guid",
""
] |
How do you add a page number from java without using any third party library in a document and which can be treated as a new page in MS Word? Can Java create/manipulate an MS Document? | Not without any third party libraries - unless you want to implement the file handling in your own code, of course... there's no built-in handling for Word documents.
You might be able to do something with Word 2007 documents which are basically zip files of XML files, but you'd still need to understand the format in a fair amount of detail. It would be a *lot* simpler to use a third party library rather than reinventing the wheel. | Not without a third part library.
[POI](http://poi.apache.org/) is all I've ever used. Only made any use of the Excel portions, but they worked fairly well.
If you just need minor things you could implement the [RTF file format](http://www.microsoft.com/downloads/details.aspx?FamilyId=DD422B8D-FF06-4207-B476-6B5396A18A2B&displaylang=en) yourself. Its not a small undertaking, but its actually practical. Sort of. | Putting Page Numbers in a Document | [
"",
"java",
"ms-word",
"page-break",
""
] |
I was wondering how a Garbage Collector can be implemented with C++ full power of pointers arithmetic. Also, In languages like Java, I can not assign literal addresses to references. In C++ it is very flexible.
I believe that C# has both, but again, the unsafe pointer in C# is the responsibility of the programmer.
EITD :: guys, I am asking if C++ pointers 'as they are currently' can be GCed in theory or not ? | Pointer arithmetic isn't the fundamental problem. GC's have to deal with pointers being reassigned all the time, and pointer arithmetic is just another example of that. (Of course, if pointer arithmetic between pointers pointing to different buffers was allowed, it would cause problems, but it isn't. The only arithmetics you're allowed to perform on a pointer pointing into an array A are the ones that repositions it within that array.
The *real* problem is the lack of metadata. A GC has to know what is a pointer and what isn't.
If it encounters the value `0x27a2c230`, it has to be able to determine if it is
* a pointer (in which case it has to follow the pointer to mark the destination as "in use" recursively)
* An integer (The same value is a perfectly valid integer. Perhaps it's not a pointer at all)
* or something else, say, a bit of a string.
It also has to be able to determine the extent of a struct. Assuming that value *is* a pointer, and it points into another struct, the GC has to be able to determine the size and extent of that struct, so it knows which range of addresses should be scanned for more pointers.
GC'ed languages have a lot of infrastructure to deal with this. C++ doesn't.
Boehm's GC is the closest you can generally get, and it it is conservative in that if something *might* be a pointer, the GC assumes it to be one, which means some data is needlessly kept alive. And so, it will likely keep data alive which should be GC'ed.
Alternatively, of course all this infrastructure *could* in principle be added to a C++ compiler. There's no rule in the standard that it's not allowed to exist. The problem is that it would be a major performance hit and eliminate a lot of optimization opportunities. | Yes. There was a system at NeXT back in the 1990s that worked like this: they keep track of every C/C++ memory block that has been allocated. Periodically they scan memory to see if the 4-byte (or 8-byte) value associated with that memory address is present. If it isn't, they assume there are no references, and they free the memory. It's neat and easy! But sometimes it screws up.
Here are some other approaches:
<http://www.hpl.hp.com/personal/Hans_Boehm/gc/>
<http://developers.sun.com/solaris/articles/libgc.html> | can a GC be implemented with C++ raw pointers? | [
"",
"c++",
"pointers",
"garbage-collection",
""
] |
Can someone explain to me why this code fails once in a while with a null exception for udpLink while sending?
```
udpLink = new UdpClient(ipAddress, 514);
using (udpLink)
{
udpLink.Send(rawMsg, rawMsg.Length);
}
```
This is the new code on how I fixed it.
```
udpLink = new UdpClient(ipAddress, 514);
using (udpLink)
{
if (udpLink != null) udpLink.Send(rawMsg, rawMsg.Length);
}
```
Any ideas? | I'm not sure if it really is the problem, but I guess it's the way how you use the using statement. I would do it like this:
```
using (UdpClient udpLink = new UdpClient(ipAddress, 514))
{
udpLink.Send(rawMsg, rawMsg.Length);
}
``` | Depending on whether or not this code segment is in a loop that executes thousands of times you might be maxing out on connections (speaking from experience). you can do a netstat -an and if it scrolls for more than a second chances are that could be your problem. | Why is my UDPClient null once in a while | [
"",
"c#",
"exception",
"network-programming",
"udp",
""
] |
I have a sql query and a mysqli prepared statement:
```
$sql = 'SELECT photographers.photographer_id, photographers.photographer_name
FROM photographers';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_result($photographer_id, $photographer_name);
$OK = $stmt->execute();
$stmt->fetch();
}
```
How can I store the results in an associative array so I can loop it later and get to all the data returned by the sql string? | Try the following:
```
$meta = $statement->result_metadata();
while ($field = $meta->fetch_field()) {
$params[] = &$row[$field->name];
}
call_user_func_array(array($statement, 'bind_result'), $params);
while ($statement->fetch()) {
foreach($row as $key => $val) {
$c[$key] = $val;
}
$hits[] = $c;
}
$statement->close();
```
First you get the query metadata and from that obtain all the fields you've fetched (you could do this manually, but this code works for all queries rather than building by hand). The [`call_user_func_array()`](http://www.php.net/manual/en/function.call-user-func-array.php) function calls the [`mysqli_stmt::bind_result()`](http://php.net/manual/en/mysqli-stmt.bind-result.php) function for you on each of those parameters.
After that it is just a matter of running through each row and creating an associative array for each row and adding that to an array resulting in all the results. | **Update:** Since PHP 5.3.0 you can [get a mysqli\_result](https://php.net/manual/en/mysqli-stmt.get-result.php) object that provides a fetch\_array method.
```
$sql = 'SELECT photographers.photographer_id, photographers.photographer_name
FROM photographers';
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_array();
``` | How can I put the results of a MySQLi prepared statement into an associative array? | [
"",
"php",
"mysqli",
"prepared-statement",
"associative-array",
""
] |
I am writing a class that has lots of getters and setters and was wondering on what people thought about the following:
The normal way is to code like the following:
```
public function setChangeSort($changeSort)
{
self::$changeSort = $changeSort;
}
public function getChangeSort()
{
return self::$changeSort;
}
```
What are your opinions on doing the following:
```
public function setChangeSort($changeSort) { self::$changeSort = $changeSort; }
public function getChangeSort() { return self::$changeSort; }
```
I have no problem doing it the orginal way, as that is how it shoul be done. It just seems to take up alot of space in my classon functions that are really obvious in what they do.
Thanks in advance. | One-line conditional blocks are fine if they're consistent, obvious and intuitive, although I'd encourage spacing them carefully so it's immediately obvious that they are functions rather than some single line of code! | I would go with the "one-line" variation. But **only** if all it does is setting and getting a value. if you add a check for null or any other validation, or doing anything other than getting or setting I would go with the first and longer variation to keep the code more readable. | Code Layout for getters and setters | [
"",
"php",
"class",
"layout",
"setter",
"getter",
""
] |
Recently I have been learning about WMI and WQL. I found out the list of Win32 classes (from MSDN) that I can query for but I am not able to find out the list of event classes (should be the subset of the list of Win32 classes isn't it ?) Does any one have a list or some kind of cheat sheet for this? I am jsut asking this out of curiosity.
Example for an event class - **Win32\_ProcessStartTrace** | Here's how to list WMI event classes in the `root\cimv2` namespace with C# and `System.Management`:
```
using System;
using System.Management;
class Program
{
static void Main()
{
string query =
@"Select * From Meta_Class Where __This Isa '__Event'";
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(query);
foreach (ManagementBaseObject cimv2Class in searcher.Get())
{
Console.WriteLine(cimv2Class.ClassPath.ClassName);
}
}
}
```
`root\cimv2` is the default WMI namespace so you don't have to use a `ManagementScope` instance. The WQL query passed to `ManagementObjectSearcher` is a WMI metadata query. It uses:
* `Meta_Class` to designate the query as a schema query, and
* `__This` property to recursively list `__Event` subclasses
(see [here](http://msdn.microsoft.com/en-us/library/aa393278(VS.85).aspx) and [here](http://msdn.microsoft.com/en-us/library/aa719643(VS.71).aspx)).
WMI class is an event class if its provider implemented as an event WMI provider and must be a subclass of `__Event`. This doesn't mean that you can't use 'ordinary' WMI classes like `Win32_Process` and `Win32_Service` in WQL event queries. You just have to use one of the `__InstanceOperationEvent` derived helper classes like `__InstanceCreationEvent` or `__InstanceDeletionEvent`, and WMI will use its own event subsystem to deliver events.
Here is a sample WQL query that subscribes to `Win32_Process` creation events:
```
Select * From __InstanceCreationEvent Within 5 Where TargetInstance Isa 'Win32_Process'
```
In this case you have to use the [`Within`](http://msdn.microsoft.com/en-us/library/aa394527(VS.85).aspx) clause. | [WMI Code Creator](http://www.microsoft.com/downloads/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en) is a great tool for learning WMI that, among other things, lets you explore WMI event classes on the local or remote computer and generate code for receiving event notifications.
**Edit:** Since you tagged your question as *C#*, you might be interested in the code for getting the list of event classes derived from a particular class programmatically:
```
using System.Management;
...
string ancestor = "WMIEvent"; // the ancestor class
string scope = "root\\wmi"; // the WMI namespace to search within
try
{
EnumerationOptions options = new EnumerationOptions();
options.ReturnImmediately = true;
options.Rewindable = false;
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, "SELECT * FROM meta_class", options);
foreach (ManagementClass cls in searcher.Get())
{
if (cls.Derivation.Contains(ancestor))
{
Console.WriteLine(cls["__CLASS"].ToString());
}
}
}
catch (ManagementException exception)
{
Console.WriteLine(exception.Message);
}
``` | List of WMIEvent classes | [
"",
"c#",
"wmi",
"wmi-query",
"wql",
""
] |
I'm looking for a straightforward way to make a **Swing component forward all received
events to its parent container** (or even all parents up to root).
**EDIT**:
Where do I need this? I have a diagram editor. Components must forward key press and
mouse clicks (to set themselves as "active" as soon as the user clicks a subelement
of that component).
First, let me present my existing solution for this. It's a bit of a workaround.
```
public interface IUiAction {
void perform(Component c);
}
public static void performRecursiveUiAction(Container parent, IUiAction action) {
if (parent == null) {
return;
}
for (Component c : parent.getComponents()) {
if (c != null) {
action.perform(c);
}
}
for (Component c : parent.getComponents()) {
if (c instanceof Container) {
performRecursiveUiAction((Container) c, action);
}
}
}
/**
* 1) Add listener to container and all existing components (recursively).
* 2) By adding a ContainerListener to container, ensure that all further added
* components will also get the desired listener.
*
* Useful example: Ensure that every component in the whole component
* tree will react on mouse click.
*/
public static void addPermanentListenerRecursively(Container container,
final IUiAction adder) {
final ContainerListener addingListener = new ContainerAdapter() {
@Override
public void componentAdded(ContainerEvent e) {
adder.perform(e.getChild());
}
};
// step 1)
performRecursiveUiAction(container, adder);
// step 2)
performRecursiveUiAction(container, new IUiAction() {
@Override
public void perform(Component c) {
if (c instanceof Container) {
((Container) c).addContainerListener(addingListener);
}
}
});
}
```
Usage:
```
addPermanentListenerRecursively(someContainer,
new IUiAction(
@Override
public void perform(Component c){
c.addMouseListener(somePermanentMouseListener);
}
)
);
```
By looking over the code, would you say it's a good concept?
The problem with my current concept is: It's forwarding only events, for which a listener was specified manually.
Can you suggest a better one? | This looks like it would get a bit tricky if every component in your view handled the same mouse event. ie, if the user drags *item 1*, *item 2* would process those events as well? if i understand correctly, you are looking to have `this` and `this.parent` and `this.parent.parent` handle mouse actions on `this`. in that case the recursion would be up, and not down.
you could create an `Interface` like this:
```
public interface MyInterface() {
public void performSpecialAction(Event event);
}
```
you then have your containers implement this interface. your components would then need to incorporate this call to their appropriate event handling:
```
public static void performRecursiveUiAction(Component comp, Event event) {
if (comp.getParent() == null) {
return;
}
if (comp.getParent() instanceof MyInteface) {
((MyInterface)comp.getParent()).performSpecialAction(event);
}
ThisUtility.performRecursiveUiAction(comp.getParent(), event);
```
} | Based on your scenario I have a suggestion for the keyboard side of things:
You could use the KeyStroke facility of swing for that:
```
JRootPane rp = getRootPane();
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0, false);
rp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "F2");
rp.getActionMap().put("F2", new AbstractAction() {
public void actionPerformed(ActionEvent e) { onF2Action(); } });
```
This way you can register 'global' event handlers for shortcuts1.
1 although it might have some limitations in your case.
For the mouse-event case I would create a recursive function, which adds a `MouseAdapter` instance to every targeted component. For example:
```
void addToAll(Container c, MouseAdapter a) {
for (Component p : c.getComponents()) {
if (p instanceof InterrestingComponent) {
p.addMouseListener(a);
p.addMouseMotionListener(a);
p.addMouseWheelListener(a);
} else
if (p instanceof Container) {
addToAll((Container)p, a);
}
}
}
```
Just to capture the concept. You might need different or multiple receivers for various components.
**Edit:** Sorry, I accidentally said WindowAdapter instead of MouseAdapter. | Swing: How to achieve forwarding of all events from subcomponents to parent container? | [
"",
"java",
"user-interface",
"swing",
"events",
""
] |
I am at chapter 9 of Jon Skeet's CSharp in Depth at a section which explains the improvements to type inference in 3.0
There is code snippet on Pg.247 that 'shouldn't compile with 2.0' - However I can't find a reason why it should not. Tried the problem with VS2008 C# Express Edition on a project **with target framework as 2.0** - **all three of the below calls compile and run too**.
2.0 introduced the ability to infer the right type of delegate.
```
new List<ThreadStart>().Add( delegate { Console.WriteLine("New Thread!"); } ); // works
```
Of course Jon can't be wrong ( ;) 'Sql is broken' + there is no mention of this on the errata page for the book.) So my prime suspicion would be that it's still using 3.0 type inference - What am I missing ?
```
delegate int MyDelegate(string s);
delegate TOutput MyConverter<TInput, TOutput>(TInput input);
static void MyParse(MyDelegate del)
{
Console.WriteLine(del("100"));
}
static void MyConvert<TInput, TOutput>(MyConverter<TInput, TOutput> del, TInput input)
{
Console.WriteLine(del(input));
}
// Jon's code snippet begin
delegate T MyFunc<T>();
static void WriteResult<T>(MyFunc<T> function)
{
Console.WriteLine(function());
}
// end
static void Main(string[] args)
{
MyParse(delegate(string s)
{
return Int32.Parse(s);
}
);
MyConvert(delegate(string s)
{
return Int32.Parse(s);
},
"100");
WriteResult(delegate { return 5; }); // Jon: Shouldn't work.
}
``` | What the 'target framework' setting does, is disable libraries and methods that have been added in newer framework versions. Most of the new language features don't require special runtime support or new libraries. So if you use them, you need the newer compiler, but your app will still work on 2.0. | I've got Visual Studio 2005 installed on my computer and I just tried out the code that you've posted.
Both MyConvert and WriteResult don't work. I get the following errors:
```
The type arguments for method 'ConsoleApplication1.Program.MyConvert<TInput,TOutput>(ConsoleApplication1.Program.MyConverter<TInput,TOutput>, TInput)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
```
and
```
The type arguments for method 'ConsoleApplication1.Program.WriteResult<T>(ConsoleApplication1.Program.MyFunc<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
``` | Why should the following snippet be a problem for C#2.0 type inference? | [
"",
"c#",
"type-inference",
""
] |
How to access and display the images that are located outside the application folder? Let's say I have a file directory that stores all the images and other file types, and this file directory is located on a different drive then my application folder. For certain file types ( such as .pdf, .doc, I want to prompt the user to download those files).
As far as I know, it's not possible to put absolute path in the `<img src` attributes, i.e, `img src="D:\\file directory">` doesn't work. And also **I want to restrict the access to login user only**.
I am using PHP as my server side language.
**Note:** `<img src="file:/// .../>` [won't work in Firefox](http://kb.mozillazine.org/Links_to_local_pages_don't_work). See here for [comments](http://forums.mozillazine.org/viewtopic.php?f=38&t=290533&start=0&st=0&sk=t&sd=a).
**Edit: Since only authenticated user can access those images, and since I have an index.php that checks for all the incoming requests, filters off non-authenticated users, I don't think creating an Apache Alias will work.**
Here's an example of my conf file:
```
NameVirtualHost *:80
<VirtualHost *:80 >
ServerName pmmenu.businessjob.net
DocumentRoot "D:\web"
DirectoryIndex index.html index.php
<Directory "D:\web">
AddDefaultCharset UTF-8
Order Deny,Allow
Allow from all
RewriteEngine on
RewriteBase /
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
# no, so we redirect to our front web controller
RewriteRule ^(.*)$ index.php [QSA,L]
</Directory>
</VirtualHost>
``` | I think you're missing a basic concept here. All HTML is interpreted client-side. Every image is downloaded seperately by the browser of your visitor. As your visitors can only access those files that are public, "file:///something" will not work for them, because this asks their browser to access the local (their) filesystem, which will either be blocked or not find the requested image as it is not stored on their disk.
So you will have to publish those pictures and make them accessible via http to allow your visitors to see them. You could do this by creating a subdomain or a virtual directory.
Since you want only authenticated users to be able to see them, you could also create a php file that checks whether the user is authenticated, e.g. like this:
```
if(user_is_authenticated()){
$pathToFile = "d:\images\myimage.jpg";
$handle = @fopen($pathToFile, "rb");
$contents = @fread($handle, filesize($pathToFile));
@fclose($handle);
//sent appropriate header
header('Content-type: image/jpeg');
echo $contents;
}
```
But you have to be aware that this script will always read the whole image and print it subsequently, which is a huge overhead. | try creating a virtual directory of the folder that holds the images and use that as away of linking to the folder. If using IIS (a virtual directory) if apache (a virtual host). There are lots of tutorials on google | Access and Display Images/ Prompt File Downloads that are located outside the application folder | [
"",
"php",
"html",
"apache",
""
] |
I have to come up with a solution to compress, version (for caching purposes) and potentially combine our JS and CSS files and I've seen two dominant approaches so far:
1) At build time: As an MSBuild task or similar.
2) Dynamically at run time: As a custom HTTPHandler (we are ASP.NET btw) for .js and .css files, with something like this ending up in your pages:
```
<link rel="stylesheet" type="text/css" href="~/StyleSheetHandler.ashx?stylesheets=~stylesheets/master.css" />
```
Can anyone provide information of pro's and con's of each? Personally, I can't see the point of doing it dynamically and wasting CPU cycles at the time of each request (I guess you'd only do with the work first time and then cache, but still) but I get the feeling I might be missing something?
Thanks!
Mark. | I think a good approach is to use different strategies for different environments:
* *no* compression for *development* (for developing & debugging)
* *runtime* compression for *test environment* (flexible, not performance-critical)
* *buildtime* compression for *staging and production* (tested, performance-critical)
I have some experience using the [YUI compressor](http://developer.yahoo.com/yui/compressor/) for both Javascript and CSS and have learned (the hard way) that testing minified JS and CSS is indeed very important.
Creating static minified JS and CSS files as part of your build for production has the following benefits:
* they are tested
* static files, can be served without ASP.NET overhead
* can be browser cached
* should be webserver-gzipped | The best way is to *not do it at all*, since all modern browsers and servers handle Gzip encoding. Look at the numbers:
* cfform.js - 21k
* cfform-minified.js - 12k
* cfform.js.gz - 4.2k
* cfform-minified.js.gz - 2.2k
This is a fairly large JS file with plenty of unnecessary whitespace but in the final equation you've saved a whopping 2k !! Not only that but thanks to caching this saving is per-visitor, not per-page. Whoo-hoo, now that was worth all the trouble wasn't it?
You'd save 10 times that by cropping a pixel width off the top of your banner and with 99% of your users on broadband you've saved them about 1 millisecond of download time. Break out the streamers and champagne!
JS compression is even worse, since you've just hit your clients with the burden of decompressing on EVERY PAGE LOAD. And the savings after gzip are just as miserable.
Seriously. The added complexity and debugging is not worth it unless you are targetting a mobile market (and even that assumes the users are still on CDMA, not 3G) or have a billion hits per day. Otherwise just don't bother. | CSS compression & combining / js minification - Better to do at runtime or at build time? | [
"",
"asp.net",
"javascript",
"css",
"caching",
"compression",
""
] |
We are writing an ASP.Net/C# based program that will potentially be accessed by a number of companies (each having separate login and data). We are thinking of having multiple sql server 2008 databases (same instance), each for one company. However, the c# program that accesses the database will be the same and will create appropriate connection string based on the database the customer will be accessing.
How many such databases can be created in the single instance of the sql server before seeing any performance degradation due to:
* Limit on the connections, because each connection (not sure if it will be pooled for accessing different databases) is created using a differents connection string.
* Limit on the number of databases, is it limited by the hardware or sql server 2008 will show degradation when the number of databases increases to say 100?
Anything else I might be missing?
Thanks for your time | * Max databases per SQL Server instance: **32,767**
* Max User connections: **32,767**
(From here: [Maximum Capacity Specifications for SQL Server](http://msdn.microsoft.com/en-us/library/ms143432.aspx))
Both are practically limited by the amount of RAM the SQL server machine has, long before it reaches those maximum values.
Of the two, I suspect user connections are going to be the bigger problem if you have thousands of users (as you are not using connection pooling).
To find the SQL Server machine's current value:
```
SELECT @@MAX_CONNECTIONS AS 'Max Connections'
```
**Updated** in response to poster's comments:
It's not really the number of databases that is the problem, but more the number of frequently accessed pages in those databases. If all the 'hot' pages fit into memory (and very few physical reads occur) then all is good. | You should also keep in mind that connections will be pooled by connection string -- in your case, you will get separate pools for each Customer DB. That might not be bad if you have high traffic for each customer, but if you have low traffic to lots of different databases you will not get the full benefit of pooling. | Maximum number of databases in sql server 2008 | [
"",
"c#",
"sql-server",
"database-connection",
""
] |
What is the best way to exit out of a loop as close to 30ms as possible in C++. Polling boost:microsec\_clock ? Polling QTime ? Something else?
Something like:
```
A = now;
for (blah; blah; blah) {
Blah();
if (now - A > 30000)
break;
}
```
It should work on Linux, OS X, and Windows.
The calculations in the loop are for updating a simulation. Every 30ms, I'd like to update the viewport. | The code snippet example in this link pretty much does what you want:
<http://www.cplusplus.com/reference/clibrary/ctime/clock/>
Adapted from their example:
```
void runwait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait)
{
/* Do stuff while waiting */
}
}
``` | > The calculations in the loop are for
> updating a simulation. Every 30ms, I'd
> like to update the viewport.
Have you considered using threads? What you describe seems the perfect example of why you should use threads instead of timers.
The main process thread keeps taking care of the UI, and have a QTimer set to 30ms to update it. It locks a [QMutex](https://doc.qt.io/qt-5/qmutex.html) to have access to the data, performs the update, and releases the mutex.
The second thread (see [QThread](https://doc.qt.io/qt-5/qthread.html)) does the simulation. For each cycle, it locks the QMutex, does the calculations and releases the mutex when the data is in a stable state (suitable for the UI update).
With the increasing trend on multi-core processors, you should think more and more on using threads than on using timers. Your applications automatically benefits from the increased power (multiple cores) of new processors. | What is the best way to exit out of a loop after an elapsed time of 30ms in C++ | [
"",
"c++",
"qt",
"timer",
"clock",
""
] |
What should 'foo' be called, given the following?
x.items is a set, y.values is a set.
function a(key) returns an ordered list of x.items
function b(x.item) returns a single y.value
Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.values defined by: map(b, a(key)).
This feels like a fairly common and generic function composition but I don't know what to call it. | ```
function a(key) returns an ordered list of x.items
function b(x.item) returns a single y.value
```
Except for the ordering, a() is in practice a filter, i.e. it "filters" or "selects" items from x.items according to a key. b() is a normal map, or function. Thus, I would choose for 'foo' the name "composeFilterWithMap", or "composeSelectorWithMap" or a similar name. | I would call it **function compositor** or something like that | What should I call this function composition? | [
"",
"python",
"math",
"functional-programming",
""
] |
i just want to know about the language transation for the Japanese,
1) Which is the best encoding for the database mysql
2) Which/how can i print that in HTML page. ?
thanks in advance. | UTF-8 without a doubt. Make everything UTF-8. To put UTF-8 encoded text on your web page, use this within your HEAD tag:
```
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
```
As for MySQL, put the following into your my.cnf (config) file:
```
[mysqld]
collation_server=utf8_unicode_ci
character_set_server=utf8
default-character-set=utf8
default-collation=utf8_general_ci
collation-server=utf8_general_ci
```
If you're getting garbage characters from the database from queries executed by your application, you might need to execute these two queries *before* fetching your Japanese text:
```
SET NAMES utf8
SET CHARACTER SET utf8
``` | Make Sure
1. Database is in UTF8
2. Database Table is in UTF 8
3. Output Headers are in UTF 8
4. HTML Meta Tag is in UTF 8
When everything is talking the encoding you can live happily :)
For MySQL: utf8 charset, utf8\_general\_ci collation
For PHP headers:
```
header('Content-type: text/html; charset=UTF-8') ;
```
For HTML
```
<meta http-equiv="Content-type" value="text/html; charset=UTF-8" />
``` | Which is the best character encoding for Japanese language for DB, php, and html display? | [
"",
"php",
"mysql",
"unicode",
"character-encoding",
""
] |
Here is a simple example of a django view with a potential race condition:
```
# myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
```
The race condition should be fairly obvious: A user can make this request twice, and the application could potentially execute `user = request.user` simultaneously, causing one of the requests to override the other.
Suppose the function `calculate_points` is relatively complicated, and makes calculations based on all kinds of weird stuff that cannot be placed in a single `update` and would be difficult to put in a stored procedure.
So here is my question: What kind of locking mechanisms are available to django, to deal with situations similar to this? | Django 1.4+ supports [select\_for\_update](https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_for_update), in earlier versions you may execute raw SQL queries e.g. `select ... for update` which depending on underlying DB will lock the row from any updates, you can do whatever you want with that row until the end of transaction. e.g.
```
from django.db import transaction
@transaction.commit_manually()
def add_points(request):
user = User.objects.select_for_update().get(id=request.user.id)
# you can go back at this point if something is not right
if user.points > 1000:
# too many points
return
user.points += calculate_points(user)
user.save()
transaction.commit()
``` | As of Django 1.1 you can use the ORM's F() expressions to solve this specific problem.
```
from django.db.models import F
user = request.user
user.points = F('points') + calculate_points(user)
user.save()
```
For more details see the documentation:
<https://docs.djangoproject.com/en/1.8/ref/models/instances/#updating-attributes-based-on-existing-fields>
<https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.F> | Race conditions in django | [
"",
"python",
"database",
"django",
"locking",
"race-condition",
""
] |
I have the following code:
```
foreach (string p in dirs)
{
string path = p;
string lastAccessTime = File.GetLastAccessTime(path).ToString();
bool DirFile = File.Exists(path);
FileInfo fInf = new FileInfo(path);
DateTime lastWriteTime = File.GetLastWriteTime(p);
dirFiles.Add(p + "|" + lastAccessTime.ToString() + "|" + DirFile.ToString() + "|" + lastWriteTime.ToString() + "|" + fInf.Length.ToString());
}
```
I have a fInf.Length.ToString() and i'd like to measure the output in terms of kbs. Any ideas on how do accomplish this? For example, instead of getting 2048 as a File Size, i'd like to just get 2Kb.
Thanks in advance for help | Here's how to get it broken down in gigabytes, megabytes or kilobytes:
```
string sLen = fInf.Length.ToString();
if (fInf.Length >= (1 << 30))
sLen = string.Format("{0}Gb", fInf.Length >> 30);
else
if (fInf.Length >= (1 << 20))
sLen = string.Format("{0}Mb", fInf.Length >> 20);
else
if (fInf.Length >= (1 << 10))
sLen = string.Format("{0}Kb", fInf.Length >> 10);
```
`sLen` will have your answer. You could wrap it in a function and just pass in the `Length`, or even the `FileInfo` object.
If instead of 'real' kilobytes, you wanted it in terms of 1000's of bytes, you could replace `1 << 10` and `>> 10` with `1000` and `/1000` respectively, and similarly for the others using 1000000 and 1000000000. | If you want the length as a (long) integer:
```
long lengthInK = fInf.Length / 1024;
string forDisplay = lengthInK.ToString("N0") + " KB"; // eg, "48,393 KB"
```
If you want the length as a floating point:
```
float lengthInK = fInf.Length / 1024f;
string forDisplay = lengthInK.ToString("N2") + " KB"; // eg, "48,393.68 KB"
``` | Measuring fileinfo.Length objects into kbs | [
"",
"c#",
"system.io.fileinfo",
""
] |
In [this question](https://stackoverflow.com/questions/1031301/can-i-implement-the-factory-method-pattern-in-c-without-using-new) creating a factory method when the compiler doesn't support *new* and placement *new* is discussed. Obviously some suitable solution could be crafted using malloc() if all necessary steps done by placement *new* are reproduced in some way.
What does placement *new* do - I'll try to list and hope not to miss anything - except the following?
* call constructors for all base classes recursively
* call constructors and initializers (if any) for all member variables
* set vtable pointer accordingly.
What other actions are there? | Placement `new` does everything a regular `new` would do, except allocate memory.
I think you've essentially nailed what happens, with some minor clarifications:
* obviously the constructor of the class itself is called as well
* vtable pointers are initialized as part of constructor calls, not separately. An implication of this is that a partially constructed object (think exceptions thrown in constructor) has its vtable set up to the point the construction proceeded to.
The order of construction/initialization is as follows:
1. virtual base classes in declaration order
2. nonvirtual base classes in declaration order
3. class members in declaration order
4. class constructor itself | *set vtable pointer accordingly*
This part is almost completely implementation-defined. Your compiler might not use vtables. There may be multiple vtable pointers, or one or more pointers to things which are not vtables. Multiple inheritance is always entertaining, as are virtual base classes. This metadata is not guaranteed to be copyable with `memcpy` to another object, so the pointer(s) needn't be absolute. There could be offsets in there which are relative to the object pointer itself.
IIRC what commonly happens is that the base class constructor is called, then the vtable pointer is set to the base class, then the first derived class constructor is called, etc. This is in order to satisfy the requirements in the specification concerning what happens when a virtual function is called in a constructor. As far as I remember, there is no "list of actions" in the standard, just a defined initialisation order.
So it is not possible to generalise what an implementation does, especially since what you have is not an implementation of the C++ standard. If it cuts corners by leaving out "new", presumably with good reason because it thinks you shouldn't be using it on the target platform, then who knows what other rules of the language it ignores. If it were possible to mock up "new" with a malloc and a bit of pointer-pushing, then why on earth does the compiler not just implement new? I think you need to ask questions tagged with your specific compiler and platform, so that any experts on your compiler can respond. | What is the full list of actions performed by placement new in C++? | [
"",
"c++",
"constructor",
"new-operator",
""
] |
This may sound like a simple question, but I just cannot seem to find an answer on google, probably because the search term will bring back quite a lot of irrelevance.
I would like a jQuery selector to select all odd table rows, that are not in <thead> and apply a css class to them all.
```
table.cp-ss-grid tr:odd
```
The above selector will bring back all odd rows in the table correctly, but will include the thead rows (on ie)
How would I in the selector do an and, i.e. something like:
```
table.cp-ss-grid tr:odd:not(thead)
```
the above doesn't work and still brings back the thead rows
Any ideas? | Why not do:
```
$('table.cp-ss-grid > tbody > tr:odd');
```
To explicitly select the body rows? All browsers will add a tbody for you if you don't have one. | An `AND` selector for jQuery would be for example: `.classA.classB`
This would select elements which have classA and classB. | jQuery selector AND operator | [
"",
"javascript",
"jquery",
"css-selectors",
""
] |
I would like to create a unique ID for each object I created - here's the class:
```
class resource_cl :
def __init__(self, Name, Position, Type, Active):
self.Name = Name
self.Position = Position
self.Type = Type
self.Active = Active
```
I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:
```
resources = []
resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True))
```
I know I can reference resource\_cl, but I'm not sure how to proceed from there... | Are you aware of the [id function](http://docs.python.org/library/functions.html#id) in python, and could you use it instead of your counter idea?
```
class C(): pass
x = C()
y = C()
print(id(x), id(y)) #(4400352, 16982704)
``` | Trying the highest voted answer in python 3 you'll run into an error since `.next()` has been removed.
Instead you could do the following:
```
import itertools
class BarFoo:
id_iter = itertools.count()
def __init__(self):
# Either:
self.id = next(BarFoo.id_iter)
# Or
self.id = next(self.id_iter)
...
``` | How do you create an incremental ID in a Python Class | [
"",
"python",
"class",
""
] |
I have lots of data with start and stop times for a given ID and I need to flatten all intersecting and adjacent timespans into one combined timespan. The sample data posted below is all for the same ID so I didn't list it.
To make things a bit clearer, take a look at the sample data for 03.06.2009:
The following timespans are overlapping or contiunous and need to merge into one timespan
* 05:54:48 - 10:00:13
* 09:26:45 - 09:59:40
The resulting timespan would be from 05:54:48 to 10:00:13. Since there's a gap between 10:00:13 and 10:12:50 we also have the following timespans:
* 10:12:50 - 10:27:25
* 10:13:12 - 11:14:56
* 10:27:25 - 10:27:31
* 10:27:39 - 13:53:38
* 11:14:56 - 11:15:03
* 11:15:30 - 14:02:14
* 13:53:38 - 13:53:43
* 14:02:14 - 14:02:31
which result in one merged timespan from 10:12:50 to 14:02:31, since they're overlapping or adjacent.
Below you will find the sample data and the flattened data as I would need it. The duration column is just informative.
Any solution - be it SQL or not - is appreciated.
---
**EDIT**: Since there are lots of different and interesting solutions I'm refining my original question by adding constraints to see the "best" (if there is one) solution bubble up:
* I'm getting the data via ODBC from another system. There's no way to change the table layout for me or adding indexes
* The data is indexed only by the date column (the time part isn't)
* There are about 2.5k rows for every day
* The estimated usage pattern of the data is roughly as follows:
+ Most of the time (lets say 90%) the user will query just one or two days (2.5k - 5k rows)
+ Sometimes (9%) the range will be up to a month (~75k rows)
+ Rarely (1%) the range will be up to a year (~900k rows)
* The query should be fast for the typical case and not "last forever" for the rare case.
* Querying a year worth of data takes about 5 minutes (plain select without joins)
Within these constraints, what would be the best solution? I'm afraid that most of the solutions will be horribly slow since they join on the combination of date and time, which is not an index field in my case.
Would you do all the merging on the client or the server side? Would you first create an optimized temp table and use one of the proposed solutions with that table? I didn't have the time to test the solutions until now but I will keep you informed what works best for me.
---
**Sample data:**
```
Date | Start | Stop
-----------+----------+---------
02.06.2009 | 05:55:28 | 09:58:27
02.06.2009 | 10:15:19 | 13:58:24
02.06.2009 | 13:58:24 | 13:58:43
03.06.2009 | 05:54:48 | 10:00:13
03.06.2009 | 09:26:45 | 09:59:40
03.06.2009 | 10:12:50 | 10:27:25
03.06.2009 | 10:13:12 | 11:14:56
03.06.2009 | 10:27:25 | 10:27:31
03.06.2009 | 10:27:39 | 13:53:38
03.06.2009 | 11:14:56 | 11:15:03
03.06.2009 | 11:15:30 | 14:02:14
03.06.2009 | 13:53:38 | 13:53:43
03.06.2009 | 14:02:14 | 14:02:31
04.06.2009 | 05:48:27 | 09:58:59
04.06.2009 | 06:00:00 | 09:59:07
04.06.2009 | 10:15:52 | 13:54:52
04.06.2009 | 10:16:01 | 13:24:20
04.06.2009 | 13:24:20 | 13:24:24
04.06.2009 | 13:24:32 | 14:00:39
04.06.2009 | 13:54:52 | 13:54:58
04.06.2009 | 14:00:39 | 14:00:49
05.06.2009 | 05:53:58 | 09:59:12
05.06.2009 | 10:16:05 | 13:59:08
05.06.2009 | 13:59:08 | 13:59:16
06.06.2009 | 06:04:00 | 10:00:00
06.06.2009 | 10:16:54 | 10:18:40
06.06.2009 | 10:18:40 | 10:18:45
06.06.2009 | 10:23:00 | 13:57:00
06.06.2009 | 10:23:48 | 13:57:54
06.06.2009 | 13:57:21 | 13:57:38
06.06.2009 | 13:57:54 | 13:57:58
07.06.2009 | 21:59:30 | 01:58:49
07.06.2009 | 22:12:16 | 01:58:39
07.06.2009 | 22:12:25 | 01:58:28
08.06.2009 | 02:10:33 | 05:56:11
08.06.2009 | 02:10:43 | 05:56:23
08.06.2009 | 02:10:49 | 05:55:59
08.06.2009 | 05:55:59 | 05:56:01
08.06.2009 | 05:56:11 | 05:56:14
08.06.2009 | 05:56:23 | 05:56:27
```
**Flattened result:**
```
Date | Start | Stop | Duration
-----------+----------+----------+---------
02.06.2009 | 05:55:28 | 09:58:27 | 04:02:59
02.06.2009 | 10:15:19 | 13:58:43 | 03:43:24
03.06.2009 | 05:54:48 | 10:00:13 | 04:05:25
03.06.2009 | 10:12:50 | 14:02:31 | 03:49:41
04.06.2009 | 05:48:27 | 09:59:07 | 04:10:40
04.06.2009 | 10:15:52 | 14:00:49 | 03:44:58
05.06.2009 | 05:53:58 | 09:59:12 | 04:05:14
05.06.2009 | 10:16:05 | 13:59:16 | 03:43:11
06.06.2009 | 06:04:00 | 10:00:00 | 03:56:00
06.06.2009 | 10:16:54 | 10:18:45 | 00:01:51
06.06.2009 | 10:23:00 | 13:57:58 | 03:34:58
07.06.2009 | 21:59:30 | 01:58:49 | 03:59:19
08.06.2009 | 02:10:33 | 05:56:27 | 03:45:54
``` | Here is a SQL only solution. I used DATETIME for the columns. Storing the time separate is a mistake in my opinion, as you will have problems when the times go past midnight. You can adjust this to handle that situation though if you need to. The solution also assumes that the start and end times are NOT NULL. Again, you can adjust as needed if that's not the case.
The general gist of the solution is to get all of the start times that don't overlap with any other spans, get all of the end times that don't overlap with any spans, then match the two together.
The results match your expected results except in one case, which checking by hand looks like you have a mistake in your expected output. On the 6th there should be a span that ends at 2009-06-06 10:18:45.000.
```
SELECT
ST.start_time,
ET.end_time
FROM
(
SELECT
T1.start_time
FROM
dbo.Test_Time_Spans T1
LEFT OUTER JOIN dbo.Test_Time_Spans T2 ON
T2.start_time < T1.start_time AND
T2.end_time >= T1.start_time
WHERE
T2.start_time IS NULL
) AS ST
INNER JOIN
(
SELECT
T3.end_time
FROM
dbo.Test_Time_Spans T3
LEFT OUTER JOIN dbo.Test_Time_Spans T4 ON
T4.end_time > T3.end_time AND
T4.start_time <= T3.end_time
WHERE
T4.start_time IS NULL
) AS ET ON
ET.end_time > ST.start_time
LEFT OUTER JOIN
(
SELECT
T5.end_time
FROM
dbo.Test_Time_Spans T5
LEFT OUTER JOIN dbo.Test_Time_Spans T6 ON
T6.end_time > T5.end_time AND
T6.start_time <= T5.end_time
WHERE
T6.start_time IS NULL
) AS ET2 ON
ET2.end_time > ST.start_time AND
ET2.end_time < ET.end_time
WHERE
ET2.end_time IS NULL
``` | In `MySQL`:
```
SELECT grouper, MIN(start) AS group_start, MAX(end) AS group_end
FROM (
SELECT start,
end,
@r := @r + (@edate < start) AS grouper,
@edate := GREATEST(end, CAST(@edate AS DATETIME))
FROM (
SELECT @r := 0,
@edate := CAST('0000-01-01' AS DATETIME)
) vars,
(
SELECT rn_date + INTERVAL TIME_TO_SEC(rn_start) SECOND AS start,
rn_date + INTERVAL TIME_TO_SEC(rn_end) SECOND + INTERVAL (rn_start > rn_end) DAY AS end
FROM t_ranges
) q
ORDER BY
start
) q
GROUP BY
grouper
ORDER BY
group_start
```
Same decision for `SQL Server` is described in the following article in my blog:
* [**Flattening timespans: SQL Server**](http://explainextended.com/2009/06/11/flattening-timespans-sql-server/)
Here's the function to do this:
```
DROP FUNCTION fn_spans
GO
CREATE FUNCTION fn_spans(@p_from DATETIME, @p_till DATETIME)
RETURNS @t TABLE
(
q_start DATETIME NOT NULL,
q_end DATETIME NOT NULL
)
AS
BEGIN
DECLARE @qs DATETIME
DECLARE @qe DATETIME
DECLARE @ms DATETIME
DECLARE @me DATETIME
DECLARE cr_span CURSOR FAST_FORWARD
FOR
SELECT s_date + s_start AS q_start,
s_date + s_stop + CASE WHEN s_start < s_stop THEN 0 ELSE 1 END AS q_end
FROM t_span
WHERE s_date BETWEEN @p_from - 1 AND @p_till
AND s_date + s_start >= @p_from
AND s_date + s_stop <= @p_till
ORDER BY
q_start
OPEN cr_span
FETCH NEXT
FROM cr_span
INTO @qs, @qe
SET @ms = @qs
SET @me = @qe
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT
FROM cr_span
INTO @qs, @qe
IF @qs > @me
BEGIN
INSERT
INTO @t
VALUES (@ms, @me)
SET @ms = @qs
END
SET @me = CASE WHEN @qe > @me THEN @qe ELSE @me END
END
IF @ms IS NOT NULL
BEGIN
INSERT
INTO @t
VALUES (@ms, @me)
END
CLOSE cr_span
RETURN
END
```
Since `SQL Server` lacks an easy way to refer to previously selected rows in a resultset, this is one of rare cases when cursors in `SQL Server` work faster than set-based decisions.
Tested on `1,440,000` rows, works for `24` seconds for the full set, and almost instant for a range of day or two.
Note the additional condition in the `SELECT` query:
```
s_date BETWEEN @p_from - 1 AND @p_till
```
This seems to be redundant, but it is actually a coarse filter to make your index on `s_date` usable. | Flattening intersecting timespans | [
"",
"sql",
"sql-server",
"sql-server-2005",
"algorithm",
"datetime",
""
] |
I have to parse a XML configuration file. I decided to do the basic validation with XMLSchema to avoid massive amounts of boilerplate code for validation. Since the parsing class should work for itself i was wondering: "How can i validate the incoming XML file with XMLSchema without having the XMLSchema stored on disc where it can be modified by third parties?" I know i can load the XMLSchema from an arbitrary InputStream, but the Schema itself must be stored somewhere. (And putting the Schema in a huge String object sounds like a very very bad idea) Has someone already did this? What are the best solution for such cases?
Have a nice start of the week! | I would place it in your deployment alongside the appropriate classes. Load it using
[ClassLoader.getResourceAsStream()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29)
If you're *really* worried about someone modifying this schema, why not deploy in a .jar file and then [sign](http://java.sun.com/docs/books/tutorial/security/toolfilex/step3.html) the .jar file ? That way you can ensure nobody will tamper with it, and you don't have to rely on third-party infrastructures, storing it remotely etc. | Put it on a public website. | XML Validation in configuration parsing code with XMLSchema: Best Practices? (Java) | [
"",
"java",
"xml",
"validation",
"parsing",
"xsd",
""
] |
I'm strugling to find any decent resources with regards consuming a webservice in an MVC/C# Asp.net App.
Any suggestions? | Rick Strahl has an [awesome writeup](http://www.west-wind.com/presentations/jquery/jQueryPart2.aspx) on using JQuery with ASP.NET MVC to make AJAX callbacks to the server. Amongst other things, he covers:
* Returning and dealing with JSON
* Using JQuery with ASMX and WCF services
* Updating client side screens using services and JQuery templates | <http://asp.net/mvc> is always a good place to start in general. If you have something more specific, post it here on SO :) | Where to go to learn about C# Asp.net with MVC & WebServices | [
"",
"c#",
"asp.net-mvc",
"web-services",
""
] |
what i want to do is having like the java script popup date chooser in my application. i am using java swing and would like to avoid any input mistakes by the user. specifying a format is easy to implement but not user friendly for the user.
what are your suggestion ? any libraries? | Use a date picker, like [JCalendar](http://www.toedter.com/en/jcalendar/index.html) or [JDatePicker](http://www.jdatepicker.org/). Since users can't type raw date strings, you don't have to worry about their mistakes.
Edit: drhorrible is right. I've fixed the link now. | There are a number of date picker libraries for Swing.
I have used the JXDatePicker from [SwingX](http://swinglabs.org/) and [JCalendar](http://www.toedter.com/en/jcalendar/index.html) in the past. | what is the best way to use dates with java swing | [
"",
"java",
"swing",
"date",
""
] |
I have the following API:
```
public interface MyApi {
/**
* Performs some stuff.
* @throws MyException if condition C1
*/
public void method() throws MyException;
}
```
I am now performing the following modification in my API implementation
```
public class MyApiImpl {
public void method() throws MyException {
if (C1) {
throw new MyException("c1 message");
}
...
}
}
```
is replaced by :
```
public class MyApiImpl {
public void method() throws MyException {
if (C1) {
throw new MyException("c1 message");
} else if (c2) {
throw new MyException("c2 message");
}
...
}
}
```
Do you consider this as an API breakage ?
Client's code will still compile but method contract defined by the API javadoc is no more respected since MyExcepiton is thrown by a "new" condition.
If only my API jar file is updated, clients application will still work but depending on the way clients catch the exception the application behavior can change a lot.
What's your point of view on that ? | Yes, you're breaking the contract of the interface by throwing an exception when C1 doesn't occur.
As a rule of thumb, the vaguer the interface contract, the easier it is not to break :) If the interface isn't defined in terms of an explicit C1, but in more general terms, that gives a lot more flexibility. | My point of view is that you should not change the contract defined by the API in the documentation. If you need new behavior you should either a.) create a new method that can be called by the client reflecting this new behavior or b.) discuss with the client the need for the change and make them aware of it.
This really can go both ways, it is between you and your clients as to what your approach will be. | Java API break | [
"",
"java",
"backwards-compatibility",
""
] |
I have a controller in ASP.NET MVC that I've restricted to the admin role:
```
[Authorize(Roles = "Admin")]
public class TestController : Controller
{
...
```
If a user who is not in the Admin role navigates to this controller they are greeted with a blank screen.
What I would like to do is redirect them to View that says "you need to be in the Admin role to be able to access this resource."
One way of doing this that I've thought of is to have a check in each action method on IsUserInRole() and if not in role then return this informational view. However, I'd have to put that in each Action which breaks the DRY principal and is obviously cumbersome to maintain. | Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.
**EDIT**: I have a couple of blog posts that go into more detail:
* <http://farm-fresh-code.blogspot.com/2011/03/revisiting-custom-authorization-in.html>
* <http://farm-fresh-code.blogspot.com/2009/11/customizing-authorization-in-aspnet-mvc.html>
Example:
```
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public class MasterEventAuthorizationAttribute : AuthorizeAttribute
{
/// <summary>
/// The name of the master page or view to use when rendering the view on authorization failure. Default
/// is null, indicating to use the master page of the specified view.
/// </summary>
public virtual string MasterName { get; set; }
/// <summary>
/// The name of the view to render on authorization failure. Default is "Error".
/// </summary>
public virtual string ViewName { get; set; }
public MasterEventAuthorizationAttribute()
: base()
{
this.ViewName = "Error";
}
protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
{
validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
}
public override void OnAuthorization( AuthorizationContext filterContext )
{
if (filterContext == null)
{
throw new ArgumentNullException( "filterContext" );
}
if (AuthorizeCore( filterContext.HttpContext ))
{
SetCachePolicy( filterContext );
}
else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// auth failed, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
}
else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
{
// is authenticated and is in the SuperUser role
SetCachePolicy( filterContext );
}
else
{
ViewDataDictionary viewData = new ViewDataDictionary();
viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
}
}
protected void SetCachePolicy( AuthorizationContext filterContext )
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}
}
``` | You can work with the overridable [`HandleUnauthorizedRequest`](http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.handleunauthorizedrequest.aspx) inside your custom `AuthorizeAttribute`
Like this:
```
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Returns HTTP 401 by default - see HttpUnauthorizedResult.cs.
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "YourActionName" },
{ "controller", "YourControllerName" },
{ "parameterName", "YourParameterValue" }
});
}
```
You can also do something like this:
```
private class RedirectController : Controller
{
public ActionResult RedirectToSomewhere()
{
return RedirectToAction("Action", "Controller");
}
}
```
Now you can use it in your `HandleUnauthorizedRequest` method this way:
```
filterContext.Result = (new RedirectController()).RedirectToSomewhere();
``` | Redirecting unauthorized controller in ASP.NET MVC | [
"",
"c#",
"asp.net-mvc",
"redirect",
"authorization",
""
] |
We've been asked to support some rather old Perl forms on a new site, as we're using a PHP based CMS we need to include the Perl scripts into our new CMS.
I've tried a bit of shell\_exec but that's disabled. Has anyone got any ideas? | ## Perl extension
There is a Perl extension available for PHP.
An article from the Zend developer zone details it [here](http://devzone.zend.com/article/1712).
The extension allows you to:
* load and execute Perl files
* evaluate Perl code
* access Perl variables
* call Perl functions
* instantiate Perl objects
* access properties of Perl objects
* call methods of Perl objects
You can obtain it from CVS using this command:
```
$ cvs -d :pserver:cvs.php.net:/repository co pecl/perl
```
An example of running a Perl script is listed here:
## Example 1 (test1.pl)
```
print "Hello from Perl! "
```
## Example 1 (test1.php)
```
<?php
print "Hello from PHP! ";
$perl = new Perl();
$perl->require("test1.pl");
print "Bye! ";
?>
``` | If you Perl script is creating the page with the forms that you client is supposed to be able to change, then you are out of luck. You might be able to come up with some PHP page that contains the output of the Perl script, but you'll never be able to feed any changes on that page back into the Perl script. | How can I include the output of a Perl script into a PHP page? | [
"",
"php",
"perl",
"forms",
"include",
""
] |
I'd like to generate insert-strings for a row in my Oracle database including all its dependent rows in other tables (and their dependent rows).
Example:
```
CREATE TABLE a (
a_id number PRIMARY KEY,
name varchar2(100)
);
CREATE TABLE b (
b_id number PRIMARY KEY,
a_id number REFERENCES a(a_id)
);
```
When I extract the row from a with a\_id = 1, the result should be an insert-string for that row and dependent rows:
```
INSERT INTO a(a_id, name) VALUES (1, 'foo');
INSERT INTO b(b_id, a_id) VALUES (1, 1);
INSERT INTO b(b_id, a_id) VALUES (2, 1);
INSERT INTO b(b_id, a_id) VALUES (3, 1);
```
The reason why I want to do this is, that I have large database with many different tables and constraints between then and I'd like to extract a small subset of the data as test data. | There may be some tool that does it already, but to arbitrarily extract all rows tables from a starting table is a small development task in itself. I can't write the whole thing for you, but I can get you started - I started to write it, but after about 20 minutes, I realized it was a little more work that I wanted to commit to a unpaid answer.
I can see it being done best by a recursive PL/SQL procedure that would use dbms\_ouput and user\_cons\_columns & user\_constraints to create inserts statement for the source table. You can cheat a little by writing all the inserts as if the columns were char values, since Oracle will implicitly convert any char values to the right datatype, assuming your NLS parameters are identical on the source & target system.
Note, the package below will have problems if you have circular relationships in your tables; also, on earlier versions of Oracle, you may run out of buffer space with dbms\_output. Both problems can be solved by inserting the generated sql into a staging table that has a unique index on the sql, and aborting the recursion if you get a unique key collision. The big time saver below is the MakeParamList function, which converts a cursor that returns a list of columns into either a comma separated list, or a single expression that will display the values of those columns in a quoted, comma separated form when run as the select clause in a query against the table.
Note also that the following package won't really work until you modify it further (one of the reasons I stopped writing it): The initial insert statement generated is based on the assumption that the constraint\_vals argument passed in will result in a single row being generated - of course, this is almost certainly not the case once you start recursing (since you will have many child rows for a parent). You'll need to change the generation of the first statement (and the subsequent recursive calls) to be inside a loop to handle the cases where the call to the first EXECUTE IMMEDIATE call generates multiple rows instead of a single one. The basics of getting it working are here, you just need to grind out the details and get the outer cursor working.
One final note also: It is unlikely that you could run this procedure to generate a set of rows that, when inserted into a target system, would result in a "clean" set of data, since although you would get all dependent data, that data may depend on other tables that you didn't import (e.g., the first child table you encounter may have other foreign keys that point to tables unrelated to your initial table). In that case, you may want to start with the detail tables and work your way up instead of down; doing that, you'd also want to reverse the order to the statements you generated, either using a scripting utility, or by inserting the sql into a staging table as I mention above, with a sequence, then selecting it out with a descending sort.
As for invoking it, you pass the comma separated list of columns to constrain as constraint\_cols and the corresponding comma separated list of values as constraint\_vals, e.g.:
```
exec Data_extractor.MakeInserts ('MYTABLE', 'COL1, COL2', '99, 105')
```
Here it is:
```
CREATE OR REPLACE PACKAGE data_extractor
IS
TYPE column_info IS RECORD(
column_name user_tab_columns.column_name%TYPE
);
TYPE column_info_cursor IS REF CURSOR
RETURN column_info;
FUNCTION makeparamlist(
column_info column_info_cursor
, get_values NUMBER
)
RETURN VARCHAR2;
PROCEDURE makeinserts(
source_table VARCHAR2
, constraint_cols VARCHAR2
, constraint_vals VARCHAR2
);
END data_extractor;
CREATE OR REPLACE PACKAGE BODY data_extractor
AS
FUNCTION makeparamlist(
column_info column_info_cursor
, get_values NUMBER
)
RETURN VARCHAR2
AS
BEGIN
DECLARE
column_name user_tab_columns.column_name%TYPE;
tempsql VARCHAR2(4000);
separator VARCHAR2(20);
BEGIN
IF get_values = 1
THEN
separator := ''''''''' || ';
ELSE
separator := '';
END IF;
LOOP
FETCH column_info
INTO column_name;
EXIT WHEN column_info%NOTFOUND;
tempsql := tempsql || separator || column_name;
IF get_values = 1
THEN
separator := ' || '''''', '''''' || ';
ELSE
separator := ', ';
END IF;
END LOOP;
IF get_values = 1
THEN
tempsql := tempsql || ' || ''''''''';
END IF;
RETURN tempsql;
END;
END;
PROCEDURE makeinserts(
source_table VARCHAR2
, constraint_cols VARCHAR2
, constraint_vals VARCHAR2
)
AS
BEGIN
DECLARE
basesql VARCHAR2(4000);
extractsql VARCHAR2(4000);
tempsql VARCHAR2(4000);
valuelist VARCHAR2(4000);
childconstraint_vals VARCHAR2(4000);
BEGIN
SELECT makeparamlist(CURSOR(SELECT column_name
FROM user_tab_columns
WHERE table_name = source_table), 0)
INTO tempsql
FROM DUAL;
basesql := 'INSERT INTO ' || source_table || '(' || tempsql || ') VALUES (';
SELECT makeparamlist(CURSOR(SELECT column_name
FROM user_tab_columns
WHERE table_name = source_table), 1)
INTO tempsql
FROM DUAL;
extractsql := 'SELECT ' || tempsql || ' FROM ' || source_table
|| ' WHERE (' || constraint_cols || ') = (SELECT '
|| constraint_vals || ' FROM DUAL)';
EXECUTE IMMEDIATE extractsql
INTO valuelist;
-- This prints out the insert statement for the root row
DBMS_OUTPUT.put_line(basesql || valuelist || ');');
-- Now we construct the constraint_vals parameter for subsequent calls:
SELECT makeparamlist(CURSOR( SELECT column_name
FROM user_cons_columns ucc
, user_constraints uc
WHERE uc.table_name = source_table
AND ucc.constraint_name = uc.constraint_name
ORDER BY position)
, 1)
INTO tempsql
FROM DUAL;
extractsql := 'SELECT ' || tempsql || ' FROM ' || source_table
|| ' WHERE ' || constraint_cols || ' = ' || constraint_vals;
EXECUTE IMMEDIATE extractsql
INTO childconstraint_vals;
childconstraint_vals := childconstraint_vals;
-- Now iterate over the dependent tables for this table
-- Cursor on this statement:
-- SELECT uc.table_name child_table, uc.constraint_name fk_name
-- FROM user_constraints uc
-- , user_constraints ucp
-- WHERE ucp.table_name = source_table
-- AND uc.r_constraint_name = ucp.constraint_name;
-- For each table in that statement, find the foreign key
-- columns that correspond to the rows
-- in the parent table
-- SELECT column_name
-- FROM user_cons_columns
-- WHERE constraint_name = fk_name
--ORDER BY POSITION;
-- Pass that columns into makeparamlist above to create
-- the constraint_cols argument of the call below:
-- makeinserts(child_table, ChildConstraint_cols, childconstrain_vals);
END;
END;
END data_extractor;
``` | I just use plain old SQL to do these tasks - use the select statements to generate your inserts:
```
set pagesize 0
set verify off
SELECT 'INSERT INTO a(a_id, name) VALUES ('
|| a_id || ', '
|| '''' || name || ''');'
FROM a
WHERE a_id = &&1;
SELECT 'INSERT INTO b(b_id, a_id) VALUES ('
|| b_id || ', '
|| a_id || ');'
FROM b
WHERE a_id = &&1;
``` | Extracting rows from a DB including depedent rows | [
"",
"sql",
"database",
"oracle",
"testing",
"export",
""
] |
```
<!-- first -->
<script>
var total = 0;
var newAccumulator = function()
{
return function(i) { total += i; };
}
var foldl = function(arr, putNum)
{
for (var i = 0; i < arr.length; ++i)
{
putNum(arr[i]);
}
}
foldl([1, 2, 3, 4], newAccumulator());
document.write("Sum: " + total + "<br/>");
</script>
<!-- second -->
<script>
var total = 0;
var newAccumulator = function(i)
{
total += i;
}
var foldl = function(arr, putNum)
{
for (var i = 0; i < arr.length; ++i)
{
putNum(arr[i]);
}
}
foldl([1, 2, 3, 4], newAccumulator());
document.write("Sum: " + total + "<br/>");
</script>
``` | In the call to `foldl` you call the `newAccumulator` function:
```
foldl([1, 2, 3, 4], newAccumulator());
```
In the first case this returns a function that does the summing up:
```
return function(i) { total += i; };
```
In the second case the call to `newAccumulator` doesn't return anything, so `foldl` doesn't have a function it can call to calculate the sum.
You should pass newAccummulator directly to `foldl`, not the value it (doesn't) return:
```
foldl([1, 2, 3, 4], newAccumulator);
``` | It think you want
```
foldl([1, 2, 3, 4], newAccumulator);
```
In the second call | First sums, second doesn't -> why? | [
"",
"javascript",
""
] |
I have a string that represents a path to a directory. I want split the string if it is a unix type path or a ms-dos type path.
How can this be done?
For example:
```
<?php
$a = some_path1/some_path2/some_path3; // unix type path
$b = some_path1\some_path2\some_path3; // MS-DOS type path
$foo = preg_split("something", $a); // what regex can be used here?
// the above should work with $a OR $b
?>
``` | Your regex would be
```
preg_split('_[\\\\/]_', $a);
```
The backslashes are escaped once for the string and again for the regular expression engine.
Edit:
If you know what type of path you've got (for example you know it's of the type of the current OS) you can do:
```
preg_split('_' . preg_quote($pathSep, '_') . '_', $a)
```
You could use the constant `DIRECTORY_SEPARATOR` in place of `$pathSep` depending on your needs.
This would solve the problem pointed out by @Alan Storm | If you are trying to write portable code (Linux, Windows, Mac OS, etc) and if the separator is always the same as the separator of the server, you can do the following:
```
<?php
$url = 'what/ever/';
$urlExploded = explode(DIRECTORY_SEPARATOR, $url);
?>
```
<http://www.php.net/manual/en/dir.constants.php> | How can I split a string if it is a MS-DOS type path OR Unix type path? | [
"",
"php",
"regex",
"unix",
"split",
"dos",
""
] |
I'm implementing home brew ACL system in web app and it gives me hard time. I believe this is trivial, just can't get my head around it.
I have 3 tables in one to many relationship:
`resource`, `perms_group`, `perms_users`
where `perms_group` is a key table while `perms_users` allowes me to fine tune access per user basis if required (it adds up to `perms_users` or just simply overrides it, both tables store permissions as boolean values in separate columns).
I'm trying to get stuff from resource as well as get permissions in single query:
```
SELECT *
FROM resource
LEFT OUTER JOIN perms_groups ON resource.id = perms_group.res_id
LEFT OUTER JOIN perms_users ON resource.id = perms_users.res_id
WHERE resource.id = 1
AND perms_group.group_id = 2
AND perms_users.user_id = 3
```
Now trouble is that fine permission for user will be set rarely and above query will return 0 rows in such case. What I'm trying to tell is get me back perms for group 2 and for user 3 *if any are set*. Basically I'm missing `AND_IF_EXISTS` operator ;). I could break it in two queries easily but since it will run with every page refresh I need it as lean as possible. Currently I'm using MySQL but would like to switch to PostgreSQL later on so ideal solution would be db independent. Any ideas?
Thanks | ```
SELECT *
FROM resource
LEFT OUTER JOIN perms_groups ON resource.id = perms_group.res_id
AND perms_group.group_id = 2
LEFT OUTER JOIN perms_users ON resource.id = perms_users.res_id
AND perms_users.user_id = 3
WHERE resource.id = 1
```
In fact, left outer join is useless if you write a condition on the table when you don't know if you will have data. | you could try moving the WHERE clause into the join for the users & groups...
```
SELECT *
FROM resource
LEFT OUTER JOIN perms_groups ON resource.id = perms_group.res_id AND perms_group.group_id = 2
LEFT OUTER JOIN perms_users ON resource.id = perms_users.res_id AND perms_users.user_id = 3
WHERE resource.id = 1
``` | Trouble with join query | [
"",
"sql",
"mysql",
"postgresql",
""
] |
Is there a well maintained package available in Python for creating and validating HTML forms? I will deploying it finally on Google Appengine. | You can use [Django form validation](http://code.google.com/appengine/articles/djangoforms.html) on GAE storage via `db.djangoforms.ModelForm`.
To smoothly integrate client-side [Dojo](http://www.dojotoolkit.org/) functionality with Django server-side web apps, I'd look at [dojango](http://code.google.com/p/dojango/), which does work fine with GAE (as well as without). However, dojango (currently at release 0.3.1) does not yet automatically provide client-side validation of Django forms -- that's on the roadmap for the forthcoming release 0.4 of dojango, but I have no idea about the timeframe in which you could expect it. | For client-side validation, check <http://plugins.jquery.com/search/node/form+validate>;
for server-side, actually ALMOST every web framework (web.py, django, etc.) has its own form generation as well as validation lib for you to use. | Package for creating and validating HTML forms in Python? - to be used in Google Appengine | [
"",
"python",
"html",
"google-app-engine",
"forms",
""
] |
I want to know is there any way to split text like this:
123456789 into 123-456-789
as to add "-" after every 3 characters?
Just wanted to know, as I know the reverse, but how to do this is over my head. ;)
and also if the text is
```
ABCDEFGHI OR A1B2C3D4E or any other format
without any space between the characters !
```
language: PHP only | ```
<?php
$i = '123456789';
echo 'result: ', wordwrap($i, 3, '-', true);
```
prints
```
result: 123-456-789
```
see <http://php.net/wordwrap> | I'm not a big fan of regexes for simple string extraction (especially fixed length extractions), preferring them for slightly more complex stuff. Almost every language has a substring function so, presuming your input has already been validated, a simple (pseudo-code since you haven't specified a language):
```
s = substring (s,0,3) + "-" + substring (s,3,3) + "-" + substring (s,6,3)
```
If you want it every three characters for a variable length string (with odd size at the end):
```
t = ""
sep = ""
while s != "":
if s.len <= 3:
t = t + sep + s
s = ""
else:
t = t + sep + substring (s,0,3)
s = substring (s,3)
sep = "-"
s = t
``` | Splitting text in PHP | [
"",
"php",
"regex",
"text",
"split",
""
] |
How to underline (with Bold & italics) a string/text assigned Control.Text property in C# *windows application* programmatically? | You want the Font property.
You can't set the underline of the Font along with the other properties - as they're read only - so you'll need to create a new Font object and assign that to the Font property. There are several constructors that take the bold, italic & underline properties. | Control provides property "Font". You can assign this by using the existing Font as prototype and define the desired style information.
This snippet makes all fonts of all top controls bold, underlined and italic:
```
foreach (Control item in this.Controls)
{
item.Font =
new Font
(
item.Font,
FontStyle.Underline | FontStyle.Bold | FontStyle.Italic
);
}
```
Flo | How to underline a string/text assigned Control.Text property in C# programmatically? | [
"",
"c#",
""
] |
I seem to have the all-familiar problem of correctly reading and viewing a web page. It looks like Python reads the page in UTF-8 but when I try to convert it to something more viewable (iso-8859-1) I get this error:
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 2: ordinal not in range(128)
```
The code looks like this:
```
#!/usr/bin/python
from urllib import urlopen
import re
url_address = 'http://www.eurohockey.net/players/show_player.cgi?serial=4722'
finished = 0
begin_record = 0
col = 0
str = ''
for line in urlopen(url_address):
if '</tr' in line:
begin_record = 0
print str
str = ''
continue
if begin_record == 1:
col = col + 1
tmp_match = re.search('<td>(.+)</td>', line.strip())
str = str + ';' + unicode(tmp_match.group(1), 'iso-8859-1')
if '<tr class=\"even\"' in line or '<tr class=\"odd\"' in line:
begin_record = 1
col = 0
continue
```
How should I handle the contents? Firefox at least thinks it's iso-8859-1 and it would make sense looking at the contents of that page. The error comes from the 'ä' character clearly.
And if I was to save that data to a database, should I not bother with changing the codec and then converting when showing it? | It doesn't look like Python is "reading it in UTF-8" at all. As already pointed out, you have an encoding problem, NOT a decoding problem. It is impossible for that error to have arisen from that line that you say. When asking a question like this, always give the full traceback and error message.
Kathy's suspicion is correct; in fact the `print str` line is the only possible source of that error, and that can only happen when sys.stdout.encoding is not set so Python punts on 'ascii'.
Variables that may affect the outcome are what version of Python you are using, what platform you are running on and exactly how you run your script -- none of which you have told us; please do.
Example: I'm using Python 2.6.2 on Windows XP and I'm running your script with some diagnostic additions:
(1) `import sys; print sys.stdout.encoding` up near the front
(2) `print repr(str)` before `print str` so that I can see what you've got before it crashes.
In a Command Prompt window, if I do `\python26\python hockey.py` it prints `cp850` as the encoding and just works.
However if I do
```
\python26\python hockey.py | more
```
or
```
\python26\python hockey.py >hockey.txt
```
it prints `None` as the encoding and crashes with your error message on the first line with the a-with-diaeresis:
```
C:\junk>\python26\python hockey.py >hockey.txt
Traceback (most recent call last):
File "hockey.py", line 18, in <module>
print str
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 2: ordinal not in range(128)
```
If that fits your case, the fix in general is to explicitly encode your output with an encoding suited to the display mechanism you plan to use. | As noted by Lennart, your problem is not the decoding. It is trying to encode into "ascii", which is often a problem with `print` statements. I suspect the line
```
print str
```
is your problem. You need to encode the str into whatever your console is using to have that line work. | Unicode problems with web pages in Python's urllib | [
"",
"python",
"unicode",
""
] |
I have a code that works only in IE anb I was looking for something similar in FF and Chrome to set user's default homepage through a link 'click here to make this site your default homepage', but so far I didn't find anything.
Does anyone know how to do this? | You can't do it in FF because of security. Check out this [article](http://forums.asp.net/t/1279376.aspx). Your user would have to change the signed.applets.codebase\_principal\_support setting to false. Probably not something that is worth counting on. | What you're asking for is generally considered very annoying page behavior and, therefore, isn't widely supported.
A better UX (User Experience) choice is to give a small set of "how-to" instructions on how the users can make your page their homepage in their respective browsers. Give the user the choice! | How can I set default homepage in FF and Chrome via javascript? | [
"",
"javascript",
"firefox",
"google-chrome",
""
] |
I have a table of data from mysql rendered on page via PHP into a HTML table.
Within this table of data, I have a row of data that should be focussed on (let's call it) row X.
I want the 2 rows above and below row X to be shown but all others hidden, as row X moves up and down, this would change (obviously) what was hidden, when row X is at the top/bottom I want to show 4 rows below/above.
I have done this with static content and JQuery, I am just unsure how to track row X and then apply the class names as required | I thought this was an interesting request so I threw up an [example here.](http://jsbin.com/ahigi/edit) The interesting part is the selectors to select the siblings to display. Here is a function i wrote.
```
function rowXMoved()
{
// hide all rows besides rowX
$('.tableCSS tr:not(.rowX)').hide();
if($('.rowX').prev('tr').size() == 0)
{
// we are row number 1, show 4 more
$('.rowX').siblings('tr:lt(4)').show(); //:lt is less than(index)
}
else if($('.rowX').next('tr').size() == 0)
{
// we are the last row
// find the index of the tableRow to show.
var rowCount = $('.tableCSS tr').size();
$('.rowX').siblings('tr:gt(' + (rowCount - 6) +')').show(); //:gt is greater than(index)
}
else
{
// show 2 rows before and after the rowX
// there is probably a better way, but this is the most straight forward
$('.rowX').prev('tr').show().prev('tr').show();
$('.rowX').next('tr').show().next('tr').show();
}
}
``` | You can show hide the normal way and based on the current row in focus change the innerHtml of the div in focus.
Lets say there are 4 divs holding four rows of data then if focus is on div 2 then it will contain row 2 data in inner html. As focus move or onchange the content in div 2 will keep changing based on which row is in focus. I hope the drift helps | Dynamically hiding a portion of a HTML table | [
"",
"php",
"jquery",
"mysql",
"html-table",
""
] |
I'm sitting down to write a massive switch() statement to turn SQL datatypes into CLR datatypes in order to generate classes from MSSQL stored procedures. I'm using [this chart](http://msdn.microsoft.com/en-us/library/ms131092.aspx) as a reference. Before I get too far into what will probably take all day and be a huge pain to fully test, I'd like to call out to the SO community to see if anyone else has already written or found something in C# to accomplish this seemingly common and assuredly tedious task. | This is the one we use. You may want to tweak it (e.g. nullable/non-nullable types etc.) but it should save you most of the typing.
```
public static Type GetClrType(SqlDbType sqlType)
{
switch (sqlType)
{
case SqlDbType.BigInt:
return typeof(long?);
case SqlDbType.Binary:
case SqlDbType.Image:
case SqlDbType.Timestamp:
case SqlDbType.VarBinary:
return typeof(byte[]);
case SqlDbType.Bit:
return typeof(bool?);
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.VarChar:
case SqlDbType.Xml:
return typeof(string);
case SqlDbType.DateTime:
case SqlDbType.SmallDateTime:
case SqlDbType.Date:
case SqlDbType.Time:
case SqlDbType.DateTime2:
return typeof(DateTime?);
case SqlDbType.Decimal:
case SqlDbType.Money:
case SqlDbType.SmallMoney:
return typeof(decimal?);
case SqlDbType.Float:
return typeof(double?);
case SqlDbType.Int:
return typeof(int?);
case SqlDbType.Real:
return typeof(float?);
case SqlDbType.UniqueIdentifier:
return typeof(Guid?);
case SqlDbType.SmallInt:
return typeof(short?);
case SqlDbType.TinyInt:
return typeof(byte?);
case SqlDbType.Variant:
case SqlDbType.Udt:
return typeof(object);
case SqlDbType.Structured:
return typeof(DataTable);
case SqlDbType.DateTimeOffset:
return typeof(DateTimeOffset?);
default:
throw new ArgumentOutOfRangeException("sqlType");
}
}
``` | ```
/****** Object: Table [dbo].[DbVsCSharpTypes] Script Date: 03/20/2010 03:07:56 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DbVsCSharpTypes]')
AND type in (N'U'))
DROP TABLE [dbo].[DbVsCSharpTypes]
GO
/****** Object: Table [dbo].[DbVsCSharpTypes] Script Date: 03/20/2010 03:07:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DbVsCSharpTypes](
[DbVsCSharpTypesId] [int] IDENTITY(1,1) NOT NULL,
[Sql2008DataType] [varchar](200) NULL,
[CSharpDataType] [varchar](200) NULL,
[CLRDataType] [varchar](200) NULL,
[CLRDataTypeSqlServer] [varchar](2000) NULL,
CONSTRAINT [PK_DbVsCSharpTypes] PRIMARY KEY CLUSTERED
(
[DbVsCSharpTypesId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET NOCOUNT ON;
SET XACT_ABORT ON;
GO
SET IDENTITY_INSERT [dbo].[DbVsCSharpTypes] ON;
BEGIN TRANSACTION;
INSERT INTO [dbo].[DbVsCSharpTypes]([DbVsCSharpTypesId], [Sql2008DataType], [CSharpDataType], [CLRDataType], [CLRDataTypeSqlServer])
SELECT 1, N'bigint', N'long', N'Int64, Nullable<Int64>', N'SqlInt64' UNION ALL
SELECT 2, N'binary', N'byte[]', N'Byte[]', N'SqlBytes, SqlBinary' UNION ALL
SELECT 3, N'bit', N'bool', N'Boolean, Nullable<Boolean>', N'SqlBoolean' UNION ALL
SELECT 4, N'char', N'char', NULL, NULL UNION ALL
SELECT 5, N'cursor', NULL, NULL, NULL UNION ALL
SELECT 6, N'date', N'DateTime', N'DateTime, Nullable<DateTime>', N'SqlDateTime' UNION ALL
SELECT 7, N'datetime', N'DateTime', N'DateTime, Nullable<DateTime>', N'SqlDateTime' UNION ALL
SELECT 8, N'datetime2', N'DateTime', N'DateTime, Nullable<DateTime>', N'SqlDateTime' UNION ALL
SELECT 9, N'DATETIMEOFFSET', N'DateTimeOffset', N'DateTimeOffset', N'DateTimeOffset, Nullable<DateTimeOffset>' UNION ALL
SELECT 10, N'decimal', N'decimal', N'Decimal, Nullable<Decimal>', N'SqlDecimal' UNION ALL
SELECT 11, N'float', N'double', N'Double, Nullable<Double>', N'SqlDouble' UNION ALL
SELECT 12, N'geography', NULL, NULL, N'SqlGeography is defined in Microsoft.SqlServer.Types.dll, which is installed with SQL Server and can be downloaded from the SQL Server 2008 feature pack.' UNION ALL
SELECT 13, N'geometry', NULL, NULL, N'SqlGeometry is defined in Microsoft.SqlServer.Types.dll, which is installed with SQL Server and can be downloaded from the SQL Server 2008 feature pack.' UNION ALL
SELECT 14, N'hierarchyid', NULL, NULL, N'SqlHierarchyId is defined in Microsoft.SqlServer.Types.dll, which is installed with SQL Server and can be downloaded from the SQL Server 2008 feature pack.' UNION ALL
SELECT 15, N'image', NULL, NULL, NULL UNION ALL
SELECT 16, N'int', N'int', N'Int32, Nullable<Int32>', N'SqlInt32' UNION ALL
SELECT 17, N'money', N'decimal', N'Decimal, Nullable<Decimal>', N'SqlMoney' UNION ALL
SELECT 18, N'nchar', N'string', N'String, Char[]', N'SqlChars, SqlString' UNION ALL
SELECT 19, N'ntext', NULL, NULL, NULL UNION ALL
SELECT 20, N'numeric', N'decimal', N'Decimal, Nullable<Decimal>', N'SqlDecimal' UNION ALL
SELECT 21, N'nvarchar', N'string', N'String, Char[]', N'SqlChars, SqlStrinG SQLChars is a better match for data transfer and access, and SQLString is a better match for performing String operations.' UNION ALL
SELECT 22, N'nvarchar(1), nchar(1)', N'string', N'Char, String, Char[], Nullable<char>', N'SqlChars, SqlString' UNION ALL
SELECT 23, N'real', N'single', N'Single, Nullable<Single>', N'SqlSingle' UNION ALL
SELECT 24, N'rowversion', N'byte[]', N'Byte[]', NULL UNION ALL
SELECT 25, N'smallint', N'smallint', N'Int16, Nullable<Int16>', N'SqlInt16' UNION ALL
SELECT 26, N'smallmoney', N'decimal', N'Decimal, Nullable<Decimal>', N'SqlMoney' UNION ALL
SELECT 27, N'sql_variant', N'object', N'Object', NULL UNION ALL
SELECT 28, N'table', NULL, NULL, NULL UNION ALL
SELECT 29, N'text', N'string', NULL, NULL UNION ALL
SELECT 30, N'time', N'TimeSpan', N'TimeSpan, Nullable<TimeSpan>', N'TimeSpan' UNION ALL
SELECT 31, N'timestamp', NULL, NULL, NULL UNION ALL
SELECT 32, N'tinyint', N'byte', N'Byte, Nullable<Byte>', N'SqlByte' UNION ALL
SELECT 33, N'uniqueidentifier', N'Guid', N'Guid, Nullable<Guid>', N'SqlGuidUser-defined type(UDT)The same class that is bound to the user-defined type in the same assembly or a dependent assembly.' UNION ALL
SELECT 34, N'varbinary ', N'byte[]', N'Byte[]', N'SqlBytes, SqlBinary' UNION ALL
SELECT 35, N'varbinary(1), binary(1)', N'byte', N'byte, Byte[], Nullable<byte>', N'SqlBytes, SqlBinary' UNION ALL
SELECT 36, N'varchar', NULL, NULL, NULL UNION ALL
SELECT 37, N'xml', NULL, NULL, N'SqlXml'
COMMIT;
RAISERROR (N'[dbo].[DbVsCSharpTypes]: Insert Batch: 1.....Done!', 10, 1) WITH NOWAIT;
GO
SET IDENTITY_INSERT [dbo].[DbVsCSharpTypes] OFF;
``` | Anybody got a C# function that maps the SQL datatype of a column to its CLR equivalent? | [
"",
"c#",
"types",
""
] |
I'm planning on using Apache torque as my object-relational mapper (ORM), and I was wondering if anybody has any suggestions around what framework to use for presentation layer with torque. maybe Spring?
I don't know if this helps, but my application is basically going to be bunch of forms to input data and based on that data, I'll generate reports in form of a graph or chart. | If your application is web-based then CSS/XHTML/JQuery & Spring MVC has always worked out great for me, otherwise, if it's thick-client, Swing.
Incidentally, if you get you 'separation-of-concerns' right your choice of ORM should have no impact what presentation layer you use.
I'd also advise using Hibernate rather than Torque, it is, from my perspective at least, practically a defacto standard nowadays, which translates into many more production hours and a lot of people to help when you run into issues. | [Turbine](http://turbine.apache.org/) is a servlet framework that integrates with Torque (Torque was originally part of Turbine). It can use either Velocity or JSP as its presentation layer. | presentation layer to go with apache torque | [
"",
"java",
"spring",
"frameworks",
"apache-torque",
""
] |
We have a current (legacy) PHP based website that is unlikely to be redeveloped for the next year or so, that acts as our main portal.
We would like to develop new applications in ASP.Net, and plug them into the current portal - but we do not want our website users to have to log in twice.
Whats the best way to share authentication state between the two platforms? They do not share the same server, database backend or even proxy. | Read this article from Microsoft on sharing session state between classic ASP and ASP.NET:
<http://msdn.microsoft.com/en-us/library/aa479313.aspx>
Conceptually, I think this is pretty similar to what you're trying to do, though I don't know just how helpful the above document will be to your specific case. Definitely worth a look though. | I needed to this a while back for a fairly large project. The languages were ASP.Net and ASP, but the method I ended up with would work just as well if it were PHP instead of ASP.
Can you abstract out the places your PHP application **modifies** session variables?
I found that even for large web applications, there were only a handful of places session variables were updated. For instance; *Login*, *Logout*, some sought of *change group action*, etc. For me, there were less than 6 scripts that needed to be modified.
For each script that modify session variables, add a server redirect to a new ASP.Net script. Hence the PHP script would do all it had to do and the final thing would be a PHP redirect ( mabye PHP *Header("Location:...")* call at the end.
Your receiving ASP.Net script updates the ASP.Net session variables in the same manner the PHP script update its session. Luckily in my case the original scripts did not output any data, but rather redirected to "success" pages.
i.e. The original scripts were the *Controller* code in a MVC design, and they redirected to the *View* code. This allowed me to neatly insert my ASP.Net scripts between the ASP controller and the view scripts. If your receiving script outputs data, then you will have to split that up into 2 pages.
That's it. In effect, doing this for Login, Logout, and a few pages effectively caused the two session scopes to stay in sync. | Passing sessions or authentication state between PHP and ASP.Net | [
"",
"php",
"asp.net",
"session-state",
""
] |
It's pretty easy to use a library in VC++ 2008 if you create a project for it and build it alongside the other projects in your solution, but what if the library has too complex of a build process and must be compiled separately via makefile?
My library is like that, and while I've had no problem compiling it on the command line, I have no clue what to do with the resulting header files and .lib file. I've put them all in one directory and added its path to my main project's Additional Include Directories, so it finds the header files just fine. I've also added the relevant info to Additional Library Directories and Additional Dependencies.
Perhaps there's another setting I'm forgetting to set besides these three? I'd appreciate all the help I can get. Thanks.
**EDIT** Here are the syntax errors I'm getting:
<http://pastebin.com/m72ece684> | Okay, based on those errors, it has nothing to do with finding your .lib files, it's choking on the header files.
Edit:
It looks like somewhere in windows.h, there is a macro definition for X942\_DH\_PARAMETERS which is breaking your dl\_group.h.
Instead of putting your botan headers at top, but windows.h at top, and then right before you #include the botan headers add this line:
```
#undef X942_DH_PARAMETERS
```
Or as I just discovered, that macro is defined in wincrypt.h, and if you add NOCRYPT to your preprocessor definitions it won't include that file. Since you're using a third party crypto library you probably don't need wincrypt. | While I can't exactly say what your problem is I can offer some advice as to how to find a solution. I suggest creating a simple library that contains a single method and a single class, build it, and then try to successfully link it to your project. Once you get that done on a smaller scale, try repeating the steps with your original library. | How to add prebuilt library to a VC++ solution? | [
"",
"c++",
"visual-studio-2008",
"visual-c++",
""
] |
Is there a way, in code, to determine what "Solutions Configuration" you are running in? For example, 'Debug' vs. 'Release?
I have a service that I like to test in the IDE in Debug, right now I have bool that I set which either runs the 'service' if set to true (which then uses the OnStart method to run my 'main' method), if it's set to false I just run the 'main' method. This works great but I often forget to reset the bool after testing and then when I go to install the service it fails and I have to go back, reset the bool, recompile etc.
If I could just determine programatically that I was running in the IDE in Debug then I could get around this issue.
*Edit:*
While thinking this through, I guess what I really need in the end is to determine if I'm in the 'playing' the app in the ide and not the soulutions configuration. This would allow me to compile in either debug or other configuration.
The simpliest solution seems to check 'System.Diagnostics.Debugger.IsAttached' | To determine whether you are running under debug in the IDE, look at the `Debugger` class, specifically the `IsAttached` property... | You can't directly look at the solution configuration, but you can use a few clues to "guess" what version you are in. For instance, the DEBUG preprocessor macro will only be defined in the Debug solution configuration for C#.
```
bool InDebugConfiguration() {
#if DEBUG
return true;
#else
return false;
#endif
}
``` | Determine Solutions Configuration (Visual Studio) | [
"",
"c#",
"visual-studio",
"debugging",
"configuration",
"service",
""
] |
I'm working on a .NET 3.5 Web Application and I was wondering what would be good way to persist user specific settings (i.e. user preferences) server-side?
Here are the conditions:
* It needs to be able to store/retrieve
settings based on a User ID
* I don't want to use SQL Server or any such DB engine
* I don't want to store it in cookies
Any guidance would be greatly appreciated.
**Edit**: If it makes any difference, it doesn't have to support a web farm. | Use the ASP.NET Profile feature for this. See [ASP.NET Profile Properties Overview](http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx) | If you want to persist data, and you don't want to use a database, then you need to save the data to disk (such as XML). If you're looking for something that isn't local to your server, you could use a SaaS solution that would host your data for you, such as [Amazon's S3 service](http://aws.amazon.com/s3/). If you do that, the latency of data retrieval will slow your application down, so you'll want to cache the data. | Persisting User Specific Settings in ASP.NET Server-Side | [
"",
"c#",
"asp.net",
"persistence",
""
] |
I want to transfer data from a vertical db layout like this:
```
---------------------
| ID | Type | Value |
---------------------
| 1 | 10 | 111 |
---------------------
| 1 | 14 | 222 |
---------------------
| 2 | 10 | 333 |
---------------------
| 2 | 25 | 444 |
---------------------
```
to a horizontal one:
```
---------------------------------
| ID | Type10 | Type14 | Type25 |
---------------------------------
| 1 | 111 | 222 | |
---------------------------------
| 2 | 333 | | 444 |
---------------------------------
```
Creating the layout is not a problem but the database is rather large with millions of entries and queries get canceled if they take to much time.
How can this be done efficiently (so that the query is not canceled). | ```
with t as
(
select 1 as ID, 10 as type, 111 as Value from dual
union
select 1, 14, 222 from dual
union
select 2, 10, 333 from dual
union
select 2, 25, 444 from dual
)
select ID,
max(case when type = 10 then Value else null end) as Type10,
max(case when type = 14 then Value else null end) as Type14,
max(case when type = 25 then Value else null end) as Type25
from t
group by id
```
Returns what you want, and I think it is the better way.
Note that the max function is just here to perform the group by clause, any group function can be use here (like sum, min...) | Break it up into smaller chunks and don't wrap the whole thing in a single transaction. First, create the table, and then do groups of inserts from the old table into the new table. Insert by range of ID, for example, in small enough chunks that it won't overwhelm the database's log and take too long. | How can I efficiently transfer data from a vertical databaselayout to a horizontal one | [
"",
"sql",
"db2",
"bulkinsert",
"transfer",
""
] |
When I press f12 on the ArrayList keyword to go to metadata generated from vs2008, I found that the generated class declaration as follows
```
public class ArrayList : IList, ICollection, IEnumerable, ICloneable
```
I know that the IList already inherits from ICollection and IEnumerable, so why does ArrayList redundantly inherit from these interfaces? | OK, I've done some research. If you create the following hierarchy:
```
public interface One
{
void DoIt();
}
public interface Two : One
{
void DoItMore();
}
public class Magic : Two
{
public void DoItMore()
{
throw new NotImplementedException();
}
public void DoIt()
{
throw new NotImplementedException();
}
}
```
And compile it, then reference the DLL in a different solution, type Magic and Press F12, you will get the following:
```
public class Magic : Two, One
{
public Magic();
public void DoIt();
public void DoItMore();
}
```
You will see that the interface hierarchy is flattened, or the compiler is adding the interfaces in? If you use reflector you get the same results too.
Update: If you open the DLL in ILDASM, you will see it saying:
implements ...Two
implements ...One. | The extra interfaces are shown because they are implied by IList. If you implement IList, you must also implement ICollection and IEnumerable. | Why collections classes in C# (like ArrayList) inherit from multiple interfaces if one of these interfaces inherits from the remaining? | [
"",
"c#",
"inheritance",
"interface",
"arraylist",
""
] |
Consider the following situation
file: ./include/functions/table-config.php
containing: ```` ```
.
.
$tablePages = 'orweb_pages';
.
.
``` ````
file: ./include/classes/uri-resolve.php
containing: ```` ```
class URIResolve {
.
.
$category = null ;
.
.
function process_uri() {
...
$this->category = $tablePages;
...
}
.
.
}
``` ````
file: ./settings.php
containing: ```` ```
.
.
require_once(ABSPATH.INC.FUNC.'/table-config.php');
require_once(ABSPATH.INC.CLASS.'/uri-resolve.php');
.
.
``` ````
Will this work. I mean will the access to $tablePages from process\_uri() be acceptable or will it give erronous results.
Please suggest corrections or workarounds if error might occur. | Use a global (not recommended), a constant or a singleton configuration class.
Simply including
```
$tablePages = 'orweb_pages';
```
will give your variable local scope so it won't be visible inside other classes. If you use a constant:
```
define('TABLE_PAGES', 'orweb_pages');
```
TABLE\_PAGES will be available for read access throughout the application regardless of scope.
The advantage of a constant over a global variable is that you dont have to worry about it being overridden in other areas of the application. | Use the [global keyword](http://se.php.net/manual/en/language.variables.scope.php):
In the file where you're assigning the value.
```
global $tablePages;
$tablePages = 'orweb_pages';
```
And in the other file:
```
class URIResolve {
var $category;
function process_uri() {
global $tablePages;
$this->category = $tablePages;
}
}
```
Also, all global variables are available in the `$GLOBALS` array (which itself is a superglobal), so you can access the global variable anywhere without using the global keyword by doing something like this:
```
$my_value = $GLOBALS['tablePages'];
```
This also serves to make it harder to accidentally overwrite the value of the global. In the former example, any changes you made to `$tablePages` would change the global variable. Many a security bug has been created by having a global `$user` and overwriting it with a more powerful user's information.
Another, even safer approach is to provide the variable in the constructor to URIResolve:
```
class URIResolve {
var $category;
function __construct ($tablePages) {
$this->category= $tablePages;
}
function process_uri() {
// Now you can access table pages here as an variable instance
}
}
// This would then be used as:
new URIResolve($tablePages);
``` | Outer Variable Access in PHP Class | [
"",
"php",
"oop",
"class",
"global-variables",
"data-access",
""
] |
Hey people would love to hear about any resources you have or know about for nServiceBus, Rhino Service Bus and MassTransit.
* Videos?
* Blog posts?
* Books?
* Demo Projects etc | The [discussion group](https://groups.google.com/forum/#!forum/particularsoftware) at Google Groups is a very good resource.
So far I have written three articles about nServiceBus at [ArtOfBabel.com](http://ArtOfBabel.com):
* [Open Source Integration with nServiceBus](http://artofbabel.com/specials/55-open-source-integration-with-nservicebus.html)
* [Up and Running with nServiceBus 1.9](http://artofbabel.com/specials/70-up-and-running-with-nservicebus-19.html)
* [nServiceBus: Building the Solution](http://artofbabel.com/specials/72-nservicebusbuildingthesolution.html)
A few more articles should be available soon too. | If you are interested in masstransit you can have a look at:
[Getting Started and Documentation](http://docs.masstransit-project.com/en/latest/index.html)
[Elegant code Podcast](http://elegantcode.com/2009/03/18/code-cast-25-masstransit/)
if you are using [structure map](http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2009/08/26/producing-and-consuming-messages-using-masstransit-and-structuremap.aspx)
[Dru Sellers Blog](http://codebetter.com/drusellers/)
[Chris Patterson Blog](http://blog.phatboyg.com/)
[Their Google Groups](http://groups.google.com/group/masstransit-discuss/)
at some point you'll get to
<http://codebetter.com/blogs/dru.sellers/archive/2009/01/11/topshelf.aspx>
Hope it helps | nServiceBus, Rhino Service Bus, MassTransit - Videos, Demos, Learning Resources | [
"",
"c#",
"nservicebus",
"rhino",
"servicebus",
"masstransit",
""
] |
I've been working on this small piece of code that seems trivial but still, i cannot really see where is the problem. My functions do a pretty simple thing. Opens a file, copy its contents, replace a string inside and copy it back to the original file (a simple search and replace inside a text file then).
I didn't really know how to do that as I'm adding lines to the original file, so I just create a copy of the file, (file.temp) copy also a backup (file.temp) then delete the original file(file) and copy the file.temp to file.
I get an exception while doing the delete of the file.
Here is the sample code:
```
private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
Boolean result = false;
FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
StreamReader streamreader = file.OpenText();
String originalPath = file.FullName;
string input = streamreader.ReadToEnd();
Console.WriteLine("input : {0}", input);
String tempString = input.Replace(extractedMethod, modifiedMethod);
Console.WriteLine("replaced String {0}", tempString);
try
{
sw.Write(tempString);
sw.Flush();
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
streamreader.Close();
streamreader.Dispose();
File.Copy(originalPath, originalPath + ".old", true);
FileInfo newFile = new FileInfo(originalPath + ".tmp");
File.Delete(originalPath);
File.Copy(fs., originalPath, true);
result = true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;
}`
```
And the related exception
```
System.IO.IOException: The process cannot access the file 'E:\mypath\myFile.cs' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.Delete(String path)
at callingMethod.modifyFile(FileInfo file, String extractedMethod, String modifiedMethod)
```
Normally these errors come from unclosed file streams, but I've taken care of that. I guess I've forgotten an important step but cannot figure out where.
Thank you very much for your help, | Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place?
```
private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
try
{
string contents = File.ReadAllText(file.FullName);
Console.WriteLine("input : {0}", contents);
contents = contents.Replace(extractedMethod, modifiedMethod);
Console.WriteLine("replaced String {0}", contents);
File.WriteAllText(file.FullName, contents);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
``` | I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used `XMLWriter` to subsequently update XML file and was receiving the same errors. I found the clean solution for this:
The `XMLWriter` uses underlying `FileStream` to access the modified file. Problem is that when you call `XMLWriter.Close()` method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your `XMLWriter` with settings and specify that you need that underlying stream closed.
Example:
```
XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);
```
Hope it helps. | System.IO.IOException: file used by another process | [
"",
"c#",
"file-io",
"io",
"ioexception",
""
] |
I've recently found myself needing (yes, needing) to define absurdly long `switch` statements and `enum` declarations in C# code, but I'm wondering what people feel is the best way to split them into logical subsections. In my situation, both the enum values and the cases (which are based on the enum values) have fairly clear groupings, yet I am slightly unsure how to reflect this in code.
Note that in my code, I have roughly 5 groups of between 10 and 30 enum values/cases each.
The three vaguely sensible options I can envisage are:
1. Define `#region` blocks around all logical groups of cases/enum values within the declaration (optionally separated by blank lines).
2. Comment each group with it's name, with a blank line before each group name comment.
3. Do nothing whatsoever - simply leave the switch/enum as a huge list of cases/values.
*Which do you prefer? Would you treat enums and switches separately?* (This would seem slightly odd to me.) Now, I wouldn't say that there is any right/wrong answer to this question, though I would nonetheless be quite interested in hearing what the general consenus of views is.
**Note 1:** This situation where I might potentially have an extremely long enum declaration of 50/100+ values is unfortunately unavoidable (and similarly with the switch), since I am attempting to write a lexer (tokeniser), and this would thus seem the most reasonable approach for several reasons.
**Note 2:** I am fully aware that several duplicate questions already exist on the question of whether to use regions in general code (for structuring classes, mainly), but I feel my question here is much more specific and hasn't yet been addressed. | Sure, region those things up. They probably don't change much, and when they do, you can expand the region, make your changes, collapse it, and move on to the rest of the file.
They are there for a reason, use them to your advantage. | You could also have a Dictionary<[your\_enum\_type], Action> (or Func instead of Action) or something like that (considering your functions have a similar signature). Then you could instead of using a switch, instead of:
```
switch (item)
{
case Enum1: func1(par1, par2)
break;
case Enum2: func2(par1, par2)
break;
}
```
you could have something like:
```
public class MyClass
{
Dictionary<int, Action<int, int>> myDictionary;
//These could have only static methods also
Group1Object myObject1;
Group2Object myObject2;
public MyClass()
{
//Again, you wouldn't have to initialize if the functions in them were static
myObject1 = new Group1Object();
myObject2 = new Group2Object();
BuildMyDictionary();
}
private Dictionary<int, Action<int, int>> BuildMyDictionary()
{
InsertGroup1Functions();
InsertGroup2Functions();
//...
}
private void InsertGroup2Functions()
{
myDictionary.Add(1, group2.AnAction2);
myDictionary.Add(2, group2.AnotherAction2);
}
private void InsertGroup1Functions()
{
myDictionary.Add(3, group1.AnAction1);
myDictionary.Add(4, group1.AnotherAction1);
}
public void DoStuff()
{
int t = 3; //Get it from wherever
//instead of switch
myDictionary[t](arg1, arg2);
}
}
``` | Would you use regions within long switch/enum declarations? | [
"",
"c#",
"enums",
"switch-statement",
"regions",
""
] |
Here is my XAML
```
<Grid
Name="grid">
<TextBlock
Text="Some Label" />
<WindowsFormsHost
Name="winFormsHost">
</WindowsFormsHost>
</Grid>
```
On the load of the form I execute the following method
```
protected void OnLoad(object sender, RoutedEventArgs e)
{
// Create a line on the fly
Line line = new Line();
line.Stroke = Brushes.Red;
line.StrokeThickness = 17;
line.X1 = 50;
line.Y1 = 50;
line.X2 = 250;
line.Y2 = 50;
this.grid.Children.Add(line);
System.Windows.Forms.TextBox oldSchoolTextbox = new System.Windows.Forms.TextBox();
oldSchoolTextbox.Text = "A bunch of Random Text will follow. ";
oldSchoolTextbox.WordWrap = true;
oldSchoolTextbox.Width = 300;
for (int i = 0; i < 250; i++)
{
oldSchoolTextbox.Text += "abc ";
if (i % 10 == 0)
{
oldSchoolTextbox.Text += Environment.NewLine;
}
}
this.winFormsHost.Child = oldSchoolTextbox;
}
```
The line only draws when I comment out the following line.
```
this.winFormsHost.Child = oldSchoolTextbox;
```
How do I draw a line over the WindowsFormsHost control? | There is something Microsoft has called "airspace" that prevents this from happening, at least easily. Here is the [WPF Interop page describing airspace](http://msdn.microsoft.com/en-us/library/aa970688.aspx). [It has a DX focus, but the same thing applies, exactly as stated, to WindowsFormsHost.]
WindowsFormsHost (when it has a child) creates a separate HWND, which prevents the WPF rendering context from displaying in that rectangle.
The best option for working around this requires .NET 3.5sp1 (at least to work reliably). You can get around this by creating an entirely separate, 100% transparent background window, and placing it over your windows forms host control. You then draw into that, and it will display correctly.
It's somewhat hacky feeling, but it works. | I've had the same problem, and after searching all over also ended up using the transparent 'overlay' window on top of the WindowsFormsHost. To keep your main window synchronized with the overlay window you need to handle the following events:
LocationChanged event for your MainWindow
and
LayoutUpdated event for your WindowsFormsHost element. Both these event handlers should call a function that moves your transparent overlay window on top of the WindowsFormsHost window (SyncOverlayPosition() in the example below).
```
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.LocationChanged += new EventHandler(MainWindow_LocationChanged);
_windowsFormsHost.LayoutUpdated += new EventHandler(_windowsFormsHost_LayoutUpdated);
}
void MainWindow_LocationChanged(object sender, EventArgs e)
{
SyncOverlayPosition();
}
void _windowsFormsHost_LayoutUpdated(object sender, EventArgs e)
{
SyncOverlayPosition();
}
void SyncOverlayPosition()
{
Point hostTopLeft = _windowsFormsHost.PointToScreen(new Point(0, 0));
_overlayWindow.Left = hostTopLeft.X;
_overlayWindow.Top = hostTopLeft.Y;
_overlayWindow.Width = _windowsFormsHost.ActualWidth;
_overlayWindow.Height = _windowsFormsHost.ActualHeight;
}
``` | In WPF how can you draw a line over a WindowsFormsHost? | [
"",
"c#",
".net",
"wpf",
"drawing",
"windowsformshost",
""
] |
I'm working in a Java project where the axis 2 library from Apache is being used. The axis 2 library is composed of about 20 jar files and some of these are not used project. What I want to know if there is a method to identify which of those jar files are the unused ones.
I'm using the Eclipse IDE an I thought that one way to solve the problem is to add one jar at time until the I get no error messages about the missing classes. However, I'm not sure if this will work as some of the missing classes errors show up only at runtime.
Does anyone know a better way to solve this problem? | tattletale FTW
<http://www.jboss.org/tattletale>
JBoss Tattletale is a tool that can help you get an overview of the project you are working on or a product that you depend on.
The tool will provide you with reports that can help you
* Identify dependencies between JAR files
* Spot if a class is located in multiple JAR files
* Spot if the same JAR file is located in multiple locations
* With a list of what each JAR file requires and provides | I would follow your original idea of adding one jar at time until it compiles.
You're right that you can still find run-time errors, but unless the application is too big for a good coverage with manual tests, I would simply run and test it to add any missing jars. | How can I identify unnecessary jars included in my project? | [
"",
"java",
"jar",
""
] |
I am getting the value of amount like 4567.00 , 8976.00 etc. Now while dispalying this value in displaytag i would like to print it as $4567.00 instead of just 4567.00. How can i do that?
Provided i just want to use display tag. I can acheive the same thing using core:out tag.
```
$<core:out value="${variableInMyList}" />
```
---
***Answer Found [ How i did it ]***
Create a new class:
```
public class NumberFormatDecorator implements DisplaytagColumnDecorator{
Logger logger = MyLogger.getInstance ( );
public Object decorate(Object columnValue, PageContext pageContext, MediaTypeEnum media) throws DecoratorException {
try
{
Object colVal = columnValue;
if ( columnValue != null ){
colVal = Double.parseDouble( (String)columnValue );
}
return colVal;
}catch ( Exception nfe ){}
logger.error( "Unable to convert to Numeric Format");
return columnValue; // even if there is some exception return the original value
}
}
```
now in display tag
```
<displaytag:column title="Amount" property="amount" decorator="com.rj.blah.utils.decorator.NumberFormatDecorator" format="$ {0,number,0,000.00}"/>
```
**Note:** we can use the MessageFormat in format attribute of displaytag:column | DisplayTab is not very JSTL or EL friendly, and doesn't support that style of formatting. Instead, you need to extend the TableDecorator class and put a reference to it using the decorator attribute of the display:table tag.
Your decorator subclass should define a getter method for your formatted currency column, something like:
```
public class MyTableDecorator extends TableDecorator {
public String getCurrency() {
MyRowType row = getCurrentRowObject();
return row.getCurrency.format();
}
}
```
and
```
<display:table name="myList" decorator="test.MyTableDecorator">
<display:column property="myProperty" title="My Property"/>
<display:column property="currency" title="Currency"/>
</display:table>
```
Alternatively, you can implement the DisplaytagColumnDecorator interface, and reference that decorator from the JSP:
```
<display:table name="myList">
<display:column property="myProperty" title="My Property"/>
<display:column property="currency" title="Currency" decorator="test.MyColumnDecorator"/>
</display:table>
```
See [the documentation](http://displaytag.sourceforge.net/1.2/tut_decorators.html) for more information | What do you need your class for?
You could write it as follows:
```
<displaytag:column property="amount" format="$ {0,number,0,000.00}"/>
``` | how to format currency in displaytag | [
"",
"java",
"displaytag",
"number-formatting",
""
] |
How would I get the number of fields/entries in a database using an SQL Statement? | mmm all the fields in all the tables? assuming standards (mssql, mysql, postgres) you can issue a query over information\_schema.columns
```
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
```
Or grouped by table:
```
SELECT TABLE_NAME, COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_NAME
```
If multiple schemas has the same table name in the same DB, you MUST include schema name as well (i.e: dbo.Books, user.Books, company.Books etc.) Otherwise you'll get the wrong results. So the best practice is:
```
SELECT TABLE_SCHEMA, TABLE_NAME, COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_SCHEMA, TABLE_NAME
``` | try this, this will exclude views, leave the where clause out if you want views
```
select count(*) from information_schema.columns c
join information_schema.tables t on c.table_name = t.table_name
and t.table_type = 'BASE TABLE'
``` | Getting number of fields in a database with an SQL Statement? | [
"",
"sql",
"database",
"get",
"field",
""
] |
I have a byte array that contains 6 bytes last 2 represents the port number while searching for a way two convert these last to bytes to a port number i have come across this snippet,
```
int port = 0;
port |= peerList[i+4] & 0xFF;
port <<= 8;
port |= peerList[i+5] & 0xFF;
```
it works but i need some clarification as to how it works? | > ```
> =======================
> | byte 5 | byte 6 |
> |----------|----------|
> | 01010101 | 01010101 |
> =======================
> ```
Basically, it takes byte #5, shift is 8 bits to the left resulting in `0101010100000000` and then uses the bitwise or operator to put the byte 6 in the place of zeros. | ```
int port = 0; // Start with zero
port |= peerList[i+4] & 0xFF; // Assign first byte to port using bitwise or.
port <<= 8; // Shift the bits left by 8 (so the byte from before is on the correct position)
port |= peerList[i+5] & 0xFF; // Assign the second, LSB, byte to port.
``` | Snippet Clarification byte array to port number | [
"",
"java",
"arrays",
"byte",
""
] |
I'm changing some classes of mine from an extensive use of getters and setters to a more pythonic use of properties.
But now I'm stuck because some of my previous getters or setters would call the corresponding method of the base class, and then perform something else. But how can this be accomplished with properties? How to call the property getter or setter in the parent class?
Of course just calling the attribute itself gives infinite recursion.
```
class Foo(object):
@property
def bar(self):
return 5
@bar.setter
def bar(self, a):
print a
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return self.bar # --> recursion!
@bar.setter
def bar(self, c):
# perform the same action
# as in the base class
self.bar = c # --> recursion!
# then do something else
print 'something else'
fb = FooBar()
fb.bar = 7
``` | You might think you could call the base class function which is called by property:
```
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return Foo.bar(self)
```
Though this is the most obvious thing to try I think - **it does not work because bar is a property, not a callable.**
But a property is just an object, with a getter method to find the corresponding attribute:
```
class FooBar(Foo):
@property
def bar(self):
# return the same value
# as in the base class
return Foo.bar.fget(self)
``` | [`super()`](http://docs.python.org/3.0/library/functions.html?highlight=super#super) should do the trick:
```
return super().bar
```
In Python 2.x you need to use the more verbose syntax:
```
return super(FooBar, self).bar
``` | How to call a property of the base class if this property is being overwritten in the derived class? | [
"",
"python",
"inheritance",
"properties",
"overloading",
"descriptor",
""
] |
I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.
So what is the most secure way to encrypt/decrypt something using python? | If your script can decode the passwords, so can someone breaking in to your server. Encryption is only really useful when someone enters a password to unlock it - if it remains unlocked (or the script has the password to unlock it), the encryption is pointless
This is why hashing is more useful, since it is a one way process - even if someone knows your password hash, they don't know the plain-text they must enter to generate it (without lots of brute-force)
I wouldn't worry about keeping the game passwords as plain-text. If you are concerned about securing them, fix up possibly SQL injections/etc, make sure your web-server and other software is up to date and configured correctly and so on.
Perhaps think of a way to make it less appealing to steal the passwords than actually play the game? For example, there was a game (I don't recall what it was) which if you used the level skip cheat, you went to the next level but it didn't mark it as "complete", or you could skip the level but didn't get any points. Or look at Project Euler, you can do any level, but you only get points if you enter the answer (and working out the answer is the whole point of the game, so cheating defeats the playing of the game)
If you are really paranoid, you could *possibly* use asymmetric crypto, where you basically encrypt something with `key A`, and you can only read it with `key B`..
I came up with an similar concept for using GPG encryption (popular asymmetric crypto system, mainly used for email encryption or signing) [to secure website data](http://neverfear.org/blog/view/Secure_website_authentication_using_GPG_keys). I'm not quite sure how this would apply to securing game level passwords, and as I said, you'd need to be really paranoid to even consider this..
In short, I'd say store the passwords in plain-text, and concentrate your security-concerns elsewhere (the web applications code itself) | The most secure encryption is no encryption. Passwords should be reduced to a hash. This is a one-way transformation, making the password (almost) unrecoverable.
When giving someone a code, you can do the following to be *actually* secure.
(1) generate some random string.
(2) give them the string.
(3) save the hash of the string you generated.
Once.
If they "forget" the code, you have to (1) be sure they're authorized to be given the code, then (2) do the process again (generate a new code, give it to them, save the hash.) | What is the most secure python "password" encryption | [
"",
"python",
"security",
"encryption",
""
] |
What is the difference between SQL, PL-SQL and T-SQL?
Can anyone explain what the differences between these three are, and provide scenarios where each would be relevantly used? | SQL is a declarative language to operate on relational data: tables, views, resultsets and similar.
It's more or less standardized, and used by almost all relational database management systems: SQL Server, Oracle, MySQL, PostgreSQL, DB2, Informix, etc.
Most database engines also support procedural languages (as opposed to declarative that SQL is). They have variables, loops, conditional operators and explicitly controlled execution flow, something that SQL lacks. Usually they are designed to closely integrate with SQL.
They are, for the most part, used to write stored procedures: pieces of code that live on the server and implement complex business rules that are hard or impossible to implement with pure set-based operations.
* PL/SQL is a proprietary procedural language used by Oracle
* PL/pgSQL is a procedural language used by PostgreSQL
* TSQL is a proprietary procedural language used by Microsoft in SQL Server. | **SQL**
> SQL is used to communicate with a database, it is the standard
> language for relational database management systems.
In detail **Structured Query Language** is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS).
Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.
**PL/SQL**
***PL/SQL is a combination of SQL along with the procedural features of programming languages.*** It was developed by Oracle Corporation
> Specialities of PL/SQL
* completely portable, high-performance transaction-processing
language.
* provides a built-in interpreted and OS independent programming
environment.
* directly be called from the command-line SQL\*Plus interface.
* Direct call can also be made from external programming language calls
to database.
* general syntax is based on that of ADA and Pascal programming
language.
* Apart from Oracle, it is available in TimesTen in-memory database and
IBM DB2.
**T-SQL**
**Short for Transaction-SQL**, an extended form of SQL that adds declared variables, transaction control, error and exceptionhandling and row processing to SQL
The Structured Query Language or SQL is a programming language that focuses on managing relational databases. **SQL has its own limitations** which spurred the software giant **Microsoft to build on top of SQL with their own extensions to enhance the functionality of SQL**.
Microsoft added code to SQL and called it Transact-SQL or T-SQL. Keep in mind that T-SQL is proprietary and is under the control of Microsoft while SQL, although developed by IBM, is already an open format.
**T-SQL adds a number of features that are not available in SQL.**
This includes procedural programming elements and a local variable to provide more flexible control of how the application flows. A number of functions were also added to T-SQL to make it more powerful; functions for mathematical operations, string operations, date and time processing, and the like. These additions make T-SQL comply with the Turing completeness test, a test that determines the universality of a computing language. SQL is not Turing complete and is very limited in the scope of what it can do.
Another significant difference between T-SQL and SQL is the changes done to the DELETE and UPDATE commands that are already available in SQL. With T-SQL, the DELETE and UPDATE commands both allow the inclusion of a FROM clause which allows the use of JOINs. This simplifies the filtering of records to easily pick out the entries that match a certain criteria unlike with SQL where it can be a bit more complicated.
**Choosing between T-SQL and SQL is all up to the user.** Still, using T-SQL is still better when you are dealing with Microsoft SQL Server installations. This is because T-SQL is also from Microsoft, and using the two together maximizes compatibility. SQL is preferred by people who have multiple backends.
**References**
, Wikipedea
, Tutorial Points
:www.differencebetween.com | What is the difference between SQL, PL-SQL and T-SQL? | [
"",
"sql",
"t-sql",
"plsql",
""
] |
How do I convert a `Map<key,value>` to a `List<value>`? Should I iterate over all map values and insert them into a list? | ```
List<Value> list = new ArrayList<Value>(map.values());
```
assuming:
```
Map<Key,Value> map;
``` | The issue here is that [`Map`](http://java.sun.com/javase/6/docs/api/java/util/Map.html) has two values (a key and value), while a [`List`](http://java.sun.com/javase/6/docs/api/java/util/List.html) only has one value (an element).
Therefore, the best that can be done is to either get a `List` of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).
Say we have a `Map`:
```
Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");
```
The keys as a `List` can be obtained by creating a new [`ArrayList`](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html) from a [`Set`](http://java.sun.com/javase/6/docs/api/java/util/Set.html) returned by the [`Map.keySet`](http://java.sun.com/javase/6/docs/api/java/util/Map.html#keySet()) method:
```
List<String> list = new ArrayList<String>(m.keySet());
```
While the values as a `List` can be obtained creating a new `ArrayList` from a [`Collection`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html) returned by the [`Map.values`](http://java.sun.com/javase/6/docs/api/java/util/Map.html#values()) method:
```
List<String> list = new ArrayList<String>(m.values());
```
The result of getting the `List` of keys:
```
Apple
Another
Hello
```
The result of getting the `List` of values:
```
3.14
Element
World
``` | How do I convert a Map to List in Java? | [
"",
"java",
"list",
"dictionary",
"collections",
""
] |
I recently started looking at MD5 hashing (in Java) and while I've found algorithms and methods to help me accomplish that, I'm left wondering how it actually works.
For one, I found the following from [this URL](http://www.anyexample.com/programming/java/java_simple_class_to_compute_md5_hash.xml):
```
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
```
I haven't found any need to use bit-shifting in Java so I'm a bit rusty on that. Someone kind enough to illustrate (in simple terms) how exactly does the above code does the conversion? ">>>"?
I also found other solutions on StackOverflow, such as [here](https://stackoverflow.com/questions/415953/generate-md5-hash-in-java) and [here](https://stackoverflow.com/questions/304268/using-java-to-get-a-files-md5-checksum), which uses BigInteger instead:
```
try {
String s = "TEST STRING";
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes(),0,s.length());
String signature = new BigInteger(1,md5.digest()).toString(16);
System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}
```
Why does that work too, and which way is more efficient?
Thanks for your time. | ```
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
```
Up till this point ... just basic set up and starting a loop to go through all bytes in the array
```
int halfbyte = (data[i] >>> 4) & 0x0F;
```
bytes when converted to hex are two hex digits or 8 binary digits depending on what base you look at it in. The above statement shifts the high 4 bits down (>>> is unsigned right shift) and logical ANDs it with 0000 1111 so that the result is an integer equal to the high 4 bits of the byte (first hex digit).
Say 23 was an input, this is 0001 0111 in binary. The shift makes and logical AND coverts this to 0000 0001.
```
int two_halfs = 0;
do {
```
This just sets up the do/while loop to run twice
```
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
```
Here we're displaying the actual hex digit, basically just using the zero or a character as a starting point and shifting up to the correct character. The first if statement covers all the digits 0-9, and the second covers all digits 10-15 (a-f in hex)
Again, using our example 0000 0001 in decimal is equal to 1. We get caught in the upper if block and add 1 to the '0' character to get the character '1', append that to the string and move on.
```
halfbyte = data[i] & 0x0F;
```
Now we set up the integer to just equal the low bits from the byte and repeat.
Again, if our input was 23 ... 0001 0111 after the logical AND becomes just 0000 0111 which is 7 in decimal. Repeat the same logic as above and the character '7' is displayed.
```
} while(two_halfs++ < 1);
```
Now we just move on to the next byte in the array and repeat.
```
}
return buf.toString();
}
```
To answer your next question, the Java API already has a base conversion utility built in to BigInteger already. See the [toString(int radix)](http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html#toString(int)) documentation.
Not knowing the implementation used by the Java API, I can't say for sure, but I'd be willing to bet that the Java implenentation is more efficient than the first somewhat simple algorithm you posted. | To answer this bit:
> Why does that work too
It doesn't. At least, not the same way that the loop version does. new BigInteger(...).toString(16) will not show leading zeroes, which the former version will. Usually for something like writing out a byte array (especially one representing something like a hash) you would want a fixed-length output so if you want to use that version you'd have to pad it out appropriately. | Can someone explain the conversion from byte array to hex string? | [
"",
"java",
"md5",
"arrays",
"hex",
""
] |
The following confirmDialog function is called midway through another jquery function. When this confirmDialog returns true the other function is supposed to continue... but it doesn't. The reason for this seems to be that the entire confirmDialog function has already executed (returning false) by the time the continue button gets clicked. How can I delay it returning anything until after the buttons have been clicked?
(Or, if I'm completely on the wrong track, what is the problem and how do I fix it?)
```
function confirmDialog(message) {
....
$('input#continue', conf_dialog).click(function() {
$(this).unbind();
$('p',conf_dialog).fadeOut().text('Are you really sure you want to '+message).fadeIn();
$(this).click(function() {
$(conf_dialog).remove();
return true;
});
});
$('input#cancel', conf_dialog).click(function() {
$(conf_dialog).remove();
return false;
});
}
``` | ```
function callingFunction() {
$('a').click(function() {
confirmDialog('are you sure?', dialogConfirmed);
// the rest of the function is in dialogConfirmed so doesnt
// get run unless the confirm button is pressed
})
}
function dialogConfirmed() {
// put the rest of your function here
}
function confirmDialog(message, callback) {
...
$('input#continue', conf_dialog).click(function() {
callback()
$(conf_dialog).remove();
return false;
}),
$('input#cancel', conf_dialog).click(function() {
$(conf_dialog).remove();
return false;
})
...
}
``` | Im' not sure you can.
AFAIK only built-in function like `confirm`, `alert` or `prompt` can be blocking while asking for an answer.
The general workaround is to refactor your code to use callbacks (or use the built-in functions). So that would mean splitting your caller function in two, and executing the second part when the input is obtained. | How to delay a function from returning until after clicks have occurred | [
"",
"javascript",
"jquery",
"return-value",
""
] |
Having the "one push build" to take your changes from development environment to live server is one thing that is very nice to have and often advocated.
I came on board with a small team running in a LAMP stack and use SVN for version control, currently deployed on a single production server (another server for development and soon to be a separate mysql server). I'm just now putting in place a lot of the organizational things that have been missing prior to me coming on board.
I am curious to see
1. how people are doing this (one step build) currently
2. see how i can implement it best for my situation (small team, LAMP environment with SVN)
Some particular challenges I'm interested in would be handling database changes (schema) and also if and what kind of "packages" are people using to keep things organized (e.g. RPMs, PEAR, etc.). | We used [ant](http://ant.apache.org/) with [Hudson](http://hudson-ci.org/). Worked like a charm.
Hudson would work with other build systems too, and not just java projects. It lets you setup multiple build targets, and will run them automatically, or manually. It also forces you to implement a way to run your build from a single command.
It doesn't solve the communication problems where the server will be unavailable during the time it takes to run the build for the deployed server.
For our schema updates and changes, we setup our ant script to do two things:
1. Update run the schema only if there's a difference in SVN.
2. Check in a schema dump after the schema changes were built.
3. If there was no update to the schema, simply use the dump to load a database
It did take a few tries to get right, but suddenly we had solved the issue of multiple developers being on different schemas. It was so easy to import the dump to update your development schema, that you could do it daily. | We do. We use a product called [Anthill Pro](http://www.anthillpro.com/html/default.html) to do all of our builds and deployments. It has a workflow process which set up to check out the files, do the builds, run the unit tests and then deploy the code to the servers. You can use it to deploy just about anything as the process can run command line programs etc. | How do you implement the "one step build" for a LAMP project? | [
"",
"php",
"version-control",
"project-management",
"lamp",
"packaging",
""
] |
I'm working on a reflection project, and now I'm stuck.
If I have an object of `myclass` that can hold a `List<SomeClass>`, does anyone know how to get the type as in the code below if the property `myclass.SomList` is empty?
```
List<myclass> myList = dataGenerator.getMyClasses();
lbxObjects.ItemsSource = myList;
lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;
private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Reflect();
}
Private void Reflect()
{
foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())
{
switch (pi.PropertyType.Name.ToLower())
{
case "list`1":
{
// This works if the List<T> contains one or more elements.
Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));
// but how is it possible to get the Type if the value is null?
// I need to be able to create a new object of the type the generic list expect.
// Type type = pi.getType?? // how to get the Type of the class inside List<T>?
break;
}
}
}
}
private Type GetGenericType(object obj)
{
if (obj != null)
{
Type t = obj.GetType();
if (t.IsGenericType)
{
Type[] at = t.GetGenericArguments();
t = at.First<Type>();
}
return t;
}
else
{
return null;
}
}
``` | ```
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0]; // use this...
}
```
---
More generally, to support any `IList<T>`, you need to check the interfaces:
```
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Type itemType = type.GetGenericArguments()[0];
// do something...
break;
}
}
``` | *Given an object which I suspect to be some kind of `IList<>`, how can I determine **of what** it's an `IList<>`?*
Here's the gutsy solution. It assumes you have the actual object to test (rather than a `Type`).
```
public static Type ListOfWhat(Object list)
{
return ListOfWhat2((dynamic)list);
}
private static Type ListOfWhat2<T>(IList<T> list)
{
return typeof(T);
}
```
Example usage:
```
object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();
```
Prints
```
typeof(DateTime)
``` | C# generic list <T> how to get the type of T? | [
"",
"c#",
"reflection",
"generic-list",
""
] |
I'm trying to implement a very, **very** simple accessibility test for Swing so I can get a handle on how big a piece of work it will be to provide accessibility support for our already established Swing application.
I have the most simple Swing program, and I'm using Narrator in Windows Vista to attempt to screen-read its GUI.
```
public class ReadableFrame extends JFrame {
private ReadableFrame() {
super();
setTitle( "Banjollity's Window" );
setSize( 640, 580 );
setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
JButton button = new JButton( "Hello World" );
getContentPane().setLayout( new FlowLayout() );
getContentPane().add( button );
setVisible( true );
}
/**
* @param args
*/
public static void main( String[] args ) {
new ReadableFrame();
}
}
```
Narrator can read the title but nothing else. I get "*Banjollity's Window, contains no other known controls*". If I replace the Swing JButton with an AWT Button like so:
```
Button button = new Button( "Hello World" );
```
...then it works properly, and I get "*Banjollity's Window, focus on Hello World button, contains Hello World button*".
I've tried installing the [Java Access Bridge](http://java.sun.com/javase/technologies/accessibility/accessbridge/) to JRE/lib/ext (and I strongly suspect this is working properly as my program refused to start up my application until I put the DLLs in Windows/System32) but to no avail.
Can anybody help, or share a few suggestions? | You don't, Narator is a bad screen reader. You need to install the java access bridge, and then use either [jaws](http://freedomscientific.com/downloads/jaws/JAWS-whats-new.asp#Enhancements) that will run for 40 minutes at a time as a demo or [NVDA](http://www.nvda-project.org) which is a free screen reader that also supports Java. | As your findings with Button shows if Narrator is willing to read labels on native Windows applications then you could perhaps use heavy weight components so the OS becomes aware of them and in turn Narrator will read them. | How do I make Vista's Narrator read my Swing components back to me? | [
"",
"java",
"windows",
"windows-vista",
"accessibility",
"narrator",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.