qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
126,631 | <p>Is it possible to pass a function/callback from javascript to a java applet?</p>
<p>For example i have an applet with a button that when pressed it will call the passed js callback</p>
<pre><code>function onCommand() {
alert('Button pressed from applet');
}
applet.onCommand(onCommand);
</code></pre>
| [
{
"answer_id": 126650,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/java_js.html\" rel=\"nofollow... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20300/"
] | Is it possible to pass a function/callback from javascript to a java applet?
For example i have an applet with a button that when pressed it will call the passed js callback
```
function onCommand() {
alert('Button pressed from applet');
}
applet.onCommand(onCommand);
``` | I tend to use something I derived from the reflection example at the bottom of [this page](http://www.rgagnon.com/javadetails/java-0172.html), as then you don't need to meddle with your classpath to get it to compile
Then I just pass JSON strings around between the applet and javascript |
126,652 | <p>(Oracle) I have to return all records from last 12 months. How to do that in PL/SQL?</p>
<p>EDIT: Sorry, I forgot to explain, I do have a column of DATA type</p>
| [
{
"answer_id": 126684,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": -1,
"selected": false,
"text": "<pre><code>SELECT *\nFROM table\nWHERE date_column > SYSDATE - 365\n</code></pre>\n"
},
{
"answer_id": 12... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3221/"
] | (Oracle) I have to return all records from last 12 months. How to do that in PL/SQL?
EDIT: Sorry, I forgot to explain, I do have a column of DATA type | Doing this in PL/SQL is pretty much synonymous with doing it in SQL.
```
SELECT *
FROM table
WHERE date_column >= ADD_MONTHS(TRUNC(SYSDATE),-12)
```
You might like to fiddle around with the TRUNC statement to get exactly the range you want -- I used TRUNC(SYSDATE) which is the same as TRUNC(SYSDATE,'D') -- ie. remove the time portion of the sysdate. For example, if it is currently Aug 12 but you want values from Feb 01 instead of Feb 12 then use:
```
SELECT *
FROM table
WHERE date_column >= ADD_MONTHS(TRUNC(SYSDATE,'MM'),-12)
```
Also, see the docs for treatment of months having different numbers of days: <http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions004.htm#SQLRF00603> |
126,656 | <p>I am doing a project at the moment, and in the interest of code reuse, I went looking for a library that can perform some probabilistic accept/reject of an item: </p>
<p>i.e., there are three people (a, b c), and each of them have a probability P{i} of getting an item, where p{a} denotes the probability of a. These probabilities are calculated at run time, and cannot be hardcoded. </p>
<p>What I wanted to do is to generate one random number (for an item), and calculate who gets that item based on their probability of getting it. The alias method (<a href="http://books.google.com/books?pg=PA133&dq=alias+method+walker&ei=D4ORR8ncFYuWtgOslpVE&sig=TjEThBUa4odbGJmjyF4daF1AKF4&id=ERSSDBDcYOIC&output=html" rel="nofollow noreferrer">http://books.google.com/books?pg=PA133&dq=alias+method+walker&ei=D4ORR8ncFYuWtgOslpVE&sig=TjEThBUa4odbGJmjyF4daF1AKF4&id=ERSSDBDcYOIC&output=html</a>) outlined here explained how, but I wanted to see if there is a ready made implementation so I wouldn't have to write it up.</p>
| [
{
"answer_id": 127132,
"author": "finalman",
"author_id": 20522,
"author_profile": "https://Stackoverflow.com/users/20522",
"pm_score": 2,
"selected": true,
"text": "<p>Would something like this do? Put all p{i}'s in the array, function will return an index to the person who gets the ite... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17335/"
] | I am doing a project at the moment, and in the interest of code reuse, I went looking for a library that can perform some probabilistic accept/reject of an item:
i.e., there are three people (a, b c), and each of them have a probability P{i} of getting an item, where p{a} denotes the probability of a. These probabilities are calculated at run time, and cannot be hardcoded.
What I wanted to do is to generate one random number (for an item), and calculate who gets that item based on their probability of getting it. The alias method (<http://books.google.com/books?pg=PA133&dq=alias+method+walker&ei=D4ORR8ncFYuWtgOslpVE&sig=TjEThBUa4odbGJmjyF4daF1AKF4&id=ERSSDBDcYOIC&output=html>) outlined here explained how, but I wanted to see if there is a ready made implementation so I wouldn't have to write it up. | Would something like this do? Put all p{i}'s in the array, function will return an index to the person who gets the item. Executes in O(n).
```
public int selectPerson(float[] probabilies, Random r) {
float t = r.nextFloat();
float p = 0.0f;
for (int i = 0; i < probabilies.length; i++) {
p += probabilies[i];
if (t < p) {
return i;
}
}
// We should not end up here if probabilities are normalized properly (sum up to one)
return probabilies.length - 1;
}
```
EDIT: I haven't really tested this. My point was that the function you described is not very complicated (if I understood what you meant correctly, that is), and you shouldn't need to download a library to solve this. |
126,678 | <p>I don't seem to be able to close the OledbDataReader object after reading data from it. Here is the relevant code -</p>
<pre><code>Dim conSyBase As New OleDb.OleDbConnection("Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;")
conSyBase.Open()
Dim cmdSyBase As New OleDb.OleDbCommand("MySQLStatement", conSyBase)
Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader
Try
While drSyBase.Read
/*Do some stuff with the data here */
End While
Catch ex As Exception
NotifyError(ex, "Read failed.")
End Try
drSyBase.Close() /* CODE HANGS HERE */
conSyBase.Close()
drSyBase.Dispose()
cmdSyBase.Dispose()
conSyBase.Dispose()
</code></pre>
<p>The console application just hangs at the point at which I try to close the reader. Opening and closing a connection is not a problem, therefore does anyone have any ideas for what may be causing this?</p>
| [
{
"answer_id": 126784,
"author": "Mikey",
"author_id": 13347,
"author_profile": "https://Stackoverflow.com/users/13347",
"pm_score": 0,
"selected": false,
"text": "<p>This is a long-shot, but try moving your .Close() and .Dispose() lines in a Finally block of the Try. Like this:</p>\n\n... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1831/"
] | I don't seem to be able to close the OledbDataReader object after reading data from it. Here is the relevant code -
```
Dim conSyBase As New OleDb.OleDbConnection("Provider=Sybase.ASEOLEDBProvider.2;Server Name=xx.xx.xx.xx;Server Port Address=5000;Initial Catalog=xxxxxxxxxx;User ID=xxxxxxxx;Password=xxxxxxxxx;")
conSyBase.Open()
Dim cmdSyBase As New OleDb.OleDbCommand("MySQLStatement", conSyBase)
Dim drSyBase As OleDb.OleDbDataReader = cmdSyBase.ExecuteReader
Try
While drSyBase.Read
/*Do some stuff with the data here */
End While
Catch ex As Exception
NotifyError(ex, "Read failed.")
End Try
drSyBase.Close() /* CODE HANGS HERE */
conSyBase.Close()
drSyBase.Dispose()
cmdSyBase.Dispose()
conSyBase.Dispose()
```
The console application just hangs at the point at which I try to close the reader. Opening and closing a connection is not a problem, therefore does anyone have any ideas for what may be causing this? | I found the answer!
Before
```
drSyBase.Close()
```
You need to call the cancel method of the Command object
```
cmdSyBase.Cancel()
```
I believe that this may be specific to Sybase databases |
126,718 | <p>I'm working on a VB6 application and I would like to send a Type as a reference and store it in another form. Is this possible?</p>
<p>Sending it is no problem, I just use the <code>ByRef</code> keyword:</p>
<pre><code>public Sub SetStopToEdit(ByRef currentStop As StopType)
</code></pre>
<p>But when I try to use Set to store <code>currentStop</code> in the receiving module I get the "Object required" error when running the program:</p>
<pre><code>Private stopToEdit As StopTypeModule.StopType
' ... Lots of code
Set stopToEdit = currentStop
</code></pre>
<p><code>StopType</code> is defined as follows in a Module (<strong>not a class module</strong>):</p>
<pre><code>Public Type StopType
MachineName As String
StartDate As Date
StartTime As String
Duration As Double
End Type
</code></pre>
<p>Is it possible to store the sent reference or do I have to turn <code>StopType</code> into a class?</p>
<p>While just setting a local variable works:</p>
<pre><code>stopToEdit = currentStop
</code></pre>
<p>When <code>stopToEdit</code> is later changed the change is not visible in the variable sent to <code>SetStopToEdit</code>.</p>
| [
{
"answer_id": 126740,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "<p>What is StopType? How is it defined? Is a Type the VB6-Record stuff? If so (and if possible), you should redefine it... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16047/"
] | I'm working on a VB6 application and I would like to send a Type as a reference and store it in another form. Is this possible?
Sending it is no problem, I just use the `ByRef` keyword:
```
public Sub SetStopToEdit(ByRef currentStop As StopType)
```
But when I try to use Set to store `currentStop` in the receiving module I get the "Object required" error when running the program:
```
Private stopToEdit As StopTypeModule.StopType
' ... Lots of code
Set stopToEdit = currentStop
```
`StopType` is defined as follows in a Module (**not a class module**):
```
Public Type StopType
MachineName As String
StartDate As Date
StartTime As String
Duration As Double
End Type
```
Is it possible to store the sent reference or do I have to turn `StopType` into a class?
While just setting a local variable works:
```
stopToEdit = currentStop
```
When `stopToEdit` is later changed the change is not visible in the variable sent to `SetStopToEdit`. | You need to refactor it into a class. |
126,737 | <p>After watching The Dark Knight I became rather enthralled with the concept of the Prisoner's Dilemma. There <em>must</em> be an algorithm that that maximizes one's own gain given a situation.</p>
<p>For those that find this foreign: <a href="http://en.wikipedia.org/wiki/Prisoner%27s_dilemma" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Prisoner%27s_dilemma</a></p>
<p>Very, very interesting stuff.</p>
<p>Edit: The question is, <em>what</em> is, if any, the most efficient algorithm that exists for the Prisoner's Dilemma?</p>
| [
{
"answer_id": 126763,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 2,
"selected": false,
"text": "<p>The whole point of the dilemma is that the optimal solution (both prisoners stay quiet) is dangerous because part of the prob... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14877/"
] | After watching The Dark Knight I became rather enthralled with the concept of the Prisoner's Dilemma. There *must* be an algorithm that that maximizes one's own gain given a situation.
For those that find this foreign: <http://en.wikipedia.org/wiki/Prisoner%27s_dilemma>
Very, very interesting stuff.
Edit: The question is, *what* is, if any, the most efficient algorithm that exists for the Prisoner's Dilemma? | Since there is only one choice to make, and in the absence of any changeable inputs, your algorithm is either going to be:
```
cooperate = true;
```
...or...
```
cooperate = false
```
It's more interesting to find a strategy for the Iterated Prisoner's Dilemma, which is something many people have done. For example <http://www.iterated-prisoners-dilemma.info/>
Even then it's not 'solvable' since the other player is not predictable. |
126,751 | <p>During a long compilation with Visual Studio 2005 (version 8.0.50727.762), I sometimes get the following error in several files in some project: </p>
<pre><code>fatal error C1033: cannot open program database 'v:\temp\apprtctest\win32\release\vc80.pdb'
</code></pre>
<p>(The file mentioned is either <code>vc80.pdb</code> or <code>vc80.idb</code> in the project's temp dir.)</p>
<p>The next build of the same project succeeds. There is no other Visual Studio open that might access the same files.</p>
<p>This is a serious problem because it makes nightly compilation impossible.</p>
| [
{
"answer_id": 127103,
"author": "SCFrench",
"author_id": 4928,
"author_profile": "https://Stackoverflow.com/users/4928",
"pm_score": 5,
"selected": false,
"text": "<p>We've seen this a lot at my site too. <a href=\"http://graphics.ethz.ch/~peterkau/coding.php\" rel=\"noreferrer\">This e... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7224/"
] | During a long compilation with Visual Studio 2005 (version 8.0.50727.762), I sometimes get the following error in several files in some project:
```
fatal error C1033: cannot open program database 'v:\temp\apprtctest\win32\release\vc80.pdb'
```
(The file mentioned is either `vc80.pdb` or `vc80.idb` in the project's temp dir.)
The next build of the same project succeeds. There is no other Visual Studio open that might access the same files.
This is a serious problem because it makes nightly compilation impossible. | It is possible that an antivirus or a similar program is touching the pdb file on write - an antivirus is the most likely suspect in this scenario. I'm afraid that I can only give you some general pointers, based on my past experience in setting nightly builds in our shop. Some of these may sound trivial, but I'm including them for the sake of completion.
* First and foremost: make sure you start up with a clean slate. That is, force-delete the output directory of the build before you start your nightly.
* If you have an antivirus, antispyware or other such programs on your nightly machine, consider removing them. If that's not an option, add your obj folder to the exclusion list of the program.
* (optional) Consider using tools such as VCBuild or MSBuild as part of your nightly. I think it's better to use MSBuild if you're on a multicore machine. We use IncrediBuild for nightlies and MSBuild for releases, and never encountered the problem you describe.
If nothing else works, you can schedule a watchdog script a few hours after the build starts and check its status; if the build fails, the watchdog should restart it. This is an ugly hack, but it's better than nothing. |
126,756 | <p>Can anybody suggest programming examples that illustrate recursive functions? There are the usual old horses such as <strong><em>Fibonacci series</em></strong> and <strong><em>Towers of Hanoi</em></strong>, but anything besides them would be fun.</p>
| [
{
"answer_id": 126768,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 1,
"selected": false,
"text": "<p>My personal favorite is <a href=\"http://en.wikipedia.org/wiki/Binary_search\" rel=\"nofollow noreferrer\">Binary Search</a... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
] | Can anybody suggest programming examples that illustrate recursive functions? There are the usual old horses such as ***Fibonacci series*** and ***Towers of Hanoi***, but anything besides them would be fun. | [This illustration](http://everything2.com/index.pl?node_id=477013) is in English, rather than an actual programming language, but is useful for explaining the process in a non-technical way:
```
A child couldn't sleep, so her mother told a story about a little frog,
who couldn't sleep, so the frog's mother told a story about a little bear,
who couldn't sleep, so bear's mother told a story about a little weasel
...who fell asleep.
...and the little bear fell asleep;
...and the little frog fell asleep;
...and the child fell asleep.
``` |
126,759 | <p>I've created an implementation of the <code>QAbstractListModel</code> class in Qt Jambi 4.4 and am finding that using the model with a <code>QListView</code> results in nothing being displayed, however using the model with a <code>QTableView</code> displays the data correctly.</p>
<p>Below is my implementation of <code>QAbstractListModel</code>:</p>
<pre><code>public class FooListModel extends QAbstractListModel
{
private List<Foo> _data = new Vector<Foo>();
public FooListModel(List<Foo> data)
{
if (data == null)
{
return;
}
for (Foo foo : data)
{
_data.add(Foo);
}
reset();
}
public Object data(QModelIndex index, int role)
{
if (index.row() < 0 || index.row() >= _data.size())
{
return new QVariant();
}
Foo foo = _data.get(index.row());
if (foo == null)
{
return new QVariant();
}
return foo;
}
public int rowCount(QModelIndex parent)
{
return _data.size();
}
}
</code></pre>
<p>And here is how I set the model:</p>
<pre><code>Foo foo = new Foo();
foo.setName("Foo!");
List<Foo> data = new Vector<Foo>();
data.add(foo);
FooListModel fooListModel = new FooListModel(data);
ui.fooListView.setModel(fooListModel);
ui.fooTableView.setModel(fooListModel);
</code></pre>
<p>Can anyone see what I'm doing wrong? I'd like to think it was a problem with my implementation because, as everyone says, select ain't broken!</p>
| [
{
"answer_id": 126768,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 1,
"selected": false,
"text": "<p>My personal favorite is <a href=\"http://en.wikipedia.org/wiki/Binary_search\" rel=\"nofollow noreferrer\">Binary Search</a... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13678/"
] | I've created an implementation of the `QAbstractListModel` class in Qt Jambi 4.4 and am finding that using the model with a `QListView` results in nothing being displayed, however using the model with a `QTableView` displays the data correctly.
Below is my implementation of `QAbstractListModel`:
```
public class FooListModel extends QAbstractListModel
{
private List<Foo> _data = new Vector<Foo>();
public FooListModel(List<Foo> data)
{
if (data == null)
{
return;
}
for (Foo foo : data)
{
_data.add(Foo);
}
reset();
}
public Object data(QModelIndex index, int role)
{
if (index.row() < 0 || index.row() >= _data.size())
{
return new QVariant();
}
Foo foo = _data.get(index.row());
if (foo == null)
{
return new QVariant();
}
return foo;
}
public int rowCount(QModelIndex parent)
{
return _data.size();
}
}
```
And here is how I set the model:
```
Foo foo = new Foo();
foo.setName("Foo!");
List<Foo> data = new Vector<Foo>();
data.add(foo);
FooListModel fooListModel = new FooListModel(data);
ui.fooListView.setModel(fooListModel);
ui.fooTableView.setModel(fooListModel);
```
Can anyone see what I'm doing wrong? I'd like to think it was a problem with my implementation because, as everyone says, select ain't broken! | [This illustration](http://everything2.com/index.pl?node_id=477013) is in English, rather than an actual programming language, but is useful for explaining the process in a non-technical way:
```
A child couldn't sleep, so her mother told a story about a little frog,
who couldn't sleep, so the frog's mother told a story about a little bear,
who couldn't sleep, so bear's mother told a story about a little weasel
...who fell asleep.
...and the little bear fell asleep;
...and the little frog fell asleep;
...and the child fell asleep.
``` |
126,772 | <h2>Background</h2>
<p>I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag).</p>
<h2>The Problem</h2>
<p>The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine.</p>
<p>Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly.</p>
<p>The problem is that the image shown <strong>does not</strong> get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears.</p>
<h2>My Solution - Not Working</h2>
<p>I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past.</p>
<pre><code>Expires: Mon, 15 Sep 2003 1:00:00 GMT
</code></pre>
<p>Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired.</p>
<p>But, this does not work either.</p>
<h2>Notes</h2>
<p>When uploading an image, its filename is not kept in the database. It is renamed as <strong>Image.jpg</strong> (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.</p>
<p>The webserver is provided by the hosting service/ISP. It uses Apache.</p>
<h2>Question</h2>
<p>Is there a way to force the web browser to NOT cache things from this page, not even images?</p>
<p>I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).</p>
| [
{
"answer_id": 126782,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 6,
"selected": false,
"text": "<p>Simple fix: Attach a random query string to the image:</p>\n\n<pre><code><img src=\"foo.cgi?random=3235275284... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7984/"
] | Background
----------
I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag).
The Problem
-----------
The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine.
Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly.
The problem is that the image shown **does not** get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears.
My Solution - Not Working
-------------------------
I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past.
```
Expires: Mon, 15 Sep 2003 1:00:00 GMT
```
Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired.
But, this does not work either.
Notes
-----
When uploading an image, its filename is not kept in the database. It is renamed as **Image.jpg** (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.
The webserver is provided by the hosting service/ISP. It uses Apache.
Question
--------
Is there a way to force the web browser to NOT cache things from this page, not even images?
I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded). | Armin Ronacher has the correct idea. The problem is random strings can collide. I would use:
```
<img src="picture.jpg?1222259157.415" alt="">
```
Where "1222259157.415" is the current time on the server.
Generate time by Javascript with `performance.now()` or by Python with `time.time()` |
126,781 | <p>I'm translating a library written in C++ to C#, and the keyword 'union' exists once. In a struct.</p>
<p>What's the correct way of translating it into C#? And what does it do? It looks something like this;</p>
<pre><code>struct Foo {
float bar;
union {
int killroy;
float fubar;
} as;
}
</code></pre>
| [
{
"answer_id": 126807,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 8,
"selected": true,
"text": "<p>You can use explicit field layouts for that:</p>\n\n<pre><code>[StructLayout(LayoutKind.Explicit)] \npublic struc... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15067/"
] | I'm translating a library written in C++ to C#, and the keyword 'union' exists once. In a struct.
What's the correct way of translating it into C#? And what does it do? It looks something like this;
```
struct Foo {
float bar;
union {
int killroy;
float fubar;
} as;
}
``` | You can use explicit field layouts for that:
```
[StructLayout(LayoutKind.Explicit)]
public struct SampleUnion
{
[FieldOffset(0)] public float bar;
[FieldOffset(4)] public int killroy;
[FieldOffset(4)] public float fubar;
}
```
Untested. The idea is that two variables have the same position in your struct. You can of course only use one of them.
More informations about unions in [struct tutorial](http://msdn.microsoft.com/en-us/library/aa288471(VS.71).aspx) |
126,794 | <p>I'm trying to write a query that will pull back the two most recent rows from the Bill table where the Estimated flag is true. The catch is that these need to be consecutive bills. </p>
<p>To put it shortly, I need to enter a row in another table if a Bill has been estimated for the last two bill cycles.</p>
<p>I'd like to do this without a cursor, if possible, since I am working with a sizable amount of data and this has to run fairly often.</p>
<p><strong>Edit</strong></p>
<p>There is an AUTOINCREMENT(1,1) column on the table. Without giving away too much of the table structure, the table is essentially of the structure:</p>
<pre><code>
CREATE TABLE Bills (
BillId INT AUTOINCREMENT(1,1,) PRIMARY KEY,
Estimated BIT NOT NULL,
InvoiceDate DATETIME NOT NULL
)
</code></pre>
<p>So you might have a set of results like:</p>
<pre>
BillId AccountId Estimated InvoiceDate
-------------------- -------------------- --------- -----------------------
1111196 1234567 1 2008-09-03 00:00:00.000
1111195 1234567 0 2008-08-06 00:00:00.000
1111194 1234567 0 2008-07-03 00:00:00.000
1111193 1234567 0 2008-06-04 00:00:00.000
1111192 1234567 1 2008-05-05 00:00:00.000
1111191 1234567 0 2008-04-04 00:00:00.000
1111190 1234567 1 2008-03-05 00:00:00.000
1111189 1234567 0 2008-02-05 00:00:00.000
1111188 1234567 1 2008-01-07 00:00:00.000
1111187 1234567 1 2007-12-04 00:00:00.000
1111186 1234567 0 2007-11-01 00:00:00.000
1111185 1234567 0 2007-10-01 00:00:00.000
1111184 1234567 1 2007-08-30 00:00:00.000
1111183 1234567 0 2007-08-01 00:00:00.000
1111182 1234567 1 2007-07-02 00:00:00.000
1111181 1234567 0 2007-06-01 00:00:00.000
1111180 1234567 1 2007-05-02 00:00:00.000
1111179 1234567 0 2007-03-30 00:00:00.000
1111178 1234567 1 2007-03-02 00:00:00.000
1111177 1234567 0 2007-02-01 00:00:00.000
1111176 1234567 1 2007-01-03 00:00:00.000
1111175 1234567 0 2006-11-29 00:00:00.000
</pre>
<p>In this case, only records 1111188 and 1111187 would be consecutive.</p>
| [
{
"answer_id": 126814,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to do a descensing sorted query on estimated = true and select top 2. I am not the best at SQL so i... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11780/"
] | I'm trying to write a query that will pull back the two most recent rows from the Bill table where the Estimated flag is true. The catch is that these need to be consecutive bills.
To put it shortly, I need to enter a row in another table if a Bill has been estimated for the last two bill cycles.
I'd like to do this without a cursor, if possible, since I am working with a sizable amount of data and this has to run fairly often.
**Edit**
There is an AUTOINCREMENT(1,1) column on the table. Without giving away too much of the table structure, the table is essentially of the structure:
```
CREATE TABLE Bills (
BillId INT AUTOINCREMENT(1,1,) PRIMARY KEY,
Estimated BIT NOT NULL,
InvoiceDate DATETIME NOT NULL
)
```
So you might have a set of results like:
```
BillId AccountId Estimated InvoiceDate
-------------------- -------------------- --------- -----------------------
1111196 1234567 1 2008-09-03 00:00:00.000
1111195 1234567 0 2008-08-06 00:00:00.000
1111194 1234567 0 2008-07-03 00:00:00.000
1111193 1234567 0 2008-06-04 00:00:00.000
1111192 1234567 1 2008-05-05 00:00:00.000
1111191 1234567 0 2008-04-04 00:00:00.000
1111190 1234567 1 2008-03-05 00:00:00.000
1111189 1234567 0 2008-02-05 00:00:00.000
1111188 1234567 1 2008-01-07 00:00:00.000
1111187 1234567 1 2007-12-04 00:00:00.000
1111186 1234567 0 2007-11-01 00:00:00.000
1111185 1234567 0 2007-10-01 00:00:00.000
1111184 1234567 1 2007-08-30 00:00:00.000
1111183 1234567 0 2007-08-01 00:00:00.000
1111182 1234567 1 2007-07-02 00:00:00.000
1111181 1234567 0 2007-06-01 00:00:00.000
1111180 1234567 1 2007-05-02 00:00:00.000
1111179 1234567 0 2007-03-30 00:00:00.000
1111178 1234567 1 2007-03-02 00:00:00.000
1111177 1234567 0 2007-02-01 00:00:00.000
1111176 1234567 1 2007-01-03 00:00:00.000
1111175 1234567 0 2006-11-29 00:00:00.000
```
In this case, only records 1111188 and 1111187 would be consecutive. | Assuming the rows have sequential IDs, something like this may be what you're looking for:
```
select top 1 *
from
Bills b1
inner join Bills b2 on b1.id = b2.id - 1
where
b1.IsEstimate = 1 and b2.IsEstimate = 1
order by
b1.BillDate desc
``` |
126,798 | <p>Does anyone know how to solve this java error?</p>
<pre><code>java.io.IOException: Invalid keystore format
</code></pre>
<p>I get it when I try and access the certificate store from the Java option in control panels. It's stopping me from loading applets that require elevated privileges.</p>
<p><a href="http://img72.imageshack.us/my.php?image=javaerrorxq7.jpg" rel="nofollow noreferrer">Error Image</a></p>
| [
{
"answer_id": 126902,
"author": "DeeCee",
"author_id": 5895,
"author_profile": "https://Stackoverflow.com/users/5895",
"pm_score": 0,
"selected": false,
"text": "<p>Seems to be a missing certificate or an invalid format.\nDid you already generate a certificate with keytool?</p>\n"
},
... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/942/"
] | Does anyone know how to solve this java error?
```
java.io.IOException: Invalid keystore format
```
I get it when I try and access the certificate store from the Java option in control panels. It's stopping me from loading applets that require elevated privileges.
[Error Image](http://img72.imageshack.us/my.php?image=javaerrorxq7.jpg) | I was able to reproduce the error by mangling the trusted.certs file at directory
`C:\Documents and Settings\CDay\Application Data\Sun\Java\Deployment\security`.
Deleting the file fixed the problem. |
126,837 | <p>I've got a local .mdf SQL database file that I am using for an integration testing project. Everything works fine on the initial machine I created the project, database, etc. on, but when I try to run the project on another machine I get the following:</p>
<p><em>System.Data.SqlClient.SqlException : A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)</em></p>
<p>I figure while I am investigating this problem I would also ask the community here to see if someone has already overcome this.</p>
<p>The exception occurs when I instantiate the new data context. I am using LINQ-to-SQL.</p>
<pre><code>m_TransLogDataContext = new TransLogDataContext ();
</code></pre>
<p>Let me know if any additional info is needed. Thanks.</p>
| [
{
"answer_id": 126972,
"author": "Scott Marlowe",
"author_id": 1683,
"author_profile": "https://Stackoverflow.com/users/1683",
"pm_score": 3,
"selected": true,
"text": "<p>I'm going to answer my own question as I have the solution.</p>\n\n<p>I was relying on the automatic connection stri... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] | I've got a local .mdf SQL database file that I am using for an integration testing project. Everything works fine on the initial machine I created the project, database, etc. on, but when I try to run the project on another machine I get the following:
*System.Data.SqlClient.SqlException : A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)*
I figure while I am investigating this problem I would also ask the community here to see if someone has already overcome this.
The exception occurs when I instantiate the new data context. I am using LINQ-to-SQL.
```
m_TransLogDataContext = new TransLogDataContext ();
```
Let me know if any additional info is needed. Thanks. | I'm going to answer my own question as I have the solution.
I was relying on the automatic connection string which had an incorrect "AttachDbFilename" property set to a location that was fine on the original machine but which did not exist on the new machine.
I'm going to have to dynamically build the connection string since I want this to run straight out of source control with no manual tweaking necessary.
Easy enough. |
126,853 | <p>I saw <a href="http://www.gnegg.ch/2008/09/automatic-language-detection/" rel="nofollow noreferrer">this</a> on reddit, and it reminded me of one of my vim gripes: It shows the UI in German. I want English. But since my OS is set up in German (the standard at our office), I guess vim is actually trying to be helpful.</p>
<p>What magic incantations must I perform to get vim to switch the UI language? I have tried googling on various occasions, but can't seem to find an answer.</p>
| [
{
"answer_id": 126858,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "<p>Start vim with a changed locale:</p>\n\n<pre><code>LC_ALL=en_GB.utf-8 vim\n</code></pre>\n\n<p>Or export that va... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I saw [this](http://www.gnegg.ch/2008/09/automatic-language-detection/) on reddit, and it reminded me of one of my vim gripes: It shows the UI in German. I want English. But since my OS is set up in German (the standard at our office), I guess vim is actually trying to be helpful.
What magic incantations must I perform to get vim to switch the UI language? I have tried googling on various occasions, but can't seem to find an answer. | As Ken noted, you want **[the `:language` command](http://vimdoc.sourceforge.net/htmldoc/mlang.html#:language)**.
Note that putting this in your `.vimrc` or `.gvimrc` won’t help you with the menus in gvim, since their definition is loaded once at startup, very early on, and not re-read again later. So you really do need to set `LC_ALL` (or more specifically `LC_MESSAGES`) in your environment – or on non-Unixoid systems (eg. Windows), you can pass the `--cmd` switch (which executes the given command first thing, as opposed to the `-c` option):
```
gvim --cmd "lang en_US"
```
As I mentioned, you don’t need to use `LC_ALL`, which will forcibly switch all aspects of your computing environment. You can do more nuanced stuff. F.ex., my own locale settings look like this:
```
LANG=en_US.utf8
LC_CTYPE=de_DE.utf8
LC_COLLATE=C
```
This means I get a largely English system, but with German semantics for letters, except that the default sort order is ASCIIbetical (ie. sort by codepoint, not according to language conventions). You could use a different variation; see [`man 7 locale`](http://man.cx/locale%287%29) for more. |
126,855 | <p>I have two tables, Users and DoctorVisit</p>
<p>User
- UserID
- Name</p>
<p>DoctorsVisit
- UserID
- Weight
- Date </p>
<p>The doctorVisit table contains all the visits a particular user did to the doctor.
The user's weight is recorded per visit.</p>
<p>Query: Sum up all the Users weight, using the last doctor's visit's numbers. (then divide by number of users to get the average weight)</p>
<p>Note: some users may have not visited the doctor at all, while others may have visited many times.</p>
<p>I need the average weight of all users, but using the latest weight.</p>
<p><b>Update</b></p>
<p>I want the average weight across all users.</p>
| [
{
"answer_id": 126892,
"author": "JPrescottSanders",
"author_id": 19444,
"author_profile": "https://Stackoverflow.com/users/19444",
"pm_score": 0,
"selected": false,
"text": "<p>This should get you the average weight per user if they have visited:</p>\n\n<pre><code>select user.name, temp... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have two tables, Users and DoctorVisit
User
- UserID
- Name
DoctorsVisit
- UserID
- Weight
- Date
The doctorVisit table contains all the visits a particular user did to the doctor.
The user's weight is recorded per visit.
Query: Sum up all the Users weight, using the last doctor's visit's numbers. (then divide by number of users to get the average weight)
Note: some users may have not visited the doctor at all, while others may have visited many times.
I need the average weight of all users, but using the latest weight.
**Update**
I want the average weight across all users. | If I understand your question correctly, you should be able to get the average weight of all users based on their last visit from the following SQL statement. We use a subquery to get the last visit as a filter.
```
SELECT avg(uv.weight) FROM (SELECT weight FROM uservisit uv INNER JOIN
(SELECT userid, MAX(dateVisited) DateVisited FROM uservisit GROUP BY userid) us
ON us.UserID = uv.UserId and us.DateVisited = uv.DateVisited
```
I should point out that this does assume that there is a unique UserID that can be used to determine uniqueness. Also, if the DateVisited doesn't include a time but just a date, one patient who visits twice on the same day could skew the data. |
126,870 | <p>I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.<br>
Here is how the class is going to be used:</p>
<pre>
ClassItem *pClassItem = myClass.Lookup(value);
if (pClassItem)
{ // item is found in class so modify and use it
pClassItem->SetAttribute(something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
</pre>
<p>However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass).
To get round that the following could be considered:</p>
<pre>
bool found = myClass.Lookup(value);
if (found)
{ // item is found in class so modify and use it
myClass.ModifyAttribute(value, something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
</pre>
<p>However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:</p>
<pre>
bool found = myClass.LookupAndModify(value, something);
if (found)
{ // item is found in class
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
</pre>
<p>But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.</p>
<p>Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?</p>
| [
{
"answer_id": 126944,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "<p>This assumes that you're setting value to the same \"something\" in both the Modify and Add cases:</p>\n\n<pre><cod... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12663/"
] | I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.
Here is how the class is going to be used:
```
ClassItem *pClassItem = myClass.Lookup(value);
if (pClassItem)
{ // item is found in class so modify and use it
pClassItem->SetAttribute(something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
```
However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass).
To get round that the following could be considered:
```
bool found = myClass.Lookup(value);
if (found)
{ // item is found in class so modify and use it
myClass.ModifyAttribute(value, something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
```
However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:
```
bool found = myClass.LookupAndModify(value, something);
if (found)
{ // item is found in class
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
```
But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.
Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)? | Two things.
The first solution is close.
Don't however, return `ClassItem *`. Return an "opaque object". An integer index or other hash code that's opaque (meaningless) to the client, but usable by the myClass instance.
Then lookup returns an index, which modify can subsequently use.
```
void *index = myClass.lookup( value );
if( index ) {
myClass.modify( index, value );
}
else {
myClass.add( value );
}
```
After writing the "primitive" Lookup, Modify and Add, then write your own composite operations built around these primitives.
Write a LookupAndModify, TryModify, AddIfNotExists and other methods built from your lower-level pieces. |
126,885 | <p>We have a SQL Server table containing Company Name, Address, and Contact name (among others).</p>
<p>We regularly receive data files from outside sources that require us to match up against this table. Unfortunately, the data is slightly different since it is coming from a completely different system. For example, we have "123 E. Main St." and we receive "123 East Main Street". Another example, we have "Acme, LLC" and the file contains "Acme Inc.". Another is, we have "Ed Smith" and they have "Edward Smith" </p>
<p>We have a legacy system that utilizes some rather intricate and CPU intensive methods for handling these matches. Some involve pure SQL and others involve VBA code in an Access database. The current system is good but not perfect and is cumbersome and difficult to maintain </p>
<p>The management here wants to expand its use. The developers who will inherit the support of the system want to replace it with a more agile solution that requires less maintenance. </p>
<p>Is there a commonly accepted way for dealing with this kind of data matching?</p>
| [
{
"answer_id": 126903,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": true,
"text": "<p>Here's something I wrote for a nearly identical stack (we needed to standardize the manufacturer names for hardware and t... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2173/"
] | We have a SQL Server table containing Company Name, Address, and Contact name (among others).
We regularly receive data files from outside sources that require us to match up against this table. Unfortunately, the data is slightly different since it is coming from a completely different system. For example, we have "123 E. Main St." and we receive "123 East Main Street". Another example, we have "Acme, LLC" and the file contains "Acme Inc.". Another is, we have "Ed Smith" and they have "Edward Smith"
We have a legacy system that utilizes some rather intricate and CPU intensive methods for handling these matches. Some involve pure SQL and others involve VBA code in an Access database. The current system is good but not perfect and is cumbersome and difficult to maintain
The management here wants to expand its use. The developers who will inherit the support of the system want to replace it with a more agile solution that requires less maintenance.
Is there a commonly accepted way for dealing with this kind of data matching? | Here's something I wrote for a nearly identical stack (we needed to standardize the manufacturer names for hardware and there were all sorts of variations). This is client side though (VB.Net to be exact) -- and use the Levenshtein distance algorithm (modified for better results):
```
Public Shared Function FindMostSimilarString(ByVal toFind As String, ByVal ParamArray stringList() As String) As String
Dim bestMatch As String = ""
Dim bestDistance As Integer = 1000 'Almost anything should be better than that!
For Each matchCandidate As String In stringList
Dim candidateDistance As Integer = LevenshteinDistance(toFind, matchCandidate)
If candidateDistance < bestDistance Then
bestMatch = matchCandidate
bestDistance = candidateDistance
End If
Next
Return bestMatch
End Function
'This will be used to determine how similar strings are. Modified from the link below...
'Fxn from: http://ca0v.terapad.com/index.cfm?fa=contentNews.newsDetails&newsID=37030&from=list
Public Shared Function LevenshteinDistance(ByVal s As String, ByVal t As String) As Integer
Dim sLength As Integer = s.Length ' length of s
Dim tLength As Integer = t.Length ' length of t
Dim lvCost As Integer ' cost
Dim lvDistance As Integer = 0
Dim zeroCostCount As Integer = 0
Try
' Step 1
If tLength = 0 Then
Return sLength
ElseIf sLength = 0 Then
Return tLength
End If
Dim lvMatrixSize As Integer = (1 + sLength) * (1 + tLength)
Dim poBuffer() As Integer = New Integer(0 To lvMatrixSize - 1) {}
' fill first row
For lvIndex As Integer = 0 To sLength
poBuffer(lvIndex) = lvIndex
Next
'fill first column
For lvIndex As Integer = 1 To tLength
poBuffer(lvIndex * (sLength + 1)) = lvIndex
Next
For lvRowIndex As Integer = 0 To sLength - 1
Dim s_i As Char = s(lvRowIndex)
For lvColIndex As Integer = 0 To tLength - 1
If s_i = t(lvColIndex) Then
lvCost = 0
zeroCostCount += 1
Else
lvCost = 1
End If
' Step 6
Dim lvTopLeftIndex As Integer = lvColIndex * (sLength + 1) + lvRowIndex
Dim lvTopLeft As Integer = poBuffer(lvTopLeftIndex)
Dim lvTop As Integer = poBuffer(lvTopLeftIndex + 1)
Dim lvLeft As Integer = poBuffer(lvTopLeftIndex + (sLength + 1))
lvDistance = Math.Min(lvTopLeft + lvCost, Math.Min(lvLeft, lvTop) + 1)
poBuffer(lvTopLeftIndex + sLength + 2) = lvDistance
Next
Next
Catch ex As ThreadAbortException
Err.Clear()
Catch ex As Exception
WriteDebugMessage(Application.StartupPath , [Assembly].GetExecutingAssembly().GetName.Name.ToString, MethodBase.GetCurrentMethod.Name, Err)
End Try
Return lvDistance - zeroCostCount
End Function
``` |
126,896 | <p>we are using git-svn to manage branches of an SVN repo. We are facing the following problem: after a number of commits by user X in the branch, user Y would like to use git-svn to merge the changes in branch to trunk. The problem we're seeing is that the commit messages for all the individual merge operations look as if they were made by user Y, whereas the actual change in branch was made by user X.</p>
<p>Is there a way to indicate to git-svn that when merging, use the original commit message/author for a given change rather than the person doing the merge?</p>
| [
{
"answer_id": 127242,
"author": "richq",
"author_id": 4596,
"author_profile": "https://Stackoverflow.com/users/4596",
"pm_score": 5,
"selected": true,
"text": "<p>The git-svn man page recommends that you <em>don't use merge</em>. \"\"It is recommended that you run git-svn fetch and reba... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | we are using git-svn to manage branches of an SVN repo. We are facing the following problem: after a number of commits by user X in the branch, user Y would like to use git-svn to merge the changes in branch to trunk. The problem we're seeing is that the commit messages for all the individual merge operations look as if they were made by user Y, whereas the actual change in branch was made by user X.
Is there a way to indicate to git-svn that when merging, use the original commit message/author for a given change rather than the person doing the merge? | The git-svn man page recommends that you *don't use merge*. ""It is recommended that you run git-svn fetch and rebase (not pull or merge)"". Having said that, you can do what you like :-)
There are 2 issues here. First is that svn only stores the *commiter*, not the author of a patch as git does. So when Y commits the merges to trunk, svn only records her name, even though the patches were authored by X. This is an *amazing* feature of git, stunningly simple yet vital for open source projects were attributing changes to the author can avoid legal problems down the road.
Secondly, git doesn't seem to use the relatively new svn merge features. This may be a temporary thing, as git is actively developed and new features are added all the time. But for now, it doesn't use them.
I've just tried with git 1.6.0.2 and it "loses" information compared to doing the same operation with svn merge. In svn 1.5, a new feature was added to the logging and annotation methods, so that svn log -g on the trunk would output something like this for a merge:
```
------------------------------------------------------------------------
r5 | Y | 2008-09-24 15:17:12 +0200 (Wed, 24 Sep 2008) | 1 line
Merged release-1.0 into trunk
------------------------------------------------------------------------
r4 | X | 2008-09-24 15:16:13 +0200 (Wed, 24 Sep 2008) | 1 line
Merged via: r5
Return 1
------------------------------------------------------------------------
r3 | X | 2008-09-24 15:15:48 +0200 (Wed, 24 Sep 2008) | 2 lines
Merged via: r5
Create a branch
```
Here, Y commits r5, which incorporates the changes from X on the branch into the trunk. The format of the log is not really that great, but it comes into its own on svn blame -g:
```
2 Y int main()
2 Y {
G 4 X return 1;
2 Y }
```
Here assuming Y only commits to trunk, we can see that one line was editted by X (on the branch) and merged.
So, if you are using svn 1.5.2, you are possibly better of merging with the real svn client for now. Although you would lose merge info in git, it is usually clever enough not to complain.
Update: I've just tried this with git 1.7.1 to see if there has been any advances in the interim. The bad news is that merge within git still does not populate the svn:mergeinfo values, so `git merge` followed by `git svn dcommit` will not set svn:mergeinfo and you will lose merge information if the Subversion repository is the canonical source, which it probably is. The good news is that `git svn clone` does read in svn:mergeinfo properties to construct a better merge history, so if you use `svn merge` correctly (it requires merging full branches) then the git clone will look correct to git users. |
126,898 | <p>I ran into a problem a few days ago when I had to introduce C++ files into a Java project. It started with a need to measure the CPU usage of the Java process and it was decided that the way to go was to use JNI to call out to a native library (a shared library on a Unix machine) written in C. The problem was to find an appropriate place to put the C files in the source repository (incidentally Clearcase) which consists of only Java files.</p>
<p>I thought of a couple of alternatives:</p>
<p>(a) Create a separate directory for putting the C files (specifically, one .h file and one .c file) at the top of the source base like:</p>
<p>/vobs/myproduct/javasrc
/vobs/myproduct/cppsrc</p>
<p>I didn't like this because I have only two C files and it seemed very odd to split the source base at the language level like this. Had substantial portions of the project been written more or less equally in C++ and Java, this could be okay.</p>
<p>(b) Put the C files into the Java package that uses it.</p>
<p>I have the calling Java classes in /vobs/myproduct/com/mycompany/myproduct/util/ and the C files also go in there.</p>
<p>I didn't like this either because I think the C files just don't belong in the Java package.</p>
<p>Has anybody solved a problem like this before? Generally, what's a good strategy to follow when organizing codebase that mixes two or more languages?</p>
<p>Update: I don't have any plan to use any C or C++ in my project, some Jython perhaps, but you never know when my customers need a feature that can be solved only by using C or best solved by using C.</p>
| [
{
"answer_id": 126922,
"author": "Linor",
"author_id": 3197,
"author_profile": "https://Stackoverflow.com/users/3197",
"pm_score": 0,
"selected": false,
"text": "<p>Personally I'd separate the two, possibly even into their own separate projects, but that's when they are both separate thi... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21647/"
] | I ran into a problem a few days ago when I had to introduce C++ files into a Java project. It started with a need to measure the CPU usage of the Java process and it was decided that the way to go was to use JNI to call out to a native library (a shared library on a Unix machine) written in C. The problem was to find an appropriate place to put the C files in the source repository (incidentally Clearcase) which consists of only Java files.
I thought of a couple of alternatives:
(a) Create a separate directory for putting the C files (specifically, one .h file and one .c file) at the top of the source base like:
/vobs/myproduct/javasrc
/vobs/myproduct/cppsrc
I didn't like this because I have only two C files and it seemed very odd to split the source base at the language level like this. Had substantial portions of the project been written more or less equally in C++ and Java, this could be okay.
(b) Put the C files into the Java package that uses it.
I have the calling Java classes in /vobs/myproduct/com/mycompany/myproduct/util/ and the C files also go in there.
I didn't like this either because I think the C files just don't belong in the Java package.
Has anybody solved a problem like this before? Generally, what's a good strategy to follow when organizing codebase that mixes two or more languages?
Update: I don't have any plan to use any C or C++ in my project, some Jython perhaps, but you never know when my customers need a feature that can be solved only by using C or best solved by using C. | *"I didn't like this because I have only two C files and it seemed very odd to split the source base at the language level like this"*
Why does it seem odd? Consider this project:
```
project1\src\java
project1\src\cpp
project1\src\python
```
Or, if you decide to split things up into modules:
```
project1\module1\src\java
project1\module1\src\cpp
project1\module2\src\java
project1\module2\src\python
```
I guess it's a matter of personal taste, but the above structure is fairly common, and I think it works quite well once you get used to it. |
126,925 | <p>I have an Internet Explorer Browser Helper Object (BHO), written in c#, and in various places I open forms as modal dialogs. Sometimes this works but in some cases it doesn't. The case that I can replicate at present is where IE is running javascript to open other child windows... I guess it's getting a bit confused somewhere.... </p>
<p>The problem is that when I call:</p>
<pre><code>(new MyForm(someParam)).ShowDialog();
</code></pre>
<p>the form is not modal, so I can click on the IE window and it gets focus. Since IE is in the middle of running my code it doesn't refresh and therefore to the user it appears that IE is hanging.</p>
<p>Is there a way of ensuring that the form will be opened as modal, ie that it's not possible for the form to be hidden behind IE windows.</p>
<p>(I'm using IE7.)</p>
<p>NB: this is a similar question to <a href="https://stackoverflow.com/questions/73000/modal-dialogs-in-ie-gets-hidden-behind-ie-if-user-clicks-on-ie-pane">this post</a> although that's using java. I guess the solution is around correctly passing in the IWin32Window of the IE window, so I'm looking into that.</p>
| [
{
"answer_id": 126959,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 2,
"selected": true,
"text": "<p>It wasn't my intention to answer my own question, but...</p>\n\n<p>It seems that if you pass in the correct IWin32Window to t... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8479/"
] | I have an Internet Explorer Browser Helper Object (BHO), written in c#, and in various places I open forms as modal dialogs. Sometimes this works but in some cases it doesn't. The case that I can replicate at present is where IE is running javascript to open other child windows... I guess it's getting a bit confused somewhere....
The problem is that when I call:
```
(new MyForm(someParam)).ShowDialog();
```
the form is not modal, so I can click on the IE window and it gets focus. Since IE is in the middle of running my code it doesn't refresh and therefore to the user it appears that IE is hanging.
Is there a way of ensuring that the form will be opened as modal, ie that it's not possible for the form to be hidden behind IE windows.
(I'm using IE7.)
NB: this is a similar question to [this post](https://stackoverflow.com/questions/73000/modal-dialogs-in-ie-gets-hidden-behind-ie-if-user-clicks-on-ie-pane) although that's using java. I guess the solution is around correctly passing in the IWin32Window of the IE window, so I'm looking into that. | It wasn't my intention to answer my own question, but...
It seems that if you pass in the correct IWin32Window to the ShowDialog() method it works fine. The trick is how to get this. Here's how I did this, where 'siteObject' is the object passed in to the SetSite() method of the BHO:
```
IWebBrowser2 browser = siteObject as IWebBrowser2;
if (browser != null) hwnd = new IntPtr(browser.HWND);
(new MyForm(someParam)).ShowDialog(new WindowWrapper(hwnd));
...
// Wrapper class so that we can return an IWin32Window given a hwnd
public class WindowWrapper : System.Windows.Forms.IWin32Window
{
public WindowWrapper(IntPtr handle)
{
_hwnd = handle;
}
public IntPtr Handle
{
get { return _hwnd; }
}
private IntPtr _hwnd;
}
```
Thanks to [Ryan](http://ryanfarley.com/blog/archive/2004/03/23/465.aspx) for the WindowWrapper class, although I'd hoped there was a built-in way to do this?
UPDATE: this won't work on IE8 with Protected Mode, since it's accessing an HWND outside what it should be. Instead you'll have to use the HWND of the current tab (or some other solution?), e.g. see .net example in [this post](http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/df0fe7f2-0153-47d9-b18f-266d57ab7909) for a way of getting that. |
126,939 | <p>I am using log4net in a C# project, in the production environment, I want to disable all the logging, but when some fatal
error occures it should log all the previous 512 messages in to a file.I have successfully configured this, and it is working fine. It logs the messages in to a file when some fatal error occures. </p>
<p>But when I run it from Visual Studio, I can see all the log messages are written to the Output window, regardless of whether it is a Fatal or not. (I cant see these messages when I run from the Windows Explorer - my application is a WinForm exe and there is no Console window to see the output)</p>
<p>Is there any way to disable this logging? I need my logs only in file, that too when some fatal error occures.</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net debug="false">
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="FATAL"/>
</evaluator>
<appender-ref ref="RollingFileAppender" />
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="BufferingForwardingAppender" />
</root>
</log4net>
</configuration>
</code></pre>
<p>And this is how I configure it in the static initializer of Windows Forms.</p>
<pre><code>static Window1()
{
Stream vStream = typeof(Window1).Assembly.GetManifestResourceStream("TestLogNet.log4net.config");
XmlConfigurator.Configure(vStream);
BasicConfigurator.Configure();
}
</code></pre>
<p>And I have the logger object initialized in the constructor of WinForm</p>
<pre><code>logger = LogManager.GetLogger(typeof(Window1));
</code></pre>
<p>[language - C#,
.NET Framework - 3.5,
Visual Studio 2008,
log4net 1.2.10,
project type - WinForms]</p>
| [
{
"answer_id": 127037,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>Do you still see the messages in Visual Studio if the application is compiled in release mode? It's possible that log4ne... | 2008/09/24 | [
"https://Stackoverflow.com/questions/126939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21653/"
] | I am using log4net in a C# project, in the production environment, I want to disable all the logging, but when some fatal
error occures it should log all the previous 512 messages in to a file.I have successfully configured this, and it is working fine. It logs the messages in to a file when some fatal error occures.
But when I run it from Visual Studio, I can see all the log messages are written to the Output window, regardless of whether it is a Fatal or not. (I cant see these messages when I run from the Windows Explorer - my application is a WinForm exe and there is no Console window to see the output)
Is there any way to disable this logging? I need my logs only in file, that too when some fatal error occures.
```xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net debug="false">
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="FATAL"/>
</evaluator>
<appender-ref ref="RollingFileAppender" />
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="BufferingForwardingAppender" />
</root>
</log4net>
</configuration>
```
And this is how I configure it in the static initializer of Windows Forms.
```
static Window1()
{
Stream vStream = typeof(Window1).Assembly.GetManifestResourceStream("TestLogNet.log4net.config");
XmlConfigurator.Configure(vStream);
BasicConfigurator.Configure();
}
```
And I have the logger object initialized in the constructor of WinForm
```
logger = LogManager.GetLogger(typeof(Window1));
```
[language - C#,
.NET Framework - 3.5,
Visual Studio 2008,
log4net 1.2.10,
project type - WinForms] | Remove the [BasicConfigurator.Configure()](http://logging.apache.org/log4net/release/sdk/log4net.Config.BasicConfigurator.Configure_overload_1.html) line. That's what that line does -- adds a ConsoleAppender pointing to Console.Out. |
127,001 | <p>I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower.</p>
| [
{
"answer_id": 127011,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 5,
"selected": true,
"text": "<p>You can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html\" rel=\"nofollow noreferrer\... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18103/"
] | I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower. | You can use [Deflater](https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html)/[Inflater](http://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html) which is built into the JDK. There are also GZIPInputStream and GZIPOutputStream, but it really depends on your exact use.
Edit:
Reading further comments it looks like the network taffic is HTTP. Depending on the server, it probably has support for compression (especially with deflate/gzip). The problem then becomes on the client. If the client is a browser it probably already supports it. If your client is a webservices client or an [http client](http://hc.apache.org/httpclient-3.x/) check the documentation for that package to see if it is supported.
It looks like jakarta-commons httpclient may require you to manually do the compression. To enable this on the client side you will need to do something like
```
.addRequestHeader("Accept-Encoding","gzip,deflate");
``` |
127,009 | <p>Suppose I want to implement in C++ a data-structure to store oriented graphs. Arcs will be stored in Nodes thanks to STL containers. I'd like users to be able to iterate over the arcs of a node, in an STL-like way.</p>
<p>The issue I have is that I don't want to expose in the Node class (that will actually be an abstract base class) which STL container I will actually use in the concrete class. I therefore don't want to have my methods return std::list::iterator or std::vector::iterator...</p>
<p>I tried this:</p>
<pre><code>class Arc;
typedef std::iterator<std::random_access_iterator_tag, Arc*> ArcIterator; // Wrong!
class Node {
public:
ArcIterator incomingArcsBegin() const {
return _incomingArcs.begin();
}
private:
std::vector<Arc*> _incomingArcs;
};
</code></pre>
<p>But this is not correct because a vector::const_iterator can't be used to create an ArcIterator. So what can be this ArcIterator?</p>
<p>I found this paper about <a href="http://www.oonumerics.org/tmpw00/becker.html" rel="nofollow noreferrer">Custom Iterators for the STL</a> but it did not help. I must be a bit heavy today... ;)</p>
| [
{
"answer_id": 127173,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 0,
"selected": false,
"text": "<p>If you really don't want the client's of that class to know that it uses a vector underneath, but still want them to ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4177/"
] | Suppose I want to implement in C++ a data-structure to store oriented graphs. Arcs will be stored in Nodes thanks to STL containers. I'd like users to be able to iterate over the arcs of a node, in an STL-like way.
The issue I have is that I don't want to expose in the Node class (that will actually be an abstract base class) which STL container I will actually use in the concrete class. I therefore don't want to have my methods return std::list::iterator or std::vector::iterator...
I tried this:
```
class Arc;
typedef std::iterator<std::random_access_iterator_tag, Arc*> ArcIterator; // Wrong!
class Node {
public:
ArcIterator incomingArcsBegin() const {
return _incomingArcs.begin();
}
private:
std::vector<Arc*> _incomingArcs;
};
```
But this is not correct because a vector::const\_iterator can't be used to create an ArcIterator. So what can be this ArcIterator?
I found this paper about [Custom Iterators for the STL](http://www.oonumerics.org/tmpw00/becker.html) but it did not help. I must be a bit heavy today... ;) | Try this:
```
class Arc;
class Node {
private:
std::vector<Arc*> incoming_;
public:
typedef std::vector<Arc*>::iterator iterator;
iterator incoming_arcs_begin()
{ return incoming_.begin(); }
};
```
And use Node::iterator in the rest of the code. When/if you change the container, you have to change the typedef in a single place. (You could take this one step further with additional typedef for the storage, in this case vector.)
As for the const issue, either define vector's const\_iterator to be your iterator, or define double iterator types (const and non-const version) as vector does. |
127,027 | <p>I use a byte to store some flag like <code>10101010</code>, and I would like to know how to verify that a specific bit is at <code>1</code> or <code>0</code>.</p>
| [
{
"answer_id": 127033,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "<p>You can use an AND operator. The example you have: 10101010 and you want to check the third bit you can do: ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
] | I use a byte to store some flag like `10101010`, and I would like to know how to verify that a specific bit is at `1` or `0`. | Here's a function that can be used to test any `bit`:
```
bool is_bit_set(unsigned value, unsigned bitindex)
{
return (value & (1 << bitindex)) != 0;
}
```
**Explanation**:
The [left shift operator](https://learn.sparkfun.com/tutorials/binary#bitwise-operators) `<<` creates a [bitmask](https://stackoverflow.com/questions/tagged/bitmask). To illustrate:
* `(1 << 0)` equals `00000001`
* `(1 << 1)` equals `00000010`
* `(1 << 3)` equals `00001000`
So a shift of `0` tests the rightmost bit. A shift of `31` would be the leftmost bit of a 32-bit value.
The [bitwise-and operator](https://learn.microsoft.com/en-us/cpp/cpp/bitwise-and-operator-amp?view=msvc-170) (`&`) gives a result where all the bits that are `1` on both sides are set. Examples:
* `1111 & 0001` equals `0001`
* `1111 & 0010` equals `0010`
* `0000 & 0001` equals `0000`.
So, the expression:
```
(value & (1 << bitindex))
```
will return the bitmask if the associated bit (`bitindex`) contains a `1`
in that position, or else it will return `0` (meaning it does **not** contain a `1` at the assoicated `bitindex`).
To simplify, the expression tests if the result is greater than `zero`.
* If `Result > 0` returns `true`, meaning the byte has a `1` in the tested
`bitindex` position.
* All else returns `false` meaning the result was zero, which means there's a `0` in tested `bitindex` position.
Note the `!= 0` is not required in the statement since it's a [bool](https://www.geeksforgeeks.org/bool-in-c/), but I like to make it explicit. |
127,040 | <p>In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?</p>
| [
{
"answer_id": 127064,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 6,
"selected": false,
"text": "<p>For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available usin... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11492/"
] | In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome? | There is now a way to easily do this in most modern browsers using
```
document.execCommand('copy');
```
This will copy currently selected text. You can select a textArea or input field using
```
document.getElementById('myText').select();
```
To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.
For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.
A full example:
```js
function copier(){
document.getElementById('myText').select();
document.execCommand('copy');
}
```
```html
<button onclick="copier()">Copy</button>
<textarea id="myText">Copy me PLEASE!!!</textarea>
``` |
127,042 | <p>I've found an <a href="http://chrison.net/UACElevationInManagedCodeStartingElevatedCOMComponents.aspx" rel="noreferrer">article</a> on how to elevate a COM object written in C++ by calling
<code>CoCreateInstanceAsAdmin</code>. But what I have not been able to find or do, is a way to implement a component of my .NET (c#) application as a COM object and then call into that object to execute the tasks which need UAC elevation. MSDN documents this as the <a href="http://msdn.microsoft.com/en-us/library/bb756990.aspx" rel="noreferrer">admin COM object model</a>.</p>
<p>I am aware that it is possible and quite easy to launch the application (or another app) as an administrator, to execute the tasks in a separate process (see for instance the <a href="http://www.danielmoth.com/Blog/2006/12/launch-elevated-and-modal-too.html" rel="noreferrer">post from Daniel Moth</a>, but what I am looking for is a way to do everything from within the same, un-elevated .NET executable. Doing so will, of course, spawn the COM object in a new process, but thanks to transparent marshalling, the caller of the .NET COM object should not be (too much) aware of it.</p>
<p>Any ideas as to how I could instanciate a COM object written in C#, from a C# project, through the <code>CoCreateInstanceAsAdmin</code> API would be very helpful. So I am really interested in learning how to write a COM object in C#, which I can then invoke from C# through the COM elevation APIs.</p>
<p>Never mind if the elevated COM object does not run in the same process. I just don't want to have to launch the whole application elevated; I would just like to have the COM object which will execute the code be elevated. If I could write something along the lines:</p>
<pre><code>// in a dedicated assembly, marked with the following attributes:
[assembly: ComVisible (true)]
[assembly: Guid ("....")]
public class ElevatedClass
{
public void X() { /* do something */ }
}
</code></pre>
<p>and then have my main application just instanciate <code>ElevatedClass</code> through the <code>CoCreateInstanceAsAdmin</code> call. But maybe I am just dreaming.</p>
| [
{
"answer_id": 127690,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>The elements of elevation are processes. So, if I understand your question correctly, and you want a way to elevate a ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4597/"
] | I've found an [article](http://chrison.net/UACElevationInManagedCodeStartingElevatedCOMComponents.aspx) on how to elevate a COM object written in C++ by calling
`CoCreateInstanceAsAdmin`. But what I have not been able to find or do, is a way to implement a component of my .NET (c#) application as a COM object and then call into that object to execute the tasks which need UAC elevation. MSDN documents this as the [admin COM object model](http://msdn.microsoft.com/en-us/library/bb756990.aspx).
I am aware that it is possible and quite easy to launch the application (or another app) as an administrator, to execute the tasks in a separate process (see for instance the [post from Daniel Moth](http://www.danielmoth.com/Blog/2006/12/launch-elevated-and-modal-too.html), but what I am looking for is a way to do everything from within the same, un-elevated .NET executable. Doing so will, of course, spawn the COM object in a new process, but thanks to transparent marshalling, the caller of the .NET COM object should not be (too much) aware of it.
Any ideas as to how I could instanciate a COM object written in C#, from a C# project, through the `CoCreateInstanceAsAdmin` API would be very helpful. So I am really interested in learning how to write a COM object in C#, which I can then invoke from C# through the COM elevation APIs.
Never mind if the elevated COM object does not run in the same process. I just don't want to have to launch the whole application elevated; I would just like to have the COM object which will execute the code be elevated. If I could write something along the lines:
```
// in a dedicated assembly, marked with the following attributes:
[assembly: ComVisible (true)]
[assembly: Guid ("....")]
public class ElevatedClass
{
public void X() { /* do something */ }
}
```
and then have my main application just instanciate `ElevatedClass` through the `CoCreateInstanceAsAdmin` call. But maybe I am just dreaming. | Look at [Windows Vista UAC Demo Sample Code](http://www.microsoft.com/downloads/details.aspx?FamilyID=2cd92e43-6cda-478a-9e3b-4f831e899433&DisplayLang=en)
(You also need the [Vista Bridge](http://msdn.microsoft.com/en-us/library/ms756482.aspx) sample for UnsafeNativeMethods.CoGetObject method)
Which gives you C# code that shows a few different ways to elevate, including a COM object
*(Incomplete code sample - grab the files above)*
```
[return: MarshalAs(UnmanagedType.Interface)]
static internal object LaunchElevatedCOMObject(Guid Clsid, Guid InterfaceID)
{
string CLSID = Clsid.ToString("B"); // B formatting directive: returns {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
string monikerName = "Elevation:Administrator!new:" + CLSID;
NativeMethods.BIND_OPTS3 bo = new NativeMethods.BIND_OPTS3();
bo.cbStruct = (uint)Marshal.SizeOf(bo);
bo.hwnd = IntPtr.Zero;
bo.dwClassContext = (int)NativeMethods.CLSCTX.CLSCTX_ALL;
object retVal = UnsafeNativeMethods.CoGetObject(monikerName, ref bo, InterfaceID);
return (retVal);
}
``` |
127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="https://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| [
{
"answer_id": 127089,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 1,
"selected": false,
"text": "<p>First of all if you only need the first result of re.findall it's better to just use re.search that returns a match or N... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581/"
] | Is there a way to determine how many capture groups there are in a given regular expression?
I would like to be able to do the follwing:
```
def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
```
This allows me to do stuff like:
```
first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
```
However, I don't know how to implement `num_of_groups`. (Currently I just work around it.)
**EDIT:** Following the [advice from rslite](https://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089), I replaced `re.findall` with `re.search`.
`sre_parse` seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.
MizardX's regular expression seems to cover all bases, so I'm going to go with that. | ```
def num_groups(regex):
return re.compile(regex).groups
``` |
127,076 | <p>In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?</p>
<p>i.e.</p>
<pre><code>dim fooArr() as foo;
gv1.datasource = fooArr;
gv1.databind();
</code></pre>
<p>On Row Select</p>
<pre><code>Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand
If e.CommandName = "Select" Then
'get and use foo(index)
End If
End Sub
</code></pre>
| [
{
"answer_id": 127114,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>in theory the index of the row, should be the index of foo (maybe +1 for header row, you'll need to test). so, y... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] | In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?
i.e.
```
dim fooArr() as foo;
gv1.datasource = fooArr;
gv1.databind();
```
On Row Select
```
Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand
If e.CommandName = "Select" Then
'get and use foo(index)
End If
End Sub
``` | If you can be sure the order of items in your data source has not changed, you can use the CommandArgument property of the CommandEventArgs.
A more robust method, however,is to use the DataKeys/SelectedDataKey properties of the GridView. The only caveat is that your command must be of type "Select" (so, by default RowCommand will not have access to the DataKey).
Assuming you have some uniqueness in the entities comprising your list, you can set one or more key property names in the GridView's DataKeys property. When the selected item in the GridView is set, you can retrieve your key value(s) and locate the item in your bound list. This method gets you out of the problem of having the ordinal position in the GridView not matching the ordinal position of your element in the data source.
Example:
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True"
DataKeyNames="Name" onrowcommand="GridView1_RowCommand1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
</asp:GridView>
```
Then the code-behind (or inline) for the Page would be something like:
```
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// Value is the Name property of the selected row's bound object.
string foo = GridView1.SelectedDataKey.Value as string;
}
```
Another choice would be to go spelunking in the Rows collection of the GridView, fetching values a column at a time by getting control values, but that's not recommended unless you have to.
Hope this helps. |
127,095 | <p>I'm used to Atlas where the preferred (from what I know) method is to use XML comments such as:</p>
<pre><code>/// <summary>
/// Method to calculate distance between two points
/// </summary>
///
/// <param name="pointA">First point</param>
/// <param name="pointB">Second point</param>
///
function calculatePointDistance(pointA, pointB) { ... }
</code></pre>
<p>Recently I've been looking into other third-party JavaScript libraries and I see syntax like:</p>
<pre><code>/*
* some comment here
* another comment here
* ...
*/
function blahblah() { ... }
</code></pre>
<p>As a bonus, are there API generators for JavaScript that could read the 'preferred' commenting style?</p>
| [
{
"answer_id": 127099,
"author": "Jim Burger",
"author_id": 20164,
"author_profile": "https://Stackoverflow.com/users/20164",
"pm_score": 2,
"selected": false,
"text": "<p>The use of the triple comment in the first example is actually used for external XML documentation tools and (in Vis... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
] | I'm used to Atlas where the preferred (from what I know) method is to use XML comments such as:
```
/// <summary>
/// Method to calculate distance between two points
/// </summary>
///
/// <param name="pointA">First point</param>
/// <param name="pointB">Second point</param>
///
function calculatePointDistance(pointA, pointB) { ... }
```
Recently I've been looking into other third-party JavaScript libraries and I see syntax like:
```
/*
* some comment here
* another comment here
* ...
*/
function blahblah() { ... }
```
As a bonus, are there API generators for JavaScript that could read the 'preferred' commenting style? | There's [JSDoc](https://jsdoc.app/)
```
/**
* Shape is an abstract base class. It is defined simply
* to have something to inherit from for geometric
* subclasses
* @constructor
*/
function Shape(color){
this.color = color;
}
``` |
127,116 | <p>I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.</p>
<p>For example 5 would be converted to "101" and stored as a varchar.</p>
| [
{
"answer_id": 127371,
"author": "Sean",
"author_id": 5446,
"author_profile": "https://Stackoverflow.com/users/5446",
"pm_score": 5,
"selected": true,
"text": "<p>Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question.</p... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4779/"
] | I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.
For example 5 would be converted to "101" and stored as a varchar. | Following could be coded into a function. You would need to trim off leading zeros to meet requirements of your question.
```
declare @intvalue int
set @intvalue=5
declare @vsresult varchar(64)
declare @inti int
select @inti = 64, @vsresult = ''
while @inti>0
begin
select @vsresult=convert(char(1), @intvalue % 2)+@vsresult
select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1
end
select @vsresult
``` |
127,124 | <p>How do you resolve an NT style device path, e.g. <code>\Device\CdRom0</code>, to its logical drive letter, e.g. <code>G:\</code> ?</p>
<p>Edit: A Volume Name isn't the same as a Device Path so unfortunately <code>GetVolumePathNamesForVolumeName()</code> won't work.</p>
| [
{
"answer_id": 127158,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you could use GetVolumeNameForMountPoint and iterate through all mount points A:\\ through Z:\\, breaking when you fin... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14260/"
] | How do you resolve an NT style device path, e.g. `\Device\CdRom0`, to its logical drive letter, e.g. `G:\` ?
Edit: A Volume Name isn't the same as a Device Path so unfortunately `GetVolumePathNamesForVolumeName()` won't work. | Hopefully the following piece of code will give you enough to solve this - after you've initialised it, you just need to iterate through the collection to find your match. You may want to convert everything to upper/lower case before you insert into the collection to help with lookup performance.
```
typedef basic_string<TCHAR> tstring;
typedef map<tstring, tstring> HardDiskCollection;
void Initialise( HardDiskCollection &_hardDiskCollection )
{
TCHAR tszLinkName[MAX_PATH] = { 0 };
TCHAR tszDevName[MAX_PATH] = { 0 };
TCHAR tcDrive = 0;
_tcscpy_s( tszLinkName, MAX_PATH, _T("a:") );
for ( tcDrive = _T('a'); tcDrive < _T('z'); ++tcDrive )
{
tszLinkName[0] = tcDrive;
if ( QueryDosDevice( tszLinkName, tszDevName, MAX_PATH ) )
{
_hardDiskCollection.insert( pair<tstring, tstring>( tszLinkName, tszDevName ) );
}
}
}
``` |
127,151 | <p>This is an exercise for the CS guys to shine with the theory.</p>
<p>Imagine you have 2 containers with elements. Folders, URLs, Files, Strings, it really doesn't matter.</p>
<p>What is AN algorithm to calculate the added and the removed?</p>
<p><strong>Notice</strong>: If there are many ways to solve this problem, please post one per answer so it can be analysed and voted up.</p>
<p><strong>Edit</strong>: All the answers solve the matter with 4 containers. Is it possible to use only the initial 2?</p>
| [
{
"answer_id": 127207,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 1,
"selected": false,
"text": "<p>I have not done this in a while but I believe the algorithm goes like this...</p>\n\n<pre><code>sort left-list and ri... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
] | This is an exercise for the CS guys to shine with the theory.
Imagine you have 2 containers with elements. Folders, URLs, Files, Strings, it really doesn't matter.
What is AN algorithm to calculate the added and the removed?
**Notice**: If there are many ways to solve this problem, please post one per answer so it can be analysed and voted up.
**Edit**: All the answers solve the matter with 4 containers. Is it possible to use only the initial 2? | Assuming you have two lists of unique items, and the ordering doesn't matter, you can think of them both as sets rather than lists
If you think of a venn diagram, with list A as one circle and list B as the other, then the intersection of these two is the constant pool.
Remove all the elements in this intersection from both A and B, and and anything left in A has been deleted, whilst anything left in B has been added.
So, iterate through A looking for each item in B. If you find it, remove it from both A and B
Then A is a list of things that were deleted, and B is a list of things that were added
I think...
[edit] Ok, with the new "only 2 container" restriction, the same still holds:
```
foreach( A ) {
if( eleA NOT IN B ) {
DELETED
}
}
foreach( B ) {
if( eleB NOT IN A ) {
ADDED
}
}
```
Then you aren't constructing a new list, or destroying your old ones...but it will take longer as with the previous example, you could just loop over the shorter list and remove the elements from the longer. Here you need to do both lists
An I'd argue my first solution didn't use 4 containers, it just destroyed two ;-) |
127,152 | <p>I had someting like this in my code (.Net 2.0, MS SQL)</p>
<pre><code>SqlConnection connection = new SqlConnection(@"Data Source=localhost;Initial
Catalog=DataBase;Integrated Security=True");
connection.Open();
SqlCommand cmdInsert = connection.CreateCommand();
SqlTransaction sqlTran = connection.BeginTransaction();
cmdInsert.Transaction = sqlTran;
cmdInsert.CommandText =
@"INSERT INTO MyDestinationTable" +
"(Year, Month, Day, Hour, ...) " +
"VALUES " +
"(@Year, @Month, @Day, @Hour, ...) ";
cmdInsert.Parameters.Add("@Year", SqlDbType.SmallInt);
cmdInsert.Parameters.Add("@Month", SqlDbType.TinyInt);
cmdInsert.Parameters.Add("@Day", SqlDbType.TinyInt);
// more fields here
cmdInsert.Prepare();
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
char[] delimeter = new char[] {' '};
String[] records;
while (!reader.EndOfStream)
{
records = reader.ReadLine().Split(delimeter, StringSplitOptions.None);
cmdInsert.Parameters["@Year"].Value = Int32.Parse(records[0].Substring(0, 4));
cmdInsert.Parameters["@Month"].Value = Int32.Parse(records[0].Substring(5, 2));
cmdInsert.Parameters["@Day"].Value = Int32.Parse(records[0].Substring(8, 2));
// more here complicated stuff here
cmdInsert.ExecuteNonQuery()
}
sqlTran.Commit();
connection.Close();
</code></pre>
<p>With <em>cmdInsert.ExecuteNonQuery()</em> commented out this code executes in less than 2 sec. With SQL execution it takes 1m 20 sec. There are around 0.5 milion records. Table is emptied before. SSIS data flow task of similar functionality takes around 20 sec.</p>
<ul>
<li>Bulk Insert <strong>was</strong> not an option (see below). I did some fancy stuff during this import.</li>
<li>My test machine is Core 2 Duo with 2 GB RAM. </li>
<li>When looking in Task Manager CPU was not fully untilized. IO seemed also not to be fully utilized.</li>
<li>Schema is simple like hell: one table with AutoInt as primary index and less than 10 ints, tiny ints and chars(10).</li>
</ul>
<p>After some answers here I found that it is possible to execute <strong>bulk copy from memory</strong>! I was refusing to use bulk copy beacuse I thought it has to be done from file...</p>
<p>Now I use this and it takes aroud 20 sec (like SSIS task)</p>
<pre><code> DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("ixMyIndex", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Year", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Month", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Day", System.Type.GetType("System.Int32")));
// ... and more to go
DataRow dataRow;
object[] objectRow = new object[dataTable.Columns.Count];
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
char[] delimeter = new char[] { ' ' };
String[] records;
int recordCount = 0;
while (!reader.EndOfStream)
{
records = reader.ReadLine().Split(delimeter, StringSplitOptions.None);
dataRow = dataTable.NewRow();
objectRow[0] = null;
objectRow[1] = Int32.Parse(records[0].Substring(0, 4));
objectRow[2] = Int32.Parse(records[0].Substring(5, 2));
objectRow[3] = Int32.Parse(records[0].Substring(8, 2));
// my fancy stuf goes here
dataRow.ItemArray = objectRow;
dataTable.Rows.Add(dataRow);
recordCount++;
}
SqlBulkCopy bulkTask = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null);
bulkTask.DestinationTableName = "MyDestinationTable";
bulkTask.BatchSize = dataTable.Rows.Count;
bulkTask.WriteToServer(dataTable);
bulkTask.Close();
</code></pre>
| [
{
"answer_id": 127175,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "<p>Is required the transaction? Using transaction need much more resources than simple commands.</p>\n\n<p>Also If you are su... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/501/"
] | I had someting like this in my code (.Net 2.0, MS SQL)
```
SqlConnection connection = new SqlConnection(@"Data Source=localhost;Initial
Catalog=DataBase;Integrated Security=True");
connection.Open();
SqlCommand cmdInsert = connection.CreateCommand();
SqlTransaction sqlTran = connection.BeginTransaction();
cmdInsert.Transaction = sqlTran;
cmdInsert.CommandText =
@"INSERT INTO MyDestinationTable" +
"(Year, Month, Day, Hour, ...) " +
"VALUES " +
"(@Year, @Month, @Day, @Hour, ...) ";
cmdInsert.Parameters.Add("@Year", SqlDbType.SmallInt);
cmdInsert.Parameters.Add("@Month", SqlDbType.TinyInt);
cmdInsert.Parameters.Add("@Day", SqlDbType.TinyInt);
// more fields here
cmdInsert.Prepare();
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
char[] delimeter = new char[] {' '};
String[] records;
while (!reader.EndOfStream)
{
records = reader.ReadLine().Split(delimeter, StringSplitOptions.None);
cmdInsert.Parameters["@Year"].Value = Int32.Parse(records[0].Substring(0, 4));
cmdInsert.Parameters["@Month"].Value = Int32.Parse(records[0].Substring(5, 2));
cmdInsert.Parameters["@Day"].Value = Int32.Parse(records[0].Substring(8, 2));
// more here complicated stuff here
cmdInsert.ExecuteNonQuery()
}
sqlTran.Commit();
connection.Close();
```
With *cmdInsert.ExecuteNonQuery()* commented out this code executes in less than 2 sec. With SQL execution it takes 1m 20 sec. There are around 0.5 milion records. Table is emptied before. SSIS data flow task of similar functionality takes around 20 sec.
* Bulk Insert **was** not an option (see below). I did some fancy stuff during this import.
* My test machine is Core 2 Duo with 2 GB RAM.
* When looking in Task Manager CPU was not fully untilized. IO seemed also not to be fully utilized.
* Schema is simple like hell: one table with AutoInt as primary index and less than 10 ints, tiny ints and chars(10).
After some answers here I found that it is possible to execute **bulk copy from memory**! I was refusing to use bulk copy beacuse I thought it has to be done from file...
Now I use this and it takes aroud 20 sec (like SSIS task)
```
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("ixMyIndex", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Year", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Month", System.Type.GetType("System.Int32")));
dataTable.Columns.Add(new DataColumn("Day", System.Type.GetType("System.Int32")));
// ... and more to go
DataRow dataRow;
object[] objectRow = new object[dataTable.Columns.Count];
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(stream);
char[] delimeter = new char[] { ' ' };
String[] records;
int recordCount = 0;
while (!reader.EndOfStream)
{
records = reader.ReadLine().Split(delimeter, StringSplitOptions.None);
dataRow = dataTable.NewRow();
objectRow[0] = null;
objectRow[1] = Int32.Parse(records[0].Substring(0, 4));
objectRow[2] = Int32.Parse(records[0].Substring(5, 2));
objectRow[3] = Int32.Parse(records[0].Substring(8, 2));
// my fancy stuf goes here
dataRow.ItemArray = objectRow;
dataTable.Rows.Add(dataRow);
recordCount++;
}
SqlBulkCopy bulkTask = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null);
bulkTask.DestinationTableName = "MyDestinationTable";
bulkTask.BatchSize = dataTable.Rows.Count;
bulkTask.WriteToServer(dataTable);
bulkTask.Close();
``` | Instead of inserting each record individually, Try using the [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx) class to bulk insert all the records at once.
Create a DataTable and add all your records to the DataTable, and then use [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx).[WriteToServer](http://msdn.microsoft.com/en-us/library/ex21zs8x.aspx) to bulk insert all the data at once. |
127,156 | <p>How do I check if an index exists on a table field in MySQL?</p>
<p>I've needed to Google this multiple times, so I'm sharing my Q/A.</p>
| [
{
"answer_id": 127157,
"author": "Sean",
"author_id": 5446,
"author_profile": "https://Stackoverflow.com/users/5446",
"pm_score": 8,
"selected": true,
"text": "<p>Use <code>SHOW INDEX</code> like so:</p>\n\n<pre><code>SHOW INDEX FROM [tablename]\n</code></pre>\n\n<p>Docs: <a href=\"https... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5446/"
] | How do I check if an index exists on a table field in MySQL?
I've needed to Google this multiple times, so I'm sharing my Q/A. | Use `SHOW INDEX` like so:
```
SHOW INDEX FROM [tablename]
```
Docs: <https://dev.mysql.com/doc/refman/5.0/en/show-index.html> |
127,190 | <p>I'm learning Haskell in the hope that it will help me get closer to functional programming. Previously, I've mostly used languages with C-like syntax, like C, Java, and D.</p>
<p>I have a little question about the coding style of an <code>if</code>/<code>else</code> control block used by the <a href="http://en.wikibooks.org/wiki/Haskell/Simple_input_and_output" rel="nofollow noreferrer">tutorial on Wikibooks</a>. The code looks like the following:</p>
<pre><code>doGuessing num = do
putStrLn "Enter your guess:"
guess <- getLine
if (read guess) < num
then do putStrLn "Too low!"
doGuessing num
else if (read guess) > num
then do putStrLn "Too high!"
doGuessing num
else do putStrLn "You Win!"
</code></pre>
<p>It makes me confused, because this coding style totally violates the recommended style in C-like languages, where we should indent <code>if</code>, <code>else if</code>, and <code>else</code> at the same column.</p>
<p>I know it just does not work in Haskell, because it would be a parse error if I indented <code>else</code> at the same column as <code>if</code>.</p>
<p>But what about the following style? I think it is much more clear than the above one. But since the above is used by Wikibooks and Yet Another Haskell Tutorial, which is marked "best tutorial available online" at the official Haskell website, I'm not sure whether this coding style is a convention in Haskell programs.</p>
<pre><code>doGuessing num = do
putStrLn "Enter your guess:"
guess <- getLine
if (read guess) < num then
do
putStrLn "Too low!"
doGuessing num
else if (read guess) > num then do
putStrLn "Too high!"
doGuessing num
else do
putStrLn "You Win!"
</code></pre>
<p>So, I'm curious about which coding style is used more often—or is there another coding style for this piece of code?</p>
| [
{
"answer_id": 127257,
"author": "Jonathan Tran",
"author_id": 12887,
"author_profile": "https://Stackoverflow.com/users/12887",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use explicit grouping with curly braces. See the layout section of <a href=\"http://www.haskell.org... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242644/"
] | I'm learning Haskell in the hope that it will help me get closer to functional programming. Previously, I've mostly used languages with C-like syntax, like C, Java, and D.
I have a little question about the coding style of an `if`/`else` control block used by the [tutorial on Wikibooks](http://en.wikibooks.org/wiki/Haskell/Simple_input_and_output). The code looks like the following:
```
doGuessing num = do
putStrLn "Enter your guess:"
guess <- getLine
if (read guess) < num
then do putStrLn "Too low!"
doGuessing num
else if (read guess) > num
then do putStrLn "Too high!"
doGuessing num
else do putStrLn "You Win!"
```
It makes me confused, because this coding style totally violates the recommended style in C-like languages, where we should indent `if`, `else if`, and `else` at the same column.
I know it just does not work in Haskell, because it would be a parse error if I indented `else` at the same column as `if`.
But what about the following style? I think it is much more clear than the above one. But since the above is used by Wikibooks and Yet Another Haskell Tutorial, which is marked "best tutorial available online" at the official Haskell website, I'm not sure whether this coding style is a convention in Haskell programs.
```
doGuessing num = do
putStrLn "Enter your guess:"
guess <- getLine
if (read guess) < num then
do
putStrLn "Too low!"
doGuessing num
else if (read guess) > num then do
putStrLn "Too high!"
doGuessing num
else do
putStrLn "You Win!"
```
So, I'm curious about which coding style is used more often—or is there another coding style for this piece of code? | Haskell style is functional, not imperative! Rather than "do this then that," think about combining functions and describing *what* your program will do, not how.
In the game, your program asks the user for a guess. A correct guess is a winner. Otherwise, the user tries again. The game continues until the user guesses correctly, so we write that:
```
main = untilM (isCorrect 42) (read `liftM` getLine)
```
This uses a combinator that repeatedly runs an action (`getLine` pulls a line of input and `read` converts that string to an integer in this case) and checks its result:
```
untilM :: Monad m => (a -> m Bool) -> m a -> m ()
untilM p a = do
x <- a
done <- p x
if done
then return ()
else untilM p a
```
The predicate (partially applied in `main`) checks the guess against the correct value and responds accordingly:
```
isCorrect :: Int -> Int -> IO Bool
isCorrect num guess =
case compare num guess of
EQ -> putStrLn "You Win!" >> return True
LT -> putStrLn "Too high!" >> return False
GT -> putStrLn "Too low!" >> return False
```
The action to be run until the player guesses correctly is
```
read `liftM` getLine
```
Why not keep it simple and just compose the two functions?
```
*Main> :type read . getLine
<interactive>:1:7:
Couldn't match expected type `a -> String'
against inferred type `IO String'
In the second argument of `(.)', namely `getLine'
In the expression: read . getLine
```
The type of `getLine` is `IO String`, but `read` wants a pure `String`.
The function [`liftM`](http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Monad.html#v%3AliftM) from Control.Monad takes a pure function and “lifts” it into a monad. The type of the expression tells us a great deal about what it does:
```
*Main> :type read `liftM` getLine
read `liftM` getLine :: (Read a) => IO a
```
It's an I/O action that when run gives us back a value converted with `read`, an `Int` in our case. Recall that `readLine` is an I/O action that yields `String` values, so you can think of `liftM` as allowing us to apply `read` “inside” the `IO` monad.
Sample game:
```
1
Too low!
100
Too high!
42
You Win!
``` |
127,205 | <p>I have a constructor like as follows:</p>
<pre><code>public Agent(){
this.name = "John";
this.id = 9;
this.setTopWorldAgent(this, "Top_World_Agent", true);
}
</code></pre>
<p>I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this?</p>
| [
{
"answer_id": 127219,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p><code>this</code> is not null, that much is sure. It's been allocated.</p>\n\n<p>That said, there's no need to pass <code... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a constructor like as follows:
```
public Agent(){
this.name = "John";
this.id = 9;
this.setTopWorldAgent(this, "Top_World_Agent", true);
}
```
I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this? | ~~You can pass this to methods, but setTopWorldAgent() cannot be abstract. You can't make a virtual call in the constructor.~~
~~In the constructor of an object, you can call methods defined in that object or base classes, but you cannot expect to call something that will be provided by a derived class, because parts of the derived class are not constructed yet. I would have expected some kind of compiler error if setTopWorldAgent() was abstract.~~
In Java, you can get surprising behavior with the contructor and derived classes -- here is an example
<http://en.wikipedia.org/wiki/Virtual_functions#Java_3>
If you are used to C# or C++, you might think it's safe to call virtual functions and not be calling overridden ones. In Java, the virtual call is made even though the derived class is not fully constructed.
If this isn't what's happening, then presumably, all of the parts of this that setTopWorldAgent() needs are initialized -- if not, it's probably one of the members of this that needs to be initialized.
Edit: thought this was C# |
127,233 | <p>This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.</p>
| [
{
"answer_id": 127254,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "<p><code>foreach</code> does <em>not</em> require <code>IEnumerable</code>, contrary to popular belief. All it require... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] | This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed. | `foreach` does *not* require `IEnumerable`, contrary to popular belief. All it requires is a method `GetEnumerator` that returns any object that has the method `MoveNext` and the get-property `Current` with the appropriate signatures.
/EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:
```
class EnumerableWrapper {
private readonly TheObjectType obj;
public EnumerableWrapper(TheObjectType obj) {
this.obj = obj;
}
public IEnumerator<YourType> GetEnumerator() {
return obj.TheMethodReturningTheIEnumerator();
}
}
// Called like this:
foreach (var xyz in new EnumerableWrapper(yourObj))
…;
```
/EDIT: The following method, proposed by several people, does *not* work if the method returns an `IEnumerator`:
```
foreach (var yz in yourObj.MethodA())
…;
``` |
127,241 | <p>We are developing a .NET 2.0 winform application. The application needs to access <a href="http://ws.lokad.com/" rel="nofollow noreferrer">Web Services</a>. Yet, we are encountering issues with users behind proxies.</p>
<p>Popular windows backup applications (think <a href="http://mozy.com/" rel="nofollow noreferrer">Mozy</a>) are providing a moderately complex dialog window dedicated the proxy settings. Yet, re-implementing yet-another proxy handling logic and GUI looks a total waste of time to me.</p>
<p>What are best ways to deal with proxy with .NET client apps?</p>
<p>More specifically, we have a case where the user has recorded his proxy settings in Internet Explorer (including username and password), so the <em>default proxy behavior</em> of .NET should work. Yet, the user is still prompted for his username and password when launching IE (both fields are pre-completed, the user just need to click OK) - and our winform application still fails at handling the proxy.</p>
<p>What should we do to enforce that the user is not prompted for his username and password when launching IE?</p>
| [
{
"answer_id": 127263,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is to use the proxy settings from IE Explorer.</p>\n"
},
{
"answer_id": 127284,
... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18858/"
] | We are developing a .NET 2.0 winform application. The application needs to access [Web Services](http://ws.lokad.com/). Yet, we are encountering issues with users behind proxies.
Popular windows backup applications (think [Mozy](http://mozy.com/)) are providing a moderately complex dialog window dedicated the proxy settings. Yet, re-implementing yet-another proxy handling logic and GUI looks a total waste of time to me.
What are best ways to deal with proxy with .NET client apps?
More specifically, we have a case where the user has recorded his proxy settings in Internet Explorer (including username and password), so the *default proxy behavior* of .NET should work. Yet, the user is still prompted for his username and password when launching IE (both fields are pre-completed, the user just need to click OK) - and our winform application still fails at handling the proxy.
What should we do to enforce that the user is not prompted for his username and password when launching IE? | Put this in your application's config file:
```
<configuration>
<system.net>
<defaultProxy>
<proxy autoDetect="true" />
</defaultProxy>
</system.net>
</configuration>
```
and your application will use the proxy settings from IE. If you can see your web service in IE using the proxy server, you should be able to "see" it from your application. |
127,258 | <p>Greetings!</p>
<p>I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object:</p>
<pre><code><Root>
<GroupA>
<Item attrib1="aaa" attrib2="000" attrib3="true" />
</GroupA>
<GroupB>
<Item attrib1="bbb" attrib2="111" attrib3="true" />
<Item attrib1="ccc" attrib2="222" attrib3="false" />
<Item attrib1="ddd" attrib2="333" attrib3="true" />
</GroupB>
<GroupC>
<Item attrib1="eee" attrib2="444" attrib3="true" />
<Item attrib1="fff" attrib2="555" attrib3="true" />
</GroupC>
</Root>
</code></pre>
<p>I'd like to get the attribute values of all of the Item child elements of a Group element. Here's what my query looks like:</p>
<pre><code>var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName)
select new
{
attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value,
attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value,
};
</code></pre>
<p>The query works, but if for example the groupName variable contains "GroupB", only one result (the first Item element) is returned instead of three. Am I missing something?</p>
| [
{
"answer_id": 127301,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, .Element() only returns the first matching element. You want .Elements() and you need to re-write your query so... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
] | Greetings!
I'm working on wrapping my head around LINQ. If I had some XML such as this loaded into an XDocument object:
```
<Root>
<GroupA>
<Item attrib1="aaa" attrib2="000" attrib3="true" />
</GroupA>
<GroupB>
<Item attrib1="bbb" attrib2="111" attrib3="true" />
<Item attrib1="ccc" attrib2="222" attrib3="false" />
<Item attrib1="ddd" attrib2="333" attrib3="true" />
</GroupB>
<GroupC>
<Item attrib1="eee" attrib2="444" attrib3="true" />
<Item attrib1="fff" attrib2="555" attrib3="true" />
</GroupC>
</Root>
```
I'd like to get the attribute values of all of the Item child elements of a Group element. Here's what my query looks like:
```
var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName)
select new
{
attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value,
attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value,
};
```
The query works, but if for example the groupName variable contains "GroupB", only one result (the first Item element) is returned instead of three. Am I missing something? | ```
XElement e = XElement.Parse(testStr);
string groupName = "GroupB";
var items = from g in e.Elements(groupName)
from i in g.Elements("Item")
select new {
attr1 = (string)i.Attribute("attrib1"),
attr2 = (string)i.Attribute("attrib2")
};
foreach (var item in items)
{
Console.WriteLine(item.attr1 + ":" + item.attr2);
}
``` |
127,267 | <p>I am currently starting a project utilizing ASP.NET MVC and would like to use NHaml as my view engine as I love Haml from Rails/Merb. The main issue I face is the laying out of my pages. In Webforms, I would place a ContentPlaceHolder in the head so that other pages can have specific CSS and JavaScript files.</p>
<p>In Rails, this is done utilizing yield and content_for</p>
<p>File: application.haml</p>
<pre><code>%html
%head
- yield :style
</code></pre>
<p>File: page.haml</p>
<pre><code>- content_for :style do
/ specific styles for this page
</code></pre>
<p>In NHaml, I can do this with partials, however any partials are global for the entire controller folder.</p>
<p>File: application.haml</p>
<pre><code>!!!
%html{xmlns="http://www.w3.org/1999/xhtml"}
%head
_ Style
</code></pre>
<p>File: _Style.haml</p>
<pre><code>%link{src="http://www.thescore.com/css/style.css?version=1.1" type="text/css"}
</code></pre>
<p>Does anyone know of a way to get NHaml to work in the Rails scenario?</p>
| [
{
"answer_id": 499496,
"author": "Parsa",
"author_id": 60996,
"author_profile": "https://Stackoverflow.com/users/60996",
"pm_score": 2,
"selected": false,
"text": "<p>Use the ^ evaluator in the master page, and set it's value in each of the layouts(content pages).<br/></p>\n\n<p>See <a h... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3412/"
] | I am currently starting a project utilizing ASP.NET MVC and would like to use NHaml as my view engine as I love Haml from Rails/Merb. The main issue I face is the laying out of my pages. In Webforms, I would place a ContentPlaceHolder in the head so that other pages can have specific CSS and JavaScript files.
In Rails, this is done utilizing yield and content\_for
File: application.haml
```
%html
%head
- yield :style
```
File: page.haml
```
- content_for :style do
/ specific styles for this page
```
In NHaml, I can do this with partials, however any partials are global for the entire controller folder.
File: application.haml
```
!!!
%html{xmlns="http://www.w3.org/1999/xhtml"}
%head
_ Style
```
File: \_Style.haml
```
%link{src="http://www.thescore.com/css/style.css?version=1.1" type="text/css"}
```
Does anyone know of a way to get NHaml to work in the Rails scenario? | Use the ^ evaluator in the master page, and set it's value in each of the layouts(content pages).
See [NHaml Samples](http://code.google.com/p/nhaml/source/browse/tags/1.4.0/src/Samples/NHaml.Samples.Mvc/) from it's source on [Google Code](http://code.google.com). |
127,283 | <p>I'm having an annoying problem registering a javascript event from inside a user control within a formview in an Async panel. I go to my formview, and press a button to switch into insert mode. This doesn't do a full page postback. Within insert mode, my user control's page_load event should then register a javascript event using ScriptManager.RegisterStartupScript:</p>
<pre><code>ScriptManager.RegisterStartupScript(base.Page, this.GetType(), ("dialogJavascript" + this.ID), "alert(\"Registered\");", true);
</code></pre>
<p>However when I look at my HTML source, the event isn't there. Hence the alert box is never shown. This is the setup of my actual aspx file:</p>
<pre><code><igmisc:WebAsyncRefreshPanel ID="WebAsyncRefreshPanel1" runat="server">
<asp:FormView ID="FormView1" runat="server" DataSourceID="odsCurrentIncident">
<EditItemTemplate>
<uc1:SearchSEDUsers ID="SearchSEDUsers1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
Hello
<asp:Button ID="Button1" runat="server" CommandName="Edit" Text="Button" />
</ItemTemplate>
</asp:FormView>
</igmisc:WebAsyncRefreshPanel>
</code></pre>
<p>Does anyone have any idea what I might be missing here?</p>
| [
{
"answer_id": 127491,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried using RegisterClientSideScript? You can always check the key for the script with IsClientSideScriptReg... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17885/"
] | I'm having an annoying problem registering a javascript event from inside a user control within a formview in an Async panel. I go to my formview, and press a button to switch into insert mode. This doesn't do a full page postback. Within insert mode, my user control's page\_load event should then register a javascript event using ScriptManager.RegisterStartupScript:
```
ScriptManager.RegisterStartupScript(base.Page, this.GetType(), ("dialogJavascript" + this.ID), "alert(\"Registered\");", true);
```
However when I look at my HTML source, the event isn't there. Hence the alert box is never shown. This is the setup of my actual aspx file:
```
<igmisc:WebAsyncRefreshPanel ID="WebAsyncRefreshPanel1" runat="server">
<asp:FormView ID="FormView1" runat="server" DataSourceID="odsCurrentIncident">
<EditItemTemplate>
<uc1:SearchSEDUsers ID="SearchSEDUsers1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
Hello
<asp:Button ID="Button1" runat="server" CommandName="Edit" Text="Button" />
</ItemTemplate>
</asp:FormView>
</igmisc:WebAsyncRefreshPanel>
```
Does anyone have any idea what I might be missing here? | Have you tried using RegisterClientSideScript? You can always check the key for the script with IsClientSideScriptRegistered to ensure you don't register it multiple times.
I'm assuming the async panel is doing a partial page past back which doesn't trigger the mechansim to regenerate the startup scripts. Perhaps someone with a better understanding of the ASP.Net Page Life Cycle and the CLR can fill in those blanks. |
127,290 | <p>Is there a side effect in doing this:</p>
<p>C code:</p>
<pre><code>struct foo {
int k;
};
int ret_foo(const struct foo* f){
return f.k;
}
</code></pre>
<p>C++ code:</p>
<pre><code>class bar : public foo {
int my_bar() {
return ret_foo( (foo)this );
}
};
</code></pre>
<p>There's an <code>extern "C"</code> around the C++ code and each code is inside its own compilation unit.</p>
<p>Is this portable across compilers?</p>
| [
{
"answer_id": 127312,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Wow, that's evil.</p>\n\n<blockquote>\n <p>Is this portable across compilers?</p>\n</blockquote>\n\n<p>Most defin... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21648/"
] | Is there a side effect in doing this:
C code:
```
struct foo {
int k;
};
int ret_foo(const struct foo* f){
return f.k;
}
```
C++ code:
```
class bar : public foo {
int my_bar() {
return ret_foo( (foo)this );
}
};
```
There's an `extern "C"` around the C++ code and each code is inside its own compilation unit.
Is this portable across compilers? | This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.
There is one caveat here. There is *no guarantee* of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor.
I *have* had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case. |
127,316 | <p>I first got an error usign the code below, explaining that "DataGridLinkButton' must be placed inside a form tag with runat=server."</p>
<p>Now I've tried setting AllowSorting to false, as well as removing the sort expression from each column, with the same error. Then I tried creating a new, plain, DataGrid, with the same data source, but now I get a blank page and FF doesn't recognise the content type properly any more. Please help.</p>
<pre><code>Response.Clear();
base.Response.Buffer = true;
base.Response.ContentType = "application/vnd.ms-excel";
base.Response.AddHeader("Content-Disposition", "attachment;filename=file.xls");
base.Response.Charset = "";
this.EnableViewState = false;
StringWriter writer = new StringWriter();
HtmlTextWriter writer2 = new HtmlTextWriter(writer);
this.lblExport.RenderControl(writer2);
base.Response.Write(writer.ToString());
</code></pre>
| [
{
"answer_id": 127334,
"author": "Erikk Ross",
"author_id": 18772,
"author_profile": "https://Stackoverflow.com/users/18772",
"pm_score": 2,
"selected": true,
"text": "<p>Add the following empty method to your code. That should fix it. </p>\n\n<pre><code>public override void VerifyRender... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | I first got an error usign the code below, explaining that "DataGridLinkButton' must be placed inside a form tag with runat=server."
Now I've tried setting AllowSorting to false, as well as removing the sort expression from each column, with the same error. Then I tried creating a new, plain, DataGrid, with the same data source, but now I get a blank page and FF doesn't recognise the content type properly any more. Please help.
```
Response.Clear();
base.Response.Buffer = true;
base.Response.ContentType = "application/vnd.ms-excel";
base.Response.AddHeader("Content-Disposition", "attachment;filename=file.xls");
base.Response.Charset = "";
this.EnableViewState = false;
StringWriter writer = new StringWriter();
HtmlTextWriter writer2 = new HtmlTextWriter(writer);
this.lblExport.RenderControl(writer2);
base.Response.Write(writer.ToString());
``` | Add the following empty method to your code. That should fix it.
```
public override void VerifyRenderingInServerForm(Control control)
{
}
``` |
127,318 | <p>I want to programmatically edit file content using windows command line (<a href="http://en.wikipedia.org/wiki/Windows_command_line" rel="noreferrer">cmd.exe</a>). In *nix there is <a href="http://en.wikipedia.org/wiki/Sed" rel="noreferrer">sed</a> for this tasks. Is there any useful native equivalent in windows?</p>
| [
{
"answer_id": 127330,
"author": "robintw",
"author_id": 1912,
"author_profile": "https://Stackoverflow.com/users/1912",
"pm_score": 3,
"selected": false,
"text": "<p>You could install Cygwin (<a href=\"http://www.cygwin.com/\" rel=\"noreferrer\">http://www.cygwin.com/</a>) and use sed f... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | I want to programmatically edit file content using windows command line ([cmd.exe](http://en.wikipedia.org/wiki/Windows_command_line)). In \*nix there is [sed](http://en.wikipedia.org/wiki/Sed) for this tasks. Is there any useful native equivalent in windows? | Today powershell saved me.
For `grep` there is:
```
get-content somefile.txt | where { $_ -match "expression"}
```
or
```
select-string somefile.txt -pattern "expression"
```
and for `sed` there is:
```
get-content somefile.txt | %{$_ -replace "expression","replace"}
```
For more detail about replace PowerShell function see [this Microsoft article](https://devblogs.microsoft.com/scripting/use-powershell-to-replace-text-in-strings/). |
127,328 | <p>I have a class that defines the names of various constants, e.g.</p>
<pre><code>class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
</code></pre>
<p>I would like to use these constants within a JSP <strong>without</strong> using Scriptlet code such as:</p>
<pre><code><%@ page import="com.example.Constants" %>
<%= Constants.ATTR_CURRENT_USER %>
</code></pre>
<p>There appears to be a tag in the Apache <a href="http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants" rel="noreferrer">unstandard</a> taglib that provides this functionality. However, I cannot find any way to download this taglib. I'm beginning to wonder if it's been deprecated and the functionality has been moved to another (Apache) tag library?</p>
<p>Does anyone know where I can get this library, or if it's not available, if there's some other way I can access constants in a JSP without using scriptlet code?</p>
<p>Cheers,
Don</p>
| [
{
"answer_id": 127384,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": -1,
"selected": false,
"text": "<p>Why do you want to print the value of the constant on the JSP? Surely you are defining them so that in the JSP you can ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] | I have a class that defines the names of various constants, e.g.
```
class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
```
I would like to use these constants within a JSP **without** using Scriptlet code such as:
```
<%@ page import="com.example.Constants" %>
<%= Constants.ATTR_CURRENT_USER %>
```
There appears to be a tag in the Apache [unstandard](http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants) taglib that provides this functionality. However, I cannot find any way to download this taglib. I'm beginning to wonder if it's been deprecated and the functionality has been moved to another (Apache) tag library?
Does anyone know where I can get this library, or if it's not available, if there's some other way I can access constants in a JSP without using scriptlet code?
Cheers,
Don | On application startup, you can add the Constants class to the servletContext and then access it in any jsp page
```
servletContext.setAttribute("Constants", com.example.Constants);
```
and then access it in a jsp page
```
<c:out value="${Constants.ATTR_CURRENT_USER}"/>
```
(you might have to create getters for each constant) |
127,336 | <p>Outlook saves its client-side rule definitions in a binary blob in a hidden message in the Inbox folder of the default store for a profile. The hidden message is named <em>"Outlook Rules Organizer"</em> with a message class <code>IPM.RuleOrganizer</code>. The binary blob is saved in property 0x6802. The same binary blob is written to the exported RWZ file when you manually export the rules through the Rules and Alerts Wizard.</p>
<p>Has anyone deciphered the layout of this binary blob?</p>
| [
{
"answer_id": 127384,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": -1,
"selected": false,
"text": "<p>Why do you want to print the value of the constant on the JSP? Surely you are defining them so that in the JSP you can ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21685/"
] | Outlook saves its client-side rule definitions in a binary blob in a hidden message in the Inbox folder of the default store for a profile. The hidden message is named *"Outlook Rules Organizer"* with a message class `IPM.RuleOrganizer`. The binary blob is saved in property 0x6802. The same binary blob is written to the exported RWZ file when you manually export the rules through the Rules and Alerts Wizard.
Has anyone deciphered the layout of this binary blob? | On application startup, you can add the Constants class to the servletContext and then access it in any jsp page
```
servletContext.setAttribute("Constants", com.example.Constants);
```
and then access it in a jsp page
```
<c:out value="${Constants.ATTR_CURRENT_USER}"/>
```
(you might have to create getters for each constant) |
127,386 | <p>In Visual Studio, we've all had "baadf00d", have seen seen "CC" and "CD" when inspecting variables in the debugger in C++ during run-time.</p>
<p>From what I understand, "CC" is in DEBUG mode only to indicate when a memory has been new() or alloc() and unitilialized. While "CD" represents delete'd or free'd memory. I've only seen "baadf00d" in RELEASE build (but I may be wrong).</p>
<p>Once in a while, we get into a situation of tacking memory leaks, buffer overflows, etc and these kind of information comes in handy.</p>
<p>Would somebody be kind enough to point out when and in what modes the memory are set to recognizable byte patterns for debugging purpose?</p>
| [
{
"answer_id": 127404,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 9,
"selected": true,
"text": "<p>This link has more information:</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values\... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7234/"
] | In Visual Studio, we've all had "baadf00d", have seen seen "CC" and "CD" when inspecting variables in the debugger in C++ during run-time.
From what I understand, "CC" is in DEBUG mode only to indicate when a memory has been new() or alloc() and unitilialized. While "CD" represents delete'd or free'd memory. I've only seen "baadf00d" in RELEASE build (but I may be wrong).
Once in a while, we get into a situation of tacking memory leaks, buffer overflows, etc and these kind of information comes in handy.
Would somebody be kind enough to point out when and in what modes the memory are set to recognizable byte patterns for debugging purpose? | This link has more information:
<https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values>
```
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
``` |
127,389 | <p>Today I stumbled about a Problem which seems to be a bug in the Zend-Framework. Given the following route:</p>
<pre><code><test>
<route>citytest/:city</route>
<defaults>
<controller>result</controller>
<action>test</action>
</defaults>
<reqs>
<city>.+</city>
</reqs>
</test>
</code></pre>
<p>and three Urls:</p>
<ul>
<li>mysite.local/citytest/Berlin</li>
<li>mysite.local/citytest/Hamburg</li>
<li>mysite.local/citytest/M%FCnchen </li>
</ul>
<p>the last Url does not match and thus the correct controller is not called. Anybody got a clue why?</p>
<p>Fyi, where are using Zend-Framework 1.0 ( Yeah, I know that's ancient but I am not in charge to change that :-/ )</p>
<p>Edit: From what I hear, we are going to upgrade to Zend 1.5.6 soon, but I don't know when, so a Patch would be great.</p>
<p>Edit: I've tracked it down to the following line (Zend/Controller/Router/Route.php:170):</p>
<pre><code>$regex = $this->_regexDelimiter . '^' .
$part['regex'] . '$' .
$this->_regexDelimiter . 'iu';
</code></pre>
<p>If I change that to </p>
<pre><code> $this->_regexDelimiter . 'i';
</code></pre>
<p>it works. From what I understand, the u-modifier is for working with asian characters. As I don't use them, I'm fine with that patch for know. Thanks for reading.</p>
| [
{
"answer_id": 127818,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 1,
"selected": false,
"text": "<p>The u modifier makes the regexp expect utf-8 input. This would suggest that ZF expects utf-8 encoded input, and not IS... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18606/"
] | Today I stumbled about a Problem which seems to be a bug in the Zend-Framework. Given the following route:
```
<test>
<route>citytest/:city</route>
<defaults>
<controller>result</controller>
<action>test</action>
</defaults>
<reqs>
<city>.+</city>
</reqs>
</test>
```
and three Urls:
* mysite.local/citytest/Berlin
* mysite.local/citytest/Hamburg
* mysite.local/citytest/M%FCnchen
the last Url does not match and thus the correct controller is not called. Anybody got a clue why?
Fyi, where are using Zend-Framework 1.0 ( Yeah, I know that's ancient but I am not in charge to change that :-/ )
Edit: From what I hear, we are going to upgrade to Zend 1.5.6 soon, but I don't know when, so a Patch would be great.
Edit: I've tracked it down to the following line (Zend/Controller/Router/Route.php:170):
```
$regex = $this->_regexDelimiter . '^' .
$part['regex'] . '$' .
$this->_regexDelimiter . 'iu';
```
If I change that to
```
$this->_regexDelimiter . 'i';
```
it works. From what I understand, the u-modifier is for working with asian characters. As I don't use them, I'm fine with that patch for know. Thanks for reading. | The problem is the following:
>
> Using the /u pattern modifier prevents
> words from being mangled but instead
> PCRE skips strings of characters with
> code values greater than 127.
> Therefore, \w will not match a
> multibyte (non-lower ascii) word at
> all (but also won’t return portions of
> it). From the pcrepattern man page;
>
>
> In UTF-8 mode, characters with values
> greater than 128 never match \d, \s,
> or \w, and always match \D, \S, and
> \W. This is true even when Unicode
> character property support is
> available.
>
>
>
From [Handling UTF-8 with PHP](http://www.phpwact.org/php/i18n/utf-8#w_w_b_b_meta_characters).
Therefore it's actually irrelevant if your URL is ISO-8859-1 encoded (mysite.local/citytest/M%FCnchen) or UTF-8 encoded (mysite.local/citytest/M%C3%BCnchen), the default regex won't match.
I also made experiments with umlauts in URLs in Zend Framework and came to the conclusion that you wouldn't really want umlauts in your URLs. The problem is, that you cannot rely on the encoding used by the browser for the URL. Firefox (prior to 3.0) for example does not UTF-8 encode URLs entered into the address textbox (if not specified in about:config) and IE does have a checkbox within its options to choose between regular and UTF-8 encoding for its URLs. But if you click on links within a page both browsers use the URL in the given encoding (UTF-8 on an UTF-8 page). Therefore you cannot be sure in which encoding the URLs are sent to your application - and detecting the encoding used is not that trivial to do.
Perhaps it's better to use transliterated parameters in your URLs (e.g. change Ä to Ae and so on). There is a really simple way to this (I don't know if this works with every language but I'm using it with German strings and it works quite well):
```
function createUrlFriendlyName($name) // $name must be an UTF-8 encoded string
{
$name=mb_convert_encoding(trim($name), 'HTML-ENTITIES', 'UTF-8');
$name=preg_replace(
array('/ß/', '/&(..)lig;/', '/&([aouAOU])uml;/', '/&(.)[^;]*;/', '/\W/'),
array('ss', '$1', '$1e', '$1', '-'),
$name);
$name=preg_replace('/-{2,}/', '-', $name);
return trim($name, '-');
}
``` |
127,391 | <p>I was asked a question in C last night and I did not know the answer since I have not used C much since college so I thought maybe I could find the answer here instead of just forgetting about it.</p>
<p>If a person has a define such as:</p>
<pre><code>#define count 1
</code></pre>
<p>Can that person find the variable name <code>count</code> using the 1 that is inside it?</p>
<p>I did not think so since I thought the count would point to the 1 but do not see how the 1 could point back to count.</p>
| [
{
"answer_id": 127402,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 0,
"selected": false,
"text": "<p>What do you mean by \"finding\"?</p>\n\n<p>The line </p>\n\n<pre><code>#define count 1\n</code></pre>\n\n<p>defines a sy... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16354/"
] | I was asked a question in C last night and I did not know the answer since I have not used C much since college so I thought maybe I could find the answer here instead of just forgetting about it.
If a person has a define such as:
```
#define count 1
```
Can that person find the variable name `count` using the 1 that is inside it?
I did not think so since I thought the count would point to the 1 but do not see how the 1 could point back to count. | The simple answer is no they can't. #Defines like that are dealt with by the preprocessor, and they only point in one direction. Of course the other problem is that even the compiler wouldn't know - as a "1" could point to anything - multiple variables can have the same value at the same time. |
127,395 | <p>Is there a way when creating web services to specify the types to use? Specifically, I want to be able to use the same type on both the client and server to reduce duplication of code.</p>
<p>Over simplified example:</p>
<pre><code> public class Name
{
public string FirstName {get; set;}
public string Surname { get; set; }
public override string ToString()
{
return string.Concat(FirstName, " ", Surname);
}
}
</code></pre>
<p>I don't want to have recode pieces of functionality in my class. The other thing is that any code that exists that manipulates this class won't work client side as the client side class that is generated would be a different type.</p>
| [
{
"answer_id": 127910,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to have a type or structure shared between your web service and your client, add a public struct to you... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9539/"
] | Is there a way when creating web services to specify the types to use? Specifically, I want to be able to use the same type on both the client and server to reduce duplication of code.
Over simplified example:
```
public class Name
{
public string FirstName {get; set;}
public string Surname { get; set; }
public override string ToString()
{
return string.Concat(FirstName, " ", Surname);
}
}
```
I don't want to have recode pieces of functionality in my class. The other thing is that any code that exists that manipulates this class won't work client side as the client side class that is generated would be a different type. | Okay, I see know that this has been an explicit design decision on the part of SOAP so you're not actually supposed to do this. I found the following [page](http://msdn.microsoft.com/en-us/library/ms978594.aspx) that explains why:
>
> **Services share schema and contract,
> not class**. Services interact solely on
> their expression of structures through
> schemas and behaviors through
> contracts. The service's contract
> describes the structure of messages
> and ordering constraints over
> messages. The formality of the
> expression allows machine verification
> of incoming messages. Machine
> verification of incoming messages
> allows you to protect the service's
> integrity. Contracts and schemas must
> remain stable over time, so building
> them flexibly is important.
>
>
>
Having said that there are two other possibilities:
1. Generate the the web references in Visual Studio or using wsdl.exe. Then go into the generated Reference.cs (or .vb) file and delete the type explicitly. Then redirect to the type that you want that is located in another assembly.
2. You can share types between web services on the client side by wsdl.exe and the /sharetypes parameter. |
127,413 | <p>I have user control named DateTimeUC which has two textboxes on its markup:</p>
<pre><code><asp:TextBox ID="dateTextBox" runat="server"></asp:TextBox>
<asp:TextBox ID="timeTextBox" runat="server"></asp:TextBox>
</code></pre>
<p>I am dynamically creating this control in another user control:</p>
<pre><code>Controls.Add(GenerateDateTime(parameter));
private DateTimeUC GenerateDateTime(SomeParameter parameter)
{
DateTimeUC uc = new DateTimeUC();
uc.ID = parameter.Name;
return uc;
}
</code></pre>
<p>But when I render the page, DateTimeUC renders nothing. I checked it like this:</p>
<pre><code>protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
StringBuilder builder = new StringBuilder();
StringWriter swriter = new StringWriter(builder);
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
base.Render(hwriter);
string s = builder.ToString();
}
</code></pre>
<p>s is empty and Controls.Count is 0. What am I doing wrong?</p>
| [
{
"answer_id": 127438,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 4,
"selected": true,
"text": "<p>You must use the <code>LoadControl( \"your_user_control_app_relative_path.ascx\" )</code> method instead of \"DateTimeUC uc... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | I have user control named DateTimeUC which has two textboxes on its markup:
```
<asp:TextBox ID="dateTextBox" runat="server"></asp:TextBox>
<asp:TextBox ID="timeTextBox" runat="server"></asp:TextBox>
```
I am dynamically creating this control in another user control:
```
Controls.Add(GenerateDateTime(parameter));
private DateTimeUC GenerateDateTime(SomeParameter parameter)
{
DateTimeUC uc = new DateTimeUC();
uc.ID = parameter.Name;
return uc;
}
```
But when I render the page, DateTimeUC renders nothing. I checked it like this:
```
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
StringBuilder builder = new StringBuilder();
StringWriter swriter = new StringWriter(builder);
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
base.Render(hwriter);
string s = builder.ToString();
}
```
s is empty and Controls.Count is 0. What am I doing wrong? | You must use the `LoadControl( "your_user_control_app_relative_path.ascx" )` method instead of "DateTimeUC uc = new DateTimeUC();" |
127,426 | <p>I have defined an interface in C++, i.e. a class containing only pure virtual functions.</p>
<p>I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like:</p>
<pre><code>class ITest{
public:
virtual void doSomething() = 0;
protected:
~ITest(){}
};
void someFunction(ITest * test){
test->doSomething(); // ok
// deleting object is not allowed
// delete test;
}
</code></pre>
<p>The GNU compiler gives me a warning saying:</p>
<blockquote>
<p>class 'ITest' has virtual functions but non-virtual destructor</p>
</blockquote>
<p>Once the destructor is protected, what is the difference in having it virtual or non-virtual?</p>
<p>Do you think this warning can be safely ignored or silenced?</p>
| [
{
"answer_id": 127453,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 0,
"selected": false,
"text": "<p>If the destructor is virtual it makes sure that the base class destructor is also called fore doing the cleanup, otherwise ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622/"
] | I have defined an interface in C++, i.e. a class containing only pure virtual functions.
I want to explicitly forbid users of the interface to delete the object through a pointer to the interface, so I declared a protected and non-virtual destructor for the interface, something like:
```
class ITest{
public:
virtual void doSomething() = 0;
protected:
~ITest(){}
};
void someFunction(ITest * test){
test->doSomething(); // ok
// deleting object is not allowed
// delete test;
}
```
The GNU compiler gives me a warning saying:
>
> class 'ITest' has virtual functions but non-virtual destructor
>
>
>
Once the destructor is protected, what is the difference in having it virtual or non-virtual?
Do you think this warning can be safely ignored or silenced? | It's more or less a bug in the compiler. Note that in more recent versions of the compiler this warning does not get thrown (at least in 4.3 it doesn't). Having the destructor be protected and non-virtual is completely legitimate in your case.
See [here](http://www.gotw.ca/publications/mill18.htm) for an excellent article by Herb Sutter on the subject. From the article:
Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual. |
127,459 | <p>I need to be able to change the users' password through a web page (in a controlled environment).
So, for that, I'm using this code:</p>
<pre><code><?php
$output = shell_exec("sudo -u dummy passwd testUser testUserPassword");
$output2 = shell_exec("dummyPassword");
echo $output;
echo $output2;
echo "done";
?>
</code></pre>
<p>My problem is that this script is not changing the password for the user "testUser".
What am I doing wrong?</p>
<p>Thanks</p>
| [
{
"answer_id": 127495,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not familiar enough with PHP to tell you how to fix it, but your problem is that the two <code>shell_exec</code> comma... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019426/"
] | I need to be able to change the users' password through a web page (in a controlled environment).
So, for that, I'm using this code:
```
<?php
$output = shell_exec("sudo -u dummy passwd testUser testUserPassword");
$output2 = shell_exec("dummyPassword");
echo $output;
echo $output2;
echo "done";
?>
```
My problem is that this script is not changing the password for the user "testUser".
What am I doing wrong?
Thanks | I'm not familiar enough with PHP to tell you how to fix it, but your problem is that the two `shell_exec` commands are entirely separate. It appears as though you're trying to use the second command to pipe input to the first one, but that's not possible. The first command shouldn't return until after that process has executed, when you run the second one it will attempt to run the program `dummyPassword`, which we can probably expect to fail. |
127,477 | <p>In WPF you can setup validation based on errors thrown in your Data Layer during Data Binding using the <code>ExceptionValidationRule</code> or <code>DataErrorValidationRule</code>.</p>
<p>Suppose you had a bunch of controls set up this way and you had a Save button. When the user clicks the Save button, you need to make sure there are no validation errors before proceeding with the save. If there are validation errors, you want to holler at them.</p>
<p>In WPF, how do you find out if any of your Data Bound controls have validation errors set?</p>
| [
{
"answer_id": 127526,
"author": "user21243",
"author_id": 21243,
"author_profile": "https://Stackoverflow.com/users/21243",
"pm_score": 0,
"selected": false,
"text": "<p>You can iterate over all your controls tree recursively and check the attached property Validation.HasErrorProperty, ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4407/"
] | In WPF you can setup validation based on errors thrown in your Data Layer during Data Binding using the `ExceptionValidationRule` or `DataErrorValidationRule`.
Suppose you had a bunch of controls set up this way and you had a Save button. When the user clicks the Save button, you need to make sure there are no validation errors before proceeding with the save. If there are validation errors, you want to holler at them.
In WPF, how do you find out if any of your Data Bound controls have validation errors set? | This post was extremely helpful. Thanks to all who contributed. Here is a LINQ version that you will either love or hate.
```
private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsValid(sender as DependencyObject);
}
private bool IsValid(DependencyObject obj)
{
// The dependency object is valid if it has no errors and all
// of its children (that are dependency objects) are error-free.
return !Validation.GetHasError(obj) &&
LogicalTreeHelper.GetChildren(obj)
.OfType<DependencyObject>()
.All(IsValid);
}
``` |
127,492 | <p>I have an EAR file that contains two WARs, war1.war and war2.war. My application.xml file looks like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<application version="5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd">
<display-name>MyEAR</display-name>
<module>
<web>
<web-uri>war1.war</web-uri>
<context-root>/</context-root>
</web>
</module>
<module>
<web>
<web-uri>war2.war</web-uri>
<context-root>/war2location</context-root>
</web>
</module>
</application>
</code></pre>
<p>This results in war2.war being available on <strong><a href="http://localhost:8080/war2location" rel="nofollow noreferrer">http://localhost:8080/war2location</a></strong>, which is correct, but war1.war is on <strong><a href="http://localhost:8080//" rel="nofollow noreferrer">http://localhost:8080//</a></strong> -- note the two slashes.</p>
<p>What am I doing wrong?</p>
<p>Note that the WARs' sun-web.xml files get ignored when contained in an EAR.</p>
| [
{
"answer_id": 127548,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "<p><code>http://localhost:8080//</code> should still be a valid URL that is equivalent to <code>http://localhost:8080/</... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13455/"
] | I have an EAR file that contains two WARs, war1.war and war2.war. My application.xml file looks like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<application version="5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd">
<display-name>MyEAR</display-name>
<module>
<web>
<web-uri>war1.war</web-uri>
<context-root>/</context-root>
</web>
</module>
<module>
<web>
<web-uri>war2.war</web-uri>
<context-root>/war2location</context-root>
</web>
</module>
</application>
```
This results in war2.war being available on **<http://localhost:8080/war2location>**, which is correct, but war1.war is on **<http://localhost:8080//>** -- note the two slashes.
What am I doing wrong?
Note that the WARs' sun-web.xml files get ignored when contained in an EAR. | In Glassfish 3.0.1 you can define the default web application in the administration console:
"Configuration\Virtual Servers\server\Default Web Module".
The drop-down box contains all deployed war modules.
The default web module is then accessible from <http://localhost:8080/>. |
127,514 | <p>I am writing a program which has two panes (via <code>CSplitter</code>), however I am having problems figuring out out to resize the controls in each frame. For simplicity, can someone tell me how I would do it for a basic frame with a single <code>CEdit</code> control? </p>
<p>I'm fairly sure it is to do with the <code>CEdit::OnSize()</code> function... But I'm not really getting anywhere...</p>
<p>Thanks! :)</p>
| [
{
"answer_id": 127520,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 4,
"selected": true,
"text": "<p>When your frame receives an OnSize message it will give you the new width and height - you can simply call the CEdit SetWindow... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] | I am writing a program which has two panes (via `CSplitter`), however I am having problems figuring out out to resize the controls in each frame. For simplicity, can someone tell me how I would do it for a basic frame with a single `CEdit` control?
I'm fairly sure it is to do with the `CEdit::OnSize()` function... But I'm not really getting anywhere...
Thanks! :) | When your frame receives an OnSize message it will give you the new width and height - you can simply call the CEdit SetWindowPos method passing it these values.
Assume CMyPane is your splitter pane and it contains a CEdit you created in OnCreate called m\_wndEdit:
```
void CMyPane::OnSize(UINT nType, int cx, int cy)
{
m_wndEdit.SetWindowPos(NULL, 0, 0, cx, cy, SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER);
}
``` |
127,530 | <p>I'm adding a new field to a list and view. To add the field to the view, I'm using this code:</p>
<pre><code>view.ViewFields.Add("My New Field");
</code></pre>
<p>However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available.</p>
| [
{
"answer_id": 127859,
"author": "Alex Angas",
"author_id": 6651,
"author_profile": "https://Stackoverflow.com/users/6651",
"pm_score": 3,
"selected": true,
"text": "<p>I've found removing all items from the list and readding them in the order that I'd like works well (although a little ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] | I'm adding a new field to a list and view. To add the field to the view, I'm using this code:
```
view.ViewFields.Add("My New Field");
```
However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available. | I've found removing all items from the list and readding them in the order that I'd like works well (although a little drastic). Here is the code I'm using:
```
string[] fieldNames = new string[] { "Title", "My New Field", "Modified", "Created" };
SPViewFieldCollection viewFields = view.ViewFields;
viewFields.DeleteAll();
foreach (string fieldName in fieldNames)
{
viewFields.Add(fieldName);
}
view.Update();
``` |
127,556 | <p>I have a listbox where the items contain checkboxes:</p>
<pre><code><ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Click="Checkbox_Click" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Content="{Binding Path=DisplayText}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>The problem I'm having is that when I click on the checkbox or its content, the parent ListBoxItem does not get selected. If I click on the white space next to the checkbox, the ListBoxItem does get selected.</p>
<p>The behavior that I'm trying to get is to be able to select one or many items in the list and use the spacebar to toggle the checkboxes on and off.</p>
<p>Some more info:</p>
<pre><code>private void Checkbox_Click(object sender, RoutedEventArgs e)
{
CheckBox chkBox = e.OriginalSource as CheckBox;
}
</code></pre>
<p>In the code above when I click on a checkbox, e.Handled is false and chkBox.Parent is null.</p>
<p>Kent's answer put me down the right path, here's what I ended up with:</p>
<pre><code><ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox" PreviewKeyDown="ListBox_PreviewKeyDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" />
<TextBlock Text="{Binding DisplayText}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>I had to use PreviewKeyDown because by default when you hit the spacebar in a list box, it deselects everything except for the most recently selected item.</p>
| [
{
"answer_id": 127589,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 4,
"selected": true,
"text": "<p>To begin with, put the content outside the <code>CheckBox</code>:</p>\n\n<pre><code><StackPanel Orientation=\"Hor... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2284/"
] | I have a listbox where the items contain checkboxes:
```
<ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Click="Checkbox_Click" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Content="{Binding Path=DisplayText}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
The problem I'm having is that when I click on the checkbox or its content, the parent ListBoxItem does not get selected. If I click on the white space next to the checkbox, the ListBoxItem does get selected.
The behavior that I'm trying to get is to be able to select one or many items in the list and use the spacebar to toggle the checkboxes on and off.
Some more info:
```
private void Checkbox_Click(object sender, RoutedEventArgs e)
{
CheckBox chkBox = e.OriginalSource as CheckBox;
}
```
In the code above when I click on a checkbox, e.Handled is false and chkBox.Parent is null.
Kent's answer put me down the right path, here's what I ended up with:
```
<ListBox Style="{StaticResource CheckBoxListStyle}" Name="EditListBox" PreviewKeyDown="ListBox_PreviewKeyDown">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" />
<TextBlock Text="{Binding DisplayText}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
I had to use PreviewKeyDown because by default when you hit the spacebar in a list box, it deselects everything except for the most recently selected item. | To begin with, put the content outside the `CheckBox`:
```
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding DisplayText}"/>
</StackPanel>
```
After that, you will need to ensure that pressing space on a `ListBoxItem` results in the `CheckBox` being checked. There are a number of ways of doing this, including a simple event handler on the `ListBoxItem`. Or you could specify a handler for `UIElement.KeyUp` or whatever in your `DataTemplate`:
```
<CheckBox IsChecked="{Binding IsChecked}" UIElement.KeyUp="..."/>
``` |
127,587 | <p>I'm trying to use <a href="http://trac.videolan.org/jvlc/" rel="nofollow noreferrer">JVLC</a> but I can't seem to get it work. I've downloaded the jar, I installed <a href="http://www.videolan.org/vlc/" rel="nofollow noreferrer">VLC</a> and passed the -D argument to the JVM telling it where VLC is installed. I also tried:</p>
<pre><code>NativeLibrary.addSearchPath("libvlc", "C:\\Program Files\\VideoLAN\\VLC");
</code></pre>
<p>with no luck. I always get:</p>
<blockquote>
<p>Exception in thread "main"
java.lang.UnsatisfiedLinkError: Unable
to load library 'libvlc': The
specified module could not be found.</p>
</blockquote>
<p>Has anyone made it work?</p>
| [
{
"answer_id": 127875,
"author": "Kris Kumler",
"author_id": 4281,
"author_profile": "https://Stackoverflow.com/users/4281",
"pm_score": 5,
"selected": false,
"text": "<p>My favorite is the command <code>.cmdtree <file></code> (undocumented, but referenced in previous release notes... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20459/"
] | I'm trying to use [JVLC](http://trac.videolan.org/jvlc/) but I can't seem to get it work. I've downloaded the jar, I installed [VLC](http://www.videolan.org/vlc/) and passed the -D argument to the JVM telling it where VLC is installed. I also tried:
```
NativeLibrary.addSearchPath("libvlc", "C:\\Program Files\\VideoLAN\\VLC");
```
with no luck. I always get:
>
> Exception in thread "main"
> java.lang.UnsatisfiedLinkError: Unable
> to load library 'libvlc': The
> specified module could not be found.
>
>
>
Has anyone made it work? | My favorite is the command `.cmdtree <file>` (undocumented, but referenced in previous release notes). This can assist in bringing up another window (that can be docked) to display helpful or commonly used commands. This can help make the user much more productive using the tool.
Initially talked about here, with an example for the `<file>` parameter:
<http://blogs.msdn.com/debuggingtoolbox/archive/2008/09/17/special-command-execute-commands-from-a-customized-user-interface-with-cmdtree.aspx>
Example:
[alt text http://blogs.msdn.com/photos/debuggingtoolbox/images/8954736/original.aspx](http://blogs.msdn.com/photos/debuggingtoolbox/images/8954736/original.aspx) |
127,598 | <p>So, I have Flex project that loads a Module using the ModuleManager - not the module loader. The problem that I'm having is that to load an external asset (like a video or image) the path to load that asset has to be relative to the Module swf...not relative to the swf that loaded the module.</p>
<p>The question is - How can I load an asset into a loaded module using a path relative to the parent swf, not the module swf?</p>
<hr>
<p>Arg! So in digging through the SWFLoader Class I found this chunk of code in private function loadContent:</p>
<pre><code> // make relative paths relative to the SWF loading it, not the top-level SWF
if (!(url.indexOf(":") > -1 || url.indexOf("/") == 0 || url.indexOf("\\") == 0))
{
var rootURL:String;
if (SystemManagerGlobals.bootstrapLoaderInfoURL != null && SystemManagerGlobals.bootstrapLoaderInfoURL != "")
rootURL = SystemManagerGlobals.bootstrapLoaderInfoURL;
else if (root)
rootURL = LoaderUtil.normalizeURL(root.loaderInfo);
else if (systemManager)
rootURL = LoaderUtil.normalizeURL(DisplayObject(systemManager).loaderInfo);
if (rootURL)
{
var lastIndex:int = Math.max(rootURL.lastIndexOf("\\"), rootURL.lastIndexOf("/"));
if (lastIndex != -1)
url = rootURL.substr(0, lastIndex + 1) + url;
}
}
}
</code></pre>
<p>So apparently, Adobe has gone through the extra effort to make images load in the actual swf and not the top level swf (with no flag to choose otherwise...), so I guess I should submit a feature request to have some sort of "load relative to swf" flag, edit the SWFLoader directly, or maybe I should have everything relative to the individual swf and not the top level...any suggestions?</p>
| [
{
"answer_id": 132670,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 3,
"selected": true,
"text": "<p>You can import <code>mx.core.Application</code> and then use <a href=\"http://livedocs.adobe.com/flex/3/langref/mx/core/App... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] | So, I have Flex project that loads a Module using the ModuleManager - not the module loader. The problem that I'm having is that to load an external asset (like a video or image) the path to load that asset has to be relative to the Module swf...not relative to the swf that loaded the module.
The question is - How can I load an asset into a loaded module using a path relative to the parent swf, not the module swf?
---
Arg! So in digging through the SWFLoader Class I found this chunk of code in private function loadContent:
```
// make relative paths relative to the SWF loading it, not the top-level SWF
if (!(url.indexOf(":") > -1 || url.indexOf("/") == 0 || url.indexOf("\\") == 0))
{
var rootURL:String;
if (SystemManagerGlobals.bootstrapLoaderInfoURL != null && SystemManagerGlobals.bootstrapLoaderInfoURL != "")
rootURL = SystemManagerGlobals.bootstrapLoaderInfoURL;
else if (root)
rootURL = LoaderUtil.normalizeURL(root.loaderInfo);
else if (systemManager)
rootURL = LoaderUtil.normalizeURL(DisplayObject(systemManager).loaderInfo);
if (rootURL)
{
var lastIndex:int = Math.max(rootURL.lastIndexOf("\\"), rootURL.lastIndexOf("/"));
if (lastIndex != -1)
url = rootURL.substr(0, lastIndex + 1) + url;
}
}
}
```
So apparently, Adobe has gone through the extra effort to make images load in the actual swf and not the top level swf (with no flag to choose otherwise...), so I guess I should submit a feature request to have some sort of "load relative to swf" flag, edit the SWFLoader directly, or maybe I should have everything relative to the individual swf and not the top level...any suggestions? | You can import `mx.core.Application` and then use [Application.application.url](http://livedocs.adobe.com/flex/3/langref/mx/core/Application.html#url) to get the path of the host application in your module and use that as the basis for building the URLs.
For help in dealing with URLs, see [the URLUtil class in the standard Flex libraries](http://livedocs.adobe.com/flex/3/langref/mx/utils/URLUtil.html) and [the URI class in the as3corelib project](http://as3corelib.googlecode.com/svn/trunk/docs/com/adobe/net/URI.html). |
127,606 | <p>I'm trying to generate customized xml files from a template xml file in python. </p>
<p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p>
<pre><code>conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| [
{
"answer_id": 127678,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not sure if converting the info set to nested dicts first is easier. Using ElementTree, you can do this:</p>\n\... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1489/"
] | I'm trying to generate customized xml files from a template xml file in python.
Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:
```
conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
```
now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write()
```
conf_new.write('config-new.xml')
```
Is there some way to do this, or can someone suggest doing this a different way? | For easy manipulation of XML in python, I like the [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) library. It works something like this:
Sample XML File:
```
<root>
<level1>leaf1</level1>
<level2>leaf2</level2>
</root>
```
Python code:
```
from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString
soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file
soup.contents[0].name
# u'root'
```
You can use the node names as methods:
```
soup.root.contents[0].name
# u'level1'
```
It is also possible to use regexes:
```
import re
tags_starting_with_level = soup.findAll(re.compile('^level'))
for tag in tags_starting_with_level: print tag.name
# level1
# level2
```
Adding and inserting new nodes is pretty straightforward:
```
# build and insert a new level with a new leaf
level3 = Tag(soup, 'level3')
level3.insert(0, NavigableString('leaf3')
soup.root.insert(2, level3)
print soup.prettify()
# <root>
# <level1>
# leaf1
# </level1>
# <level2>
# leaf2
# </level2>
# <level3>
# leaf3
# </level3>
# </root>
``` |
127,625 | <p>I'm currently working on a class that calculates the difference between two objects. I'm trying to decide what the best design for this class would be. I see two options:</p>
<p>1) Single-use class instance. Takes the objects to diff in the constructor and calculates the diff for that.</p>
<pre><code>public class MyObjDiffer {
public MyObjDiffer(MyObj o1, MyObj o2) {
// Calculate diff here and store results in member variables
}
public boolean areObjectsDifferent() {
// ...
}
public Vector getOnlyInObj1() {
// ...
}
public Vector getOnlyInObj2() {
// ...
}
// ...
}
</code></pre>
<p>2) Re-usable class instance. Constructor takes no arguments. Has a "calculateDiff()" method that takes the objects to diff, and returns the results.</p>
<pre><code>public class MyObjDiffer {
public MyObjDiffer() { }
public DiffResults getResults(MyObj o1, MyObj o2) {
// calculate and return the results. Nothing is stored in this class's members.
}
}
public class DiffResults {
public boolean areObjectsDifferent() {
// ...
}
public Vector getOnlyInObj1() {
// ...
}
public Vector getOnlyInObj2() {
// ...
}
}
</code></pre>
<p>The diffing will be fairly complex (details don't matter for the question), so there will need to be a number of helper functions. If I take solution 1 then I can store the data in member variables and don't have to pass everything around. It's slightly more compact, as everything is handled within a single class.</p>
<p>However, conceptually, it seems weird that a "Differ" would be specific to a certain set of results. Option 2 splits the results from the logic that actually calculates them.</p>
<p>EDIT: Option 2 also provides the ability to make the "MyObjDiffer" class static. Thanks kitsune, I forgot to mention that.</p>
<p>I'm having trouble seeing any significant pro or con to either option. I figure this kind of thing (a class that just handles some one-shot calculation) has to come up fairly often, and maybe I'm missing something. So, I figured I'd pose the question to the cloud. Are there significant pros or cons to one or the other option here? Is one inherently better? Does it matter?</p>
<p>I am doing this in Java, so there might be some restrictions on the possibilities, but the overall question of design is probably language-agnostic.</p>
| [
{
"answer_id": 127631,
"author": "kitsune",
"author_id": 13466,
"author_profile": "https://Stackoverflow.com/users/13466",
"pm_score": 0,
"selected": false,
"text": "<p>I'd take numero 2 and reflect on whether I should make this static.</p>\n"
},
{
"answer_id": 127670,
"autho... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409/"
] | I'm currently working on a class that calculates the difference between two objects. I'm trying to decide what the best design for this class would be. I see two options:
1) Single-use class instance. Takes the objects to diff in the constructor and calculates the diff for that.
```
public class MyObjDiffer {
public MyObjDiffer(MyObj o1, MyObj o2) {
// Calculate diff here and store results in member variables
}
public boolean areObjectsDifferent() {
// ...
}
public Vector getOnlyInObj1() {
// ...
}
public Vector getOnlyInObj2() {
// ...
}
// ...
}
```
2) Re-usable class instance. Constructor takes no arguments. Has a "calculateDiff()" method that takes the objects to diff, and returns the results.
```
public class MyObjDiffer {
public MyObjDiffer() { }
public DiffResults getResults(MyObj o1, MyObj o2) {
// calculate and return the results. Nothing is stored in this class's members.
}
}
public class DiffResults {
public boolean areObjectsDifferent() {
// ...
}
public Vector getOnlyInObj1() {
// ...
}
public Vector getOnlyInObj2() {
// ...
}
}
```
The diffing will be fairly complex (details don't matter for the question), so there will need to be a number of helper functions. If I take solution 1 then I can store the data in member variables and don't have to pass everything around. It's slightly more compact, as everything is handled within a single class.
However, conceptually, it seems weird that a "Differ" would be specific to a certain set of results. Option 2 splits the results from the logic that actually calculates them.
EDIT: Option 2 also provides the ability to make the "MyObjDiffer" class static. Thanks kitsune, I forgot to mention that.
I'm having trouble seeing any significant pro or con to either option. I figure this kind of thing (a class that just handles some one-shot calculation) has to come up fairly often, and maybe I'm missing something. So, I figured I'd pose the question to the cloud. Are there significant pros or cons to one or the other option here? Is one inherently better? Does it matter?
I am doing this in Java, so there might be some restrictions on the possibilities, but the overall question of design is probably language-agnostic. | ### Use Object-Oriented Programming
Use option 2, but do *not* make it static.
### The Strategy Pattern
This way, an instance `MyObjDiffer` can be passed to anyone that needs a [Strategy](http://en.wikipedia.org/wiki/Strategy_pattern) for computing the difference between objects.
If, down the road, you find that different rules are used for computation in different contexts, you can create a new strategy to suit. With your code as it stands, you'd extend MyObjDiffer and override its methods, which is certainly workable. A better approach would be to define an interface, and have MyObjDiffer as one implementation.
Any decent refactoring tool will be able to "extract an interface" from MyObjDiffer and replace references to that type with the interface type at some later time if you want to delay the decision. Using "Option 2" with instance methods, rather than class procedures, gives you that flexibility.
### Configure an Instance
Even if you never need to write a new comparison method, you might find that specifying options to tailor the behavior of your basic method is useful. If you think about using the "diff" command to compare text files, you'll remember how many different options there are: whitespace- and case-sensitivity, output options, etc. The best analog to this in OO programming is to consider each diff process as an object, with options set as properties on that object. |
127,654 | <p>I'm working on an existing report and I would like to test it with the database. The problem is that the catalog set during the initial report creation no longer exists. I just need to change the catalog parameter to a new database. The report is using a stored proc for its data. It looks like if try and remove the proc to re-add it all the fields on the report will disapear and I'll have to start over.</p>
<p>I'm working in the designer in Studio and just need to tweak the catalog property to get a preview. I have code working to handle things properly from the program.</p>
| [
{
"answer_id": 127674,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 0,
"selected": false,
"text": "<p>EDIT: Saw your edit, so i'll keep my original post but have to say.. I've never had a crystal report in design... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
] | I'm working on an existing report and I would like to test it with the database. The problem is that the catalog set during the initial report creation no longer exists. I just need to change the catalog parameter to a new database. The report is using a stored proc for its data. It looks like if try and remove the proc to re-add it all the fields on the report will disapear and I'll have to start over.
I'm working in the designer in Studio and just need to tweak the catalog property to get a preview. I have code working to handle things properly from the program. | If you just need to do it in the designer then right click in some whitespace and click on Database->set datasource location. From there you can use a current connection or add a new connection. Set a new connection using the new catalog. Then click on your current connection in the top section and click update. Your data source will change. But if you need to do this at runtime then the following code is the best manner.
```
#'SET REPORT CONNECTION INFO
For i = 0 To rsource.ReportDocument.DataSourceConnections.Count - 1
rsource.ReportDocument.DataSourceConnections(i).SetConnection(crystalServer, crystalDB, crystalUser, crystalPassword)
Next
``` |
127,669 | <p>I have a computer A with two directory trees. The first directory contains the original mod dates that span back several years. The second directory is a copy of the first with a few additional files. There is a second computer be which contains a directory tree which is the same as the second directory on computer A (new mod times and additional files). How update the files in the two newer directories on both machines so that the mod times on the files are the same as the original? Note that these directory trees are in the order of 10s of gigabytes so the solution would have to include some method of sending only the date information to the second computer.</p>
| [
{
"answer_id": 128303,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 0,
"selected": false,
"text": "<p>I think rsync (with the right options)\nwill do this - it claims to only send\nfile differences, so presuma... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] | I have a computer A with two directory trees. The first directory contains the original mod dates that span back several years. The second directory is a copy of the first with a few additional files. There is a second computer be which contains a directory tree which is the same as the second directory on computer A (new mod times and additional files). How update the files in the two newer directories on both machines so that the mod times on the files are the same as the original? Note that these directory trees are in the order of 10s of gigabytes so the solution would have to include some method of sending only the date information to the second computer. | The following command will make sure that TEST2 gets the same date assigned that TEST1 has
```
touch -t `stat -t '%Y%m%d%H%M.%S' -f '%Sa' TEST1` TEST2
```
Now instead of using hard-coded values here, you could find the files using "find" utility and then run touch via SSH on the remote machine. However, that means you may have to enter the password for each file, unless you switch SSH to cert authentication. I'd rather not do it all in a super fancy one-liner. Instead let's work with temp files. First go to the directory in question and run a find (you can filter by file type, size, extension, whatever pleases you, see "man find" for details. I'm just filtering by type file here to exclude any directories):
```
find . -type f -print -exec stat -t '%Y%m%d%H%M.%S' -f '%Sm' "{}" \; > /tmp/original_dates.txt
```
Now we have a file that looks like this (in my example there are only two entries there):
```
# cat /tmp/original_dates.txt
./test1
200809241840.55
./test2
200809241849.56
```
Now just copy the file over to the other machine and place it in the directory (so the relative file paths match) and apply the dates:
```
cat original_dates.txt | (while read FILE && read DATE; do touch -t $DATE "$FILE"; done)
```
Will also work with file names containing spaces.
One note: I used the last "modification" date at stat, as that's what you wrote in the question. However, it rather sounds as if you want to use the "creation" date (every file has a creation date, last modification date and last access date), you need to alter the stat call a bit.
```
'%Sm' - last modification date
'%Sc' - creation date
'%Sa' - last access date
```
However, touch can only change the modification time and access time, I think it can't change the creation time of a file ... so if that was your real intention, my solution might be sub-optimal... but in that case your question was as well ;-) |
127,679 | <p>How do I view the grants (access rights) for a given user in MySQL?</p>
| [
{
"answer_id": 127683,
"author": "alanc10n",
"author_id": 14059,
"author_profile": "https://Stackoverflow.com/users/14059",
"pm_score": 6,
"selected": true,
"text": "<pre><code>mysql> show grants for 'user'@'host'\n</code></pre>\n"
},
{
"answer_id": 127710,
"author": "Kevi... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14059/"
] | How do I view the grants (access rights) for a given user in MySQL? | ```
mysql> show grants for 'user'@'host'
``` |
127,704 | <p>I want to write a function that takes an array of letters as an argument and a number of those letters to select. </p>
<p>Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:</p>
<pre><code>8! / ((8 - 3)! * 3!) = 56
</code></pre>
<p>Arrays (or words) in return consisting of 3 letters each.</p>
| [
{
"answer_id": 127856,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 10,
"selected": true,
"text": "<p><a href=\"http://portal.acm.org/citation.cfm?id=1036677&dl=&coll=\" rel=\"noreferrer\">Art of Computer Programmin... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9191/"
] | I want to write a function that takes an array of letters as an argument and a number of those letters to select.
Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:
```
8! / ((8 - 3)! * 3!) = 56
```
Arrays (or words) in return consisting of 3 letters each. | [Art of Computer Programming Volume 4: Fascicle 3](http://portal.acm.org/citation.cfm?id=1036677&dl=&coll=) has a ton of these that might fit your particular situation better than how I describe.
Gray Codes
----------
An issue that you will come across is of course memory and pretty quickly, you'll have problems by 20 elements in your set -- 20C3 = 1140. And if you want to iterate over the set it's best to use a modified gray code algorithm so you aren't holding all of them in memory. These generate the next combination from the previous and avoid repetitions. There are many of these for different uses. Do we want to maximize the differences between successive combinations? minimize? et cetera.
Some of the original papers describing gray codes:
1. [Some Hamilton Paths and a Minimal Change Algorithm](http://portal.acm.org/citation.cfm?id=2422.322413)
2. [Adjacent Interchange Combination Generation Algorithm](http://portal.acm.org/citation.cfm?id=49203&jmp=indexterms&coll=GUIDE&dl=GUIDE&CFID=81503149&CFTOKEN=96444237)
Here are some other papers covering the topic:
1. [An Efficient Implementation of the Eades, Hickey, Read Adjacent Interchange Combination Generation Algorithm](http://www.cs.uvic.ca/%7Eruskey/Publications/EHR/HoughRuskey.pdf) (PDF, with code in Pascal)
2. [Combination Generators](http://portal.acm.org/citation.cfm?doid=355826.355830)
3. [Survey of Combinatorial Gray Codes](http://www4.ncsu.edu/%7Esavage/AVAILABLE_FOR_MAILING/survey.ps) (PostScript)
4. [An Algorithm for Gray Codes](https://link.springer.com/content/pdf/10.1007/BF02248780.pdf)
Chase's Twiddle (algorithm)
---------------------------
Phillip J Chase, `[Algorithm 382: Combinations of M out of N Objects](http://portal.acm.org/citation.cfm?id=362502)' (1970)
[The algorithm in C](http://www.netlib.no/netlib/toms/382)...
Index of Combinations in Lexicographical Order (Buckles Algorithm 515)
----------------------------------------------------------------------
You can also reference a combination by its index (in lexicographical order). Realizing that the index should be some amount of change from right to left based on the index we can construct something that should recover a combination.
So, we have a set {1,2,3,4,5,6}... and we want three elements. Let's say {1,2,3} we can say that the difference between the elements is one and in order and minimal. {1,2,4} has one change and is lexicographically number 2. So the number of 'changes' in the last place accounts for one change in the lexicographical ordering. The second place, with one change {1,3,4} has one change but accounts for more change since it's in the second place (proportional to the number of elements in the original set).
The method I've described is a deconstruction, as it seems, from set to the index, we need to do the reverse – which is much trickier. This is how [Buckles](http://portal.acm.org/citation.cfm?id=355739) solves the problem. I wrote some [C to compute them](https://stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data#794), with minor changes – I used the index of the sets rather than a number range to represent the set, so we are always working from 0...n.
Note:
1. Since combinations are unordered, {1,3,2} = {1,2,3} --we order them to be lexicographical.
2. This method has an implicit 0 to start the set for the first difference.
Index of Combinations in Lexicographical Order (McCaffrey)
----------------------------------------------------------
There is [another way](https://web.archive.org/web/20170325012457/https://msdn.microsoft.com/en-us/library/aa289166.aspx):, its concept is easier to grasp and program but it's without the optimizations of Buckles. Fortunately, it also does not produce duplicate combinations:
The set [](https://i.stack.imgur.com/Txetz.gif) that maximizes [](https://i.stack.imgur.com/HOj5o.gif), where [](https://i.stack.imgur.com/vIeiI.gif).
For an example: `27 = C(6,4) + C(5,3) + C(2,2) + C(1,1)`. So, the 27th lexicographical combination of four things is: {1,2,5,6}, those are the indexes of whatever set you want to look at. Example below (OCaml), requires `choose` function, left to reader:
```fs
(* this will find the [x] combination of a [set] list when taking [k] elements *)
let combination_maccaffery set k x =
(* maximize function -- maximize a that is aCb *)
(* return largest c where c < i and choose(c,i) <= z *)
let rec maximize a b x =
if (choose a b ) <= x then a else maximize (a-1) b x
in
let rec iterate n x i = match i with
| 0 -> []
| i ->
let max = maximize n i x in
max :: iterate n (x - (choose max i)) (i-1)
in
if x < 0 then failwith "errors" else
let idxs = iterate (List.length set) x k in
List.map (List.nth set) (List.sort (-) idxs)
```
A small and simple combinations iterator
----------------------------------------
The following two algorithms are provided for didactic purposes. They implement an iterator and (a more general) folder overall combinations.
They are as fast as possible, having the complexity O(nCk). The memory consumption is bound by `k`.
We will start with the iterator, which will call a user provided function for each combination
```fs
let iter_combs n k f =
let rec iter v s j =
if j = k then f v
else for i = s to n - 1 do iter (i::v) (i+1) (j+1) done in
iter [] 0 0
```
A more general version will call the user provided function along with the state variable, starting from the initial state. Since we need to pass the state between different states we won't use the for-loop, but instead, use recursion,
```fs
let fold_combs n k f x =
let rec loop i s c x =
if i < n then
loop (i+1) s c @@
let c = i::c and s = s + 1 and i = i + 1 in
if s < k then loop i s c x else f c x
else x in
loop 0 0 [] x
``` |
127,713 | <p>Why does the following method hang?</p>
<pre>
public void pipe(Reader in, Writer out) {
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
out.append(buf.flip());
}
}
</pre>
| [
{
"answer_id": 127729,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": true,
"text": "<p>Answering my own question: you have to call <code>buf.clear()</code> between <code>read</code>s. Presumably, <code>re... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | Why does the following method hang?
```
public void pipe(Reader in, Writer out) {
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
out.append(buf.flip());
}
}
``` | Answering my own question: you have to call `buf.clear()` between `read`s. Presumably, `read` is hanging because the buffer is full. The correct code is
```
public void pipe(Reader in, Writer out) {
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while( in.read(buf) >= 0 ) {
out.append(buf.flip());
buf.clear();
}
}
``` |
127,728 | <p>I'm working with ASP.NET 3.5.
I have a list box that users must add items to (I've written the code for this). My requirement is that at least one item must be added to the listbox or they cannot submit the form. I have several other validators on the page and they all write to a ValidationSummary control. I would like this listbox validation to write to the Validation Summary control as well. Any help is greatly appreciated. Thank you.</p>
| [
{
"answer_id": 127805,
"author": "Jason N. Gaylord",
"author_id": 21318,
"author_profile": "https://Stackoverflow.com/users/21318",
"pm_score": -1,
"selected": false,
"text": "<p>You will want to register your control with the page by sending in the ClientID. Then, you can use Microsoft ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm working with ASP.NET 3.5.
I have a list box that users must add items to (I've written the code for this). My requirement is that at least one item must be added to the listbox or they cannot submit the form. I have several other validators on the page and they all write to a ValidationSummary control. I would like this listbox validation to write to the Validation Summary control as well. Any help is greatly appreciated. Thank you. | Drop in a custom validator, Add your desired error message to it, double click on the custom validator to get to the code behind for the event handler, and then you would implement server side like this:
```
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = ListBox1.Items.Count > 0;
}
```
Also you can implement client side javascript as well.
I just threw this up on a page and tested it quickly, so you might need to tweak it a bit: (The button1 only adds an item to the List Box)
```
<script language="JavaScript">
<!--
function ListBoxValid(sender, args)
{
args.IsValid = sender.options.length > 0;
}
// -->
</script>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="NOVALID" />
<asp:Button ID="Button2" runat="server" Text="ButtonsUBMIT" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="CustomValidator"
onservervalidate="CustomValidator1_ServerValidate" ClientValidationFunction="ListBoxValid"></asp:CustomValidator>
```
If you add a validation summary to the page, you error text should show up in that summary if there is no items in the ListBox, or other collection-able control, what ever you want to use, as long as the ValidationGroup is the same. |
127,736 | <p>Greetings, currently I am refactoring one of my programs, and I found an interesting problem.</p>
<p>I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol.</p>
<p>I need the following operations: </p>
<ul>
<li>check if the transition has a label</li>
<li>get this label</li>
<li>add a label to a transition</li>
<li>check if the transition has a condition </li>
<li>get this condition</li>
<li>check for equality</li>
</ul>
<p>Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base:</p>
<pre><code>class Transition(object):
def __init__(self, start, end):
self.start = start
self.end = end
def get_label(self):
return None
def has_label(self):
return False
def collect_decorations(self, decorations):
return decorations
def internal_equality(self, my_decorations, other):
try:
return (self.start == other.start
and self.end == other.end
and my_decorations = other.collect_decorations())
def __eq__(self, other):
return self.internal_equality(self.collect_decorations({}), other)
class Labeled(object):
def __init__(self, label, base):
self.base = base
self.label = label
def has_label(self):
return True
def get_label(self):
return self.label
def collect_decorations(self, decorations):
assert 'label' not in decorations
decorations['label'] = self.label
return self.base.collect_decorations(decorations)
def __getattr__(self, attribute):
return self.base.__getattr(attribute)
</code></pre>
<p>Is this a clean approach? Am I missing something?</p>
<p>I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance:</p>
<pre><code>class Transition(object):
def __init__(self, **kwargs):
# init is pythons MI-madness ;-)
super(Transition, self).__init__(**kwargs)
self.start = kwargs['start']
self.end = kwargs['end']
def get_label(self):
return None
def get_condition(self):
return None
def __eq__(self, other):
try:
return self.start == other.start and self.end == other.end
except AttributeError:
return False
class LabeledTransition(Transition):
def __init__(self, **kwargs):
super(LabeledTransition).__init__(**kwargs)
self.label = kwargs['label']
def get_label(self):
return self.label
def __eq__(self):
super_result = super(LabeledTransition, self).__eq__(other)
try:
return super_result and self.label == other.label
except AttributeError:
return False
class ConditionalTransition(Transition):
def __init__(self, **kwargs):
super(ConditionalTransition, self).__init__(**kwargs)
self.condition = kwargs['condition']
def get_condition(self):
return self.condition
def __eq__(self, other):
super_result = super(ConditionalTransition, self).__eq__(other)
try:
return super_result and self.condition = other.condition
except AttributeError:
return False
# ConditionalTransition about the same, with get_condition
class LabeledConditionalTransition(LabeledTransition, ConditionalTransition):
pass
</code></pre>
<p>the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size.</p>
<p>Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has_label/has_transition.</p>
<p>So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around?</p>
<p><em>EDIT</em>:
Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct.</p>
| [
{
"answer_id": 128005,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 0,
"selected": false,
"text": "<p>From the code that was posted, the only difference between Transition and Labeled Transition is the return of get_labl... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17663/"
] | Greetings, currently I am refactoring one of my programs, and I found an interesting problem.
I have Transitions in an automata. Transitions always have a start-state and an end-state. Some Transitions have a label, which encodes a certain Action that must be performed upon traversal. No label means no action. Some transitions have a condition, which must be fulfilled in order to traverse this condition, if there is no condition, the transition is basically an epsilon-transition in an NFA and will be traversed without consuming an input symbol.
I need the following operations:
* check if the transition has a label
* get this label
* add a label to a transition
* check if the transition has a condition
* get this condition
* check for equality
Judging from the first five points, this sounds like a clear decorator, with a base transition and two decorators: Labeled and Condition. However, this approach has a problem: two transitions are considered equal if their start-state and end-state are the same, the labels at both transitions are equal (or not-existing) and both conditions are the same (or not existing). With a decorator, I might have two transitions Labeled("foo", Conditional("bar", Transition("baz", "qux"))) and Conditional("bar", Labeled("foo", Transition("baz", "qux"))) which need a non-local equality, that is, the decorators would need to collect all the data and the Transition must compare this collected data on a set-base:
```
class Transition(object):
def __init__(self, start, end):
self.start = start
self.end = end
def get_label(self):
return None
def has_label(self):
return False
def collect_decorations(self, decorations):
return decorations
def internal_equality(self, my_decorations, other):
try:
return (self.start == other.start
and self.end == other.end
and my_decorations = other.collect_decorations())
def __eq__(self, other):
return self.internal_equality(self.collect_decorations({}), other)
class Labeled(object):
def __init__(self, label, base):
self.base = base
self.label = label
def has_label(self):
return True
def get_label(self):
return self.label
def collect_decorations(self, decorations):
assert 'label' not in decorations
decorations['label'] = self.label
return self.base.collect_decorations(decorations)
def __getattr__(self, attribute):
return self.base.__getattr(attribute)
```
Is this a clean approach? Am I missing something?
I am mostly confused, because I can solve this - with longer class names - using cooperative multiple inheritance:
```
class Transition(object):
def __init__(self, **kwargs):
# init is pythons MI-madness ;-)
super(Transition, self).__init__(**kwargs)
self.start = kwargs['start']
self.end = kwargs['end']
def get_label(self):
return None
def get_condition(self):
return None
def __eq__(self, other):
try:
return self.start == other.start and self.end == other.end
except AttributeError:
return False
class LabeledTransition(Transition):
def __init__(self, **kwargs):
super(LabeledTransition).__init__(**kwargs)
self.label = kwargs['label']
def get_label(self):
return self.label
def __eq__(self):
super_result = super(LabeledTransition, self).__eq__(other)
try:
return super_result and self.label == other.label
except AttributeError:
return False
class ConditionalTransition(Transition):
def __init__(self, **kwargs):
super(ConditionalTransition, self).__init__(**kwargs)
self.condition = kwargs['condition']
def get_condition(self):
return self.condition
def __eq__(self, other):
super_result = super(ConditionalTransition, self).__eq__(other)
try:
return super_result and self.condition = other.condition
except AttributeError:
return False
# ConditionalTransition about the same, with get_condition
class LabeledConditionalTransition(LabeledTransition, ConditionalTransition):
pass
```
the class LabledConditionalTransition behaves exactly as expected - and having no code in there is appealing and I do not thing MI is confusing at this size.
Of course, the third option would be to just hammer everything into a single transition class with a bunch of in has\_label/has\_transition.
So... I am confused. Am I missing something? Which implementation looks better? How do you handle similar cases, that is, objects which look like a Decorator could handle them, but then, such a non-local method comes around?
*EDIT*:
Added the ConditionalTransition-class. Basically, this kinda behaves like the decorator, minus the order created by the order of creating the decorators, the transition checks for start and end being correct, the LabeledTransition-class checks for label being correct and ConditionalTransition checks for condition being correct. | I think its clear that nobody really understands your question. I would suggest putting it in context and making it shorter. As an example, here's one possible implementation of the state pattern in python, please study it to get an idea.
```
class State(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
class Automaton(object):
def __init__(self, instance, start):
self._state = start
self.transitions = instance.transitions()
def get_state(self):
return self._state
def set_state(self, target):
transition = self.transitions.get((self.state, target))
if transition:
action, condition = transition
if condition:
if condition():
if action:
action()
self._state = target
else:
self._state = target
else:
self._state = target
state = property(get_state, set_state)
class Door(object):
open = State('open')
closed = State('closed')
def __init__(self, blocked=False):
self.blocked = blocked
def close(self):
print 'closing door'
def do_open(self):
print 'opening door'
def not_blocked(self):
return not self.blocked
def transitions(self):
return {
(self.open, self.closed):(self.close, self.not_blocked),
(self.closed, self.open):(self.do_open, self.not_blocked),
}
if __name__ == '__main__':
door = Door()
automaton = Automaton(door, door.open)
print 'door is', automaton.state
automaton.state = door.closed
print 'door is', automaton.state
automaton.state = door.open
print 'door is', automaton.state
door.blocked = True
automaton.state = door.closed
print 'door is', automaton.state
```
the output of this programm would be:
```
door is open
closing door
door is closed
opening door
door is open
door is open
``` |
127,739 | <pre><code> $a = '{ "tag": "<b></b>" }';
echo json_encode( json_decode($a) );
</code></pre>
<p>This outputs:</p>
<pre><code>{"tag":"<b><\/b>"}
</code></pre>
<p>when you would think it would output exactly the input. For some reason json_encode adds an extra slash.</p>
| [
{
"answer_id": 127775,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 5,
"selected": true,
"text": "<p>Because it's part of the JSON standard</p>\n<p><a href=\"http://json.org/\" rel=\"noreferrer\">http://json.org/</a></... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19087/"
] | ```
$a = '{ "tag": "<b></b>" }';
echo json_encode( json_decode($a) );
```
This outputs:
```
{"tag":"<b><\/b>"}
```
when you would think it would output exactly the input. For some reason json\_encode adds an extra slash. | Because it's part of the JSON standard
<http://json.org/>
>
> char
>
>
>
> ```
> any-Unicode-character-
> except-"-or-\-or-
> control-character
> \"
> \\
> \/ <---- see here?
> \b
> \f
> \n
> \r
> \t
> \u four-hex-digits
>
> ```
>
> |
127,753 | <p>Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following?</p>
<pre><code>public void pipe(Reader in, Writer out) {
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while (in.read(buf) >= 0 ) {
out.append(buf.flip());
buf.clear();
}
}
</code></pre>
<p>[EDIT] Please note the <code>Reader</code> and <code>Writer</code> are <em>given</em>. The correct answer will demonstrate how to take <code>in</code> and <code>out</code> and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where <code>in</code> and <code>out</code> are an <code>InputStream</code> and an <code>OutputStream</code> (preferably with a conversion from/to <code>Reader</code>/<code>Writer</code>). I will not accept answers where either <code>in</code> or <code>out</code> is a <em>subclass</em> of <code>Reader</code>/<code>InputStream</code> or <code>Writer</code>/<code>OutputStrem</code>.</p>
| [
{
"answer_id": 127788,
"author": "Einar",
"author_id": 2964,
"author_profile": "https://Stackoverflow.com/users/2964",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at <a href=\"http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html\" rel=\"nofollow noreferrer\">... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following?
```
public void pipe(Reader in, Writer out) {
CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
while (in.read(buf) >= 0 ) {
out.append(buf.flip());
buf.clear();
}
}
```
[EDIT] Please note the `Reader` and `Writer` are *given*. The correct answer will demonstrate how to take `in` and `out` and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where `in` and `out` are an `InputStream` and an `OutputStream` (preferably with a conversion from/to `Reader`/`Writer`). I will not accept answers where either `in` or `out` is a *subclass* of `Reader`/`InputStream` or `Writer`/`OutputStrem`. | [IOUtils](http://commons.apache.org/io/) from the Apache Commons project has a number of [utilily methods](http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html) that do exactly what you need.
`IOUtils.copy(in, out)` will perform a buffered copy of all input to the output. If there is more than one spot in your codebase that requires `Stream` or `Reader`/`Writer` handling, using IOUtils could be a good idea. |
127,761 | <p>Have you managed to get Aptana Studio debugging to work? I tried following this, but I don't see <code>Windows -> Preferences -> Aptana -> Editors -> PHP -> PHP Interpreters</code> in my menu (I have <code>PHP plugin</code> installed) and any attempt to set up the servers menu gives me "socket error" when I try to debug. <code>Xdebug</code> is installed, confirmed through <code>php info</code>.</p>
| [
{
"answer_id": 128612,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 2,
"selected": false,
"text": "<p>This is not related to Aptana Studio, but if you are looking for a PHP XDebug debugger client on OS X, you can try <a hre... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] | Have you managed to get Aptana Studio debugging to work? I tried following this, but I don't see `Windows -> Preferences -> Aptana -> Editors -> PHP -> PHP Interpreters` in my menu (I have `PHP plugin` installed) and any attempt to set up the servers menu gives me "socket error" when I try to debug. `Xdebug` is installed, confirmed through `php info`. | I've been using ZendDebugger with Eclipse (on OS X) for a while now and it works great!
Here's the recipe that's worked well for me.
1. install Eclipse PDT via "All in one" package at: <http://www.zend.com/en/community/pdt>
2. install ZendDebugger.so (<http://www.zend.com/en/community/pdt>)
3. configure your php.ini w/ the ZendDebugger extenssion (info below)
Configuring ZendDebugger:
1. edit php.ini
2. add the following:
[Zend]
zend\_extension=/full/path/to/ZendDebugger.so
zend\_debugger.allow\_hosts=127.0.0.1
zend\_debugger.expose\_remotely=always
zend\_debugger.connector\_port=10013
Now run "php -m" in the command line to output all the installed modules. If you see the following then its installed just fine
```
[Zend Modules]
Zend Debugger
```
Now restart Apache so that it reloads PHP w/ the ZendDebugger. Create a dummy page with in it and examine the output to make sure the PHP apache module picked up ZendDebugger as well. If it's setup right you will see something like the following text somewhere in phpinfo()'s output.
>
> with Zend Debugger v5.2.14, Copyright (c) 1999-2008, by Zend Technologies
>
>
>
OK - but you wanted Aptana Studio... at this point I install the Aptana Studio Plugin into the PDT build of Eclipse. The instructions for that are at: <http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration>
That setup has served me well for a while - hopefully it helps you too
-Arin |
127,794 | <p>Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) :)</p>
<p>I basically have a <code>StyledWindow</code> control, which is essentially a glorified <code>Panel</code> with ability to do other bits (like add borders etc).</p>
<p>Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls:</p>
<pre><code> protected override void CreateChildControls()
{
_panel = new Panel();
if (_editable != null)
_editable.InstantiateIn(_panel);
_regions = new List<IAttributeAccessor>();
_regions.Add(_panel);
}
</code></pre>
<p>The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the <code>RegisterClientScriptBlock</code> is the only reason I need the page ref).</p>
<p>Now, this was causing "object null" errors, but I localized this down to the render method, which was of course trying to call the method against the [null] <code>Page</code> object.</p>
<p>What's confusing me is that the control works fine as a standalone, but when placed in the <code>StyledWindow</code> it all goes horribly wrong!</p>
<p><strong>So, it looks like I am missing something in either my <code>StyledWindow</code> or <code>ChildControl</code>. Any ideas?</strong></p>
<h2>Update</h2>
<p>As <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#127824">Brad Wilson</a> quite rightly pointed out, you do not see the controls being added to the <code>Controls</code> collection. This is what the <code>_panel</code> is for, this was there to handle that for me, basically then override <code>Controls</code> (I got this from a guide somewhere):</p>
<pre><code> Panel _panel; // Sub-Control to store the "Content".
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return _panel.Controls;
}
}
</code></pre>
<p>I hope that helps clarify things. Apologies.</p>
<h2>Update Following <a href="https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#128299">Longhorn213's Answer</a></h2>
<p>Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page.</p>
<p>The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's <code>OnLoad</code> event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) :D</p>
<p>Thanks for your help guys, appreciated :)</p>
| [
{
"answer_id": 127824,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>I don't see you adding your controls to the Controls collection anywhere, which would explain why they can't access t... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) :)
I basically have a `StyledWindow` control, which is essentially a glorified `Panel` with ability to do other bits (like add borders etc).
Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls:
```
protected override void CreateChildControls()
{
_panel = new Panel();
if (_editable != null)
_editable.InstantiateIn(_panel);
_regions = new List<IAttributeAccessor>();
_regions.Add(_panel);
}
```
The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the `RegisterClientScriptBlock` is the only reason I need the page ref).
Now, this was causing "object null" errors, but I localized this down to the render method, which was of course trying to call the method against the [null] `Page` object.
What's confusing me is that the control works fine as a standalone, but when placed in the `StyledWindow` it all goes horribly wrong!
**So, it looks like I am missing something in either my `StyledWindow` or `ChildControl`. Any ideas?**
Update
------
As [Brad Wilson](https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#127824) quite rightly pointed out, you do not see the controls being added to the `Controls` collection. This is what the `_panel` is for, this was there to handle that for me, basically then override `Controls` (I got this from a guide somewhere):
```
Panel _panel; // Sub-Control to store the "Content".
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return _panel.Controls;
}
}
```
I hope that helps clarify things. Apologies.
Update Following [Longhorn213's Answer](https://stackoverflow.com/questions/127794/child-control-initialization-in-custom-composite-in-aspnet#128299)
-----------------------------------------------------------------------------------------------------------------------------------------------------
Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page.
The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's `OnLoad` event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) :D
Thanks for your help guys, appreciated :) | Solved!
=======
Right, I was determined to get this cracked today! Here were my thoughts:
* I thought the use of `Panel` was a bit of a hack, so I should remove it and find out how it is really done.
* I didn't want to have to do something like `MyCtl.Controls[0].Controls` to access the controls added to the composite.
* I wanted the damn thing to work!
So, I got searching and hit [MSDN](http://msdn.microsoft.com/), [this artcle](http://msdn.microsoft.com/en-us/library/aa478964(printer).aspx) was **REALLY** helpful (i.e. like almost copy 'n' paste, and explained well - something MSDN is traditionally bad at). Nice!
So, I ripped out the use of `Panel` and pretty much followed the artcle and took it as gospel, making notes as I went.
Here's what I have now:
* I learned I was using the wrong term. I should have been calling it a ***Templated Control***. While templated controls are technically composites, there is a distinct difference. Templated controls can define the interface for items that are added to them.
* Templated controls are very powerful and actually pretty quick and easy to set up once you get your head round them!
* I will play some more with the designer support to ensure I fully understand it all, then get a blog post up :)
* A "Template" control is used to specify the interface for templated data.
For example, here is the ASPX markup for a templated control:
```
<cc1:TemplatedControl ID="MyCtl" runat="server">
<Template>
<!-- Templated Content Goes Here -->
</Template>
</cc1:TemplatedControl>
```
### Heres the Code I Have Now
```
public class DummyWebControl : WebControl
{
// Acts as the surrogate for the templated controls.
// This is essentially the "interface" for the templated data.
}
```
In TemplateControl.cs...
```
ITemplate _template;
// Surrogate to hold the controls instantiated from
// within the template.
DummyWebControl _owner;
protected override void CreateChildControls()
{
// Note we are calling base.Controls here
// (you will see why in a min).
base.Controls.Clear();
_owner = new DummyWebControl();
// Load the Template Content
ITemplate template = _template;
if (template == null)
template = new StyledWindowDefaultTemplate();
template.InstantiateIn(_owner);
base.Controls.Add(_owner);
ChildControlsCreated = true;
}
```
Then, to provide easy access to the Controls of the [Surrogate] Object:
(this is why we needed to clear/add to the base.Controls)
```
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return _owner.Controls;
}
}
```
And that is pretty much it, easy when you know how! :)
**Next:** Design Time Region Support! |
127,803 | <p>I need to parse <a href="https://www.rfc-editor.org/rfc/rfc3339" rel="noreferrer">RFC 3339</a> strings like <code>"2008-09-03T20:56:35.450686Z"</code> into Python's <code>datetime</code> type.</p>
<p>I have found <a href="https://docs.python.org/library/datetime.html#datetime.datetime.strptime" rel="noreferrer"><code>strptime</code></a> in the Python standard library, but it is not very convenient.</p>
<p>What is the best way to do this?</p>
| [
{
"answer_id": 127825,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": false,
"text": "<p>What is the exact error you get? Is it like the following?</p>\n\n<pre><code>>>> datetime.datetime.strptime(\"2008-... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70293/"
] | I need to parse [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339) strings like `"2008-09-03T20:56:35.450686Z"` into Python's `datetime` type.
I have found [`strptime`](https://docs.python.org/library/datetime.html#datetime.datetime.strptime) in the Python standard library, but it is not very convenient.
What is the best way to do this? | `isoparse` function from *python-dateutil*
==========================================
The [*python-dateutil*](https://pypi.python.org/pypi/python-dateutil) package has [`dateutil.parser.isoparse`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse) to parse not only RFC 3339 datetime strings like the one in the question, but also other [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date).
```
>>> import dateutil.parser
>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=tzutc())
>>> dateutil.parser.isoparse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903T205635.450686') # ISO 8601 basic format
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
>>> dateutil.parser.isoparse('20080903') # ISO 8601 basic format, date only
datetime.datetime(2008, 9, 3, 0, 0)
```
The *python-dateutil* package also has [`dateutil.parser.parse`](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse). Compared with `isoparse`, it is presumably less strict, but both of them are quite forgiving and will attempt to interpret the string that you pass in. If you want to eliminate the possibility of any misreads, you need to use something stricter than either of these functions.
#### Comparison with Python 3.7+’s built-in [`datetime.datetime.fromisoformat`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat)
`dateutil.parser.isoparse` is a full ISO-8601 format parser, but in Python ≤ 3.10 `fromisoformat` is deliberately *not*. In Python 3.11, `fromisoformat` supports almost all strings in valid ISO 8601. See `fromisoformat`'s docs for this cautionary caveat. (See [this answer](https://stackoverflow.com/a/49784038/247696)). |
127,817 | <p>I'm having a little problem and I don't see why, it's easy to go around it, but still I want to understand. </p>
<p>I have the following class :</p>
<pre><code>public class AccountStatement : IAccountStatement
{
public IList<IAccountStatementCharge> StatementCharges { get; set; }
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
public AccountStatement(IPeriod period, int accountID)
{
StatementCharges = new List<IAccountStatementCharge>();
StartDate = new Date(period.PeriodStartDate);
EndDate = new Date(period.PeriodEndDate);
AccountID = accountID;
}
public void AddStatementCharge(IAccountStatementCharge charge)
{
StatementCharges.Add(charge);
}
</code></pre>
<p>}</p>
<p>(note startdate,enddate,accountID are automatic property to...)</p>
<p>If I use it this way :</p>
<pre><code>var accountStatement = new AccountStatement{
StartDate = new Date(2007, 1, 1),
EndDate = new Date(2007, 1, 31),
StartingBalance = 125.05m
};
</code></pre>
<p>When I try to use the method "AddStatementCharge: I end up with a "null" StatementCharges list... In step-by-step I clearly see that my list get a value, but as soon as I quit de instantiation line, my list become "null"</p>
| [
{
"answer_id": 127840,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 5,
"selected": true,
"text": "<p>This code:</p>\n\n<pre><code>public AccountStatement()\n{\n new AccountStatement(new Period(new NullDate().DateTime... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7419/"
] | I'm having a little problem and I don't see why, it's easy to go around it, but still I want to understand.
I have the following class :
```
public class AccountStatement : IAccountStatement
{
public IList<IAccountStatementCharge> StatementCharges { get; set; }
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
public AccountStatement(IPeriod period, int accountID)
{
StatementCharges = new List<IAccountStatementCharge>();
StartDate = new Date(period.PeriodStartDate);
EndDate = new Date(period.PeriodEndDate);
AccountID = accountID;
}
public void AddStatementCharge(IAccountStatementCharge charge)
{
StatementCharges.Add(charge);
}
```
}
(note startdate,enddate,accountID are automatic property to...)
If I use it this way :
```
var accountStatement = new AccountStatement{
StartDate = new Date(2007, 1, 1),
EndDate = new Date(2007, 1, 31),
StartingBalance = 125.05m
};
```
When I try to use the method "AddStatementCharge: I end up with a "null" StatementCharges list... In step-by-step I clearly see that my list get a value, but as soon as I quit de instantiation line, my list become "null" | This code:
```
public AccountStatement()
{
new AccountStatement(new Period(new NullDate().DateTime,newNullDate().DateTime), 0);
}
```
is undoubtedly not what you wanted. That makes a second instance of AccountStatement and does nothing with it.
I think what you meant was this instead:
```
public AccountStatement() : this(new Period(new NullDate().DateTime, new NullDate().DateTime), 0)
{
}
``` |
127,867 | <p>I have great doubts about this forum, but I am willing to be pleasantly surprised ;) <strong>Kudos and great karma to those who get me back on track.</strong></p>
<p>I am attempting to use the blitz implementation of JavaSpaces (<a href="http://www.dancres.org/blitz/blitz_js.html" rel="nofollow noreferrer">http://www.dancres.org/blitz/blitz_js.html</a>) to implement the ComputeFarm example provided at <a href="http://today.java.net/pub/a/today/2005/04/21/farm.html" rel="nofollow noreferrer">http://today.java.net/pub/a/today/2005/04/21/farm.html</a></p>
<p>The in memory example works fine, but whenever I attempt to use the blitz out-of-box implementation i get the following error:</p>
<p>(yes <strong><code>com.sun.jini.mahalo.TxnMgrProxy</code></strong> is in the class path)</p>
<pre><code>2008-09-24 09:57:37.316 ERROR [Thread-4] JavaSpaceComputeSpace 155 - Exception while taking task.
java.rmi.ServerException: RemoteException in server thread; nested exception is:
java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:644)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_FROM_SERVER__________(Util.java:108)
at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(Util.java:101)
at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHandler.java:1303)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:832)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659)
at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528)
at $Proxy0.take(Unknown Source)
at org.dancres.blitz.remote.BlitzProxy.take(BlitzProxy.java:157)
at compute.impl.javaspaces.JavaSpaceComputeSpace.take(JavaSpaceComputeSpace.java:138)
at example.squares.SquaresJob.collectResults(SquaresJob.java:47)
at compute.impl.AbstractJobRunner$CollectThread.run(AbstractJobRunner.java:28)
Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:619)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoader.java:922)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:242)
at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassProvider.java:613)
at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138)
at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:296)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1544)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221)
at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvocationDispatcher.java:1049)
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:599)
... 17 more
</code></pre>
| [
{
"answer_id": 128250,
"author": "jiriki",
"author_id": 19907,
"author_profile": "https://Stackoverflow.com/users/19907",
"pm_score": 0,
"selected": false,
"text": "<p>Well, your java spaces server does not seem to find the class:</p>\n\n<p>com.sun.jini.mahalo.TxnMgrProxy.</p>\n\n<p>So I... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21707/"
] | I have great doubts about this forum, but I am willing to be pleasantly surprised ;) **Kudos and great karma to those who get me back on track.**
I am attempting to use the blitz implementation of JavaSpaces (<http://www.dancres.org/blitz/blitz_js.html>) to implement the ComputeFarm example provided at <http://today.java.net/pub/a/today/2005/04/21/farm.html>
The in memory example works fine, but whenever I attempt to use the blitz out-of-box implementation i get the following error:
(yes **`com.sun.jini.mahalo.TxnMgrProxy`** is in the class path)
```
2008-09-24 09:57:37.316 ERROR [Thread-4] JavaSpaceComputeSpace 155 - Exception while taking task.
java.rmi.ServerException: RemoteException in server thread; nested exception is:
java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:644)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_FROM_SERVER__________(Util.java:108)
at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(Util.java:101)
at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHandler.java:1303)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:832)
at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659)
at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528)
at $Proxy0.take(Unknown Source)
at org.dancres.blitz.remote.BlitzProxy.take(BlitzProxy.java:157)
at compute.impl.javaspaces.JavaSpaceComputeSpace.take(JavaSpaceComputeSpace.java:138)
at example.squares.SquaresJob.collectResults(SquaresJob.java:47)
at compute.impl.AbstractJobRunner$CollectThread.run(AbstractJobRunner.java:28)
Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is:
java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:619)
at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597)
at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212)
at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568)
at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565)
at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540)
at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778)
at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148)
at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244)
at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241)
at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoader.java:922)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:242)
at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassProvider.java:613)
at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138)
at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:296)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1544)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221)
at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvocationDispatcher.java:1049)
at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:599)
... 17 more
``` | So com.sun.jini.mahalo.TxnMgrProxy is contained in some jar, that is contained in your CLASSPATH environment variable.
But probably your are using some script to start the server. And this most probably starts java by specifying a "-classpath" commandline switch which takes precendence over your environment CLASSPATH variable.
<http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html>
You can simulate this by executing:
javap -classpath someUnknownJar.jar com.sun.jini.mahalo.TxnMgrProxy
... and suddenly the class cannot be found anymore. So can you please try and find out the way the java VM of the client and server are started and provide the complete command line.
(If you are using some kind of script just add an "echo ..." in front of the java command and paste the output in here). |
127,886 | <p>I'm confused with how views are organized, and it is important to understand this as ASP.NET MVC uses conventions to get everything working right.</p>
<p>Under the views directory, there are subdirectories. Inside these subdirectories are views. I'm assuming that the subdirectories map to controllers, and the controllers act on the views contained within their subdirectories.</p>
<p>Is there an emerging expectation of what types of views are contained within these directories? For instance, should the default page for each directory be index.aspx? Should the pages follow a naming convention such as Create[controller].aspx, List[controller].aspx, etc? Or does it not matter?</p>
| [
{
"answer_id": 128045,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 4,
"selected": true,
"text": "<p>View directory naming and file naming are important, because the ASP.NET MVC framework makes certain assumptions abou... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm confused with how views are organized, and it is important to understand this as ASP.NET MVC uses conventions to get everything working right.
Under the views directory, there are subdirectories. Inside these subdirectories are views. I'm assuming that the subdirectories map to controllers, and the controllers act on the views contained within their subdirectories.
Is there an emerging expectation of what types of views are contained within these directories? For instance, should the default page for each directory be index.aspx? Should the pages follow a naming convention such as Create[controller].aspx, List[controller].aspx, etc? Or does it not matter? | View directory naming and file naming are important, because the ASP.NET MVC framework makes certain assumptions about them. If you do not conform to these assumptions, then you must write code to let the framework know what you are doing. Generally speaking, you should conform to these assumptions unless you have a good reason not to.
Let's look at the simplest possible controller action:
```
public ActionResult NotAuthorized()
{
return View();
}
```
Because no view name has been specified in the call to View(), the framework will presume that the view filename will be the same as the Action name. The framework has a type called ViewEngine which will supply the extension. The default ViewEngine is WebFormViewEngine, which will take that name and append an .aspx to it. So the full filename in this case would be NotAuthorized.aspx.
But in which folder will the file be found? Again, the ViewEngine supplies that information. With WebFormViewEngine, it will look in two folders: ~/Views/Shared and ~/Views/{controller}
So if your controller was called AccountController, it would look in ~/Views/Account
But there might be times when you don't want to follow these rules. For instance, two different actions might return the same view (with a different model, or something). In this case, if you specify the view name explicitly in your action:
```
public ActionResult NotAuthorized()
{
return View("Foo");
}
```
Note that with WebFormViewEngine, the "view name" is generally the same as the filename, less the extension, but the framework does not require that of other view engines.
Similarly, you might also have a reason to want your application to look for views and non-default folders. You can do that by creating your own ViewEngine. I show the technique in [this blog post](http://blogs.teamb.com/craigstuntz/2008/07/31/37827 "Alternate View Folders in ASP.NET MVC"), but the type names are different, since it was written for an earlier version of the framework. The basic idea is still the same, however. |
127,899 | <p>i have a control that is organized like this</p>
<p><img src="https://dl-web.getdropbox.com/get/jsstructure.GIF?w=faef1ed3" alt="alt text"></p>
<p>and i want to have the javascript registered on the calling master pages, etc, so that anywhere this control folder is dropped and then registered, it will know how to find the URL to the js.</p>
<p>Here is what i have so far (in the user control )</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsClientScriptBlockRegistered("jqModal"))
Page.ClientScript.RegisterClientScriptInclude("jqModal", ResolveClientUrl("~js/jqModal.js"));
if (!Page.IsClientScriptBlockRegistered("jQuery"))
Page.ClientScript.RegisterClientScriptInclude("jQuery", ResolveClientUrl("~/js/jQuery.js"));
if (!Page.IsClientScriptBlockRegistered("tellAFriend"))
Page.ClientScript.RegisterClientScriptInclude("tellAFriend", ResolveClientUrl("js/tellAFriend.js"));
}
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 127935,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a helper class with static method:</p>\n\n<pre><code>public static class PageHelper {\n public static void ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
] | i have a control that is organized like this

and i want to have the javascript registered on the calling master pages, etc, so that anywhere this control folder is dropped and then registered, it will know how to find the URL to the js.
Here is what i have so far (in the user control )
```
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsClientScriptBlockRegistered("jqModal"))
Page.ClientScript.RegisterClientScriptInclude("jqModal", ResolveClientUrl("~js/jqModal.js"));
if (!Page.IsClientScriptBlockRegistered("jQuery"))
Page.ClientScript.RegisterClientScriptInclude("jQuery", ResolveClientUrl("~/js/jQuery.js"));
if (!Page.IsClientScriptBlockRegistered("tellAFriend"))
Page.ClientScript.RegisterClientScriptInclude("tellAFriend", ResolveClientUrl("js/tellAFriend.js"));
}
```
Any ideas? | You can use a helper class with static method:
```
public static class PageHelper {
public static void RegisterClientScriptIfNeeded( Page page, string key, string url ) {
if( false == page.IsClientScriptBlockRegistered( key )) {
page.ClientScript.RegisterClientScriptInclude( key , ResolveClientUrl( url ));
}
}
}
```
or you can have a similar instance method in some base class for page/webcontrol/usercontrol, which will do the same thing. |
127,973 | <p>I've been aware of Steve Yegge's advice to <a href="http://steve.yegge.googlepages.com/effective-emacs#item1" rel="nofollow noreferrer">swap Ctrl and Caps Lock</a> for a while now, although I don't use Emacs. I've just tried swapping them over as an experiment and I'm finding it difficult to adjust. There are several shortcuts that are second nature to me now and I hadn't realised quite how ingrained they are in how I use the keyboard.</p>
<p>In particular, I keep going to the old Ctrl key for <kbd>Ctrl</kbd>+<kbd>Z</kbd> (undo), and for cut, copy & paste operations (<kbd>Ctrl</kbd>+ <kbd>X</kbd>, <kbd>C</kbd> and <kbd>V</kbd>). Experimenting with going from the home position to <kbd>Ctrl</kbd>+<kbd>Z</kbd> I don't know which finger to put on <kbd>Z</kbd>, as it feels awkward with either my ring, middle or index finger. Is this something I'll get used to the same way I've got used to the original position and I should just give it time or <strong>is this arrangement not suited to windows keyboard shortcuts</strong>.</p>
<p>I'd be interested to hear from people who have successfully made the transition as well as those who have tried it and move back, but particularly from people who were doing it on <strong>windows</strong>. </p>
<p>Will it lead to any improvement in my typing speed or comfort when typing.</p>
<p>Do you have any tips for finger positions or typing training to speed up the transition.</p>
| [
{
"answer_id": 127984,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 2,
"selected": false,
"text": "<p>I've done it for quite a while now, and it's natural to me, even though I'm not an Emacs user either (I'm in the ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] | I've been aware of Steve Yegge's advice to [swap Ctrl and Caps Lock](http://steve.yegge.googlepages.com/effective-emacs#item1) for a while now, although I don't use Emacs. I've just tried swapping them over as an experiment and I'm finding it difficult to adjust. There are several shortcuts that are second nature to me now and I hadn't realised quite how ingrained they are in how I use the keyboard.
In particular, I keep going to the old Ctrl key for `Ctrl`+`Z` (undo), and for cut, copy & paste operations (`Ctrl`+ `X`, `C` and `V`). Experimenting with going from the home position to `Ctrl`+`Z` I don't know which finger to put on `Z`, as it feels awkward with either my ring, middle or index finger. Is this something I'll get used to the same way I've got used to the original position and I should just give it time or **is this arrangement not suited to windows keyboard shortcuts**.
I'd be interested to hear from people who have successfully made the transition as well as those who have tried it and move back, but particularly from people who were doing it on **windows**.
Will it lead to any improvement in my typing speed or comfort when typing.
Do you have any tips for finger positions or typing training to speed up the transition. | I ended up taking the advice in Zach's answer, but I also made `Caps Lock` behave as an `ESC` key if it was held and released on it's own using the AutoHotKey script in this gist: [CapsLockCtrlEscape.ahk](https://gist.github.com/sedm0784/4443120)
I also bound `Ctrl`+`Shift`+`Caps Lock` to `Caps Lock` for the rare occasions when I might need it using this AutoHotKey script:
```
#IfWinActive
^+Capslock::Capslock ; make CTRL+SHIFT+Caps-Lock the Caps Lock toggle
return
``` |
127,974 | <p>SQL is not my forte, but I'm working on it - thank you for the replies.</p>
<p>I am working on a report that will return the completion percent of services for indiviudals in our contracts. There is a master table "Contracts," each individual Contract can have multiple services from the "services" table, each service has multiple standards for the "standards" table which records the percent complete for each standard.</p>
<p>I've gotten as far as calculating the total percent complete for each individual service for a specific Contract_ServiceID, but how do I return all the services percentages for all the contracts? Something like this:</p>
<p>Contract Service Percent complete
<hr>
abc Company service 1 98%<br>
abc Company service 2 100%<br>
xyz Company service 1 50%
<br>
<br>
Here's what I have so far:</p>
<pre><code>SELECT
Contract_ServiceId,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta WITH (NOLOCK)
INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId
LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId
AND conSer.StandardReportId = standResp.StandardReportId
WHERE Contract_ServiceId = '[an id]'
GROUP BY Contract_ServiceID
</code></pre>
<p>This gets me too:<br><br>
Contract_serviceid Percent Complete
<hr>
[an id] 100%</p>
<p>EDIT: Tables didn't show up in post.</p>
| [
{
"answer_id": 128017,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to add in your select the company name and group by that and the service id and ditch the wher... | 2008/09/24 | [
"https://Stackoverflow.com/questions/127974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21717/"
] | SQL is not my forte, but I'm working on it - thank you for the replies.
I am working on a report that will return the completion percent of services for indiviudals in our contracts. There is a master table "Contracts," each individual Contract can have multiple services from the "services" table, each service has multiple standards for the "standards" table which records the percent complete for each standard.
I've gotten as far as calculating the total percent complete for each individual service for a specific Contract\_ServiceID, but how do I return all the services percentages for all the contracts? Something like this:
Contract Service Percent complete
---
abc Company service 1 98%
abc Company service 2 100%
xyz Company service 1 50%
Here's what I have so far:
```
SELECT
Contract_ServiceId,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta WITH (NOLOCK)
INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId
LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId
AND conSer.StandardReportId = standResp.StandardReportId
WHERE Contract_ServiceId = '[an id]'
GROUP BY Contract_ServiceID
```
This gets me too:
Contract\_serviceid Percent Complete
---
[an id] 100%
EDIT: Tables didn't show up in post. | I'm not sure if I understand the problem, if the result is ok for a service\_contract you canContract Service
```
SELECT con.ContractId,
con.Contract,
conSer.Contract_ServiceID,
conSer.Service,
(SUM(CompletionPercentage)/COUNT(CompletionPercentage)) * 100 as "Percent Complete"
FROM dbo.Standard sta WITH (NOLOCK)
INNER JOIN dbo.Contract_Service conSer ON sta.ServiceId = conSer.ServiceId
INNER JOIN dbo.Contract con ON con.ContractId = conSer.ContractId
LEFT OUTER JOIN dbo.StandardResponse standResp ON sta.StandardId = standResp.StandardId
AND conSer.StandardReportId = standResp.StandardReportId
GROUP BY con.ContractId, con.Contract, conSer.Contract_ServiceID, conSer.Service
```
make sure you have all the columns you select from the Contract table in the group by clause |
128,011 | <p>In a <code>CakePHP 1.2</code> app, I'm using </p>
<pre><code><?php $session->flash();?>
</code></pre>
<p>to output messages like "Record edited". It's working great.</p>
<p>However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message.</p>
<p>The flash message wraps itself in a <code>DIV tag</code>. I want to insert my dismiss code into that div, but I don't know how.</p>
| [
{
"answer_id": 128033,
"author": "Justin",
"author_id": 43,
"author_profile": "https://Stackoverflow.com/users/43",
"pm_score": 2,
"selected": true,
"text": "<p>Figured this out:\nCreate a new layout in your layouts folder:</p>\n\n<pre><code>layouts/message.ctp\n</code></pre>\n\n<p>In th... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
] | In a `CakePHP 1.2` app, I'm using
```
<?php $session->flash();?>
```
to output messages like "Record edited". It's working great.
However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message.
The flash message wraps itself in a `DIV tag`. I want to insert my dismiss code into that div, but I don't know how. | Figured this out:
Create a new layout in your layouts folder:
```
layouts/message.ctp
```
In that layout, include the call to output the content:
```
<?php echo $content_for_layout; ?>
```
Then when you set the flash message, specify the layout to use:
```
$this->Session->setFlash('Your record has been created! Wicked!','message');
``` |
128,012 | <p>I want to create a UITableView with varying row heights, and I'm trying to accomplish this by creating UILabels inside the UITableViewCells.</p>
<p>Here's my code so far:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"EntryCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
textView.numberOfLines = 0;
textView.text = [entries objectAtIndex:[indexPath row]];
[cell.contentView addSubview:textView];
[textView release];
return cell;
}
</code></pre>
<p>This gives me 2 lines of text per cell. However, each "entry" has a different number of lines, and I want the UITableViewCells to resize automatically, wrapping text as necessary, without changing the font size.</p>
<p><code>[textView sizeToFit]</code> and/or <code>[cell sizeToFit]</code> don't seem to work.</p>
<p>Here's how I want the UITableView to look:</p>
<pre><code>----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
</code></pre>
<p>Does anyone know how to do this properly?</p>
<p>Thanks.</p>
| [
{
"answer_id": 128329,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 5,
"selected": true,
"text": "<p>The UITableViewDelegate defines an optional method heightForRowAtIndexPath, which will get you started. You then n... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2119/"
] | I want to create a UITableView with varying row heights, and I'm trying to accomplish this by creating UILabels inside the UITableViewCells.
Here's my code so far:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"EntryCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
textView.numberOfLines = 0;
textView.text = [entries objectAtIndex:[indexPath row]];
[cell.contentView addSubview:textView];
[textView release];
return cell;
}
```
This gives me 2 lines of text per cell. However, each "entry" has a different number of lines, and I want the UITableViewCells to resize automatically, wrapping text as necessary, without changing the font size.
`[textView sizeToFit]` and/or `[cell sizeToFit]` don't seem to work.
Here's how I want the UITableView to look:
```
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
Lorem ipsum
----------------
Lorem ipsum
----------------
Lorem ipsum
Lorem ipsum
----------------
```
Does anyone know how to do this properly?
Thanks. | The UITableViewDelegate defines an optional method heightForRowAtIndexPath, which will get you started. You then need to use sizeWithFont.
There is some discussion of your precise problem here:
<http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/>
Text sizing was also discussed in [this thread](https://stackoverflow.com/questions/50467/how-do-i-size-a-uitextview-to-its-content) |
128,016 | <p>I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a <code>JFileChooser</code>; when it is closed, the absolute path of the selected file is written to a <code>JTextField</code>.</p>
<p>The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide.</p>
<p>I've tried this, but it didn't do anything, the text field is still too wide:</p>
<pre><code>fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647));
</code></pre>
<p>Currently, when it is empty, it is already 400px long, because of <code>GridBagConstraints</code> attached to it.</p>
<p>I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long.</p>
<p>So, how do I set the max size for a <code>JTextField</code> ?</p>
| [
{
"answer_id": 128040,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 5,
"selected": true,
"text": "<p>It may depend on the layout manager your text field is in. Some layout managers expand and some do not. Some expand... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] | I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a `JFileChooser`; when it is closed, the absolute path of the selected file is written to a `JTextField`.
The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide.
I've tried this, but it didn't do anything, the text field is still too wide:
```
fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647));
```
Currently, when it is empty, it is already 400px long, because of `GridBagConstraints` attached to it.
I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long.
So, how do I set the max size for a `JTextField` ? | It may depend on the layout manager your text field is in. Some layout managers expand and some do not. Some expand only in some cases, others always.
I'm assuming you're doing
```
filedNameTextField = new JTextField(80); // 80 == columns
```
If so, for most reasonable layouts, the field should not change size (at least, it shouldn't grow). Often layout managers behave badly when put into `JScrollPane`s.
In my experience, trying to control the sizes via `setMaximumSize` and `setPreferredWidth` and so on are precarious at best. Swing decided on its own with the layout manager and there's little you can do about it.
All that being said, I have no had the problem you are experiencing, which leads me to believe that some judicious use of a layout manager will solve the problem. |
128,028 | <p>We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.</p>
<p>For example, the page at the URL <a href="http://oursite/Page.aspx?a=1&b=2" rel="nofollow noreferrer">http://oursite/Page.aspx?a=1&b=2</a> would have JavaScript in it to read the "a" and "b" parameters. The JavaScript would then set the "src" attribute of an iframe based on those parameters. For example, "<iframe src="http://someothersite/Page.aspx?a=1&b=2" />"</p>
<p>We're currently doing this with server-side code that uses Microsoft's Anti Cross-Scripting library to check the parameters. However, a new requirement has come stating that we need to use JavaScript, and that it can't use any third-party JavaScript tools (such as jQuery or Prototype).</p>
<p>One way I know of is to replace any instances of "<", single quote, and double quote from the parameters before using them, but that doesn't seem secure enough to me.</p>
<p>One of the parameters is always a "P" followed by 9 integers.
The other parameter is always 15 alpha-numeric characters.
(Thanks Liam for suggesting I make that clear).</p>
<p>Does anybody have any suggestions for us?</p>
<p>Thank you very much for your time.</p>
| [
{
"answer_id": 128044,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 2,
"selected": false,
"text": "<p>Using a whitelist-approach would be better I guess.\nAvoid only stripping out \"bad\" things. Strip out anything excep... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21732/"
] | We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.
For example, the page at the URL <http://oursite/Page.aspx?a=1&b=2> would have JavaScript in it to read the "a" and "b" parameters. The JavaScript would then set the "src" attribute of an iframe based on those parameters. For example, "<iframe src="http://someothersite/Page.aspx?a=1&b=2" />"
We're currently doing this with server-side code that uses Microsoft's Anti Cross-Scripting library to check the parameters. However, a new requirement has come stating that we need to use JavaScript, and that it can't use any third-party JavaScript tools (such as jQuery or Prototype).
One way I know of is to replace any instances of "<", single quote, and double quote from the parameters before using them, but that doesn't seem secure enough to me.
One of the parameters is always a "P" followed by 9 integers.
The other parameter is always 15 alpha-numeric characters.
(Thanks Liam for suggesting I make that clear).
Does anybody have any suggestions for us?
Thank you very much for your time. | Upadte Sep 2022: Most JS runtimes now have a *URL* type which exposes query parameters via the [*searchParams*](https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams) property.
You need to supply a base URL even if you just want to get URL parameters from a relative URL, but it's better than rolling your own.
```
let searchParams/*: URLSearchParams*/ = new URL(
myUrl,
// Supply a base URL whose scheme allows
// query parameters in case `myUrl` is scheme or
// path relative.
'http://example.com/'
).searchParams;
console.log(searchParams.get('paramName')); // One value
console.log(searchParams.getAll('paramName'));
```
The difference between `.get` and `.getAll` is that the second returns an array which can be important if the same parameter name is mentioned multiple time as in `/path?foo=bar&foo=baz`.
---
Don't use escape and unescape, use decodeURIComponent.
E.g.
```
function queryParameters(query) {
var keyValuePairs = query.split(/[&?]/g);
var params = {};
for (var i = 0, n = keyValuePairs.length; i < n; ++i) {
var m = keyValuePairs[i].match(/^([^=]+)(?:=([\s\S]*))?/);
if (m) {
var key = decodeURIComponent(m[1]);
(params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));
}
}
return params;
}
```
and pass in document.location.search.
As far as turning < into <, that is not sufficient to make sure that the content can be safely injected into HTML without allowing script to run. Make sure you escape the following <, >, &, and ".
It will not guarantee that the parameters were not spoofed. If you need to verify that one of your servers generated the URL, do a search on URL signing. |
128,035 | <p>Note: while the use-case described is about using submodules within a project, the same applies to a normal <code>git clone</code> of a repository over HTTP.</p>
<p>I have a project under Git control. I'd like to add a submodule:</p>
<pre><code>git submodule add http://github.com/jscruggs/metric_fu.git vendor/plugins/metric_fu
</code></pre>
<p>But I get</p>
<pre><code>...
got 1b0313f016d98e556396c91d08127c59722762d0
got 4c42d44a9221209293e5f3eb7e662a1571b09421
got b0d6414e3ca5c2fb4b95b7712c7edbf7d2becac7
error: Unable to find abc07fcf79aebed56497e3894c6c3c06046f913a under http://github.com/jscruggs/metri...
Cannot obtain needed commit abc07fcf79aebed56497e3894c6c3c06046f913a
while processing commit ee576543b3a0820cc966cc10cc41e6ffb3415658.
fatal: Fetch failed.
Clone of 'http://github.com/jscruggs/metric_fu.git' into submodule path 'vendor/plugins/metric_fu'
</code></pre>
<p>I have my HTTP_PROXY set up:</p>
<pre><code>c:\project> echo %HTTP_PROXY%
http://proxy.mycompany:80
</code></pre>
<p>I even have a global Git setting for the http proxy:</p>
<pre><code>c:\project> git config --get http.proxy
http://proxy.mycompany:80
</code></pre>
<p>Has anybody gotten HTTP fetches to consistently work through a proxy? What's really strange is that a few project on GitHub work fine (<a href="http://github.com/collectiveidea/awesome_nested_set/" rel="noreferrer"><code>awesome_nested_set</code></a> for example), but others consistently fail (<a href="http://github.com/rails/rails/" rel="noreferrer">rails</a> for example).</p>
| [
{
"answer_id": 128198,
"author": "sethbc",
"author_id": 21722,
"author_profile": "https://Stackoverflow.com/users/21722",
"pm_score": 6,
"selected": false,
"text": "<p>It looks like you're using a mingw compile of Git on windows (or possibly another one I haven't heard about). There are... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | Note: while the use-case described is about using submodules within a project, the same applies to a normal `git clone` of a repository over HTTP.
I have a project under Git control. I'd like to add a submodule:
```
git submodule add http://github.com/jscruggs/metric_fu.git vendor/plugins/metric_fu
```
But I get
```
...
got 1b0313f016d98e556396c91d08127c59722762d0
got 4c42d44a9221209293e5f3eb7e662a1571b09421
got b0d6414e3ca5c2fb4b95b7712c7edbf7d2becac7
error: Unable to find abc07fcf79aebed56497e3894c6c3c06046f913a under http://github.com/jscruggs/metri...
Cannot obtain needed commit abc07fcf79aebed56497e3894c6c3c06046f913a
while processing commit ee576543b3a0820cc966cc10cc41e6ffb3415658.
fatal: Fetch failed.
Clone of 'http://github.com/jscruggs/metric_fu.git' into submodule path 'vendor/plugins/metric_fu'
```
I have my HTTP\_PROXY set up:
```
c:\project> echo %HTTP_PROXY%
http://proxy.mycompany:80
```
I even have a global Git setting for the http proxy:
```
c:\project> git config --get http.proxy
http://proxy.mycompany:80
```
Has anybody gotten HTTP fetches to consistently work through a proxy? What's really strange is that a few project on GitHub work fine ([`awesome_nested_set`](http://github.com/collectiveidea/awesome_nested_set/) for example), but others consistently fail ([rails](http://github.com/rails/rails/) for example). | What finally worked was setting the `http_proxy` environment variable. I had set `HTTP_PROXY` correctly, but git apparently likes the lower-case version better. |
128,038 | <p>I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have to explicitly open it in the first process with some sort of flag or argument?</p>
<h3>To clarify:</h3>
<p>I have a Java app that lists a folder and opens each file in the listing for processing it. It processes each file after the other. The processing of each file consists of reading it and doing some calculations based on the contents and it takes about 2 minutes. I also have another Java app that does the same thing but instead writes on the file. What I want is to be able to run these apps at the same time so the scenario goes like this. ReadApp lists the folder and finds files A, B, C. It opens file A and starts the reading. WriteApp lists the folder and finds files A, B, C. It opens file A, sees that is is open (by an exception or whatever way) and goes to file B. ReadApp finishes file A and continues to B. It sees that it is open and continues to C. It is crucial that WriteApp doesn't write while ReadApp is reading the same file or vice versa. They are different processes.</p>
| [
{
"answer_id": 128119,
"author": "KC Baltz",
"author_id": 9910,
"author_profile": "https://Stackoverflow.com/users/9910",
"pm_score": 4,
"selected": false,
"text": "<p>If you can use <strong>Java NIO</strong> (<em>JDK 1.4 or greater</em>), then I think you're looking for <code>java.nio.c... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11906/"
] | I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the file is already opened? Does this automatically make the second process get an exception if the file is open (which solves my problem) or do I have to explicitly open it in the first process with some sort of flag or argument?
### To clarify:
I have a Java app that lists a folder and opens each file in the listing for processing it. It processes each file after the other. The processing of each file consists of reading it and doing some calculations based on the contents and it takes about 2 minutes. I also have another Java app that does the same thing but instead writes on the file. What I want is to be able to run these apps at the same time so the scenario goes like this. ReadApp lists the folder and finds files A, B, C. It opens file A and starts the reading. WriteApp lists the folder and finds files A, B, C. It opens file A, sees that is is open (by an exception or whatever way) and goes to file B. ReadApp finishes file A and continues to B. It sees that it is open and continues to C. It is crucial that WriteApp doesn't write while ReadApp is reading the same file or vice versa. They are different processes. | FileChannel.lock is probably what you want.
```
try (
FileInputStream in = new FileInputStream(file);
java.nio.channels.FileLock lock = in.getChannel().lock();
Reader reader = new InputStreamReader(in, charset)
) {
...
}
```
(Disclaimer: Code not compiled and certainly not tested.)
Note the section entitled "platform dependencies" in the [API doc for FileLock](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileLock.html#pdep). |
128,042 | <p>In Java, I use a class in which some fields can be <code>null</code>. For example:</p>
<pre><code>class Foo {
String bar;
//....
}
</code></pre>
<p>I want to write a BarComparator for this class,</p>
<pre><code> private static class BarComparator
implements Comparator<Foo> {
public int compare( final Foo o1, final Foo o2 )
{
// Implementation goes here
}
}
</code></pre>
<p>Is there a standard way to deal with the fact that any of <code>o1</code>, <code>o2</code>, <code>o1.bar</code>, <code>o2.bar</code> can be <code>null</code>, without writing lots of nested <code>if</code>...<code>else</code>?</p>
<p>Cheers!</p>
| [
{
"answer_id": 128084,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>I think early return statements would be the other alternative to lots of ifs</p>\n\n<p>e.g.</p>\n\n<pre><code>if(o1=... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
] | In Java, I use a class in which some fields can be `null`. For example:
```
class Foo {
String bar;
//....
}
```
I want to write a BarComparator for this class,
```
private static class BarComparator
implements Comparator<Foo> {
public int compare( final Foo o1, final Foo o2 )
{
// Implementation goes here
}
}
```
Is there a standard way to deal with the fact that any of `o1`, `o2`, `o1.bar`, `o2.bar` can be `null`, without writing lots of nested `if`...`else`?
Cheers! | I guess you could wrap the call to the field compareTo method with a small static method to sort nulls high or low:
```
static <T extends Comparable<T>> int cp(T a, T b) {
return
a==null ?
(b==null ? 0 : Integer.MIN_VALUE) :
(b==null ? Integer.MAX_VALUE : a.compareTo(b));
}
```
Simple usage (multiple fields is as you would normally):
```
public int compare( final Foo o1, final Foo o2 ) {
return cp(o1.field, o2.field);
}
``` |
128,083 | <p>I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.</p>
<p>I cannot seem to find an easyway to essentially do the following:</p>
<pre><code>if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text")
<asp:TextBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
else
<asp:CheckBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
</code></pre>
<p>Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work</p>
| [
{
"answer_id": 128101,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": true,
"text": "<p>What about something similar to this in your markup in each the textbox and checkbox controls?</p>\n\n<blockquote>\n<pr... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20032/"
] | I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.
I cannot seem to find an easyway to essentially do the following:
```
if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text")
<asp:TextBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
else
<asp:CheckBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
```
Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work | What about something similar to this in your markup in each the textbox and checkbox controls?
>
>
> ```
> Visible=<%= Eval("type").tostring() == "text") %>
>
> ```
>
> |
128,103 | <p>Given an <code>Item</code> that has been appended to a <code>Form</code>, whats the best way to find out what index that item is at on the Form?</p>
<p><code>Form.append(Item)</code> will give me the index its initially added at, but if I later insert items before that the index will be out of sync.</p>
| [
{
"answer_id": 128355,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 2,
"selected": true,
"text": "<p>This was the best I could come up with:</p>\n\n<pre><code>private int getItemIndex(Item item, Form form) {\n for(int i = 0,... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270/"
] | Given an `Item` that has been appended to a `Form`, whats the best way to find out what index that item is at on the Form?
`Form.append(Item)` will give me the index its initially added at, but if I later insert items before that the index will be out of sync. | This was the best I could come up with:
```
private int getItemIndex(Item item, Form form) {
for(int i = 0, size = form.size(); i < size; i++) {
if(form.get(i).equals(item)) {
return i;
}
}
return -1;
}
```
I haven't actually tested this but it should work, I just don't like having to enumerate every item but then there should never be that many so I guess its ok. |
128,104 | <p>What is a good implementation of a IsLeapYear function in VBA? </p>
<p><b>Edit: </b>I ran the if-then and the DateSerial implementation with iterations wrapped in a timer, and the DateSerial was quicker on the average by 1-2 ms (5 runs of 300 iterations, with 1 average cell worksheet formula also working).</p>
| [
{
"answer_id": 128105,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 6,
"selected": true,
"text": "<pre><code>Public Function isLeapYear(Yr As Integer) As Boolean \n\n ' returns FALSE if not Leap Year, TRUE if Le... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] | What is a good implementation of a IsLeapYear function in VBA?
**Edit:** I ran the if-then and the DateSerial implementation with iterations wrapped in a timer, and the DateSerial was quicker on the average by 1-2 ms (5 runs of 300 iterations, with 1 average cell worksheet formula also working). | ```
Public Function isLeapYear(Yr As Integer) As Boolean
' returns FALSE if not Leap Year, TRUE if Leap Year
isLeapYear = (Month(DateSerial(Yr, 2, 29)) = 2)
End Function
```
I originally got this function from Chip Pearson's great Excel site.
[Pearson's site](http://www.cpearson.com/excel/MainPage.aspx) |
128,162 | <p>My program generates relatively simple PDF documents on request, but I'm having trouble with unicode characters, like kanji or odd math symbols. To write a normal string in PDF, you place it in brackets:</p>
<pre><code>(something)
</code></pre>
<p>There is also the option to escape a character with octal codes:</p>
<pre><code>(\527)
</code></pre>
<p>but this only goes up to 512 characters. How do you encode or escape higher characters? I've seen references to byte streams and hex-encoded strings, but none of the references I've read seem to be willing to tell me how to actually do it.</p>
<hr>
<p><strong>Edit:</strong> Alternatively, point me to a good Java PDF library that will do the job for me. The one I'm currently using is a version of gnujpdf (which I've fixed several bugs in, since the original author appears to have gone AWOL), that allows you to program against an AWT Graphics interface, and ideally any replacement should do the same.</p>
<p>The alternatives seem to be either HTML -> PDF, or a programmatic model based on paragraphs and boxes that feels very much like HTML. iText is an example of the latter. This would mean rewriting my existing code, and I'm not convinced they'd give me the same flexibility in laying out.</p>
<hr>
<p><strong>Edit 2:</strong> I didn't realise before, but the iText library has a Graphics2D API and seems to handle unicode perfectly, so that's what I'll be using. Though it isn't an answer to the question as asked, it solves the problem for me.</p>
<hr>
<p><strong>Edit 3:</strong> iText is working nicely for me. I guess the lesson is, when faced with something that seems pointlessly difficult, look for somebody who knows more about it than you.</p>
| [
{
"answer_id": 128351,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not a PDF expert, and (as Ferruccio said) the PDF specs at Adobe should tell you everything, but a thought popped u... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000/"
] | My program generates relatively simple PDF documents on request, but I'm having trouble with unicode characters, like kanji or odd math symbols. To write a normal string in PDF, you place it in brackets:
```
(something)
```
There is also the option to escape a character with octal codes:
```
(\527)
```
but this only goes up to 512 characters. How do you encode or escape higher characters? I've seen references to byte streams and hex-encoded strings, but none of the references I've read seem to be willing to tell me how to actually do it.
---
**Edit:** Alternatively, point me to a good Java PDF library that will do the job for me. The one I'm currently using is a version of gnujpdf (which I've fixed several bugs in, since the original author appears to have gone AWOL), that allows you to program against an AWT Graphics interface, and ideally any replacement should do the same.
The alternatives seem to be either HTML -> PDF, or a programmatic model based on paragraphs and boxes that feels very much like HTML. iText is an example of the latter. This would mean rewriting my existing code, and I'm not convinced they'd give me the same flexibility in laying out.
---
**Edit 2:** I didn't realise before, but the iText library has a Graphics2D API and seems to handle unicode perfectly, so that's what I'll be using. Though it isn't an answer to the question as asked, it solves the problem for me.
---
**Edit 3:** iText is working nicely for me. I guess the lesson is, when faced with something that seems pointlessly difficult, look for somebody who knows more about it than you. | The simple answer is that there's no simple answer. If you take a look at the PDF specification, you'll see an entire chapter — and a long one at that — devoted to the mechanisms of text display. I implemented all of the PDF support for my company, and handling text was by far the most complex part of exercise. The solution you discovered — use a 3rd party library to do the work for you — is really the best choice, unless you have very specific, special-purpose requirements for your PDF files. |
128,190 | <p>I need help logging errors from T-SQL in SQL Server 2000. We need to log errors that we trap, but are having trouble getting the same information we would have had sitting in front of SQL Server Management Studio.</p>
<p>I can get a message without any argument substitution like this:</p>
<pre><code>SELECT MSG.description from master.dbo.sysmessages MSG
INNER JOIN sys.syslanguages LANG ON MSG.msglangID=LANG.msglangid
WHERE MSG.error=@err AND LANG.langid=@@LANGID
</code></pre>
<p>But I have not found any way of finding out the error arguments. I want to see:</p>
<p>Constraint violation MYCONSTRAINT2 on table MYTABLE7</p>
<p>not</p>
<p>Constraint violation %s on table %s</p>
<p>Googling has only turned up exotic schemes using DBCC OUTPUTBUFFER that require admin access and aren't appropriate for production code. How do I get an error message with argument replacement?</p>
| [
{
"answer_id": 128202,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 0,
"selected": false,
"text": "<p>Any chance you'll be upgrading to SQL2005 soon? If so, you could probably leverage their TRY/CATCH model to more ... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/945/"
] | I need help logging errors from T-SQL in SQL Server 2000. We need to log errors that we trap, but are having trouble getting the same information we would have had sitting in front of SQL Server Management Studio.
I can get a message without any argument substitution like this:
```
SELECT MSG.description from master.dbo.sysmessages MSG
INNER JOIN sys.syslanguages LANG ON MSG.msglangID=LANG.msglangid
WHERE MSG.error=@err AND LANG.langid=@@LANGID
```
But I have not found any way of finding out the error arguments. I want to see:
Constraint violation MYCONSTRAINT2 on table MYTABLE7
not
Constraint violation %s on table %s
Googling has only turned up exotic schemes using DBCC OUTPUTBUFFER that require admin access and aren't appropriate for production code. How do I get an error message with argument replacement? | In .Net, retrieving error messages (and anything output from *print* or *raiserror*) from sql server is as simple as setting one property on your SqlConnection ( *.FireInfoMessageEventOnUserErrors = True*) and handling the connection's InfoMessage event. The data received by .Net matches what you get in the *Messages* window in the SQL Server Management Studio results grid.
All the code goes in the function that handles the event, and you can abstract that so that all your connections point to the same method, so there's nothing else to change in the rest of the app aside from the two lines of code when you create new connections to set the property and event (*and you have that abstracted away so you only need to do it in one place, right?*)
Here is a link to what I consider the [definitive error guide for SQL Server](http://www.sommarskog.se/error-handling-I.html).
<http://www.sommarskog.se/error-handling-I.html>
In certain circumstances SQL Server will continue processing even after an error. See the heading labeled *[What Happens when an Error Occurs?](http://www.sommarskog.se/error-handling-I.html#whathappens)* from the previous link. |
128,232 | <p>I am trying to do the following in <code>SQL*PLUS</code> in <code>ORACLE</code>.</p>
<ul>
<li>Create a variable</li>
<li>Pass it as output variable to my method invocation</li>
<li>Print the value from output variable</li>
</ul>
<p>I get</p>
<blockquote>
<p><em>undeclared variable</em></p>
</blockquote>
<p>error. I am trying to create a variable that persists in the session till i close the <code>SQL*PLUS</code> window.</p>
<pre><code>variable subhandle number;
exec MYMETHOD - (CHANGE_SET => 'SYNC_SET', - DESCRIPTION => 'Change data for emp',
- SUBSCRIPTION_HANDLE => :subhandle);
print subhandle;
</code></pre>
| [
{
"answer_id": 128275,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>Please can you re-post, but formatting the code with the code tag.... (ie the 101 010 button) I think some extra \"-... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15425/"
] | I am trying to do the following in `SQL*PLUS` in `ORACLE`.
* Create a variable
* Pass it as output variable to my method invocation
* Print the value from output variable
I get
>
> *undeclared variable*
>
>
>
error. I am trying to create a variable that persists in the session till i close the `SQL*PLUS` window.
```
variable subhandle number;
exec MYMETHOD - (CHANGE_SET => 'SYNC_SET', - DESCRIPTION => 'Change data for emp',
- SUBSCRIPTION_HANDLE => :subhandle);
print subhandle;
``` | It should be OK - check what you did carefully against this:
```
SQL> create procedure myproc (p1 out number)
2 is
3 begin
4 p1 := 42;
5 end;
6 /
Procedure created.
SQL> variable subhandle number
SQL> exec myproc(:subhandle)
PL/SQL procedure successfully completed.
SQL> print subhandle
SUBHANDLE
----------
42
``` |
128,241 | <p>Here's a question that's been haunting me for a year now. The root question is how do I set the size of an element relative to its parent so that it is inset by N pixels from every edge? Setting the width would be nice, but you don't know the width of the parent, and you want the elements to resize with the window. (You don't want to use percents because you need a specific number of pixels.) </p>
<p>Edit
I also need to prevent the content (or lack of content) from stretching or shrinking both elements. First answer I got was to use padding on the parent, which would work great. I want the parent to be exactly 25% wide, and exactly the same height as the browser client area, without the child being able to push it and get a scroll bar.
/Edit</p>
<p>I tried solving this problem using {top:Npx;left:Npx;bottom:Npx;right:Npx;} but it only works in certain browsers.</p>
<p>I could potentially write some javascript with jquery to fix all elements with every page resize, but I'm not real happy with that solution. (What if I want the top offset by 10px but the bottom only 5px? It gets complicated.)</p>
<p>What I'd like to know is either how to solve this in a cross-browser way, or some list of browsers which allow the easy CSS solution. Maybe someone out there has a trick that makes this easy.</p>
| [
{
"answer_id": 128253,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 0,
"selected": false,
"text": "<p>Simply apply some padding to the parent element, and no width on the child element. Assuming they're both <code>display:blo... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5114/"
] | Here's a question that's been haunting me for a year now. The root question is how do I set the size of an element relative to its parent so that it is inset by N pixels from every edge? Setting the width would be nice, but you don't know the width of the parent, and you want the elements to resize with the window. (You don't want to use percents because you need a specific number of pixels.)
Edit
I also need to prevent the content (or lack of content) from stretching or shrinking both elements. First answer I got was to use padding on the parent, which would work great. I want the parent to be exactly 25% wide, and exactly the same height as the browser client area, without the child being able to push it and get a scroll bar.
/Edit
I tried solving this problem using {top:Npx;left:Npx;bottom:Npx;right:Npx;} but it only works in certain browsers.
I could potentially write some javascript with jquery to fix all elements with every page resize, but I'm not real happy with that solution. (What if I want the top offset by 10px but the bottom only 5px? It gets complicated.)
What I'd like to know is either how to solve this in a cross-browser way, or some list of browsers which allow the easy CSS solution. Maybe someone out there has a trick that makes this easy. | The [The CSS Box model](http://www.hicksdesign.co.uk/journal/3d-css-box-model) might provide insight for you, but my guess is that you're not going to achieve pixel-perfect layout with CSS alone.
If I understand correctly, you want the parent to be 25% wide and exactly the height of the browser display area. Then you want the child to be 25% - 2n pixels wide and 100%-2n pixels in height with n pixels surrounding the child. No current CSS specification includes support these types of calculations (although IE5, IE6, and IE7 have non-standard [support for CSS expressions](http://msdn.microsoft.com/en-us/library/ms531196(VS.85).aspx) and [IE8 is dropping support](http://support.microsoft.com/kb/949787) for CSS expressions in IE8-standards mode).
You can force the parent to 100% of the browser area and 25% wide, but you cannot stretch the child's height to pixel perfection with this...
```
<style type="text/css">
html { height: 100%; }
body { font: normal 11px verdana; height: 100%; }
#one { background-color:gray; float:left; height:100%; padding:5px; width:25%; }
#two { height: 100%; background-color:pink;}
</style>
</head>
<body>
<div id="one">
<div id="two">
<p>content ... content ... content</p>
</div>
</div>
```
...but a horizontal scrollbar will appear. Also, if the content is squeezed, the parent background will not extend past 100%. This is perhaps the padding example you presented in the question itself.
You can achieve the *illusion* that you're seeking through images and additional divs, but CSS alone, I don't believe, can achieve pixel perfection with that height requirement in place. |
128,259 | <p>I have a list of data in the following form:</p>
<p><code>[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))</code></p>
<p>The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.</p>
<p>Sometimes for the same id the descriptions can vary slightly, as follows:</p>
<p>IPI00110753</p>
<ul>
<li>Tubulin alpha-1A chain</li>
<li>Tubulin alpha-1 chain</li>
<li>Alpha-tubulin 1</li>
<li>Alpha-tubulin isotype M-alpha-1</li>
</ul>
<p>(Note that this example is taken from the <a href="http://www.uniprot.org/uniprot/P68369" rel="nofollow noreferrer">uniprot protein database</a>.) </p>
<p>I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.</p>
<p>I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.</p>
<p>I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing? </p>
<p>Thank you for reading my question, <br>
Tim</p>
<p><strong>Update</strong></p>
<p>based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time. </p>
<p>Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?</p>
<p>*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot.</p>
| [
{
"answer_id": 128361,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>Sets don't have keys. The element <strong>is</strong> the key.</p>\n\n<p>If you think you want keys, you have a mapping... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14107/"
] | I have a list of data in the following form:
`[(id\__1_, description, id\_type), (id\__2_, description, id\_type), ... , (id\__n_, description, id\_type))`
The data are loaded from files that belong to the same group. In each group there could be multiples of the same id, each coming from different files. I don't care about the duplicates, so I thought that a nice way to store all of this would be to throw it into a Set type. But there's a problem.
Sometimes for the same id the descriptions can vary slightly, as follows:
IPI00110753
* Tubulin alpha-1A chain
* Tubulin alpha-1 chain
* Alpha-tubulin 1
* Alpha-tubulin isotype M-alpha-1
(Note that this example is taken from the [uniprot protein database](http://www.uniprot.org/uniprot/P68369).)
I don't care if the descriptions vary. I cannot throw them away because there is a chance that the protein database I am using will not contain a listing for a certain identifier. If this happens I will want to be able to display the human readable description to the biologists so they know roughly what protein they are looking at.
I am currently solving this problem by using a dictionary type. However I don't really like this solution because it uses a lot of memory (I have a lot of these ID's). This is only an intermediary listing of them. There is some additional processing the ID's go through before they are placed in the database so I would like to keep my data-structure smaller.
I have two questions really. First, will I get a smaller memory footprint using the Set type (over the dictionary type) for this, or should I use a sorted list where I check every time I insert into the list to see if the ID exists, or is there a third solution that I haven't thought of? Second, if the Set type is the better answer how do I key it to look at just the first element of the tuple instead of the whole thing?
Thank you for reading my question,
Tim
**Update**
based on some of the comments I received let me clarify a little. Most of what I do with data-structure is insert into it. I only read it twice, once to annotate it with additional information,\* and once to do be inserted into the database. However down the line there may be additional annotation that is done before I insert into the database. Unfortunately I don't know if that will happen at this time.
Right now I am looking into storing this data in a structure that is not based on a hash-table (ie. a dictionary). I would like the new structure to be fairly quick on insertion, but reading it can be linear since I only really do it twice. I am trying to move away from the hash table to save space. Is there a better structure or is a hash-table about as good as it gets?
\*The information is a list of Swiss-Prot protein identifiers that I get by querying uniprot. | Sets don't have keys. The element **is** the key.
If you think you want keys, you have a mapping. More-or-less by definition.
Sequential list lookup can be slow, even using a binary search. Mappings use hashes and are fast.
Are you talking about a dictionary like this?
```
{ 'id1': [ ('description1a', 'type1'), ('description1b','type1') ],
'id2': [ ('description2', 'type2') ],
...
}
```
This sure seems minimal. ID's are only represented once.
Perhaps you have something like this?
```
{ 'id1': ( ('description1a', 'description1b' ), 'type1' ),
'id2': ( ('description2',), 'type2' ),
...
}
```
I'm not sure you can find anything more compact unless you resort to using the `struct` module. |
128,267 | <p>I'm trying to define a task that emits (using echo) a message when a target completes execution, regardless of whether that target was successful or not. Specifically, the target executes a task to run some unit tests, and I want to emit a message indicating where the results are available:</p>
<pre><code><target name="mytarget">
<testng outputDir="${results}" ...>
...
</testng>
<echo>Tests complete. Results available in ${results}</echo>
</target>
</code></pre>
<p>Unfortunately, if the tests fail, the task fails and execution aborts. So the message is only output if the tests pass - the opposite of what I want. I know I can put the task before the task, but this will make it easier for users to miss this message. Is what I'm trying to do possible?</p>
<p><strong>Update:</strong> It turns out I'm dumb. I had haltOnFailure="true" in my <testng> task, which explains the behaviour I was seeing. Now the issue is that setting this to false causes the overall ant build to succeed even if tests fail, which is not what I want. The answer below using the task looks like it might be what I want..</p>
| [
{
"answer_id": 128323,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 3,
"selected": false,
"text": "<p>According to the <a href=\"http://ant.apache.org/manual/Tasks/exec.html\" rel=\"nofollow noreferrer\">Ant docs</a>, there a... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16977/"
] | I'm trying to define a task that emits (using echo) a message when a target completes execution, regardless of whether that target was successful or not. Specifically, the target executes a task to run some unit tests, and I want to emit a message indicating where the results are available:
```
<target name="mytarget">
<testng outputDir="${results}" ...>
...
</testng>
<echo>Tests complete. Results available in ${results}</echo>
</target>
```
Unfortunately, if the tests fail, the task fails and execution aborts. So the message is only output if the tests pass - the opposite of what I want. I know I can put the task before the task, but this will make it easier for users to miss this message. Is what I'm trying to do possible?
**Update:** It turns out I'm dumb. I had haltOnFailure="true" in my <testng> task, which explains the behaviour I was seeing. Now the issue is that setting this to false causes the overall ant build to succeed even if tests fail, which is not what I want. The answer below using the task looks like it might be what I want.. | The solution to your problem is to use the `failureProperty` in conjunction with the `haltOnFailure` property of the testng task like this:
```
<target name="mytarget">
<testng outputDir="${results}" failureProperty="tests.failed" haltOnFailure="false" ...>
...
</testng>
<echo>Tests complete. Results available in ${results}</echo>
</target>
```
Then, elsewhere when you want the build to fail you add ant code like this:
```
<target name="doSomethingIfTestsWereSuccessful" unless="tests.failed">
...
</target>
<target name="doSomethingIfTestsFailed" if="tests.failed">
...
<fail message="Tests Failed" />
</target>
```
You can then call doSomethingIfTestsFailed where you want your ant build to fail. |
128,277 | <p><strong>UPDATE</strong></p>
<p>I'm basically binding the query to a WinForms <code>DataGridView</code>. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be <code>First Name</code> instead of <code>FirstName</code>.</p>
<hr>
<p>How do you create your own custom column names in LINQ? </p>
<p>For example:</p>
<pre><code>Dim query = From u In db.Users _
Select u.FirstName AS 'First Name'
</code></pre>
| [
{
"answer_id": 128286,
"author": "James Hall",
"author_id": 514,
"author_profile": "https://Stackoverflow.com/users/514",
"pm_score": 2,
"selected": false,
"text": "<p>I dont see why you would have to do that, if you are trying to do that for a grid or something, why not just name the he... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] | **UPDATE**
I'm basically binding the query to a WinForms `DataGridView`. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be `First Name` instead of `FirstName`.
---
How do you create your own custom column names in LINQ?
For example:
```
Dim query = From u In db.Users _
Select u.FirstName AS 'First Name'
``` | I solved my own problem but all of your answers were very helpful and pointed me in the right direction.
In my `LINQ` query, if a column name had more than one word I would separate the words with an underscore:
```
Dim query = From u In Users _
Select First_Name = u.FirstName
```
Then, within the `Paint` method of the `DataGridView`, I replaced all underscores within the header with a space:
```
Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint
For Each c As DataGridViewColumn In DataGridView1.Columns
c.HeaderText = c.HeaderText.Replace("_", " ")
Next
End Sub
``` |
128,279 | <p>I have a <a href="http://en.wikipedia.org/wiki/WiX" rel="nofollow noreferrer">WiX</a> installer and a single custom action (plus undo and rollback) for it which uses a property from the installer. The custom action has to happen after all the files are on the hard disk. It seems that you need 16 entries in the WXS file for this; eight within the root, like so:</p>
<pre><code><CustomAction Id="SetForRollbackDo" Execute="immediate" Property="RollbackDo" Value="[MYPROP]"/>
<CustomAction Id="RollbackDo" Execute="rollback" BinaryKey="MyDLL" DllEntry="UndoThing" Return="ignore"/>
<CustomAction Id="SetForDo" Execute="immediate" Property="Do" Value="[MYPROP]"/>
<CustomAction Id="Do" Execute="deferred" BinaryKey="MyDLL" DllEntry="DoThing" Return="check"/>
<CustomAction Id="SetForRollbackUndo" Execute="immediate" Property="RollbackUndo" Value="[MYPROP]"/>
<CustomAction Id="RollbackUndo" Execute="rollback" BinaryKey="MyDLL" DllEntry="DoThing" Return="ignore"/>
<CustomAction Id="SetForUndo" Execute="immediate" Property="Undo" Value="[MYPROP]"/>
<CustomAction Id="Undo" Execute="deferred" BinaryKey="MyDLL" DllEntry="UndoThing" Return="check"/>
</code></pre>
<p>And eight within the <code>InstallExecuteSequence</code>, like so:</p>
<pre><code><Custom Action="SetForRollbackDo" After="InstallFiles">REMOVE&lt;>"ALL"</Custom>
<Custom Action="RollbackDo" After="SetForRollbackDo">REMOVE&lt;>"ALL"</Custom>
<Custom Action="SetForDo" After="RollbackDo">REMOVE&lt;>"ALL"</Custom>
<Custom Action="Do" After="SetForDo">REMOVE&lt;>"ALL"</Custom>
<Custom Action="SetForRollbackUndo" After="InstallInitialize">REMOVE="ALL"</Custom>
<Custom Action="RollbackUndo" After="SetForRollbackUndo">REMOVE="ALL"</Custom>
<Custom Action="SetForUndo" After="RollbackUndo">REMOVE="ALL"</Custom>
<Custom Action="Undo" After="SetForUndo">REMOVE="ALL"</Custom>
</code></pre>
<p>Is there a better way?</p>
| [
{
"answer_id": 144688,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 2,
"selected": false,
"text": "<p>If you have complex custom actions that need to support rollback, you might consider writing a Wix extension. Exten... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20686/"
] | I have a [WiX](http://en.wikipedia.org/wiki/WiX) installer and a single custom action (plus undo and rollback) for it which uses a property from the installer. The custom action has to happen after all the files are on the hard disk. It seems that you need 16 entries in the WXS file for this; eight within the root, like so:
```
<CustomAction Id="SetForRollbackDo" Execute="immediate" Property="RollbackDo" Value="[MYPROP]"/>
<CustomAction Id="RollbackDo" Execute="rollback" BinaryKey="MyDLL" DllEntry="UndoThing" Return="ignore"/>
<CustomAction Id="SetForDo" Execute="immediate" Property="Do" Value="[MYPROP]"/>
<CustomAction Id="Do" Execute="deferred" BinaryKey="MyDLL" DllEntry="DoThing" Return="check"/>
<CustomAction Id="SetForRollbackUndo" Execute="immediate" Property="RollbackUndo" Value="[MYPROP]"/>
<CustomAction Id="RollbackUndo" Execute="rollback" BinaryKey="MyDLL" DllEntry="DoThing" Return="ignore"/>
<CustomAction Id="SetForUndo" Execute="immediate" Property="Undo" Value="[MYPROP]"/>
<CustomAction Id="Undo" Execute="deferred" BinaryKey="MyDLL" DllEntry="UndoThing" Return="check"/>
```
And eight within the `InstallExecuteSequence`, like so:
```
<Custom Action="SetForRollbackDo" After="InstallFiles">REMOVE<>"ALL"</Custom>
<Custom Action="RollbackDo" After="SetForRollbackDo">REMOVE<>"ALL"</Custom>
<Custom Action="SetForDo" After="RollbackDo">REMOVE<>"ALL"</Custom>
<Custom Action="Do" After="SetForDo">REMOVE<>"ALL"</Custom>
<Custom Action="SetForRollbackUndo" After="InstallInitialize">REMOVE="ALL"</Custom>
<Custom Action="RollbackUndo" After="SetForRollbackUndo">REMOVE="ALL"</Custom>
<Custom Action="SetForUndo" After="RollbackUndo">REMOVE="ALL"</Custom>
<Custom Action="Undo" After="SetForUndo">REMOVE="ALL"</Custom>
```
Is there a better way? | I came across the same problem when writing WiX installers. My approach to the problem is mostly like what Mike suggested and I have a blog post *[Implementing WiX custom actions part 2: using custom tables](http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/)*.
In short, you can define a custom table for your data:
```xml
<CustomTable Id="LocalGroupPermissionTable">
<Column Id="GroupName" Category="Text" PrimaryKey="yes" Type="string"/>
<Column Id="ACL" Category="Text" PrimaryKey="no" Type="string"/>
<Row>
<Data Column="GroupName">GroupToCreate</Data>
<Data Column="ACL">SeIncreaseQuotaPrivilege</Data>
</Row>
</CustomTable>
```
Then write a single immediate custom action to schedule the deferred, rollback, and commit custom actions:
```c
extern "C" UINT __stdcall ScheduleLocalGroupCreation(MSIHANDLE hInstall)
{
try {
ScheduleAction(hInstall,L"SELECT * FROM CreateLocalGroupTable", L"CA.LocalGroupCustomAction.deferred", L"create");
ScheduleAction(hInstall,L"SELECT * FROM CreateLocalGroupTable", L"CA.LocalGroupCustomAction.rollback", L"create");
}
catch( CMsiException & ) {
return ERROR_INSTALL_FAILURE;
}
return ERROR_SUCCESS;
}
```
The following code shows how to schedule a single custom action. Basically you just open the custom table, read the property you want (you can get the schema of any custom table by calling **MsiViewGetColumnInfo()**), then format the properties needed into the **CustomActionData** property (I use the form `/propname:value`, although you can use anything you want).
```c
void ScheduleAction(MSIHANDLE hInstall,
const wchar_t *szQueryString,
const wchar_t *szCustomActionName,
const wchar_t *szAction)
{
CTableView view(hInstall,szQueryString);
PMSIHANDLE record;
//For each record in the custom action table
while( view.Fetch(record) ) {
//get the "GroupName" property
wchar_t recordBuf[2048] = {0};
DWORD dwBufSize(_countof(recordBuf));
MsiRecordGetString(record, view.GetPropIdx(L"GroupName"), recordBuf, &dwBufSize);
//Format two properties "GroupName" and "Operation" into
//the custom action data string.
CCustomActionDataUtil formatter;
formatter.addProp(L"GroupName", recordBuf);
formatter.addProp(L"Operation", szAction );
//Set the "CustomActionData" property".
MsiSetProperty(hInstall,szCustomActionName,formatter.GetCustomActionData());
//Add the custom action into installation script. Each
//MsiDoAction adds a distinct custom action into the
//script, so if we have multiple entries in the custom
//action table, the deferred custom action will be called
//multiple times.
nRet = MsiDoAction(hInstall,szCustomActionName);
}
}
```
As for implementing the deferred, rollback and commit custom actions, I prefer to use only one function and use **MsiGetMode()** to distinguish what should be done:
```c
extern "C" UINT __stdcall LocalGroupCustomAction(MSIHANDLE hInstall)
{
try {
//Parse the properties from the "CustomActionData" property
std::map<std::wstring,std::wstring> mapProps;
{
wchar_t szBuf[2048]={0};
DWORD dwBufSize = _countof(szBuf); MsiGetProperty(hInstall,L"CustomActionData",szBuf,&dwBufSize);
CCustomActionDataUtil::ParseCustomActionData(szBuf,mapProps);
}
//Find the "GroupName" and "Operation" property
std::wstring sGroupName;
bool bCreate = false;
std::map<std::wstring,std::wstring>::const_iterator it;
it = mapProps.find(L"GroupName");
if( mapProps.end() != it ) sGroupName = it->second;
it = mapProps.find(L"Operation");
if( mapProps.end() != it )
bCreate = wcscmp(it->second.c_str(),L"create") == 0 ? true : false ;
//Since we know what opeartion to perform, and we know whether it is
//running rollback, commit or deferred script by MsiGetMode, the
//implementation is straight forward
if( MsiGetMode(hInstall,MSIRUNMODE_SCHEDULED) ) {
if( bCreate )
CreateLocalGroup(sGroupName.c_str());
else
DeleteLocalGroup(sGroupName.c_str());
}
else if( MsiGetMode(hInstall,MSIRUNMODE_ROLLBACK) ) {
if( bCreate )
DeleteLocalGroup(sGroupName.c_str());
else
CreateLocalGroup(sGroupName.c_str());
}
}
catch( CMsiException & ) {
return ERROR_INSTALL_FAILURE;
}
return ERROR_SUCCESS;
}
```
By using the above technique, for a typical custom action set you can reduce the custom action table to five entries:
```
<CustomAction Id="CA.ScheduleLocalGroupCreation"
Return="check"
Execute="immediate"
BinaryKey="CustomActionDLL"
DllEntry="ScheduleLocalGroupCreation"
HideTarget="yes"/>
<CustomAction Id="CA.ScheduleLocalGroupDeletion"
Return="check"
Execute="immediate"
BinaryKey="CustomActionDLL"
DllEntry="ScheduleLocalGroupDeletion"
HideTarget="yes"/>
<CustomAction Id="CA.LocalGroupCustomAction.deferred"
Return="check"
Execute="deferred"
BinaryKey="CustomActionDLL"
DllEntry="LocalGroupCustomAction"
HideTarget="yes"/>
<CustomAction Id="CA.LocalGroupCustomAction.commit"
Return="check"
Execute="commit"
BinaryKey="CustomActionDLL"
DllEntry="LocalGroupCustomAction"
HideTarget="yes"/>
<CustomAction Id="CA.LocalGroupCustomAction.rollback"
Return="check"
Execute="rollback"
BinaryKey="CustomActionDLL"
DllEntry="LocalGroupCustomAction"
HideTarget="yes"/>
```
And InstallSquence table to only two entries:
```
<InstallExecuteSequence>
<Custom Action="CA.ScheduleLocalGroupCreation"
After="InstallFiles">
Not Installed
</Custom>
<Custom Action="CA.ScheduleLocalGroupDeletion"
After="InstallFiles">
Installed
</Custom>
</InstallExecuteSequence>
```
In addition, with a little effort most of the code can be written to be reused (such as reading from custom table, getting the properties, formatting the needed properties and set to CustomActionData properties), and the entries in the custom action table now is not application specific (the application specific data is written in the custom table), we can put custom action table in a file of its own and just include it in each WiX project.
For the custom action DLL file, since the application data is read from the custom table, we can keep application specific details out of the DLL implementation, so the custom action table can become a library and thus easier to reuse.
This is how currently I write my WiX custom actions, if anyone knows how to improve further I would very appreciate it. :)
(You can also find the complete source code in my blog post, *[Implementing Wix custom actions part 2: using custom tables](http://technicaltrack.wordpress.com/2011/06/15/implmenting-wix-custom-actions-part-2-using-custom-tables/)*.). |
128,282 | <p>I am currently using the following code to create a web request:</p>
<pre><code>Dim myRequest As WebRequest = WebRequest.Create("http://foo.com/bar")
Dim myResponse As WebResponse = myRequest.GetResponse()
</code></pre>
<p>The problem is that this "locks" up the program until the request is completed (and program will hang if the request never completes). How do you change something like this to execute asynchronously so that other tasks can be completed while the web request completes?</p>
| [
{
"answer_id": 128289,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>myRequest.BeginGetResponse()</p>\n\n<p>You'll also need to call EndGetReponse() when the request is finished (deter... | 2008/09/24 | [
"https://Stackoverflow.com/questions/128282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9129/"
] | I am currently using the following code to create a web request:
```
Dim myRequest As WebRequest = WebRequest.Create("http://foo.com/bar")
Dim myResponse As WebResponse = myRequest.GetResponse()
```
The problem is that this "locks" up the program until the request is completed (and program will hang if the request never completes). How do you change something like this to execute asynchronously so that other tasks can be completed while the web request completes? | You'll use BeginGetResponse to add a AsyncCallback, which basically points to some other method in your code that will be called when the WebRequest returns. There is a good [sample here](http://www.sitepoint.com/forums/showpost.php?p=3753215).
<http://www.sitepoint.com/forums/showpost.php?p=3753215> |