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 |
|---|---|---|---|---|---|---|
59,819 | <p>I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure:</p>
<pre><code>Contact
{
string First
string Last
string Phone
}
</code></pre>
<p>How would I go about creating this so that I could use it in function like the following:</p>
<pre><code>function PrintContact
{
param( [Contact]$contact )
"Customer Name is " + $contact.First + " " + $contact.Last
"Customer Phone is " + $contact.Phone
}
</code></pre>
<p>Is something like this possible, or even recommended in PowerShell?</p>
| [
{
"answer_id": 59887,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 2,
"selected": false,
"text": "<p>There is the concept of PSObject and Add-Member that you could use.</p>\n\n<pre><code>$contact = New-Object PSObjec... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] | I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure:
```
Contact
{
string First
string Last
string Phone
}
```
How would I go about creating this so that I could use it in function like the following:
```
function PrintContact
{
param( [Contact]$contact )
"Customer Name is " + $contact.First + " " + $contact.Last
"Customer Phone is " + $contact.Phone
}
```
Is something like this possible, or even recommended in PowerShell? | Prior to PowerShell 3
---------------------
PowerShell's Extensible Type System didn't originally let you create concrete types you can test against the way you did in your parameter. If you don't need that test, you're fine with any of the other methods mentioned above.
If you want an actual type that you can cast to or type-check with, as in your example script ... it **cannot** be done without writing it in C# or VB.net and compiling. In PowerShell 2, you can use the "Add-Type" command to do it quite simmple:
```
add-type @"
public struct contact {
public string First;
public string Last;
public string Phone;
}
"@
```
***Historical Note***: In PowerShell 1 it was even harder. You had to manually use CodeDom, there is a very old function [new-struct](http://poshcode.org/scripts/190) script on PoshCode.org which will help. Your example becomes:
```
New-Struct Contact @{
First=[string];
Last=[string];
Phone=[string];
}
```
Using `Add-Type` or `New-Struct` will let you actually test the class in your `param([Contact]$contact)` and make new ones using `$contact = new-object Contact` and so on...
In PowerShell 3
===============
If you don't need a "real" class that you can cast to, you don't have to use the Add-Member way that [Steven and others have demonstrated](https://stackoverflow.com/a/59980/8718) above.
Since PowerShell 2 you could use the -Property parameter for New-Object:
```
$Contact = New-Object PSObject -Property @{ First=""; Last=""; Phone="" }
```
And in PowerShell 3, we got the ability to use the `PSCustomObject` accelerator to add a TypeName:
```
[PSCustomObject]@{
PSTypeName = "Contact"
First = $First
Last = $Last
Phone = $Phone
}
```
You're still only getting a single object, so you should make a `New-Contact` function to make sure that every object comes out the same, but you can now easily verify a parameter "is" one of those type by decorating a parameter with the `PSTypeName` attribute:
```
function PrintContact
{
param( [PSTypeName("Contact")]$contact )
"Customer Name is " + $contact.First + " " + $contact.Last
"Customer Phone is " + $contact.Phone
}
```
In PowerShell 5
===============
In PowerShell 5 everything changes, and we finally got `class` and `enum` as language keywords for defining types (there's no `struct` but that's ok):
```
class Contact
{
# Optionally, add attributes to prevent invalid values
[ValidateNotNullOrEmpty()][string]$First
[ValidateNotNullOrEmpty()][string]$Last
[ValidateNotNullOrEmpty()][string]$Phone
# optionally, have a constructor to
# force properties to be set:
Contact($First, $Last, $Phone) {
$this.First = $First
$this.Last = $Last
$this.Phone = $Phone
}
}
```
We also got a new way to create objects without using `New-Object`: `[Contact]::new()` -- in fact, if you kept your class simple and don't define a constructor, you can create objects by casting a hashtable (although without a constructor, there would be no way to enforce that all properties must be set):
```
class Contact
{
# Optionally, add attributes to prevent invalid values
[ValidateNotNullOrEmpty()][string]$First
[ValidateNotNullOrEmpty()][string]$Last
[ValidateNotNullOrEmpty()][string]$Phone
}
$C = [Contact]@{
First = "Joel"
Last = "Bennett"
}
``` |
59,825 | <p>Suppose the following:</p>
<pre><code>>>> s = set([1, 2, 3])
</code></pre>
<p>How do I get a value (any value) out of <code>s</code> without doing <code>s.pop()</code>? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.</p>
<p>Quick and dirty:</p>
<pre><code>>>> elem = s.pop()
>>> s.add(elem)
</code></pre>
<p>But do you know of a better way? Ideally in constant time.</p>
| [
{
"answer_id": 59841,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 11,
"selected": true,
"text": "<p>Two options that don't require copying the whole set:</p>\n\n<pre><code>for e in s:\n break\n# e is now an element... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | Suppose the following:
```
>>> s = set([1, 2, 3])
```
How do I get a value (any value) out of `s` without doing `s.pop()`? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
```
>>> elem = s.pop()
>>> s.add(elem)
```
But do you know of a better way? Ideally in constant time. | Two options that don't require copying the whole set:
```
for e in s:
break
# e is now an element from s
```
Or...
```
e = next(iter(s))
```
But in general, sets don't support indexing or slicing. |
59,832 | <p>I am currently calling the following line of code:</p>
<pre><code>java.net.URL connection_url = new java.net.URL("http://<ip address>:<port>/path");
</code></pre>
<p>and I get the exception above when it executes. Any ideas as to why this is happening?</p>
| [
{
"answer_id": 59851,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 2,
"selected": false,
"text": "<p>As a side note, you should be using <a href=\"http://java.sun.com/javase/6/docs/api/java/net/URI.html\" rel=\"nofollow nore... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
] | I am currently calling the following line of code:
```
java.net.URL connection_url = new java.net.URL("http://<ip address>:<port>/path");
```
and I get the exception above when it executes. Any ideas as to why this is happening? | Your code works perfectly fine for me:
```
public static void main(String[] args) {
try {
java.net.URL connection_url = new java.net.URL("http://:/path");
System.out.println("Instantiated new URL: " + connection_url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
```
>
> Instantiated new URL: <http://:/path>
>
>
>
Sure you have the right line of code? |
59,838 | <p>What command checks if a directory exists or not within a Bash shell script?</p>
| [
{
"answer_id": 59839,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 13,
"selected": true,
"text": "<p>To check if a directory exists:</p>\n<pre><code>if [ -d "$DIRECTORY" ]; then\n echo "$DIRECTORY does ... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120/"
] | What command checks if a directory exists or not within a Bash shell script? | To check if a directory exists:
```
if [ -d "$DIRECTORY" ]; then
echo "$DIRECTORY does exist."
fi
```
To check if a directory does not exist:
```
if [ ! -d "$DIRECTORY" ]; then
echo "$DIRECTORY does not exist."
fi
```
---
However, as [Jon Ericson](https://stackoverflow.com/users/1438/jon-ericson) points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.
E.g. running this:
```
ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then
rmdir "$SYMLINK"
fi
```
Will produce the error message:
```none
rmdir: failed to remove `symlink': Not a directory
```
So symbolic links may have to be treated differently, if subsequent commands expect directories:
```
if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It is a symlink!
# Symbolic link specific commands go here.
rm "$LINK_OR_DIR"
else
# It's a directory!
# Directory command goes here.
rmdir "$LINK_OR_DIR"
fi
fi
```
---
Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean [in another answer](https://stackoverflow.com/a/67458/102401).
If the variables contain spaces or other unusual characters it will probably cause the script to fail. |
59,840 | <p>I found a bug in the Contains statement in Linq (not sure if it is really in Linq or Linq to SQL) and want to know if anyone else has seen this and if there is a fix or workaround.</p>
<p>If the querysource you do the contains with has more than 10 items in it, it does not pass the items correctly to the SQL query. It is hard to explain what it does, an example will show it best.</p>
<p>If you look at the raw query, the parameters look like this:</p>
<pre><code>@P0 = 'aaa'
@P1 = 'bbb'
@P2 = 'ccc'
... [@P3 through @P9]
@P10 = '111'
@P11 = '222'
... [@p12 through @P19]
@P20 = 'sss'
... [@P21 through @P99]
@P100 = 'qqq'
</code></pre>
<p>when the values are passed into the final query (all parameters resolved) it has resolved the parameters as if these were the values passed:</p>
<pre><code>@P0 = 'aaa'
@P1 = 'bbb'
@P2 = 'ccc'
...
@P10 = 'bbb'0
@P11 = 'bbb'1
...
@P20 = 'ccc'0
...
@P100 = 'bbb'00
</code></pre>
<p>So it looks like the parameter resolving looks at the first digit only after the <code>@P</code> and resolves that, then adds on anything left at the end of the parameter name.</p>
<p>At least that is what the Sql Server Query Visualizer plugin to Visual Studio shows the query doing.</p>
<p>Really strange.</p>
<p>So if any one has advice please share. Thanks!</p>
<p><strong>Update:</strong><br>
I have rewritten the original linq statement to where I now use a join instead of the Contains, but would still like to know if there is a way around this issue.</p>
| [
{
"answer_id": 59854,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 2,
"selected": true,
"text": "<p>The more I look at it, and after running more tests, I'm thinking the bug may be in the Sql Server Query Visualizer p... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1215/"
] | I found a bug in the Contains statement in Linq (not sure if it is really in Linq or Linq to SQL) and want to know if anyone else has seen this and if there is a fix or workaround.
If the querysource you do the contains with has more than 10 items in it, it does not pass the items correctly to the SQL query. It is hard to explain what it does, an example will show it best.
If you look at the raw query, the parameters look like this:
```
@P0 = 'aaa'
@P1 = 'bbb'
@P2 = 'ccc'
... [@P3 through @P9]
@P10 = '111'
@P11 = '222'
... [@p12 through @P19]
@P20 = 'sss'
... [@P21 through @P99]
@P100 = 'qqq'
```
when the values are passed into the final query (all parameters resolved) it has resolved the parameters as if these were the values passed:
```
@P0 = 'aaa'
@P1 = 'bbb'
@P2 = 'ccc'
...
@P10 = 'bbb'0
@P11 = 'bbb'1
...
@P20 = 'ccc'0
...
@P100 = 'bbb'00
```
So it looks like the parameter resolving looks at the first digit only after the `@P` and resolves that, then adds on anything left at the end of the parameter name.
At least that is what the Sql Server Query Visualizer plugin to Visual Studio shows the query doing.
Really strange.
So if any one has advice please share. Thanks!
**Update:**
I have rewritten the original linq statement to where I now use a join instead of the Contains, but would still like to know if there is a way around this issue. | The more I look at it, and after running more tests, I'm thinking the bug may be in the Sql Server Query Visualizer plugin for Visual Studio, not actually in Linq to SQL itself. So it is not nearly as bad a situation as I thought - the query will return the right results, but you can't trust what the Visualizer is showing. Not great, but better than what I thought was going on. |
59,850 | <p>I'd like to create a spring bean that holds the value of a double. Something like:</p>
<pre><code><bean id="doubleValue" value="3.7"/>
</code></pre>
| [
{
"answer_id": 59852,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you just use a <strong>Double</strong>? any reason?</p>\n"
},
{
"answer_id": 59875,
"author": "Pav... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] | I'd like to create a spring bean that holds the value of a double. Something like:
```
<bean id="doubleValue" value="3.7"/>
``` | Declare it like this:
```
<bean id="doubleValue" class="java.lang.Double">
<constructor-arg index="0" value="3.7"/>
</bean>
```
And use like this:
```
<bean id="someOtherBean" ...>
<property name="value" ref="doubleValue"/>
</bean>
``` |
59,857 | <p>Should I use a dedicated network channel between the database and the application server?</p>
<p>...or... </p>
<p>Connecting both in the switch along with all other computer nodes makes no diference at all?</p>
<p>The matter is <strong>performance!</strong></p>
| [
{
"answer_id": 59852,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you just use a <strong>Double</strong>? any reason?</p>\n"
},
{
"answer_id": 59875,
"author": "Pav... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] | Should I use a dedicated network channel between the database and the application server?
...or...
Connecting both in the switch along with all other computer nodes makes no diference at all?
The matter is **performance!** | Declare it like this:
```
<bean id="doubleValue" class="java.lang.Double">
<constructor-arg index="0" value="3.7"/>
</bean>
```
And use like this:
```
<bean id="someOtherBean" ...>
<property name="value" ref="doubleValue"/>
</bean>
``` |
59,880 | <p>Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them <strong>ALL THE TIME</strong>.</p>
<p>I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procedures are necessary in modern databases such as MySQL, SQL Server, Oracle, or <<em>Insert_your_DB_here</em>>. Is it overkill to have ALL access through stored procedures?</p>
| [
{
"answer_id": 59883,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know that they are faster. I like using ORM for data access (to not re-invent the wheel) but I realize... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
] | Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them **ALL THE TIME**.
I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procedures are necessary in modern databases such as MySQL, SQL Server, Oracle, or <*Insert\_your\_DB\_here*>. Is it overkill to have ALL access through stored procedures? | >
> **NOTE** that this is a general look at stored procedures not regulated to a specific
> DBMS. Some DBMS (and even, different
> versions of the same DBMS!) may operate
> contrary to this, so you'll want to
> double-check with your target DBMS
> before assuming all of this still holds.
>
>
> I've been a Sybase ASE, MySQL, and SQL Server DBA on-and off since for almost a decade (along with application development in C, PHP, PL/SQL, C#.NET, and Ruby). So, I have no particular axe to grind in this (sometimes) holy war.
>
>
>
The historical performance benefit of stored procs have generally been from the following (in no particular order):
* Pre-parsed SQL
* Pre-generated query execution plan
* Reduced network latency
* Potential cache benefits
**Pre-parsed SQL** -- similar benefits to compiled vs. interpreted code, except on a very micro level.
*Still an advantage?*
Not very noticeable at all on the modern CPU, but if you are sending a single SQL statement that is VERY large eleventy-billion times a second, the parsing overhead can add up.
**Pre-generated query execution plan**.
If you have many JOINs the permutations can grow quite unmanageable (modern optimizers have limits and cut-offs for performance reasons). It is not unknown for very complicated SQL to have distinct, measurable (I've seen a complicated query take 10+ seconds just to generate a plan, before we tweaked the DBMS) latencies due to the optimizer trying to figure out the "near best" execution plan. Stored procedures will, generally, store this in memory so you can avoid this overhead.
*Still an advantage?*
Most DBMS' (the latest editions) will cache the query plans for INDIVIDUAL SQL statements, greatly reducing the performance differential between stored procs and ad hoc SQL. There are some caveats and cases in which this isn't the case, so you'll need to test on your target DBMS.
Also, more and more DBMS allow you to provide optimizer path plans (abstract query plans) to significantly reduce optimization time (for both ad hoc and stored procedure SQL!!).
>
> **WARNING** Cached query plans are not a performance panacea. Occasionally the query plan that is generated is sub-optimal.
> For example, if you send `SELECT *
> FROM table WHERE id BETWEEN 1 AND
> 99999999`, the DBMS may select a
> full-table scan instead of an index
> scan because you're grabbing every row
> in the table (so sayeth the
> statistics). If this is the cached
> version, then you can get poor
> performance when you later send
> `SELECT * FROM table WHERE id BETWEEN
> 1 AND 2`. The reasoning behind this is
> outside the scope of this posting, but
> for further reading see:
> <http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx>
> and
> <http://msdn.microsoft.com/en-us/library/ms181055.aspx>
> and <http://www.simple-talk.com/sql/performance/execution-plan-basics/>
>
>
> "In summary, they determined that
> supplying anything other than the
> common values when a compile or
> recompile was performed resulted in
> the optimizer compiling and caching
> the query plan for that particular
> value. Yet, when that query plan was
> reused for subsequent executions of
> the same query for the common values
> (‘M’, ‘R’, or ‘T’), it resulted in
> sub-optimal performance. This
> sub-optimal performance problem
> existed until the query was
> recompiled. At that point, based on
> the @P1 parameter value supplied, the
> query might or might not have a
> performance problem."
>
>
>
**Reduced network latency**
A) If you are running the same SQL over and over -- and the SQL adds up to many KB of code -- replacing that with a simple "exec foobar" can really add up.
B) Stored procs can be used to move procedural code into the DBMS. This saves shuffling large amounts of data off to the client only to have it send a trickle of info back (or none at all!). Analogous to doing a JOIN in the DBMS vs. in your code (everyone's favorite WTF!)
*Still an advantage?*
A) Modern 1Gb (and 10Gb and up!) Ethernet really make this negligible.
B) Depends on how saturated your network is -- why shove several megabytes of data back and forth for no good reason?
**Potential cache benefits**
Performing server-side transforms of data can potentially be faster if you have sufficient memory on the DBMS and the data you need is in memory of the server.
*Still an advantage?*
Unless your app has shared memory access to DBMS data, the edge will always be to stored procs.
Of course, no discussion of Stored Procedure optimization would be complete without a discussion of parameterized and ad hoc SQL.
**Parameterized / Prepared SQL**
Kind of a cross between stored procedures and ad hoc SQL, they are embedded SQL statements in a host language that uses "parameters" for query values, e.g.:
```
SELECT .. FROM yourtable WHERE foo = ? AND bar = ?
```
These provide a more generalized version of a query that modern-day optimizers can use to cache (and re-use) the query execution plan, resulting in much of the performance benefit of stored procedures.
**Ad Hoc SQL**
Just open a console window to your DBMS and type in a SQL statement. In the past, these were the "worst" performers (on average) since the DBMS had no way of pre-optimizing the queries as in the parameterized/stored proc method.
*Still a disadvantage?*
Not necessarily. Most DBMS have the ability to "abstract" ad hoc SQL into parameterized versions -- thus more or less negating the difference between the two. Some do this implicitly or must be enabled with a command setting (SQL server: <http://msdn.microsoft.com/en-us/library/ms175037.aspx> , Oracle: <http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>).
**Lessons learned?**
Moore's law continues to march on and DBMS optimizers, with every release, get more sophisticated. Sure, you can place every single silly teeny SQL statement inside a stored proc, but just know that the programmers working on optimizers are very smart and are continually looking for ways to improve performance. Eventually (if it's not here already) ad hoc SQL performance will become indistinguishable (on average!) from stored procedure performance, so any sort of *massive* stored procedure use \*\* solely for "performance reasons"\*\* sure sounds like premature optimization to me.
Anyway, I think if you avoid the edge cases and have fairly vanilla SQL, you won't notice a difference between ad hoc and stored procedures. |
59,895 | <p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p>
<p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p>
<pre><code>$ ./application
</code></pre>
| [
{
"answer_id": 59916,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 10,
"selected": false,
"text": "<p>Use <code>dirname "$0"</code>:</p>\n<pre><code>#!/usr/bin/env bash\n\necho "The script you are running has ... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
] | How do I get the path of the directory in which a [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29) script is located, *inside* that script?
I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:
```
$ ./application
``` | ```
#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
```
is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
```
#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
SOURCE=$(readlink "$SOURCE")
[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
```
This last one will work with any combination of aliases, `source`, `bash -c`, symlinks, etc.
**Beware:** if you `cd` to a different directory before running this snippet, the result may be incorrect!
Also, watch out for [`$CDPATH` gotchas](http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/), and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling `update_terminal_cwd >&2` on Mac). Adding `>/dev/null 2>&1` at the end of your `cd` command will take care of both possibilities.
To understand how it works, try running this more verbose form:
```
#!/usr/bin/env bash
SOURCE=${BASH_SOURCE[0]}
while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET=$(readlink "$SOURCE")
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE=$TARGET
else
DIR=$( dirname "$SOURCE" )
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR=$( dirname "$SOURCE" )
DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
```
And it will print something like:
```none
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
``` |
59,896 | <p>I have a page that uses </p>
<pre><code>$(id).show("highlight", {}, 2000);
</code></pre>
<p>to highlight an element when I start a ajax request, that might fail so that I want to use something like</p>
<pre><code>$(id).show("highlight", {color: "#FF0000"}, 2000);
</code></pre>
<p>in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?</p>
| [
{
"answer_id": 59904,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 5,
"selected": true,
"text": "<p>From the jQuery docs: </p>\n\n<p><a href=\"http://docs.jquery.com/Effects/stop\" rel=\"nofollow noreferrer\">ht... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6093/"
] | I have a page that uses
```
$(id).show("highlight", {}, 2000);
```
to highlight an element when I start a ajax request, that might fail so that I want to use something like
```
$(id).show("highlight", {color: "#FF0000"}, 2000);
```
in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect? | From the jQuery docs:
<http://docs.jquery.com/Effects/stop>
>
> *Stop the currently-running animation on the matched elements.*...
>
>
> When `.stop()` is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with `.slideUp()` when `.stop()` is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.
>
>
> If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When `.stop()` is called, the next animation in the queue begins immediately. If the `clearQueue` parameter is provided with a value of `true`, then the rest of the animations in the queue are removed and never run.
>
>
> If the `jumpToEnd` argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above `.slideUp()` example, the element would be immediately hidden. The callback function is then immediately called, if provided...
>
>
> |
59,986 | <p>I have a simple type that explicitly implemets an Interface.</p>
<pre><code>public interface IMessageHeader
{
string FromAddress { get; set; }
string ToAddress { get; set; }
}
[Serializable]
public class MessageHeader:IMessageHeader
{
private string from;
private string to;
[XmlAttribute("From")]
string IMessageHeade.FromAddress
{
get { return this.from;}
set { this.from = value;}
}
[XmlAttribute("To")]
string IMessageHeade.ToAddress
{
get { return this.to;}
set { this.to = value;}
}
}
</code></pre>
<p>Is there a way to Serialize and Deserialize objects of type IMessageHeader??</p>
<p>I got the following error when tried</p>
<p>"Cannot serialize interface IMessageHeader"</p>
| [
{
"answer_id": 59992,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>You can create an abstract base class the implements IMessageHeader and also inherits MarshalByRefObject</p>\n"
}... | 2008/09/12 | [
"https://Stackoverflow.com/questions/59986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647/"
] | I have a simple type that explicitly implemets an Interface.
```
public interface IMessageHeader
{
string FromAddress { get; set; }
string ToAddress { get; set; }
}
[Serializable]
public class MessageHeader:IMessageHeader
{
private string from;
private string to;
[XmlAttribute("From")]
string IMessageHeade.FromAddress
{
get { return this.from;}
set { this.from = value;}
}
[XmlAttribute("To")]
string IMessageHeade.ToAddress
{
get { return this.to;}
set { this.to = value;}
}
}
```
Is there a way to Serialize and Deserialize objects of type IMessageHeader??
I got the following error when tried
"Cannot serialize interface IMessageHeader" | You cannot serialize IMessageHeader because you can't do Activator.CreateInstance(typeof(IMessageHeader)) which is what serialization is going to do under the covers. You need a concrete type.
You can do typeof(MessageHeader) or you could say, have an instance of MessageHeader and do
```
XmlSerializer serializer = new XmlSerializer(instance.GetType())
``` |
60,000 | <p>In C++, can member function pointers be used to point to derived (or even base) class members? </p>
<p>EDIT:
Perhaps an example will help. Suppose we have a hierarchy of three classes <code>X</code>, <code>Y</code>, <code>Z</code> in order of inheritance.
<code>Y</code> therefore has a base class <code>X</code> and a derived class <code>Z</code>.</p>
<p>Now we can define a member function pointer <code>p</code> for class <code>Y</code>. This is written as:</p>
<pre><code>void (Y::*p)();
</code></pre>
<p>(For simplicity, I'll assume we're only interested in functions with the signature <code>void f()</code> ) </p>
<p>This pointer <code>p</code> can now be used to point to member functions of class <code>Y</code>.</p>
<p>This question (two questions, really) is then:</p>
<ol>
<li>Can <code>p</code> be used to point to a function in the derived class <code>Z</code>?</li>
<li>Can <code>p</code> be used to point to a function in the base class <code>X</code>?</li>
</ol>
| [
{
"answer_id": 60010,
"author": "Steve Duitsman",
"author_id": 4575,
"author_profile": "https://Stackoverflow.com/users/4575",
"pm_score": 1,
"selected": false,
"text": "<p>I believe so. Since the function pointer uses the signature to identify itself, the base/derived behavior would re... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1077/"
] | In C++, can member function pointers be used to point to derived (or even base) class members?
EDIT:
Perhaps an example will help. Suppose we have a hierarchy of three classes `X`, `Y`, `Z` in order of inheritance.
`Y` therefore has a base class `X` and a derived class `Z`.
Now we can define a member function pointer `p` for class `Y`. This is written as:
```
void (Y::*p)();
```
(For simplicity, I'll assume we're only interested in functions with the signature `void f()` )
This pointer `p` can now be used to point to member functions of class `Y`.
This question (two questions, really) is then:
1. Can `p` be used to point to a function in the derived class `Z`?
2. Can `p` be used to point to a function in the base class `X`? | C++03 std, [§4.11 2 Pointer to member conversions](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem):
>
> An rvalue of type “pointer to member of B of type *cv* T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type *cv* T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer to member of D of type *cv* T,” it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B sub-object of D. The null member pointer value is converted to the null member pointer value of the destination type. 52)
>
>
> 52)The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to member cannot be converted to a void\*.
>
>
>
In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn't ambiguous.
```
class A {
public:
void foo();
};
class B : public A {};
class C {
public:
void bar();
};
class D {
public:
void baz();
};
class E : public A, public B, private C, public virtual D {
public:
typedef void (E::*member)();
};
class F:public E {
public:
void bam();
};
...
int main() {
E::member mbr;
mbr = &A::foo; // invalid: ambiguous; E's A or B's A?
mbr = &C::bar; // invalid: C is private
mbr = &D::baz; // invalid: D is virtual
mbr = &F::bam; // invalid: conversion isn't defined by the standard
...
```
Conversion in the other direction (via `static_cast`) is governed by [§ 5.2.9](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.static.cast) 9:
>
> An rvalue of type "pointer to member of D of type *cv1* T" can be converted to an rvalue of type "pointer to member of B of type *cv2* T", where B is a base class (clause [10 class.derived](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/derived.html#class.derived)) of D, if a valid standard conversion from "pointer to member of B of type T" to "pointer to member of D of type T" exists ([4.11 conv.mem](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem)), and *cv2* is the same cv-qualification as, or greater cv-qualification than, *cv1*.11) The null member pointer value ([4.11 conv.mem](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem)) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the result of the cast is undefined. [Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see [5.5 expr.mptr.oper](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.mptr.oper).]
>
>
> 11) Function types (including those used in pointer to member function
> types) are never cv-qualified; see [8.3.5 dcl.fct](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/decl.html#dcl.fct).
>
>
>
In short, you can convert from a derived `D::*` to a base `B::*` if you can convert from a `B::*` to a `D::*`, though you can only use the `B::*` on objects that are of type D or are descended from D. |
60,019 | <p>I am wanting to use ActiveScaffold to create <em>assignment</em> records for several <em>students</em> in a single step. The records will all contain identical data, with the exception of the student_id.</p>
<p>I was able to override the default form and replace the dropdown box for selecting the student name with a multi-select box - which is what I want. That change however, was only cosmetic, as the underlying code only grabs the first selected name from that box, and creates a single record.</p>
<p>Can somebody suggest a good way to accomplish this in a way that doesn't require my deciphering and rewriting too much of the underlying ActiveScaffold code?</p>
<hr>
<p>Update: I still haven't found a good answer to this problem.</p>
| [
{
"answer_id": 60366,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 0,
"selected": false,
"text": "<p>if your assingnments have <code>has_many :students</code> or <code>has_and_belongs_to_many :students</code>, then y... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] | I am wanting to use ActiveScaffold to create *assignment* records for several *students* in a single step. The records will all contain identical data, with the exception of the student\_id.
I was able to override the default form and replace the dropdown box for selecting the student name with a multi-select box - which is what I want. That change however, was only cosmetic, as the underlying code only grabs the first selected name from that box, and creates a single record.
Can somebody suggest a good way to accomplish this in a way that doesn't require my deciphering and rewriting too much of the underlying ActiveScaffold code?
---
Update: I still haven't found a good answer to this problem. | I suppose you have defined your multi-select box adding :multiple => true to html parameters of select\_tag. Then, in the controller, you need to access the list of names selected, what you can do like this:
```
params[:students].collect{|student| insert_student(student, params[:assignment_id]) }
```
With collect applied to an array or enum you can loop through each item of that array, and then do what you need with each student (in the example, to call a function for insert the students). Collect returns an array with the results of doing the code inside. |
60,030 | <p>In Firefox you can enter the following into the awesome bar and hit enter:</p>
<pre><code>javascript:self.resizeTo(1024,768);
</code></pre>
<p>How do you do the same thing in IE?</p>
| [
{
"answer_id": 60038,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>javascript:resizeTo(1024,768);\n</code></pre>\n\n<p>This works in IE7 at least.</p>\n"
},
{
"a... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496/"
] | In Firefox you can enter the following into the awesome bar and hit enter:
```
javascript:self.resizeTo(1024,768);
```
How do you do the same thing in IE? | ```
javascript:resizeTo(1024,768);
vbscript:resizeto(1024,768)
```
Will work in IE7, But consider using something like
```
javascript:moveTo(0,0);resizeTo(1024,768);
```
because IE7 doesn't allow the window to "resize" beyond the screen borders. If you work on a 1024,768 desktop, this is what happens...* Firefox: 1024x768 Window, going behind the taskbar. If you drop the moveTo part, the top left corner of the window won't change position.(You still get a 1024x768 window)
* IE7: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders.
* safari: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders, but you can ommit the moveTo part. Safari will move the top left corner of the window for you.
* Opera: Nothing happens.
* Chrome: Nothing happens. |
60,032 | <p>How do I get the key of the current element in a <code>foreach</code> loop in C#?</p>
<p>For example:</p>
<h2>PHP</h2>
<pre><code>foreach ($array as $key => $value)
{
echo("$value is assigned to key: $key");
}
</code></pre>
<h3>What I'm trying to do in C#:</h3>
<pre><code>int[] values = { 5, 14, 29, 49, 99, 150, 999 };
foreach (int val in values)
{
if(search <= val && !stop)
{
// Set key to a variable
}
}
</code></pre>
| [
{
"answer_id": 60035,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 2,
"selected": false,
"text": "<p>Alas there is no built-in way to do this. Either use a for loop or create a temp variable that you increment on eac... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] | How do I get the key of the current element in a `foreach` loop in C#?
For example:
PHP
---
```
foreach ($array as $key => $value)
{
echo("$value is assigned to key: $key");
}
```
### What I'm trying to do in C#:
```
int[] values = { 5, 14, 29, 49, 99, 150, 999 };
foreach (int val in values)
{
if(search <= val && !stop)
{
// Set key to a variable
}
}
``` | [Grauenwolf's way](https://stackoverflow.com/questions/60032/getting-the-array-key-in-a-foreach-loop#60035) is the most straightforward and performant way of doing this with an array:
>
> Either use a for loop or create a temp variable that you increment on each pass.
>
>
>
Which would of course look like this:
```
int[] values = { 5, 14, 29, 49, 99, 150, 999 };
for (int key = 0; key < values.Length; ++key)
if (search <= values[key] && !stop)
{
// set key to a variable
}
```
With .NET 3.5 you can take a more functional approach as well, but it is a little more verbose at the site, and would likely rely on a couple [support functions](http://en.wikipedia.org/wiki/Apply) for [visiting](http://en.wikipedia.org/wiki/Visitor_pattern) the elements in an IEnumerable. Overkill if this is all you need it for, but handy if you tend to do a lot of collection processing. |
60,033 | <p>I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the <strong>id</strong>). What is the simplest way to accomplish this?</p>
<p>I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.</p>
<p>Perhaps something like this:</p>
<pre class="lang-ruby prettyprint-override"><code> new_record = Record.copy(:id)
</code></pre>
| [
{
"answer_id": 60053,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 10,
"selected": true,
"text": "<p>To get a copy, use the <a href=\"https://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup\" rel=\"no... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] | I want to make a copy of an ActiveRecord object, changing a single field in the process (in addition to the **id**). What is the simplest way to accomplish this?
I realize I could create a new record, and then iterate over each of the fields copying the data field-by-field - but I figured there must be an easier way to do this.
Perhaps something like this:
```ruby
new_record = Record.copy(:id)
``` | To get a copy, use the [dup](https://api.rubyonrails.org/classes/ActiveRecord/Core.html#method-i-dup) (or clone for < rails 3.1+) method:
```
#rails >= 3.1
new_record = old_record.dup
# rails < 3.1
new_record = old_record.clone
```
Then you can change whichever fields you want.
[ActiveRecord overrides the built-in Object#clone](http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001363) to give you a new (not saved to the DB) record with an unassigned ID.
Note that it does not copy associations, so you'll have to do this manually if you need to.
[Rails 3.1 clone is a shallow copy, use dup instead...](https://gist.github.com/994614) |
60,034 | <p>I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?</p>
| [
{
"answer_id": 60055,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": false,
"text": "<p>I don't think there's a way to do it with any built-in commands. I would suggest you download something like <a href=\"h... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions? | A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.
I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:
```
powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"
```
To explain it:
* `powershell` starts up powershell.exe, which is included in Windows 7
* `-Command "... "` is a command line arg for powershell.exe containing the command to run
* `(gc myFile.txt)` reads the content of `myFile.txt` (`gc` is short for the `Get-Content` command)
* `-replace 'foo', 'bar'` simply runs the replace command to replace `foo` with `bar`
* `| Out-File myFile.txt` pipes the output to the file `myFile.txt`
* `-encoding ASCII` prevents transcribing the output file to unicode, as the comments point out
Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is `C:\WINDOWS\system32\WindowsPowerShell\v1.0`
**Update**
Apparently modern windows systems have PowerShell built in allowing you to access this directly using
```
(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
``` |
60,046 | <p>I'm embedding the Google Maps Flash API in Flex and it runs fine locally with the watermark on it, etc. When I upload it to the server (flex.mydomain.com) I get a sandbox security error listed below: </p>
<pre><code>SecurityError: Error #2121: Security sandbox violation: Loader.content: http://mydomain.com/main.swf?Fri, 12 Sep 2008 21:46:03 UTC cannot access http://maps.googleapis.com/maps/lib/map_1_6.swf. This may be worked around by calling Security.allowDomain.
at flash.display::Loader/get content()
at com.google.maps::ClientBootstrap/createFactory()
at com.google.maps::ClientBootstrap/executeNextFrameCalls()
</code></pre>
<p>Does anyone have any experience with embedding the Google Maps Flash API into Flex components and specifically settings security settings to make this work? I did get a new API key that is registered to my domain and am using that when it's published.</p>
<p>I've tried doing the following in the main application as well as the component:</p>
<pre><code>Security.allowDomain('*')
Security.allowDomain('maps.googleapis.com')
Security.allowDomain('mydomain.com')
</code></pre>
| [
{
"answer_id": 60453,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 2,
"selected": false,
"text": "<p>This sounds like a <code>crossdomain.xml</code> related problem. I did a quick search and there seems to be many people with ... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4760/"
] | I'm embedding the Google Maps Flash API in Flex and it runs fine locally with the watermark on it, etc. When I upload it to the server (flex.mydomain.com) I get a sandbox security error listed below:
```
SecurityError: Error #2121: Security sandbox violation: Loader.content: http://mydomain.com/main.swf?Fri, 12 Sep 2008 21:46:03 UTC cannot access http://maps.googleapis.com/maps/lib/map_1_6.swf. This may be worked around by calling Security.allowDomain.
at flash.display::Loader/get content()
at com.google.maps::ClientBootstrap/createFactory()
at com.google.maps::ClientBootstrap/executeNextFrameCalls()
```
Does anyone have any experience with embedding the Google Maps Flash API into Flex components and specifically settings security settings to make this work? I did get a new API key that is registered to my domain and am using that when it's published.
I've tried doing the following in the main application as well as the component:
```
Security.allowDomain('*')
Security.allowDomain('maps.googleapis.com')
Security.allowDomain('mydomain.com')
``` | This sounds like a `crossdomain.xml` related problem. I did a quick search and there seems to be many people with the same issue. Some proxy requests through XMLHttpRequest etc..
[Issue 406: Add crossdomain.xml for Google Accounts](http://code.google.com/p/gdata-issues/issues/detail?id=406) |
60,051 | <p>My question is pertaining to the best practice for accessing a child object's parent. So let's say a class instantiates another class, that class instance is now referenced with an object. From that child object, what is the best way to reference back to the parent object? Currently I know of a couple ways that I use often, but I'm not sure if A) there is a better way to do it or B) which of them is the better practice</p>
<p>The first method is to use getDefinitionByName, which would not instantiate that class, but allow access to anything inside of it that was publicly declared.</p>
<pre><code>_class:Class = getDefinitionByName("com.site.Class") as Class;
</code></pre>
<p>And then reference that variable based on its parent to child hierarchy.<br>
Example, if the child is attempting to reference a class that's two levels up from itself:</p>
<pre><code>_class(parent.parent).function();
</code></pre>
<p>This seems to work fine, but you are required to know the level at which the child is at compared to the level of the parent you are attempting to access.</p>
<p>I can also get the following statement to trace out [object ClassName] into Flash's output.</p>
<pre><code>trace(Class);
</code></pre>
<p>I'm not 100% on the implementation of that line, I haven't persued it as a way to reference an object outside of the current object I'm in.</p>
<p>Another method I've seen used is to simply pass a reference to this into the class object you are creating and just catch it with a constructor argument</p>
<pre><code>var class:Class = new Class(this);
</code></pre>
<p>and then in the Class file</p>
<pre><code>public function Class(objectRef:Object) {
_parentRef = objectRef;
}
</code></pre>
<p>That reference also requires you to step back up using the child to parent hierarchy though.</p>
<p>I could also import that class, and then use the direct filepath to reference a method inside of that class, regardless of its the parent or not.</p>
<pre><code>import com.site.Class;
com.site.Class.method();
</code></pre>
<p>Of course there the parent to child relationship is irrelevant because I'm accessing the method or property directly through the imported class.</p>
<p>I just feel like I'm missing something really obvious here. I'm basically looking for confirmation if these are the correct ways to reference the parent, and if so which is the most ideal, or am I over-looking something else?</p>
| [
{
"answer_id": 60074,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 2,
"selected": false,
"text": "<p>I've always used your second method, passing a pointer to the parent object to the child and storing that pointer in a membe... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1945/"
] | My question is pertaining to the best practice for accessing a child object's parent. So let's say a class instantiates another class, that class instance is now referenced with an object. From that child object, what is the best way to reference back to the parent object? Currently I know of a couple ways that I use often, but I'm not sure if A) there is a better way to do it or B) which of them is the better practice
The first method is to use getDefinitionByName, which would not instantiate that class, but allow access to anything inside of it that was publicly declared.
```
_class:Class = getDefinitionByName("com.site.Class") as Class;
```
And then reference that variable based on its parent to child hierarchy.
Example, if the child is attempting to reference a class that's two levels up from itself:
```
_class(parent.parent).function();
```
This seems to work fine, but you are required to know the level at which the child is at compared to the level of the parent you are attempting to access.
I can also get the following statement to trace out [object ClassName] into Flash's output.
```
trace(Class);
```
I'm not 100% on the implementation of that line, I haven't persued it as a way to reference an object outside of the current object I'm in.
Another method I've seen used is to simply pass a reference to this into the class object you are creating and just catch it with a constructor argument
```
var class:Class = new Class(this);
```
and then in the Class file
```
public function Class(objectRef:Object) {
_parentRef = objectRef;
}
```
That reference also requires you to step back up using the child to parent hierarchy though.
I could also import that class, and then use the direct filepath to reference a method inside of that class, regardless of its the parent or not.
```
import com.site.Class;
com.site.Class.method();
```
Of course there the parent to child relationship is irrelevant because I'm accessing the method or property directly through the imported class.
I just feel like I'm missing something really obvious here. I'm basically looking for confirmation if these are the correct ways to reference the parent, and if so which is the most ideal, or am I over-looking something else? | It's generally good to have the class as it's own instance and reduce tight coupling to something else (as in this case, it's parent). If you do something like parent.doSomething() it's not possible to use that class in container that doesn't have the doSometing() method. I think it's definitely better to pass in whatever the class may need and then inside the class it doesn't have to do any parent.parent etc anymore.
With this if you in the future want to change the structure, it's very easy to just pass in a new reference; the implementation of the child class doesn't have to change at all.
The third alternative you have here is also very different, it's accessing a class level static method (you don't have to type the whole class path when accessing that method), not an instance method as in the first two. |
60,098 | <p>I wrote a simple web service in C# using SharpDevelop (which I just got and I love).</p>
<p>The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)</p>
<p>But I get this error when I try to load the service now.</p>
<pre>
Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'.
Source Error:
Line 1: <%@ WebService Class="flightinfo.Soap,flightinfo" %>
</pre>
<p>I have deleted the bins and rebuilt, and I have searched google (and stackoverflow). I have scoured the project files for any remnants of C#.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 60108,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<pre><code><%@ WebService Class=\"flightinfo.Soap,flightinfo\" %>\n</code></pre>\n\n<p>What is the name of your class?<... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
] | I wrote a simple web service in C# using SharpDevelop (which I just got and I love).
The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)
But I get this error when I try to load the service now.
```
Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'.
Source Error:
Line 1: <%@ WebService Class="flightinfo.Soap,flightinfo" %>
```
I have deleted the bins and rebuilt, and I have searched google (and stackoverflow). I have scoured the project files for any remnants of C#.
Any ideas? | In VB.NET, namespace declarations are relative to the default namespace of the project. So if the default namespace for the project is set to X.Y, everithyng between `Namespace Z` and `End Namespace` will be in the X.Y.Z namespace.
In C# you have to provide the full namespace name, regardless of the default namespace of the project.
So if the C# project had the default namespace X.Y, the CS files would still include the `namespace X.Y` declaration. After converting to VB, if both the default namespace and the namespace declarations in the files stay the same you end up with classes in the X.Y.X.Y namespace.
So in your case, the Soap class is now in the flightinfo.flightinfo namespace. Thus there are three possible solutions:
* change the asmx file to
* remove the default namespace from the project
* remove the namespace declarations from the vb files |
60,160 | <p>Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.</p>
| [
{
"answer_id": 60161,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 10,
"selected": true,
"text": "<p>Since <a href=\"http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)\" rel=\... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338/"
] | Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input. | Since [Java 1.5, yes](http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)):
```
Pattern.quote("$5");
``` |
60,168 | <p>Here is an example of what I've got going on:</p>
<pre><code>CREATE TABLE Parent (id BIGINT NOT NULL,
PRIMARY KEY (id)) ENGINE=InnoDB;
CREATE TABLE Child (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB;
CREATE TABLE Uncle (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
childid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
KEY (childid),
CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE,
CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB;
</code></pre>
<p>Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa.</p>
<p>When I have a Parent and an Uncle with the same Child, and I delete the Parent, it <em>seems</em> like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well). However, instead, I get the following:</p>
<pre><code> ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`))
</code></pre>
<p>InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it.</p>
<p>Am I missing something? Is this <em>supposed</em> to fail for some reason I don't understand? Or is there some trick to making it work (or is it a bug in MySQL)?</p>
| [
{
"answer_id": 60185,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 3,
"selected": false,
"text": "<p>In the simpler case, what happens if a record is deleted from Child and it has a referencing Uncle? That's unspecified, ... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6198/"
] | Here is an example of what I've got going on:
```
CREATE TABLE Parent (id BIGINT NOT NULL,
PRIMARY KEY (id)) ENGINE=InnoDB;
CREATE TABLE Child (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
CONSTRAINT fk_parent FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE) ENGINE=InnoDB;
CREATE TABLE Uncle (id BIGINT NOT NULL,
parentid BIGINT NOT NULL,
childid BIGINT NOT NULL,
PRIMARY KEY (id),
KEY (parentid),
KEY (childid),
CONSTRAINT fk_parent_u FOREIGN KEY (parentid) REFERENCES Parent (id) ON DELETE CASCADE,
CONSTRAINT fk_child FOREIGN KEY (childid) REFERENCES Child (id)) ENGINE=InnoDB;
```
Notice there is no ON DELETE CASCADE for the Uncle-Child relationship; i.e. deleting a Child does not delete its Uncle(s) and vice-versa.
When I have a Parent and an Uncle with the same Child, and I delete the Parent, it *seems* like InnoDB should be able to just "figure it out" and let the cascade ripple through the whole family (i.e. deleting the Parent deletes the Uncle and the Child as well). However, instead, I get the following:
```
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`cascade_test/uncle`, CONSTRAINT `fk_child` FOREIGN KEY (`childid`) REFERENCES `child` (`id`))
```
InnoDB is trying to cascade-delete the Child before the Uncle(s) that refer to it.
Am I missing something? Is this *supposed* to fail for some reason I don't understand? Or is there some trick to making it work (or is it a bug in MySQL)? | The parent deletion is triggering the child deletion as you stated and I don't know why it goes to the child table before the uncle table. I imagine you would have to look at the dbms code to know for sure, but im sure there is an algorithm that picks which tables to cascade to first.
The system does not really 'figure out' stuff the way you imply here and it is just following its constraint rules. The problem is the schema you created in that it encounters a constraint that will not let it pass further.
I see what you are saying.. if it hit the uncle table first it would delete the record and then delete the child (and not hit the uncle cascade from the child deletion). But even so, I don't think a schema would be set up to rely on that kind of behavior in reality. I think the only way to know for sure what is going on is to look through the code or get one of the mysql/postgresql programmers in here to say how it processes fk constraints. |
60,174 | <p>If user input is inserted without modification into an SQL query, then the application becomes vulnerable to <a href="https://stackoverflow.com/a/332367/">SQL injection</a>, like in the following example:</p>
<pre class="lang-php prettyprint-override"><code>$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
</code></pre>
<p>That's because the user can input something like <code>value'); DROP TABLE table;--</code>, and the query becomes:</p>
<pre><code>INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
</code></pre>
<p>What can be done to prevent this from happening?</p>
| [
{
"answer_id": 60180,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 10,
"selected": false,
"text": "<p>I'd recommend using <a href=\"http://ca3.php.net/manual/en/book.pdo.php\" rel=\"noreferrer\">PDO</a> (PHP Data Objects) to... | 2008/09/12 | [
"https://Stackoverflow.com/questions/60174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] | If user input is inserted without modification into an SQL query, then the application becomes vulnerable to [SQL injection](https://stackoverflow.com/a/332367/), like in the following example:
```php
$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
```
That's because the user can input something like `value'); DROP TABLE table;--`, and the query becomes:
```
INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
```
What can be done to prevent this from happening? | The *correct* way to avoid SQL injection attacks, no matter which database you use, is to **separate the data from SQL**, so that data stays data and will **never be interpreted** as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't *fully* understand the details, you should always **use prepared statements and parameterized queries.** These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
1. Using [**PDO**](http://php.net/manual/en/book.pdo.php) (for any supported database driver):
```php
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute([ 'name' => $name ]);
foreach ($stmt as $row) {
// Do something with $row
}
```
2. Using [**MySQLi**](http://php.net/manual/en/book.mysqli.php) (for MySQL):
```php
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with $row
}
```
If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, `pg_prepare()` and `pg_execute()` for PostgreSQL). PDO is the universal option.
---
Correctly setting up the connection
-----------------------------------
#### PDO
Note that when using **PDO** to access a MySQL database *real* prepared statements are **not used by default**. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using **PDO** is:
```php
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'user', 'password');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
```
In the above example, the error mode isn't strictly necessary, **but it is advised to add it**. This way PDO will inform you of all MySQL errors by means of throwing the `PDOException`.
What is **mandatory**, however, is the first `setAttribute()` line, which tells PDO to disable emulated prepared statements and use *real* prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the `charset` in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) [silently ignored the charset parameter](http://php.net/manual/en/ref.pdo-mysql.connection.php) in the DSN.
#### Mysqli
For mysqli we have to follow the same routine:
```php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
$dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
$dbConnection->set_charset('utf8mb4'); // charset
```
---
Explanation
-----------
The SQL statement you pass to `prepare` is parsed and compiled by the database server. By specifying parameters (either a `?` or a named parameter like `:name` in the example above) you tell the database engine where you want to filter on. Then when you call `execute`, the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend.
Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the `$name` variable contains `'Sarah'; DELETE FROM employees` the result would simply be a search for the string `"'Sarah'; DELETE FROM employees"`, and you will not end up with [an empty table](http://xkcd.com/327/).
Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
```php
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute([ 'column' => $unsafeValue ]);
```
---
Can prepared statements be used for dynamic queries?
----------------------------------------------------
While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
```
// Value whitelist
// $dir can only be 'DESC', otherwise it will be 'ASC'
if (empty($dir) || $dir !== 'DESC') {
$dir = 'ASC';
}
``` |
60,204 | <p>I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:</p>
<p><a href="/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types">What is the best way to handle multiple permission types?</a></p>
<p>It sounds like an innovative approach, so instead of a many-to-many relationship users_to_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer</p>
<p>I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.</p>
<p>Here is the original answer in the off chance the other question gets deleted:</p>
<p>"Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.</p>
<pre><code>[Flags]
public enum Permission
{
VIEWUSERS = 1, // 2^0 // 0000 0001
EDITUSERS = 2, // 2^1 // 0000 0010
VIEWPRODUCTS = 4, // 2^2 // 0000 0100
EDITPRODUCTS = 8, // 2^3 // 0000 1000
VIEWCLIENTS = 16, // 2^4 // 0001 0000
EDITCLIENTS = 32, // 2^5 // 0010 0000
DELETECLIENTS = 64, // 2^6 // 0100 0000
}
</code></pre>
<p>Then, you can combine several permissions using the AND bitwise operator. </p>
<p>For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3.
You can then store the permission of one user into a single column of your DataBase (in our case it would be 3).</p>
<p>Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not."</p>
| [
{
"answer_id": 60206,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 2,
"selected": false,
"text": "<p>Actually, this is how we determine authority within a fairly large web application that I'm the DBA for. </p>\n\n<p>If you a... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:
[What is the best way to handle multiple permission types?](/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types)
It sounds like an innovative approach, so instead of a many-to-many relationship users\_to\_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer
I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.
Here is the original answer in the off chance the other question gets deleted:
"Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.
```
[Flags]
public enum Permission
{
VIEWUSERS = 1, // 2^0 // 0000 0001
EDITUSERS = 2, // 2^1 // 0000 0010
VIEWPRODUCTS = 4, // 2^2 // 0000 0100
EDITPRODUCTS = 8, // 2^3 // 0000 1000
VIEWCLIENTS = 16, // 2^4 // 0001 0000
EDITCLIENTS = 32, // 2^5 // 0010 0000
DELETECLIENTS = 64, // 2^6 // 0100 0000
}
```
Then, you can combine several permissions using the AND bitwise operator.
For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3.
You can then store the permission of one user into a single column of your DataBase (in our case it would be 3).
Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not." | You use bitwise operations. The pseudo-code would be something like:
```
bool HasPermission(User user, Permission permission) {
return (user.Permission & permission) != 0;
}
void SetPermission(User user, Permission permission) {
user.Permission |= permission;
}
void ClearPermission(User user, Permission permission) {
user.Permission &= ~permission;
}
```
Permission is the enum type defined in your post, though whatever type it is needs to be based on an integer-like type. The same applies to the User.Permission field.
If those operators (&, |=, and &=) don't make sense to you, then read up on bitwise operations (bitwise AND and bitwise OR). |
60,208 | <p>I want to write a function in Python that returns different fixed values based on the value of an input index. </p>
<p>In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions in this scenario?</p>
| [
{
"answer_id": 60211,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 12,
"selected": true,
"text": "<p>The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the <a href=\"https://www.pyth... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4907/"
] | I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a `switch` or `case` statement, but Python does not appear to have a `switch` statement. What are the recommended Python solutions in this scenario? | The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the [`match`-`case`](https://www.python.org/dev/peps/pep-0634/) statement which provides a first-class implementation of a "switch" for Python. For example:
```
def f(x):
match x:
case 'a':
return 1
case 'b':
return 2
case _:
return 0 # 0 is the default case if x is not found
```
The `match`-`case` statement is considerably more powerful than this simple example.
---
You could use a dictionary:
```
def f(x):
return {
'a': 1,
'b': 2,
}[x]
``` |
60,221 | <p>I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:</p>
<blockquote>
<p>[======> ] 37%</p>
</blockquote>
<p>and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?</p>
| [
{
"answer_id": 60226,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 7,
"selected": true,
"text": "<p>There are two ways I know of to do this:</p>\n\n<ul>\n<li>Use the backspace escape character ('\\b') to erase your line</li>... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
] | I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:
>
> [======> ] 37%
>
>
>
and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction? | There are two ways I know of to do this:
* Use the backspace escape character ('\b') to erase your line
* Use the `curses` package, if your programming language of choice has bindings for it.
And a Google revealed [ANSI Escape Codes](http://en.wikipedia.org/wiki/ANSI_escape_code), which appear to be a good way. For reference, here is a function in C++ to do this:
```
void DrawProgressBar(int len, double percent) {
cout << "\x1B[2K"; // Erase the entire current line.
cout << "\x1B[0E"; // Move to the beginning of the current line.
string progress;
for (int i = 0; i < len; ++i) {
if (i < static_cast<int>(len * percent)) {
progress += "=";
} else {
progress += " ";
}
}
cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
flush(cout); // Required.
}
``` |
60,244 | <p>I need to join two binary files with a <code>*.bat</code> script on Windows.</p>
<p>How can I achieve that?</p>
| [
{
"answer_id": 60248,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": false,
"text": "<p>You can use <code>copy /b</code> like this:</p>\n\n<pre><code>copy /b file1+file2 destfile\n</code></pre>\n"
},
{
... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] | I need to join two binary files with a `*.bat` script on Windows.
How can I achieve that? | Windows `type` command works similarly to UNIX `cat`.
**Example 1:**
```
type file1 file2 > file3
```
is equivalent of:
```
cat file1 file2 > file3
```
**Example 2:**
```
type *.vcf > all_in_one.vcf
```
This command will merge all the vcards into one. |
60,259 | <p>Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding.
Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.</p>
<p>Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source? </p>
<p>Code snippets would be great.</p>
<p>Update: To make it more clear,
Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls. </p>
| [
{
"answer_id": 60398,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 1,
"selected": false,
"text": "<p>using your webservice get your XML and create an XML Document from it, You can then set the Source of your xmlDataProvider t... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747/"
] | Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding.
Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.
Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source?
Code snippets would be great.
Update: To make it more clear,
Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls. | Here is some code I used to load a XML file from disk and bind it to a TreeView. I removed some of the normal tests for conciseness. The XML in the example is an OPML file.
```
XmlDataProvider provider = new XmlDataProvider();
if (provider != null)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(fileName);
provider.Document = doc;
provider.XPath = "/opml/body/outline";
FeedListTreeView.DataContext = provider;
}
``` |
60,260 | <p>I've been working through <a href="http://gigamonkeys.com/book" rel="nofollow noreferrer">Practical Common Lisp</a> and as an exercise decided to write a macro to determine if a number is a multiple of another number:</p>
<p><code>(defmacro multp (value factor)<br>
`(= (rem ,value ,factor) 0))</code></p>
<p>so that :
<code>(multp 40 10)</code>
evaluates to true whilst
<code>(multp 40 13)</code>
does not </p>
<p>The question is does this macro <a href="http://gigamonkeys.com/book/macros-defining-your-own.html#plugging-the-leaks" rel="nofollow noreferrer">leak</a> in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?</p>
| [
{
"answer_id": 60267,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here.... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5303/"
] | I've been working through [Practical Common Lisp](http://gigamonkeys.com/book) and as an exercise decided to write a macro to determine if a number is a multiple of another number:
`(defmacro multp (value factor)
`(= (rem ,value ,factor) 0))`
so that :
`(multp 40 10)`
evaluates to true whilst
`(multp 40 13)`
does not
The question is does this macro [leak](http://gigamonkeys.com/book/macros-defining-your-own.html#plugging-the-leaks) in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used? | Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both `value` and `factor` are evaluated only once and in order, and `rem` doesn't have any side effects.
This is not good Lisp though, because there's no reason to use a macro in this case. A function
```
(defun multp (value factor)
(zerop (rem value factor)))
```
is identical for all practical purposes. (Note the use of `zerop`. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, `(= ... 0)` might be better) |
60,269 | <p>How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.</p>
<p><strong>EDIT</strong>: <a href="http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html" rel="noreferrer">The Java Tutorials - Drag and Drop and Data Transfer</a>.</p>
| [
{
"answer_id": 60279,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 3,
"selected": false,
"text": "<p>Found this code out there on the <a href=\"http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] | How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.
**EDIT**: [The Java Tutorials - Drag and Drop and Data Transfer](http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html). | I liked [Terai Atsuhiro san's DnDTabbedPane](http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html), but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another.
Inspired by @[Tom](https://stackoverflow.com/questions/60269/how-to-implement-draggable-tab-using-java-swing#60306)'s effort, I decided to modify the code myself.
There are some details I added. For example, the ghost tab now slides along the tabbed pane instead of moving together with the mouse.
`setAcceptor(TabAcceptor a_acceptor)` should let the consumer code decide whether to let one tab transfer from one tabbed pane to another. The default acceptor always returns `true`.
```
/** Modified DnDTabbedPane.java
* http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html
* originally written by Terai Atsuhiro.
* so that tabs can be transfered from one pane to another.
* eed3si9n.
*/
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
public class DnDTabbedPane extends JTabbedPane {
public static final long serialVersionUID = 1L;
private static final int LINEWIDTH = 3;
private static final String NAME = "TabTransferData";
private final DataFlavor FLAVOR = new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType, NAME);
private static GhostGlassPane s_glassPane = new GhostGlassPane();
private boolean m_isDrawRect = false;
private final Rectangle2D m_lineRect = new Rectangle2D.Double();
private final Color m_lineColor = new Color(0, 100, 255);
private TabAcceptor m_acceptor = null;
public DnDTabbedPane() {
super();
final DragSourceListener dsl = new DragSourceListener() {
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext()
.setCursor(DragSource.DefaultMoveNoDrop);
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
s_glassPane.setPoint(new Point(-1000, -1000));
s_glassPane.repaint();
}
public void dragOver(DragSourceDragEvent e) {
//e.getLocation()
//This method returns a Point indicating the cursor location in screen coordinates at the moment
TabTransferData data = getTabTransferData(e);
if (data == null) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
/*
Point tabPt = e.getLocation();
SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
if (DnDTabbedPane.this.contains(tabPt)) {
int targetIdx = getTargetTabIndex(tabPt);
int sourceIndex = data.getTabIndex();
if (getTabAreaBound().contains(tabPt)
&& (targetIdx >= 0)
&& (targetIdx != sourceIndex)
&& (targetIdx != sourceIndex + 1)) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
return;
} // if
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
*/
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
}
public void dragDropEnd(DragSourceDropEvent e) {
m_isDrawRect = false;
m_lineRect.setRect(0, 0, 0, 0);
// m_dragTabIndex = -1;
if (hasGhost()) {
s_glassPane.setVisible(false);
s_glassPane.setImage(null);
}
}
public void dropActionChanged(DragSourceDragEvent e) {
}
};
final DragGestureListener dgl = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent e) {
// System.out.println("dragGestureRecognized");
Point tabPt = e.getDragOrigin();
int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
if (dragTabIndex < 0) {
return;
} // if
initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);
try {
e.startDrag(DragSource.DefaultMoveDrop,
new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl);
} catch (InvalidDnDOperationException idoe) {
idoe.printStackTrace();
}
}
};
//dropTarget =
new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,
new CDropTargetListener(), true);
new DragSource().createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dgl);
m_acceptor = new TabAcceptor() {
public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) {
return true;
}
};
}
public TabAcceptor getAcceptor() {
return m_acceptor;
}
public void setAcceptor(TabAcceptor a_value) {
m_acceptor = a_value;
}
private TabTransferData getTabTransferData(DropTargetDropEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getDragSourceContext()
.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class TabTransferable implements Transferable {
private TabTransferData m_data = null;
public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex);
}
public Object getTransferData(DataFlavor flavor) {
return m_data;
// return DnDTabbedPane.this;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] f = new DataFlavor[1];
f[0] = FLAVOR;
return f;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getHumanPresentableName().equals(NAME);
}
}
class TabTransferData {
private DnDTabbedPane m_tabbedPane = null;
private int m_tabIndex = -1;
public TabTransferData() {
}
public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) {
m_tabbedPane = a_tabbedPane;
m_tabIndex = a_tabIndex;
}
public DnDTabbedPane getTabbedPane() {
return m_tabbedPane;
}
public void setTabbedPane(DnDTabbedPane pane) {
m_tabbedPane = pane;
}
public int getTabIndex() {
return m_tabIndex;
}
public void setTabIndex(int index) {
m_tabIndex = index;
}
}
private Point buildGhostLocation(Point a_location) {
Point retval = new Point(a_location);
switch (getTabPlacement()) {
case JTabbedPane.TOP: {
retval.y = 1;
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.BOTTOM: {
retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();
retval.x -= s_glassPane.getGhostWidth() / 2;
} break;
case JTabbedPane.LEFT: {
retval.x = 1;
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
case JTabbedPane.RIGHT: {
retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();
retval.y -= s_glassPane.getGhostHeight() / 2;
} break;
} // switch
retval = SwingUtilities.convertPoint(DnDTabbedPane.this,
retval, s_glassPane);
return retval;
}
class CDropTargetListener implements DropTargetListener {
public void dragEnter(DropTargetDragEvent e) {
// System.out.println("DropTarget.dragEnter: " + DnDTabbedPane.this);
if (isDragAcceptable(e)) {
e.acceptDrag(e.getDropAction());
} else {
e.rejectDrag();
} // if
}
public void dragExit(DropTargetEvent e) {
// System.out.println("DropTarget.dragExit: " + DnDTabbedPane.this);
m_isDrawRect = false;
}
public void dropActionChanged(DropTargetDragEvent e) {
}
public void dragOver(final DropTargetDragEvent e) {
TabTransferData data = getTabTransferData(e);
if (getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM) {
initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);
} else {
initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);
} // if-else
repaint();
if (hasGhost()) {
s_glassPane.setPoint(buildGhostLocation(e.getLocation()));
s_glassPane.repaint();
}
}
public void drop(DropTargetDropEvent a_event) {
// System.out.println("DropTarget.drop: " + DnDTabbedPane.this);
if (isDropAcceptable(a_event)) {
convertTab(getTabTransferData(a_event),
getTargetTabIndex(a_event.getLocation()));
a_event.dropComplete(true);
} else {
a_event.dropComplete(false);
} // if-else
m_isDrawRect = false;
repaint();
}
public boolean isDragAcceptable(DropTargetDragEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
public boolean isDropAcceptable(DropTargetDropEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
}
private boolean m_hasGhost = true;
public void setPaintGhost(boolean flag) {
m_hasGhost = flag;
}
public boolean hasGhost() {
return m_hasGhost;
}
/**
* returns potential index for drop.
* @param a_point point given in the drop site component's coordinate
* @return returns potential index for drop.
*/
private int getTargetTabIndex(Point a_point) {
boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM;
// if the pane is empty, the target index is always zero.
if (getTabCount() == 0) {
return 0;
} // if
for (int i = 0; i < getTabCount(); i++) {
Rectangle r = getBoundsAt(i);
if (isTopOrBottom) {
r.setRect(r.x - r.width / 2, r.y, r.width, r.height);
} else {
r.setRect(r.x, r.y - r.height / 2, r.width, r.height);
} // if-else
if (r.contains(a_point)) {
return i;
} // if
} // for
Rectangle r = getBoundsAt(getTabCount() - 1);
if (isTopOrBottom) {
int x = r.x + r.width / 2;
r.setRect(x, r.y, getWidth() - x, r.height);
} else {
int y = r.y + r.height / 2;
r.setRect(r.x, y, r.width, getHeight() - y);
} // if-else
return r.contains(a_point) ? getTabCount() : -1;
}
private void convertTab(TabTransferData a_data, int a_targetIndex) {
DnDTabbedPane source = a_data.getTabbedPane();
int sourceIndex = a_data.getTabIndex();
if (sourceIndex < 0) {
return;
} // if
Component cmp = source.getComponentAt(sourceIndex);
String str = source.getTitleAt(sourceIndex);
if (this != source) {
source.remove(sourceIndex);
if (a_targetIndex == getTabCount()) {
addTab(str, cmp);
} else {
if (a_targetIndex < 0) {
a_targetIndex = 0;
} // if
insertTab(str, null, cmp, null, a_targetIndex);
} // if
setSelectedComponent(cmp);
// System.out.println("press="+sourceIndex+" next="+a_targetIndex);
return;
} // if
if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
//System.out.println("press="+prev+" next="+next);
return;
} // if
if (a_targetIndex == getTabCount()) {
//System.out.println("last: press="+prev+" next="+next);
source.remove(sourceIndex);
addTab(str, cmp);
setSelectedIndex(getTabCount() - 1);
} else if (sourceIndex > a_targetIndex) {
//System.out.println(" >: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex);
setSelectedIndex(a_targetIndex);
} else {
//System.out.println(" <: press="+prev+" next="+next);
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex - 1);
setSelectedIndex(a_targetIndex - 1);
}
}
private void initTargetLeftRightLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);
m_isDrawRect = true;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
}
}
private void initTargetTopBottomLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
}
}
private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {
//Point p = (Point) pt.clone();
getRootPane().setGlassPane(s_glassPane);
if (hasGhost()) {
Rectangle rect = getBoundsAt(a_tabIndex);
BufferedImage image = new BufferedImage(c.getWidth(),
c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
c.paint(g);
image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
s_glassPane.setImage(image);
} // if
s_glassPane.setPoint(buildGhostLocation(tabPt));
s_glassPane.setVisible(true);
}
private Rectangle getTabAreaBound() {
Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (m_isDrawRect) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(m_lineColor);
g2.fill(m_lineRect);
} // if
}
public interface TabAcceptor {
boolean isDropAcceptable(DnDTabbedPane a_component, int a_index);
}
}
class GhostGlassPane extends JPanel {
public static final long serialVersionUID = 1L;
private final AlphaComposite m_composite;
private Point m_location = new Point(0, 0);
private BufferedImage m_draggingGhost = null;
public GhostGlassPane() {
setOpaque(false);
m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);
}
public void setImage(BufferedImage draggingGhost) {
m_draggingGhost = draggingGhost;
}
public void setPoint(Point a_location) {
m_location.x = a_location.x;
m_location.y = a_location.y;
}
public int getGhostWidth() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getWidth(this);
}
public int getGhostHeight() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getHeight(this);
}
public void paintComponent(Graphics g) {
if (m_draggingGhost == null) {
return;
} // if
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(m_composite);
g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);
}
}
``` |
60,278 | <p>In all the Git tutorials I've read they say that you can do:</p>
<pre><code>git init
git add .
git commit
</code></pre>
<p>When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.</p>
| [
{
"answer_id": 60283,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>git commit</code> command will open up the editor specified in the <code>EDITOR</code> environment variable ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In all the Git tutorials I've read they say that you can do:
```
git init
git add .
git commit
```
When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything. | You're meant to put the commit message in this text file, then save and quit.
You can change the default text editor that git uses with this command:
```
git config --global core.editor "nano"
```
You have to change nano to whatever command would normally open your text editor. |
60,290 | <p>Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>
| [
{
"answer_id": 60294,
"author": "Flame",
"author_id": 5387,
"author_profile": "https://Stackoverflow.com/users/5387",
"pm_score": 1,
"selected": false,
"text": "<p>The way I usually see things done with smaller images such as buttons it that only a certain portion of the image is shown. ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] | Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)? | [Here's some good information about image opacity and transparency with CSS](http://www.w3schools.com/css/css_image_transparency.asp).
So to make an image with opacity 50%, you'd do this:
```
<img src="image.png" style="opacity: 0.5; filter: alpha(opacity=50)" />
```
The **opacity:** part is how Firefox does it, and it's a value between 0.0 and 1.0. **filter:** is how IE does it, and it's a value from 0 to 100. |
60,293 | <p>I have a little problem with a Listview.</p>
<p>I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow strip that doesn't paint. The width of that strip is approximately the same as a row header would be if I had a row header. </p>
<p>If you have a thought on what can be done to make the background draw I'd love to hear it. </p>
<p>Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view. [I love legacy code.]</p>
<p><strong>Edit:</strong></p>
<p>Here is a sample that exhibits the problem.</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListView lv = new ListView();
lv.Dock = System.Windows.Forms.DockStyle.Fill;
lv.FullRowSelect = true;
lv.GridLines = true;
lv.HideSelection = false;
lv.Location = new System.Drawing.Point(0, 0);
lv.TabIndex = 0;
lv.View = System.Windows.Forms.View.Details;
lv.AllowColumnReorder = true;
this.Controls.Add(lv);
lv.MultiSelect = true;
ColumnHeader ch = new ColumnHeader();
ch.Name = "Foo";
ch.Text = "Foo";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch);
ColumnHeader ch2 = new ColumnHeader();
ch.Name = "Bar";
ch.Text = "Bar";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch2);
lv.BeginUpdate();
for (int i = 0; i < 3; i++)
{
ListViewItem lvi = new ListViewItem("1", "2");
lvi.BackColor = Color.Black;
lvi.ForeColor = Color.White;
lv.Items.Add(lvi);
}
lv.EndUpdate();
}
}
</code></pre>
| [
{
"answer_id": 60300,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 1,
"selected": false,
"text": "<p>(Prior to the Edit...)</p>\n\n<p>I've just tried setting the BackColor on a System.Windows.Forms.ListView, and the color is... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1327/"
] | I have a little problem with a Listview.
I can load it with listview items fine, but when I set the background color it doesn't draw the color all the way to the left side of the row [The listViewItems are loaded with ListViewSubItems to make a grid view, only the first column shows the error]. There is a a narrow strip that doesn't paint. The width of that strip is approximately the same as a row header would be if I had a row header.
If you have a thought on what can be done to make the background draw I'd love to hear it.
Now just to try a new idea, I'm offering a ten vote bounty for the first solution that still has me using this awful construct of a mess of a pseudo grid view. [I love legacy code.]
**Edit:**
Here is a sample that exhibits the problem.
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListView lv = new ListView();
lv.Dock = System.Windows.Forms.DockStyle.Fill;
lv.FullRowSelect = true;
lv.GridLines = true;
lv.HideSelection = false;
lv.Location = new System.Drawing.Point(0, 0);
lv.TabIndex = 0;
lv.View = System.Windows.Forms.View.Details;
lv.AllowColumnReorder = true;
this.Controls.Add(lv);
lv.MultiSelect = true;
ColumnHeader ch = new ColumnHeader();
ch.Name = "Foo";
ch.Text = "Foo";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch);
ColumnHeader ch2 = new ColumnHeader();
ch.Name = "Bar";
ch.Text = "Bar";
ch.Width = 40;
ch.TextAlign = HorizontalAlignment.Left;
lv.Columns.Add(ch2);
lv.BeginUpdate();
for (int i = 0; i < 3; i++)
{
ListViewItem lvi = new ListViewItem("1", "2");
lvi.BackColor = Color.Black;
lvi.ForeColor = Color.White;
lv.Items.Add(lvi);
}
lv.EndUpdate();
}
}
``` | Ah! I see now :}
You want hacky? I present unto you the following:
```
...
lv.OwnerDraw = true;
lv.DrawItem += new DrawListViewItemEventHandler( lv_DrawItem );
...
void lv_DrawItem( object sender, DrawListViewItemEventArgs e )
{
Rectangle foo = e.Bounds;
foo.Offset( -10, 0 );
e.Graphics.FillRectangle( new SolidBrush( e.Item.BackColor ), foo );
e.DrawDefault = true;
}
```
For a more inventive - and no less hacky - approach, you could try utilising the background image of the ListView ;) |
60,302 | <p>If I start a process via Java's <a href="http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html" rel="noreferrer">ProcessBuilder</a> class, I have full access to that process's standard in, standard out, and standard error streams as Java <code>InputStreams</code> and <code>OutputStreams</code>. However, I can't find a way to seamlessly connect those streams to <code>System.in</code>, <code>System.out</code>, and <code>System.err</code>.</p>
<p>It's possible to use <code>redirectErrorStream()</code> to get a single <code>InputStream</code> that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C <code>system()</code> call.</p>
<p>This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of <a href="http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html" rel="noreferrer"><code>isatty()</code></a> in the child process carries through the redirection.</p>
| [
{
"answer_id": 60578,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 5,
"selected": true,
"text": "<p>You will need to copy the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Process.html\" rel=\"noreferrer\">... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5696/"
] | If I start a process via Java's [ProcessBuilder](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html) class, I have full access to that process's standard in, standard out, and standard error streams as Java `InputStreams` and `OutputStreams`. However, I can't find a way to seamlessly connect those streams to `System.in`, `System.out`, and `System.err`.
It's possible to use `redirectErrorStream()` to get a single `InputStream` that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C `system()` call.
This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of [`isatty()`](http://www.opengroup.org/onlinepubs/009695399/functions/isatty.html) in the child process carries through the redirection. | You will need to copy the [Process](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) out, err, and input streams to the System versions. The easiest way to do that is using the [IOUtils](http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html) class from the Commons IO package. The [copy method](http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29) looks to be what you need. The copy method invocations will need to be in separate threads.
Here is the basic code:
```
// Assume you already have a processBuilder all configured and ready to go
final Process process = processBuilder.start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getOutputStream(), System.out);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getErrorStream(), System.err);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(System.in, process.getInputStream());
} } ).start();
``` |
60,352 | <p>If all of my <code>__init__.py</code> files are empty, do I have to store them into version control, or is there a way to make <code>distutils</code> create empty <code>__init__.py</code> files during installation?</p>
| [
{
"answer_id": 60431,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>In Python, <code>__init__.py</code> files actually have a meaning! They mean that the folder they are in is a Python module.... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2679/"
] | If all of my `__init__.py` files are empty, do I have to store them into version control, or is there a way to make `distutils` create empty `__init__.py` files during installation? | Is there a reason you want to *avoid* putting empty `__init__.py` files in version control? If you do this you won't be able to `import` your packages from the source directory wihout first running distutils.
If you really want to, I suppose you can create `__init__.py` in `setup.py`. It has to be *before* running `distutils.setup`, so `setup` itself is able to find your packages:
```
from distutils import setup
import os
for path in [my_package_directories]:
filename = os.path.join(pagh, '__init__.py')
if not os.path.exists(filename):
init = open(filename, 'w')
init.close()
setup(
...
)
```
but... what would you gain from this, compared to having the empty `__init__.py` files there in the first place? |
60,369 | <p>I'm currently playing around with <a href="http://pear.php.net/package/HTML_QuickForm" rel="noreferrer">HTML_QuickForm</a> for generating forms in PHP. It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements.</p>
<p>Are there any alternatives to QuickForm that might provide more flexibility?</p>
| [
{
"answer_id": 60372,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "<p>If you find it hard to insert Javascript into the form elements, consider using a JavaScript framework such as <a hr... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | I'm currently playing around with [HTML\_QuickForm](http://pear.php.net/package/HTML_QuickForm) for generating forms in PHP. It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements.
Are there any alternatives to QuickForm that might provide more flexibility? | If you find it hard to insert Javascript into the form elements, consider using a JavaScript framework such as [Prototype](http://www.prototypejs.org/) or [jQuery](http://jquery.com/). There, you can centralize the task of injecting event handling into form controls.
By that, I mean that you won't need to insert event handlers into the HTML form code. Instead, you register those events from somewhere else. For example, in Prototype you would be able to write something like this:
```
$('myFormControl').observe('click', myClickFunction)
```
Also have a look at the answers to [another question](https://stackoverflow.com/questions/34126/whats-the-best-way-to-add-event-in-javascript).
/EDIT: of course, you can also insert custom attributes and thus event handlers into the form elements using HTML\_QuickForm. However, the above way is superior. |
60,409 | <p>I know in php you can embed variables inside variables, like:</p>
<pre><code><? $var1 = "I\'m including {$var2} in this variable.."; ?>
</code></pre>
<p>But I was wondering how, and if it was possible to include a function inside a variable.
I know I could just write:</p>
<pre><code><?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
</code></pre>
<p>But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:</p>
<pre><code><?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?>
</code></pre>
<p>Or I want dynamic changes in that load of code:</p>
<pre><code><?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?>
</code></pre>
<p>Well?</p>
| [
{
"answer_id": 60420,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 6,
"selected": true,
"text": "<p>Function calls within strings are supported since PHP5 by having a variable containing the name of the function to ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4867/"
] | I know in php you can embed variables inside variables, like:
```
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
```
But I was wondering how, and if it was possible to include a function inside a variable.
I know I could just write:
```
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
```
But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions:
```
<?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?>
```
Or I want dynamic changes in that load of code:
```
<?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?>
```
Well? | Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call:
```
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
```
will output "`foo <b>bar</b> baz`".
I find it easier however (and this works in PHP4) to either just call the function outside of the string:
```
<?
echo "foo " . somefunc("bar") . " baz";
?>
```
or assign to a temporary variable:
```
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
``` |
60,422 | <p>As part of a JavaScript Profiler for IE 6/7 I needed to load a custom debugger that I created into IE. I got this working fine on XP, but couldn't get it working on Vista (full story here: <a href="http://damianblog.com/2008/09/09/tracejs-v2-rip/" rel="nofollow noreferrer">http://damianblog.com/2008/09/09/tracejs-v2-rip/</a>).</p>
<p>The call to GetProviderProcessData is failing on Vista. Anyone have any suggestions?</p>
<p>Thanks,
Damian</p>
<pre><code>// Create the MsProgramProvider
IDebugProgramProvider2* pIDebugProgramProvider2 = 0;
HRESULT st = CoCreateInstance(CLSID_MsProgramProvider, 0, CLSCTX_ALL, IID_IDebugProgramProvider2, (void**)&pIDebugProgramProvider2);
if(st != S_OK) {
return st;
}
// Get the IDebugProgramNode2 instances running in this process
AD_PROCESS_ID processID;
processID.ProcessId.dwProcessId = GetCurrentProcessId();
processID.ProcessIdType = AD_PROCESS_ID_SYSTEM;
CONST_GUID_ARRAY engineFilter;
engineFilter.dwCount = 0;
PROVIDER_PROCESS_DATA processData;
st = pIDebugProgramProvider2->GetProviderProcessData(PFLAG_GET_PROGRAM_NODES|PFLAG_DEBUGGEE, 0, processID, engineFilter, &processData);
if(st != S_OK) {
ShowError(L"GPPD Failed", st);
pIDebugProgramProvider2->Release();
return st;
}
</code></pre>
| [
{
"answer_id": 60468,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not familiar with these interfaces, but unexpected failures in Vista may require being past a UAC prompt. Have you t... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3390/"
] | As part of a JavaScript Profiler for IE 6/7 I needed to load a custom debugger that I created into IE. I got this working fine on XP, but couldn't get it working on Vista (full story here: <http://damianblog.com/2008/09/09/tracejs-v2-rip/>).
The call to GetProviderProcessData is failing on Vista. Anyone have any suggestions?
Thanks,
Damian
```
// Create the MsProgramProvider
IDebugProgramProvider2* pIDebugProgramProvider2 = 0;
HRESULT st = CoCreateInstance(CLSID_MsProgramProvider, 0, CLSCTX_ALL, IID_IDebugProgramProvider2, (void**)&pIDebugProgramProvider2);
if(st != S_OK) {
return st;
}
// Get the IDebugProgramNode2 instances running in this process
AD_PROCESS_ID processID;
processID.ProcessId.dwProcessId = GetCurrentProcessId();
processID.ProcessIdType = AD_PROCESS_ID_SYSTEM;
CONST_GUID_ARRAY engineFilter;
engineFilter.dwCount = 0;
PROVIDER_PROCESS_DATA processData;
st = pIDebugProgramProvider2->GetProviderProcessData(PFLAG_GET_PROGRAM_NODES|PFLAG_DEBUGGEE, 0, processID, engineFilter, &processData);
if(st != S_OK) {
ShowError(L"GPPD Failed", st);
pIDebugProgramProvider2->Release();
return st;
}
``` | It would help to know what the error result was.
Possible problems I can think of:
If your getting permission denied, your most likely missing some requried [Privilege](http://msdn.microsoft.com/en-us/library/aa375728(VS.85).aspx) in your ACL. New ones are sometimes not doceumented well, check the latest Platform SDK headers to see if any new ones that still out. It may be that under vista the Privilege is not assigned my default to your ACL any longer.
If your getting some sort of Not Found type error, then it may be 32bit / 64bit problem. Your debbugging API may only be available under 64bit COM on vista 64. The 32bit/64bit interoperation can be very confusing. |
60,438 | <p>I am using jQuery. I call a JavaScript function with next html:</p>
<pre><code><li><span><a href="javascript:uncheckEl('tagVO-$id')">$tagname</a></span></li>
</code></pre>
<p>I would like to remove the <code>li</code> element and I thought this would be easy with the <code>$(this)</code> object. This is my JavaScript function:</p>
<pre><code>function uncheckEl(id) {
$("#"+id+"").attr("checked","");
$("#"+id+"").parent("li").css("color","black");
$(this).parent("li").remove(); // This is not working
retrieveItems();
}
</code></pre>
<p>But <code>$(this)</code> is undefined. Any ideas?</p>
| [
{
"answer_id": 60449,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 3,
"selected": true,
"text": "<p>Try something like this (e.g. to hide the <code><li></code>):</p>\n\n<pre><code>function unCheckEl(id, ref) {\n (...)\n... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I am using jQuery. I call a JavaScript function with next html:
```
<li><span><a href="javascript:uncheckEl('tagVO-$id')">$tagname</a></span></li>
```
I would like to remove the `li` element and I thought this would be easy with the `$(this)` object. This is my JavaScript function:
```
function uncheckEl(id) {
$("#"+id+"").attr("checked","");
$("#"+id+"").parent("li").css("color","black");
$(this).parent("li").remove(); // This is not working
retrieveItems();
}
```
But `$(this)` is undefined. Any ideas? | Try something like this (e.g. to hide the `<li>`):
```
function unCheckEl(id, ref) {
(...)
$(ref).parent().parent().hide(); // this should be your <li>
}
```
And your link:
```
<a href="javascript:uncheckEl('tagVO-$id', \$(this))">
```
`$(this)` is not present inside your function, because how is it supposed to know where the action is called from? You pass no reference in it, so `$(this)` could refer to everything but the `<a>`. |
60,455 | <p>Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server?</p>
<p>I'm not so concerned with browser security issues. etc. as the implementation would be for <a href="http://msdn.microsoft.com/en-us/library/ms536471(vs.85).aspx" rel="noreferrer">HTA</a>. But is it possible?</p>
| [
{
"answer_id": 60471,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 1,
"selected": false,
"text": "<p>You can achieve that using HTA and <a href=\"http://en.wikipedia.org/wiki/VBScript\" rel=\"nofollow noreferrer\">VBScript</a>... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915/"
] | Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server?
I'm not so concerned with browser security issues. etc. as the implementation would be for [HTA](http://msdn.microsoft.com/en-us/library/ms536471(vs.85).aspx). But is it possible? | I have done this for an HTA by using an ActiveX control. It was pretty easy to build the control in VB6 to take the screenshot. I had to use the keybd\_event API call because SendKeys can't do PrintScreen. Here's the code for that:
```
Declare Sub keybd_event Lib "user32" _
(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Public Const CaptWindow = 2
Public Sub ScreenGrab()
keybd_event &H12, 0, 0, 0
keybd_event &H2C, CaptWindow, 0, 0
keybd_event &H2C, CaptWindow, &H2, 0
keybd_event &H12, 0, &H2, 0
End Sub
```
That only gets you as far as getting the window to the clipboard.
Another option, if the window you want a screenshot of is an HTA would be to just use an XMLHTTPRequest to send the DOM nodes to the server, then create the screenshots server-side. |
60,456 | <p>I have this in a page :</p>
<pre><code><textarea id="taEditableContent" runat="server" rows="5"></textarea>
<ajaxToolkit:DynamicPopulateExtender ID="dpeEditPopulate" runat="server" TargetControlID="taEditableContent"
ClearContentsDuringUpdate="true" PopulateTriggerControlID="hLink" ServicePath="/Content.asmx"
ServiceMethod="EditContent" ContextKey='<%=ContextKey %>' />
</code></pre>
<p>Basically, a DynamicPopulateExtender that fills the contents of a textarea from a webservice. Problem is, no matter how I return the line breaks, the text in the text area will have no line feeds.</p>
<p>If I return the newlines as "br/" the entire text area remains empty. If I return new lines as "/r/n" , I get all the text as one continous line. The webservice returns the string correctly:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://rprealm.com/">First line
Third line
Fourth line</string>
</code></pre>
<p>But what I get in the text area is :</p>
<pre><code>First line Third line Fourth line
</code></pre>
| [
{
"answer_id": 60490,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 0,
"selected": false,
"text": "<p>Try to add the following style on textarea: <strong>style=\"white-space: pre\"</strong></p>\n"
},
{
"answer_id... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
] | I have this in a page :
```
<textarea id="taEditableContent" runat="server" rows="5"></textarea>
<ajaxToolkit:DynamicPopulateExtender ID="dpeEditPopulate" runat="server" TargetControlID="taEditableContent"
ClearContentsDuringUpdate="true" PopulateTriggerControlID="hLink" ServicePath="/Content.asmx"
ServiceMethod="EditContent" ContextKey='<%=ContextKey %>' />
```
Basically, a DynamicPopulateExtender that fills the contents of a textarea from a webservice. Problem is, no matter how I return the line breaks, the text in the text area will have no line feeds.
If I return the newlines as "br/" the entire text area remains empty. If I return new lines as "/r/n" , I get all the text as one continous line. The webservice returns the string correctly:
```
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://rprealm.com/">First line
Third line
Fourth line</string>
```
But what I get in the text area is :
```
First line Third line Fourth line
``` | The problem is that the white space is ignored by default when the XML is processed. Try to add the `xml:space="preserve"` attribute to the string element. You'll also need to define the xml prefix as `xmlns:xml="http://www.w3.org/XML/1998/namespace"`. |
60,470 | <p>If I'm running a signed Java applet. Can I load additional classes from remote sources, in the same domain or maybe even the same host, and run them?</p>
<p>I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once.</p>
<p>Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?</p>
| [
{
"answer_id": 60574,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like it should be possible (but I've never done it). Have you already had a look at Remote Method Invocation ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If I'm running a signed Java applet. Can I load additional classes from remote sources, in the same domain or maybe even the same host, and run them?
I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once.
Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status? | I think classes are lazy loaded in applets. being loaded on demand.
Anyway, if the classes are outside of a jar you can simply use the applet classloader and load them by name. Ex:
```
ClassLoader loader = this.getClass().getClassLoader();
Class clazz = loader.loadClass("acme.AppletAddon");
```
If you want to load classes from a jar I think you will need to create a new instance of URLClassLoader with the url(s) of the jar(s).
```
URL[] urls = new URL[]{new URL("http://localhost:8080/addon.jar")};
URLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader());
Class clazz = loader.loadClass("acme.AppletAddon");
```
By default, applets are forbidden to create new classloaders. But if you sign your applet and include permission to create new classloaders you can do it. |
60,507 | <p>Say I have:</p>
<pre><code>void Render(void(*Call)())
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
</code></pre>
<p>This is fine as long as the function I want to use to render is a function or a <code>static</code> member function:</p>
<pre><code>Render(MainMenuRender);
Render(MainMenu::Render);
</code></pre>
<p>However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g.</p>
<pre><code>Render(MainMenu->Render);
</code></pre>
<p>However I really have no idea how to do this, and still allow functions and <code>static</code> member functions to be used.</p>
| [
{
"answer_id": 60512,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "<p>You can make a wrapper function <code>void Wrap(T *t)</code> that just calls <code>t->Call()</code> and have <code>Ren... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] | Say I have:
```
void Render(void(*Call)())
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
```
This is fine as long as the function I want to use to render is a function or a `static` member function:
```
Render(MainMenuRender);
Render(MainMenu::Render);
```
However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g.
```
Render(MainMenu->Render);
```
However I really have no idea how to do this, and still allow functions and `static` member functions to be used. | There are a lot of ways to skin this cat, including templates. My favorite is [Boost.function](http://www.boost.org/doc/libs/1_36_0/doc/html/function.html) as I've found it to be the most flexible in the long run. Also read up on [Boost.bind](http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html) for binding to member functions as well as many other tricks.
It would look like this:
```
#include <boost/bind.hpp>
#include <boost/function.hpp>
void Render(boost::function0<void> Call)
{
// as before...
}
Render(boost::bind(&MainMenu::Render, myMainMenuInstance));
``` |
60,558 | <p>I need to do some emulation of some old DOS or mainframe terminals in Flex. Something like the image below for example.</p>
<p><img src="https://i.stack.imgur.com/qFtvP.png" alt="alt text"></p>
<p>The different coloured text is easy enough, but the ability to do different background colours, such as the yellow background is beyond the capabilities of the standard Flash text.</p>
<p>I may also need to be able to enter text at certain places and scroll text up the "terminal". Any idea how I'd attack this? Or better still, any existing code/components for this sort of thing?</p>
| [
{
"answer_id": 60564,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 1,
"selected": false,
"text": "<p>The font is fixed width and height, so making a background bitmap dynamically isn't difficult, and is probably the quic... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6277/"
] | I need to do some emulation of some old DOS or mainframe terminals in Flex. Something like the image below for example.

The different coloured text is easy enough, but the ability to do different background colours, such as the yellow background is beyond the capabilities of the standard Flash text.
I may also need to be able to enter text at certain places and scroll text up the "terminal". Any idea how I'd attack this? Or better still, any existing code/components for this sort of thing? | Use [`TextField.getCharBoundaries`](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html) to get a rectangle of the first and last characters in the areas where you want a background. From these rectangles you can construct a rectangle that spans the whole area. Use this to draw the background in a `Shape` placed behind the text field, or in the parent of the text field.
*Update* you asked for an example, here is how to get a rectangle from a range of characters:
```
var firstCharBounds : Rectangle = textField.getCharBoundaries(firstCharIndex);
var lastCharBounds : Rectangle = textField.getCharBoundaries(lastCharIndex);
var rangeBounds : Rectangle = new Rectangle();
rangeBounds.topLeft = firstCharBounds.topLeft;
rangeBounds.bottomRight = lastCharBounds.bottomRight;
```
If you want to find a rectangle for a whole line you can do this instead:
```
var charBounds : Rectangle = textField.getCharBoundaries(textField.getLineOffset(lineNumber));
var lineBounds : Rectangle = new Rectangle(0, charBounds.y, textField.width, firstCharBounds.height);
```
When you have the bounds of the text range you want to paint a background for, you can do this in the `updateDisplayList` method of the parent of the text field (assuming the text field is positioned at [0, 0] and has white text, and that `textRangesWithYellowBackground` is an array of rectangles that represent the text ranges that should have yellow backgrounds):
```
graphics.clear();
// this draws the black background
graphics.beginFill(0x000000);
graphics.drawRect(0, 0, textField.width, textField.height);
graphics.endFill();
// this draws yellow text backgrounds
for each ( var r : Rectangle in textRangesWithYellowBackground )
graphics.beginFill(0xFFFF00);
graphics.drawRect(r.x, r.y, r.width, r.height);
graphics.endFill();
}
``` |
60,570 | <p>Backgrounder:</p>
<p>The <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="noreferrer">PIMPL Idiom</a> (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.</p>
<p>This hides internal implementation details and data from the user of the library.</p>
<p>When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?</p>
<p>To illustrate, this code puts the <code>Purr()</code> implementation on the impl class and wraps it as well.</p>
<p><strong>Why not implement Purr directly on the public class?</strong></p>
<pre class="lang-c++ prettyprint-override"><code>// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
</code></pre>
| [
{
"answer_id": 60575,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 2,
"selected": false,
"text": "<p>Placing the call to the impl->Purr inside the .cpp file means that in the future you could do something completely ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | Backgrounder:
The [PIMPL Idiom](http://en.wikipedia.org/wiki/Opaque_pointer) (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.
This hides internal implementation details and data from the user of the library.
When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?
To illustrate, this code puts the `Purr()` implementation on the impl class and wraps it as well.
**Why not implement Purr directly on the public class?**
```c++
// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
``` | * Because you want `Purr()` to be able to use private members of `CatImpl`. `Cat::Purr()` would not be allowed such an access without a `friend` declaration.
* Because you then don't mix responsibilities: one class implements, one class forwards. |
60,573 | <p>Using C# .NET 2.0, I have a composite data class that does have the <code>[Serializable]</code> attribute on it. I am creating an <code>XMLSerializer</code> class and passing that into the constructor:</p>
<pre><code>XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
</code></pre>
<p>I am getting an exception saying: </p>
<blockquote>
<p>There was an error reflecting type.</p>
</blockquote>
<p>Inside the data class there is another composite object. Does this also need to have the <code>[Serializable]</code> attribute, or by having it on the top object, does it recursively apply it to all objects inside?</p>
| [
{
"answer_id": 60581,
"author": "Lamar",
"author_id": 3566,
"author_profile": "https://Stackoverflow.com/users/3566",
"pm_score": 10,
"selected": true,
"text": "<p>Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing. ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] | Using C# .NET 2.0, I have a composite data class that does have the `[Serializable]` attribute on it. I am creating an `XMLSerializer` class and passing that into the constructor:
```
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
```
I am getting an exception saying:
>
> There was an error reflecting type.
>
>
>
Inside the data class there is another composite object. Does this also need to have the `[Serializable]` attribute, or by having it on the top object, does it recursively apply it to all objects inside? | Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [`[XmlIgnore]`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlignoreattribute) attribute.
`XmlSerializer` does not use the [`[Serializable]`](https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute) attribute, so I doubt that is the problem. |
60,585 | <p>I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM).</p>
<p>I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP. What is the equivalent for standalone machines?</p>
| [
{
"answer_id": 61062,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 0,
"selected": false,
"text": "<p>Good Question!</p>\n\n<p>I've given this some thought... and I can't think of a good solution. What I can think of... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] | I'm running PHP, Apache, and Windows. I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM).
I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP. What is the equivalent for standalone machines? | I haven't found a simple solution either. There are examples using CreateObject and the WinNT ADSI provider. But eventually they all bump into [User authentication issues with the Active Directory Service Interfaces WinNT provider](http://support.microsoft.com/kb/218497). I'm not 100% sure but I *guess* the WSH/network connect approach has the same problem.
According to [How to validate user credentials on Microsoft operating systems](http://support.microsoft.com/kb/180548/) you should use LogonUser or SSPI.
It also says
>
> ```
> LogonUser Win32 API does not require TCB privilege in Microsoft Windows Server 2003, however, for downlevel compatibility, this is still the best approach.
> ```
>
On Windows XP, it is no longer required that a process have the SE\_TCB\_NAME privilege in order to call LogonUser. Therefore, the simplest method to validate a user's credentials on Windows XP, is to call the LogonUser API.Therefore, if I were certain Win9x/2000 support isn't needed, I would write an extension that exposes LogonUser to php.
You might also be interested in [User Authentication from NT Accounts](http://www.codewalkers.com/c/a/User-Management-Code/User-Authentication-from-NT-Accounts/). It uses the w32api extension, and needs a support dll ...I'd rather write that small LogonUser-extension ;-)
If that's not feasible I'd probably look into the fastcgi module for IIS and how stable it is and let the IIS handle the authentication.
edit:
I've also tried to utilize [System.Security.Principal.WindowsIdentity](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx) and php's [com/.net extension](http://uk.php.net/manual/en/book.com.php). But the dotnet constructor doesn't seem to allow passing parameters to the objects constructor and my "experiment" to get the assembly (and with it CreateInstance()) from GetType() has failed with an "unknown zval" error. |
60,590 | <p>On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment."</p>
<p>A couple of <strong>possible approaches</strong> I know about, and browser compatibility (based on a quick test):</p>
<p><strong>1) Do a <code>window.open</code> pointing to the new file.</strong> </p>
<pre><code>- FireFox 3 blocks this.
- IE6 blocks this.
- IE7 blocks this.
</code></pre>
<p><strong>2) Create an iframe pointing to the new file.</strong> </p>
<pre><code>- FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?)
- IE6 blocks this.
- IE7 blocks this.
How can I do this so that at least these three browsers will not object?
</code></pre>
<p>Bonus: is there a method that doesn't require browser-conditional statements? </p>
<p>(I believe that download.com employs both methods conditionally, but I can't get either one to work.)</p>
<p><strong>Responses and Clarifications:</strong></p>
<pre><code>Q: "Why not point the current window to the file?"
A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?"
</code></pre>
<p><strong>UPDATE: I have abandoned this approach. See my answer below for reasons.</strong></p>
| [
{
"answer_id": 60598,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 0,
"selected": false,
"text": "<p>How about changing the location to point to the new file? (e.g. by changing window.location)</p>\n"
},
{
"answer_id": ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4376/"
] | On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment."
A couple of **possible approaches** I know about, and browser compatibility (based on a quick test):
**1) Do a `window.open` pointing to the new file.**
```
- FireFox 3 blocks this.
- IE6 blocks this.
- IE7 blocks this.
```
**2) Create an iframe pointing to the new file.**
```
- FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?)
- IE6 blocks this.
- IE7 blocks this.
How can I do this so that at least these three browsers will not object?
```
Bonus: is there a method that doesn't require browser-conditional statements?
(I believe that download.com employs both methods conditionally, but I can't get either one to work.)
**Responses and Clarifications:**
```
Q: "Why not point the current window to the file?"
A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?"
```
**UPDATE: I have abandoned this approach. See my answer below for reasons.** | You can also do a meta refresh, which most browsers support. Download.com places one in a noscript tag.
```
<meta http-equiv="refresh" content="5;url=/download.php?doc=123.zip"/>
``` |
60,607 | <p>What are the pros/cons of doing either way. Is there One Right Way(tm) ?</p>
| [
{
"answer_id": 60631,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on the situation. I tend to use Exceptions when I am writing business logic/application internals, and ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What are the pros/cons of doing either way. Is there One Right Way(tm) ? | If you want to use exceptions instead of errors for your entire application, you can do it with [ErrorException](http://php.net/ErrorException) and a custom error handler (see the ErrorException page for a sample error handler). The only downside to this method is that non-fatal errors will still throw exceptions, which are always fatal unless caught. Basically, even an `E_NOTICE` will halt your entire application if your [error\_reporting](http://php.net/error_reporting) settings do not suppress them.
In my opinion, there are several benefits to using ErrorException:
1. A custom exception handler will let you display nice messages, even for errors, using [set\_exception\_handler](http://php.net/set_exception_handler).
2. It does not disrupt existing code in any way... [trigger\_error](http://php.net/trigger_error) and other error functions will still work normally.
3. It makes it really hard to ignore stupid coding mistakes that trigger `E_NOTICE`s and `E_WARNING`s.
4. You can use `try`/`catch` to wrap code that may generate a PHP error (not just exceptions), which is a nice way to avoid using the `@` error suppression hack:
```
try {
$foo = $_GET['foo'];
} catch (ErrorException $e) {
$foo = NULL;
}
```
5. You can wrap your entire script in a single `try`/`catch` block if you want to display a friendly message to your users when any uncaught error happens. (Do this carefully, because only uncaught errors and exceptions are logged.) |
60,645 | <p>Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE_FLAG_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure. </p>
| [
{
"answer_id": 60681,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 4,
"selected": false,
"text": "<p>No. As explained <a href=\"http://msdn.microsoft.com/en-us/library/aa365141%28VS.85%29.aspx\" rel=\"noreferrer\">here</a>, ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3923/"
] | Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE\_FLAG\_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure. | Here is an implementation for an anonymous pipe function with the possibility to specify FILE\_FLAG\_OVERLAPPED:
```
/******************************************************************************\
* This is a part of the Microsoft Source Code Samples.
* Copyright 1995 - 1997 Microsoft Corporation.
* All rights reserved.
* This source code is only intended as a supplement to
* Microsoft Development Tools and/or WinHelp documentation.
* See these sources for detailed information regarding the
* Microsoft samples programs.
\******************************************************************************/
/*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
pipeex.c
Abstract:
CreatePipe-like function that lets one or both handles be overlapped
Author:
Dave Hart Summer 1997
Revision History:
--*/
#include <windows.h>
#include <stdio.h>
static volatile long PipeSerialNumber;
BOOL
APIENTRY
MyCreatePipeEx(
OUT LPHANDLE lpReadPipe,
OUT LPHANDLE lpWritePipe,
IN LPSECURITY_ATTRIBUTES lpPipeAttributes,
IN DWORD nSize,
DWORD dwReadMode,
DWORD dwWriteMode
)
/*++
Routine Description:
The CreatePipeEx API is used to create an anonymous pipe I/O device.
Unlike CreatePipe FILE_FLAG_OVERLAPPED may be specified for one or
both handles.
Two handles to the device are created. One handle is opened for
reading and the other is opened for writing. These handles may be
used in subsequent calls to ReadFile and WriteFile to transmit data
through the pipe.
Arguments:
lpReadPipe - Returns a handle to the read side of the pipe. Data
may be read from the pipe by specifying this handle value in a
subsequent call to ReadFile.
lpWritePipe - Returns a handle to the write side of the pipe. Data
may be written to the pipe by specifying this handle value in a
subsequent call to WriteFile.
lpPipeAttributes - An optional parameter that may be used to specify
the attributes of the new pipe. If the parameter is not
specified, then the pipe is created without a security
descriptor, and the resulting handles are not inherited on
process creation. Otherwise, the optional security attributes
are used on the pipe, and the inherit handles flag effects both
pipe handles.
nSize - Supplies the requested buffer size for the pipe. This is
only a suggestion and is used by the operating system to
calculate an appropriate buffering mechanism. A value of zero
indicates that the system is to choose the default buffering
scheme.
Return Value:
TRUE - The operation was successful.
FALSE/NULL - The operation failed. Extended error status is available
using GetLastError.
--*/
{
HANDLE ReadPipeHandle, WritePipeHandle;
DWORD dwError;
UCHAR PipeNameBuffer[ MAX_PATH ];
//
// Only one valid OpenMode flag - FILE_FLAG_OVERLAPPED
//
if ((dwReadMode | dwWriteMode) & (~FILE_FLAG_OVERLAPPED)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
//
// Set the default timeout to 120 seconds
//
if (nSize == 0) {
nSize = 4096;
}
sprintf( PipeNameBuffer,
"\\\\.\\Pipe\\RemoteExeAnon.%08x.%08x",
GetCurrentProcessId(),
InterlockedIncrement(&PipeSerialNumber)
);
ReadPipeHandle = CreateNamedPipeA(
PipeNameBuffer,
PIPE_ACCESS_INBOUND | dwReadMode,
PIPE_TYPE_BYTE | PIPE_WAIT,
1, // Number of pipes
nSize, // Out buffer size
nSize, // In buffer size
120 * 1000, // Timeout in ms
lpPipeAttributes
);
if (! ReadPipeHandle) {
return FALSE;
}
WritePipeHandle = CreateFileA(
PipeNameBuffer,
GENERIC_WRITE,
0, // No sharing
lpPipeAttributes,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | dwWriteMode,
NULL // Template file
);
if (INVALID_HANDLE_VALUE == WritePipeHandle) {
dwError = GetLastError();
CloseHandle( ReadPipeHandle );
SetLastError(dwError);
return FALSE;
}
*lpReadPipe = ReadPipeHandle;
*lpWritePipe = WritePipeHandle;
return( TRUE );
}
``` |
60,653 | <p>Is global memory initialized in C++? And if so, how?</p>
<p>(Second) clarification:</p>
<p>When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example.</p>
<p>The situation is: can a singleton reference be set - via an <code>instance()</code> call, prior to its initialization:</p>
<pre><code>MySingleton* MySingleton::_instance = NULL;
</code></pre>
<p>and get two singleton instances as a result?</p>
<p>See my C++ quiz on on multiple instances of a singleton...</p>
| [
{
"answer_id": 60655,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": true,
"text": "<p>Yes global primitives are initialized to NULL.</p>\n\n<p>Example:</p>\n\n<pre><code>int x;\n\nint main(int argc, cha... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2167252/"
] | Is global memory initialized in C++? And if so, how?
(Second) clarification:
When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example.
The situation is: can a singleton reference be set - via an `instance()` call, prior to its initialization:
```
MySingleton* MySingleton::_instance = NULL;
```
and get two singleton instances as a result?
See my C++ quiz on on multiple instances of a singleton... | Yes global primitives are initialized to NULL.
Example:
```
int x;
int main(int argc, char**argv)
{
assert(x == 0);
int y;
//assert(y == 0); <-- wrong can't assume this.
}
```
You cannot make any assumptions about classes, structs, arrays, blocks of memory on the heap...
It's safest just to always initialize everything. |
60,664 | <p>is it possible to display ⇓ entity in ie6? It is being display in every browser but not IE 6.I am writing markup such as: </p>
<pre><code><span>&#8659;</span>
</code></pre>
| [
{
"answer_id": 60679,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": true,
"text": "<p>According to <a href=\"https://web.archive.org/web/20080221144246/http://www.ackadia.com:80/web-design/character-code/chara... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | is it possible to display ⇓ entity in ie6? It is being display in every browser but not IE 6.I am writing markup such as:
```
<span>⇓</span>
``` | According to [this page](https://web.archive.org/web/20080221144246/http://www.ackadia.com:80/web-design/character-code/character-code-symbols.php), that symbol doesn't show in IE6 at all.
```
Symbol Character Numeric Description
⇓ ⇓ ⇓ Down double arrow - - * Doesn't show with MS IE6
```
If you really need that particular symbol, you may just have to go for a small graphic of the arrow - not an ideal solution, but if you need it to display in IE6 then that may be your only option. |
60,672 | <p>I want to implement an ISAPI filter like feature using HttpModule in IIS7 running under IIS Integrated Request Processing Pipeline mode.</p>
<p>The goal is to look at the incoming request at the Web Server level, and inject some custom HttpHeaders into the request. <code>(for ex: HTTP\_EAUTH\_ID)</code></p>
<p>And later in the page lifecycle of an ASPX page, i should be able to use that variable as</p>
<pre><code>string eauthId = Request.ServerVariables["HTTP\_EAUTH\_ID"].ToString();
</code></pre>
<p>So implementing this module at the Web Server level, is it possible to alter the ServerVariables collection ?? </p>
| [
{
"answer_id": 60696,
"author": "Joel Martinez",
"author_id": 5416,
"author_profile": "https://Stackoverflow.com/users/5416",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the server variables list only contains the headers sent from the browser to the server.</p>\n"
},
{
... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647/"
] | I want to implement an ISAPI filter like feature using HttpModule in IIS7 running under IIS Integrated Request Processing Pipeline mode.
The goal is to look at the incoming request at the Web Server level, and inject some custom HttpHeaders into the request. `(for ex: HTTP\_EAUTH\_ID)`
And later in the page lifecycle of an ASPX page, i should be able to use that variable as
```
string eauthId = Request.ServerVariables["HTTP\_EAUTH\_ID"].ToString();
```
So implementing this module at the Web Server level, is it possible to alter the ServerVariables collection ?? | [HttpRequest.ServerVariables](http://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables.aspx) Property is a read-only collection. So, you cannot directly modify that. I would suggest storing your custom data in [httpcontext](http://www.odetocode.com/Articles/111.aspx) (or global application object or your database) from your httpmodule and then reading that shared value in the aspx page.
If you still want to modify server variables, there is a hack technique mentioned in this [thread](http://forums.asp.net/t/1125149.aspx) using Reflection. |
60,673 | <p>What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people <em>insist</em> that every <code>if</code> statement is followed by a brace block (<code>{...}</code>).</p>
<p>I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few?</p>
<p>To get the ball rolling, I'll mention a few to start with:</p>
<ul>
<li>Always use braces after every <code>if</code> / <code>else</code> statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break:</li>
</ul>
<pre>
// top of file:
#define statement doSomething(); doSomethingElse
// in implementation:
if (somecondition)
doSomething();
</pre>
<p>but if you use braces then it will work as expected.</p>
<ul>
<li>Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc!</li>
</ul>
<p>Now over to you.</p>
| [
{
"answer_id": 60682,
"author": "DShook",
"author_id": 370,
"author_profile": "https://Stackoverflow.com/users/370",
"pm_score": 0,
"selected": false,
"text": "<p>make sure you indent properly</p>\n"
},
{
"answer_id": 60687,
"author": "MP24",
"author_id": 6206,
"autho... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] | What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people *insist* that every `if` statement is followed by a brace block (`{...}`).
I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few?
To get the ball rolling, I'll mention a few to start with:
* Always use braces after every `if` / `else` statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break:
```
// top of file:
#define statement doSomething(); doSomethingElse
// in implementation:
if (somecondition)
doSomething();
```
but if you use braces then it will work as expected.
* Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc!
Now over to you. | A few of my personal favorites:
Strive to write code that is [const correct](http://www.parashift.com/c++-faq-lite/const-correctness.html). You will enlist the compiler to help weed out easy to fix but sometimes painful bugs. Your code will also tell a story of what you had in mind at the time you wrote it -- valuable for newcomers or maintainers once you're gone.
Get out of the memory management business. Learn to use smart pointers: `std::auto_ptr`, `std::tr1::shared_ptr` (or `boost::shared_ptr`) and `boost::scoped_ptr`. Learn the differences between them and when to use one vs. another.
You're probably going to be using the Standard Template Library. Read the [Josuttis book](https://rads.stackoverflow.com/amzn/click/com/0201379260). Don't just stop after the first few chapters on containers thinking that you know the STL. Push through to the good stuff: algorithms and function objects. |
60,680 | <p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p>
<p>What I'm doing now:</p>
<pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def doGET
[...]
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
server.serve_forever()
</code></pre>
| [
{
"answer_id": 60753,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 6,
"selected": true,
"text": "<p>Sure; just start two different servers on two different ports in two different threads that each use the same handl... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4321/"
] | I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?
What I'm doing now:
```
class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def doGET
[...]
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
server.serve_forever()
``` | Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <http://localhost:1111/> and <http://localhost:2222/>
```
from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write("Hello World!")
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
def serve_on_port(port):
server = ThreadingHTTPServer(("localhost",port), Handler)
server.serve_forever()
Thread(target=serve_on_port, args=[1111]).start()
serve_on_port(2222)
```
*update:*
This also works with Python 3 but three lines need to be slightly changed:
```
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
```
and
```
self.wfile.write(bytes("Hello World!", "utf-8"))
``` |
60,683 | <p>Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated.</p>
<p>I am using visual studio 2005</p>
| [
{
"answer_id": 60695,
"author": "Winter",
"author_id": 6227,
"author_profile": "https://Stackoverflow.com/users/6227",
"pm_score": 4,
"selected": true,
"text": "<p>Allan Anderson created a custom control to let you do this.\nYou can find it here: <a href=\"http://www.codeproject.com/KB/l... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] | Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated.
I am using visual studio 2005 | Allan Anderson created a custom control to let you do this.
You can find it here: <http://www.codeproject.com/KB/list/aa_listview.aspx>
Here's some example code for that control:
```
GlacialList mylist = new GlacialList();
mylist.Columns.Add( "Column1", 100 ); // this can also be added
// through the design time support
mylist.Columns.Add( "Column2", 100 );
mylist.Columns.Add( "Column3", 100 );
mylist.Columns.Add( "Column4", 100 );
GLItem item;
item = this.glacialList1.Items.Add( "Atlanta Braves" );
item.SubItems[1].Text = "8v";
item.SubItems[2].Text = "Live";
item.SubItems[2].BackColor = Color.Bisque;
item.SubItems[3].Text = "MLB.TV";
item = this.glacialList1.Items.Add( "Florida Marlins" );
item.SubItems[1].Text = "";
item.SubItems[2].Text = "Delayed";
item.SubItems[2].BackColor = Color.LightCoral;
item.SubItems[3].Text = "Audio";
item.SubItems[1].BackColor = Color.Aqua; // set the background
// of this particular subitem ONLY
item.UserObject = myownuserobjecttype; // set a private user object
item.Selected = true; // set this item to selected state
item.SubItems[1].Span = 2; // set this sub item to span 2 spaces
ArrayList selectedItems = mylist.SelectedItems;
// get list of selected items
``` |
60,684 | <p><strong><em>Edit:</em></strong> This question had been tagged "Tolstoy" in appreciation of the quality and length of my writing:) Just reading the first and the last paragraph should be enough:) If you tend to select and move code with the mouse, the stuff in middle could be interesting to you.</p>
<p>This question is about how you use text editors in general. I’m looking for the best way to <em>delete</em> a plurality of lines of code (no intent to patent it:) This extends to <em>transposing</em> lines, i.e. deleting and adding them somewhere else. Most importantly, I don’t want to be creating any blank lines that I have to delete separately. Sort of like Visual Studio's SHIFT+DELETE feature, but working for multiple lines at once.</p>
<p>Say you want to delete line 3 from following code (tabs and newlines visualized as well). The naïve way would be to select the text between angle brackets:</p>
<pre>
if (true) {\n
\t int i = 1;\n
\t <i *= 2;>\n
\t i += 3;\n
}\n
</pre>
<p>Then hit backspace. This creates a blank line. Hit backspace twice more to delete \t and \n. </p>
<p>You end up with:</p>
<pre>
if (true) {\n
\t int i = 1;\n
\t i += 3;\n
}\n
</pre>
<p>When you try to select a whole line, Visual Studio doesn't let you select the trailing newline character. For example, placing the cursor on a line and hitting SHIFT+END will not select the newline at the end. Neither will you select the newline if you use your mouse, i.e. clicking in the middle of a line and dragging the cursor all the way to the right. You only select the trailing newline characters if you make a selection that spans at least two lines. Most editors I use do it this way; Microsoft WordPad and Word are counter-examples (and I frequently get newlines wrong when deleting text there; at least Word has a way to display end-of-line and end-of-paragraph characters explicitly).</p>
<p>When using Visual Studio and other editors in general, here’s the solution that currently works best for me:</p>
<p>Using the mouse, I select the characters that I put between angle brackets:</p>
<pre>
if (true) {\n
\t int i = 1;<\n
\t i *= 2;>\n
\t i += 3;\n
}\n
</pre>
<p>Hitting backspace now, you delete the line in one go without having to delete any other characters. This works for several contiguous lines at once. Additionally, it can be used for transposing lines. You could drag the selection between the angle brackets to the point marked with a caret:</p>
<pre>
if (true) {\n
\t int i = 1;<\n
\t i *= 2;>\n
\t i += 3;^\n
}\n
</pre>
<p>This leaves you with:</p>
<pre>
if (true) {\n
\t int i = 1;\n
\t i += 3;<\n
\t i *= 2;>\n
}\n
</pre>
<p>where lines 3 and 4 have switched place.</p>
<p>There are variations on this theme. When you want to delete line 3, you could also select the following characters:</p>
<pre>
if (true) {\n
\t int i = 1;\n
<\t i *= 2;\n
>\t i += 3;\n
}\n
</pre>
<p>In fact, this is what Visual Studio does if you tell it to select a complete line. You do this by clicking in the margin between your code and the column where the red circles go which indicate breakpoints. The mouse pointer is mirrored in that area to distinguish it a little better, but I think it's too narrow and physically too far removed from the code I want to select.</p>
<p>Maybe this method is useful to other people as well, even if it only serves to make them aware of how newlines are handled when selecting/deleting text:) It works nicely for most non-specialized text editors. However, given the vast amount of features and plugins for Visual Studio (which I use most), I'm sure there is better way to use it to delete and move lines of code. Getting the indentation right automatically when moving code between different blocks would be nice (i.e. without hitting "Format Document/Selection"). I'm looking forward to suggestions; no rants on micro-optimization, please:)</p>
<hr>
<p><strong><em>Summary of Answers</em></strong></p>
<p>With respect to Visual Studio: Navigating well with the cursor keys.</p>
<p>The solution that would best suit my style of going over and editing code is the <em>Eclipse</em> way:</p>
<p>You can select several consecutive lines of code, where the first and the last selected line may be selected only partially. Pressing ALT+{up,down} moves the complete lines (not just the selection) up and down, fixing indentation as you go. Hitting CTRL+D deletes the lines completely (not just the selection) without leaving any unwanted blank lines. I would love to see this in Visual Studio!</p>
| [
{
"answer_id": 60697,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>In Emacs:</p>\n\n<ul>\n<li>kill-line C-k </li>\n<li>transpose-lines C-x C-t</li>\n</ul>\n\n<p>C-a C-k C-k -- kill whole line i... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6103/"
] | ***Edit:*** This question had been tagged "Tolstoy" in appreciation of the quality and length of my writing:) Just reading the first and the last paragraph should be enough:) If you tend to select and move code with the mouse, the stuff in middle could be interesting to you.
This question is about how you use text editors in general. I’m looking for the best way to *delete* a plurality of lines of code (no intent to patent it:) This extends to *transposing* lines, i.e. deleting and adding them somewhere else. Most importantly, I don’t want to be creating any blank lines that I have to delete separately. Sort of like Visual Studio's SHIFT+DELETE feature, but working for multiple lines at once.
Say you want to delete line 3 from following code (tabs and newlines visualized as well). The naïve way would be to select the text between angle brackets:
```
if (true) {\n
\t int i = 1;\n
\t <i *= 2;>\n
\t i += 3;\n
}\n
```
Then hit backspace. This creates a blank line. Hit backspace twice more to delete \t and \n.
You end up with:
```
if (true) {\n
\t int i = 1;\n
\t i += 3;\n
}\n
```
When you try to select a whole line, Visual Studio doesn't let you select the trailing newline character. For example, placing the cursor on a line and hitting SHIFT+END will not select the newline at the end. Neither will you select the newline if you use your mouse, i.e. clicking in the middle of a line and dragging the cursor all the way to the right. You only select the trailing newline characters if you make a selection that spans at least two lines. Most editors I use do it this way; Microsoft WordPad and Word are counter-examples (and I frequently get newlines wrong when deleting text there; at least Word has a way to display end-of-line and end-of-paragraph characters explicitly).
When using Visual Studio and other editors in general, here’s the solution that currently works best for me:
Using the mouse, I select the characters that I put between angle brackets:
```
if (true) {\n
\t int i = 1;<\n
\t i *= 2;>\n
\t i += 3;\n
}\n
```
Hitting backspace now, you delete the line in one go without having to delete any other characters. This works for several contiguous lines at once. Additionally, it can be used for transposing lines. You could drag the selection between the angle brackets to the point marked with a caret:
```
if (true) {\n
\t int i = 1;<\n
\t i *= 2;>\n
\t i += 3;^\n
}\n
```
This leaves you with:
```
if (true) {\n
\t int i = 1;\n
\t i += 3;<\n
\t i *= 2;>\n
}\n
```
where lines 3 and 4 have switched place.
There are variations on this theme. When you want to delete line 3, you could also select the following characters:
```
if (true) {\n
\t int i = 1;\n
<\t i *= 2;\n
>\t i += 3;\n
}\n
```
In fact, this is what Visual Studio does if you tell it to select a complete line. You do this by clicking in the margin between your code and the column where the red circles go which indicate breakpoints. The mouse pointer is mirrored in that area to distinguish it a little better, but I think it's too narrow and physically too far removed from the code I want to select.
Maybe this method is useful to other people as well, even if it only serves to make them aware of how newlines are handled when selecting/deleting text:) It works nicely for most non-specialized text editors. However, given the vast amount of features and plugins for Visual Studio (which I use most), I'm sure there is better way to use it to delete and move lines of code. Getting the indentation right automatically when moving code between different blocks would be nice (i.e. without hitting "Format Document/Selection"). I'm looking forward to suggestions; no rants on micro-optimization, please:)
---
***Summary of Answers***
With respect to Visual Studio: Navigating well with the cursor keys.
The solution that would best suit my style of going over and editing code is the *Eclipse* way:
You can select several consecutive lines of code, where the first and the last selected line may be selected only partially. Pressing ALT+{up,down} moves the complete lines (not just the selection) up and down, fixing indentation as you go. Hitting CTRL+D deletes the lines completely (not just the selection) without leaving any unwanted blank lines. I would love to see this in Visual Studio! | In Emacs:
* kill-line C-k
* transpose-lines C-x C-t
C-a C-k C-k -- kill whole line including newline (or `kill-whole-line` by C-S-backspace).
C-u <number> C-k -- kill <number> of lines (including newlines).
C-y -- yank back the most recently killed text (aka paste) |
60,685 | <p>What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.</p>
<p>Here's the regex:</p>
<pre><code>\s*#define(.*\\\n)+[\S]+(?!\\)
</code></pre>
<p>It should match all of this:</p>
<pre><code>#define foo(x) if(x) \
doSomething(x)
</code></pre>
<p>But only some of this (shouldn't match the next line of code:</p>
<pre><code>#define foo(x) if(x) \
doSomething(x)
normalCode();
</code></pre>
<p>And also shouldn't match single-line preprocessor macros.</p>
<p>I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. Can anyone suggest any?</p>
| [
{
"answer_id": 60723,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": true,
"text": "<p>This is a simple test program I knocked up:</p>\n\n<pre><code>#!/usr/bin/env python\n\nTEST1=\"\"\"\n#include \"Foo.... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] | What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.
Here's the regex:
```
\s*#define(.*\\\n)+[\S]+(?!\\)
```
It should match all of this:
```
#define foo(x) if(x) \
doSomething(x)
```
But only some of this (shouldn't match the next line of code:
```
#define foo(x) if(x) \
doSomething(x)
normalCode();
```
And also shouldn't match single-line preprocessor macros.
I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. Can anyone suggest any? | This is a simple test program I knocked up:
```
#!/usr/bin/env python
TEST1="""
#include "Foo.h"
#define bar foo\\
x
#include "Bar.h"
"""
TEST2="""
#define bar foo
#define x 1 \\
12 \\
2 \\\\ 3
Foobar
"""
TEST3="""
#define foo(x) if(x) \\
doSomething(x)
"""
TEST4="""
#define foo(x) if(x) \\
doSomething(x)
normalCode();
"""
import re
matcher = re.compile(r"^[ \t]*#define(.*\\\n)+.*$",re.MULTILINE)
def extractDefines(s):
mo = matcher.search(s)
if not mo:
print mo
return
print mo.group(0)
extractDefines(TEST1)
extractDefines(TEST2)
extractDefines(TEST3)
extractDefines(TEST4)
```
The re I used:
```
r"^[ \t]*#define(.*\\\n)+.*$"
```
Is very similar to the one use used, the changes:
1. [ \t] To avoid newlines at the start
of the define.
2. I rely on + being
greedy, so I can use a simple .\*$ at
the end to get the first line of the
define that doesn't end with \ |
60,736 | <p>I have a laptop running Ubuntu that I would like to act as a Subversion server. Both for myself to commit to locally, and for others remotely. What are the steps required to get this working? Please include steps to:</p>
<ul>
<li>Get and configure Apache, and necessary modules (I know there are other ways to create a SVN server, but I would like it Apache-specific)</li>
<li>Configure a secure way of accessing the server (SSH/HTTPS)</li>
<li>Configure a set of authorised users (as in, they must authorised to commit, but are free to browse)</li>
<li>Validate the setup with an initial commit (a "Hello world" of sorts)</li>
</ul>
<p>These steps can involve any mixture of command line or GUI application instructions. If you can, please note where instructions are specific to a particular distribution or version, and where a users' choice of a particular tool can be used instead (say, <a href="https://en.wikipedia.org/wiki/GNU_nano" rel="noreferrer">nano</a> instead of <a href="http://en.wikipedia.org/wiki/Vi" rel="noreferrer">vi</a>).</p>
| [
{
"answer_id": 60741,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": -1,
"selected": false,
"text": "<p>For Apache:</p>\n\n<pre><code>sudo apt-get -yq install apache2\n</code></pre>\n\n<p>For SSH:</p>\n\n<pre><code>sudo apt-g... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4120/"
] | I have a laptop running Ubuntu that I would like to act as a Subversion server. Both for myself to commit to locally, and for others remotely. What are the steps required to get this working? Please include steps to:
* Get and configure Apache, and necessary modules (I know there are other ways to create a SVN server, but I would like it Apache-specific)
* Configure a secure way of accessing the server (SSH/HTTPS)
* Configure a set of authorised users (as in, they must authorised to commit, but are free to browse)
* Validate the setup with an initial commit (a "Hello world" of sorts)
These steps can involve any mixture of command line or GUI application instructions. If you can, please note where instructions are specific to a particular distribution or version, and where a users' choice of a particular tool can be used instead (say, [nano](https://en.wikipedia.org/wiki/GNU_nano) instead of [vi](http://en.wikipedia.org/wiki/Vi)). | Steps I've taken to make my laptop a Subversion server. Credit must go to [AlephZarro](http://alephzarro.com/blog/) for his directions [here](http://alephzarro.com/blog/2007/01/07/installation-of-subversion-on-ubuntu-with-apache-ssl-and-basicauth/). I now have a working SVN server (which has currently only been tested locally).
Specific setup:
Kubuntu 8.04 Hardy Heron
Requirements to follow this guide:
* apt-get package manager program
* text editor (I use kate)
* sudo access rights
1: Install Apache HTTP server and required modules:
```
sudo apt-get install libapache2-svn apache2
```
The following extra packages will be installed:
```
apache2-mpm-worker apache2-utils apache2.2-common
```
2: Enable SSL
```
sudo a2enmod ssl
sudo kate /etc/apache2/ports.conf
```
Add or check that the following is in the file:
```
<IfModule mod_ssl.c>
Listen 443
</IfModule>
```
3: Generate an SSL certificate:
```
sudo apt-get install ssl-cert
sudo mkdir /etc/apache2/ssl
sudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/apache.pem
```
4: Create virtual host
```
sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/svnserver
sudo kate /etc/apache2/sites-available/svnserver
```
Change (in ports.conf):
```
"NameVirtualHost *" to "NameVirtualHost *:443"
```
and (in svnserver)
```
<VirtualHost *> to <VirtualHost *:443>
```
Add, under ServerAdmin (also in file svnserver):
```
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.pem
SSLProtocol all
SSLCipherSuite HIGH:MEDIUM
```
5: Enable the site:
```
sudo a2ensite svnserver
sudo /etc/init.d/apache2 restart
```
To overcome warnings:
```
sudo kate /etc/apache2/apache2.conf
```
Add:
```
"ServerName $your_server_name"
```
6: Adding repository(ies):
The following setup assumes we want to host multiple repositories.
Run this for creating the first repository:
```
sudo mkdir /var/svn
REPOS=myFirstRepo
sudo svnadmin create /var/svn/$REPOS
sudo chown -R www-data:www-data /var/svn/$REPOS
sudo chmod -R g+ws /var/svn/$REPOS
```
6.a. For more repositories: do step 6 again (changing the value of REPOS), skipping the step `mkdir /var/svn`
7: Add an authenticated user
```
sudo htpasswd -c -m /etc/apache2/dav_svn.passwd $user_name
```
8: Enable and configure WebDAV and SVN:
```
sudo kate /etc/apache2/mods-available/dav_svn.conf
```
Add or uncomment:
```
<Location /svn>
DAV svn
# for multiple repositories - see comments in file
SVNParentPath /var/svn
AuthType Basic
AuthName "Subversion Repository"
AuthUserFile /etc/apache2/dav_svn.passwd
Require valid-user
SSLRequireSSL
</Location>
```
9: Restart apache server:
```
sudo /etc/init.d/apache2 restart
```
10: Validation:
Fired up a browser:
```
http://localhost/svn/$REPOS
https://localhost/svn/$REPOS
```
Both required a username and password. I think uncommenting:
```
<LimitExcept GET PROPFIND OPTIONS REPORT>
</LimitExcept>
```
in `/etc/apache2/mods-available/dav_svn.conf`, would allow anonymous browsing.
The browser shows "Revision 0: /"
Commit something:
```
svn import --username $user_name anyfile.txt https://localhost/svn/$REPOS/anyfile.txt -m “Testing”
```
Accept the certificate and enter password.
Check out what you've just committed:
```
svn co --username $user_name https://localhost/svn/$REPOS
```
Following these steps (assuming I haven't made any error copy/pasting), I had a working SVN repository on my laptop. |
60,751 | <p>Currently my app uses just Direct3D9 for graphics, however in the future I' m planning to extend this to D3D10 and possibly OpenGL. The question is how can I do this in a tidy way?</p>
<p>At present there are various Render methods in my code</p>
<pre><code>void Render(boost::function<void()> &Call)
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
</code></pre>
<p>The function passed then depends on the exact state, eg MainMenu->Render, Loading->Render, etc. These will then oftern call the methods of other objects.</p>
<pre><code>void RenderGame()
{
for(entity::iterator it = entity::instances.begin();it != entity::instance.end(); ++it)
(*it)->Render();
UI->Render();
}
</code></pre>
<p>And a sample class derived from entity::Base</p>
<pre><code>class Sprite: public Base
{
IDirect3DTexture9 *Tex;
Point2 Pos;
Size2 Size;
public:
Sprite(IDirect3DTexture9 *Tex, const Point2 &Pos, const Size2 &Size);
virtual void Render();
};
</code></pre>
<p>Each method then takes care of how best to render given the more detailed settings (eg are pixel shaders supported or not).</p>
<p>The problem is I'm really not sure how to extend this to be able to use one of, what may be somewhat different (D3D v OpenGL) render modes...</p>
| [
{
"answer_id": 60790,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 4,
"selected": true,
"text": "<p>Define an interface that is sufficient for your application's graphic output demands. Then implement this interface for every ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] | Currently my app uses just Direct3D9 for graphics, however in the future I' m planning to extend this to D3D10 and possibly OpenGL. The question is how can I do this in a tidy way?
At present there are various Render methods in my code
```
void Render(boost::function<void()> &Call)
{
D3dDevice->BeginScene();
Call();
D3dDevice->EndScene();
D3dDevice->Present(0,0,0,0);
}
```
The function passed then depends on the exact state, eg MainMenu->Render, Loading->Render, etc. These will then oftern call the methods of other objects.
```
void RenderGame()
{
for(entity::iterator it = entity::instances.begin();it != entity::instance.end(); ++it)
(*it)->Render();
UI->Render();
}
```
And a sample class derived from entity::Base
```
class Sprite: public Base
{
IDirect3DTexture9 *Tex;
Point2 Pos;
Size2 Size;
public:
Sprite(IDirect3DTexture9 *Tex, const Point2 &Pos, const Size2 &Size);
virtual void Render();
};
```
Each method then takes care of how best to render given the more detailed settings (eg are pixel shaders supported or not).
The problem is I'm really not sure how to extend this to be able to use one of, what may be somewhat different (D3D v OpenGL) render modes... | Define an interface that is sufficient for your application's graphic output demands. Then implement this interface for every renderer you want to support.
```
class IRenderer {
public:
virtual ~IRenderer() {}
virtual void RenderModel(CModel* model) = 0;
virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) = 0;
// ...etc...
};
class COpenGLRenderer : public IRenderer {
public:
virtual void RenderModel(CModel* model) {
// render model using OpenGL
}
virtual void DrawScreenQuad(int x1, int y1, int x2, int y2) {
// draw screen aligned quad using OpenGL
}
};
class CDirect3DRenderer : public IRenderer {
// similar, but render using Direct3D
};
```
Properly designing and maintaining these interfaces can be very challenging though.
In case you also operate with render driver dependent objects like textures, you can use a factory pattern to have the separate renderers each create their own implementation of e.g. ITexture using a factory method in IRenderer:
```
class IRenderer {
//...
virtual ITexture* CreateTexture(const char* filename) = 0;
//...
};
class COpenGLRenderer : public IRenderer {
//...
virtual ITexture* CreateTexture(const char* filename) {
// COpenGLTexture is the OpenGL specific ITexture implementation
return new COpenGLTexture(filename);
}
//...
};
```
Isn't it an idea to look at existing (3d) engines though? In my experience designing this kind of interfaces really distracts from what you actually want to make :) |
60,764 | <p>Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own <code>ClassLoader</code>, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.</p>
<p>Any suggestions for simple code that does this?</p>
| [
{
"answer_id": 60766,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 7,
"selected": false,
"text": "<p>The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly:</p>\n\n<... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] | Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own `ClassLoader`, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.
Any suggestions for simple code that does this? | The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader:
```
URLClassLoader child = new URLClassLoader(
new URL[] {myJar.toURI().toURL()},
this.getClass().getClassLoader()
);
Class classToLoad = Class.forName("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod("myMethod");
Object instance = classToLoad.newInstance();
Object result = method.invoke(instance);
```
Painful, but there it is. |
60,768 | <p>I am trying to dynamicaly compile code using CodeDom. I can load other assemblies, but I cannot load System.Data.Linq.dll. I get an error:</p>
<p>Metadata file 'System.Data.Linq.dll' could not be found</p>
<p>My code looks like:</p>
<pre><code>CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library /optimize";
compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Data.Linq.dll");
</code></pre>
<p>Any ideas? </p>
| [
{
"answer_id": 60781,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 3,
"selected": true,
"text": "<p>That may be because this assembly is stored in a different location than mscorlib is. It should work if you provide... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5189/"
] | I am trying to dynamicaly compile code using CodeDom. I can load other assemblies, but I cannot load System.Data.Linq.dll. I get an error:
Metadata file 'System.Data.Linq.dll' could not be found
My code looks like:
```
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library /optimize";
compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Data.Linq.dll");
```
Any ideas? | That may be because this assembly is stored in a different location than mscorlib is. It should work if you provide a full path to the assembly. The most convenient way to get the full path is to let the .NET loader do the work for you. I would try something like this:
```
compilerParams.ReferencedAssemblies.Add(typeof(DataContext).Assembly.Location);
``` |
60,779 | <p>Trying to do this sort of thing...</p>
<pre><code>WHERE username LIKE '%$str%'
</code></pre>
<p>...but using bound parameters to prepared statements in PDO. e.g.:</p>
<pre><code>$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
</code></pre>
<p>I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.</p>
<p>I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?</p>
| [
{
"answer_id": 60782,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 5,
"selected": true,
"text": "<p>Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evalu... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | Trying to do this sort of thing...
```
WHERE username LIKE '%$str%'
```
...but using bound parameters to prepared statements in PDO. e.g.:
```
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
```
I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.
I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters? | Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:
```
$str = "%$str%";
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
``` |
60,785 | <p>How can I show a grey transparent overlay in C#?<br>
It should overlay other process which are not owned by the application doing the overlay.</p>
| [
{
"answer_id": 60782,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 5,
"selected": true,
"text": "<p>Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evalu... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44972/"
] | How can I show a grey transparent overlay in C#?
It should overlay other process which are not owned by the application doing the overlay. | Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:
```
$str = "%$str%";
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
``` |
60,802 | <p>I'm having trouble ordering by more than one field in my Linq to NHibernate query. Does anyone either know what might be wrong or if there is a work around?</p>
<p>Code:</p>
<pre><code>IQueryable<AgendaItem> items = _agendaRepository.GetAgendaItems(location)
.Where(item => item.Minutes.Contains(query) || item.Description.Contains(query));
int total = items.Count();
var results = items
.OrderBy(item => item.Agenda.Date)
.ThenBy(item => item.OutcomeType)
.ThenBy(item => item.OutcomeNumber)
.Skip((page - 1)*pageSize)
.Take(pageSize)
.ToArray();
return new SearchResult(query, total, results);
</code></pre>
<p>I've tried replacing ThenBy with multiple OrderBy calls. Same result. The method works great if I comment out the two ThenBy calls.</p>
<p>Error I'm receiving:</p>
<pre>
[SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.
Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
[ADOException: could not execute query
[ SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc ]
Positional parameters: #0>1 #0>%Core% #0>%Core%
[SQL: SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc]]
NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +258
NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18
NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +87
NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) +342
NHibernate.Impl.CriteriaImpl.List(IList results) +41
NHibernate.Impl.CriteriaImpl.List() +35
NHibernate.Linq.CriteriaResultReader`1.List() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:22
NHibernate.Linq.d__0.MoveNext() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:27
</pre>
| [
{
"answer_id": 61081,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<p>although i dont think it'd make a difference, what happens if you do your linq like this:</p>\n\n<p>(from i in items or... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595/"
] | I'm having trouble ordering by more than one field in my Linq to NHibernate query. Does anyone either know what might be wrong or if there is a work around?
Code:
```
IQueryable<AgendaItem> items = _agendaRepository.GetAgendaItems(location)
.Where(item => item.Minutes.Contains(query) || item.Description.Contains(query));
int total = items.Count();
var results = items
.OrderBy(item => item.Agenda.Date)
.ThenBy(item => item.OutcomeType)
.ThenBy(item => item.OutcomeNumber)
.Skip((page - 1)*pageSize)
.Take(pageSize)
.ToArray();
return new SearchResult(query, total, results);
```
I've tried replacing ThenBy with multiple OrderBy calls. Same result. The method works great if I comment out the two ThenBy calls.
Error I'm receiving:
```
[SqlException (0x80131904): Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.
Invalid column name '__hibernate_sort_expr_0____hibernate_sort_expr_1__'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1948826
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4844747
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
[ADOException: could not execute query
[ SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc ]
Positional parameters: #0>1 #0>%Core% #0>%Core%
[SQL: SELECT this_.Id as Id5_2_, this_.AgendaId as AgendaId5_2_, this_.Description as Descript3_5_2_, this_.OutcomeType as OutcomeT4_5_2_, this_.OutcomeNumber as OutcomeN5_5_2_, this_.Minutes as Minutes5_2_, agenda1_.Id as Id2_0_, agenda1_.LocationId as LocationId2_0_, agenda1_.Date as Date2_0_, location2_.Id as Id7_1_, location2_.Name as Name7_1_ FROM AgendaItem this_ left outer join Agenda agenda1_ on this_.AgendaId=agenda1_.Id left outer join Location location2_ on agenda1_.LocationId=location2_.Id WHERE location2_.Id = ? and (this_.Minutes like ? or this_.Description like ?) ORDER BY agenda1_.Date asc, this_.OutcomeType asc, this_.OutcomeNumber asc]]
NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +258
NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18
NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +87
NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) +342
NHibernate.Impl.CriteriaImpl.List(IList results) +41
NHibernate.Impl.CriteriaImpl.List() +35
NHibernate.Linq.CriteriaResultReader`1.List() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:22
NHibernate.Linq.d__0.MoveNext() in C:\home\dev\tools\NHibernate\NHibernateContribSrc\src\NHibernate.Linq\src\NHibernate.Linq\CriteriaResultReader.cs:27
``` | This looks to me like a bug with Linq to NHybernate. One possible workaround is to convert to an array before sorting. A potentially big downside is that you can't limit the results using Skip() and Take() before enumerating, so this may not be sufficient for you.
```
var results = items
.ToArray()
.OrderBy(item => item.Agenda.Date)
.ThenBy(item => item.OutcomeType)
.ThenBy(item => item.OutcomeNumber)
.Skip((page - 1)*pageSize)
.Take(pageSize)
``` |
60,805 | <p>How do I select one or more random rows from a table using SQLAlchemy? </p>
| [
{
"answer_id": 60811,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": -1,
"selected": false,
"text": "<p>Theres a couple of ways through SQL, depending on which data base is being used.</p>\n\n<p>(I think SQLAlchemy can us... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | How do I select one or more random rows from a table using SQLAlchemy? | This is very much a database-specific issue.
I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy:
```
from sqlalchemy.sql.expression import func, select
select.order_by(func.random()) # for PostgreSQL, SQLite
select.order_by(func.rand()) # for MySQL
select.order_by('dbms_random.value') # For Oracle
```
Next, you need to limit the query by the number of records you need (for example using `.limit()`).
Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; [here](http://www.depesz.com/index.php/2007/09/16/my-thoughts-on-getting-random-row/) is good article about it. |
60,820 | <p>Does anyone know of a way to find out how much memory an instance of an object is taking?</p>
<p>For example, if I have an instance of the following object:</p>
<pre><code>TestClass tc = new TestClass();
</code></pre>
<p>Is there a way to find out how much memory the instance <code>tc</code> is taking?</p>
<p>The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something).</p>
<p>There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools. </p>
| [
{
"answer_id": 60829,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 2,
"selected": false,
"text": "<p>I have good experiences with <a href=\"http://memprofiler.com/\" rel=\"nofollow noreferrer\">MemProfiler</a>. It giv... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6301/"
] | Does anyone know of a way to find out how much memory an instance of an object is taking?
For example, if I have an instance of the following object:
```
TestClass tc = new TestClass();
```
Is there a way to find out how much memory the instance `tc` is taking?
The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something).
There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools. | If you are not trying to do it in code itself, which I'm assuming based on your ANTS reference, try taking a look at CLRProfiler (currently v2.0). It's free and if you don't mind the rather simplistic UI, it can provide valuable information. It will give you a in-depth overview of all kinds of stats. I used it a while back as one tool for finding a memory leek.
Download here: <https://github.com/MicrosoftArchive/clrprofiler>
If you do want to do it in code, the CLR has profiling APIs you could use. If you find the information in CLRProfiler, since it uses those APIs, you should be able to do it in code too. More info here:
<http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx>
(It's not as cryptic as using WinDbg, but be prepared to do mighty deep into the CLR.) |
60,825 | <p>I am working on a web application, where I transfer data from the server to the browser in XML.</p>
<p>Since I'm danish, I quickly run into problems with the characters <code>æøå</code>.</p>
<p>I know that in html, I use the <code>"&amp;aelig;&amp;oslash;&amp;aring;"</code> for <code>æøå</code>.</p>
<p>however, as soon as the chars pass through JavaScript, I get black boxes with <code>"?"</code> in them when using <code>æøå</code>, and <code>"&aelig;&oslash;&aring;"</code> is printed as is.</p>
<p>I've made sure to set it to utf-8, but that isn't helping much.</p>
<p>Ideally, I want it to work with any special characters (naturally).</p>
<p>The example that isn't working is included below:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" charset="utf-8">
alert("&aelig;&oslash;&aring;");
alert("æøå");
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p>What am I doing wrong?</p>
<hr>
<p>Ok, thanks to Grapefrukts answer, I got it working.</p>
<p>I actually needed it for data coming from an MySQL server. Since the saving of the files in UTF-8 encoding only solves the problem for static content, I figure I'd include the solution for strings from a MySQL server, pulled out using PHP:</p>
<p><code>utf8_encode($MyStringHere)</code></p>
| [
{
"answer_id": 60832,
"author": "chryss",
"author_id": 5169,
"author_profile": "https://Stackoverflow.com/users/5169",
"pm_score": 0,
"selected": false,
"text": "<p>This works as expected for me:</p>\n\n<pre><code>alert(\"&aelig;&oslash;&aring;\");\n</code></pre>\n\n<p>... cr... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
] | I am working on a web application, where I transfer data from the server to the browser in XML.
Since I'm danish, I quickly run into problems with the characters `æøå`.
I know that in html, I use the `"&aelig;&oslash;&aring;"` for `æøå`.
however, as soon as the chars pass through JavaScript, I get black boxes with `"?"` in them when using `æøå`, and `"æøå"` is printed as is.
I've made sure to set it to utf-8, but that isn't helping much.
Ideally, I want it to work with any special characters (naturally).
The example that isn't working is included below:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" charset="utf-8">
alert("æøå");
alert("æøå");
</script>
</head>
<body>
</body>
</html>
```
What am I doing wrong?
---
Ok, thanks to Grapefrukts answer, I got it working.
I actually needed it for data coming from an MySQL server. Since the saving of the files in UTF-8 encoding only solves the problem for static content, I figure I'd include the solution for strings from a MySQL server, pulled out using PHP:
`utf8_encode($MyStringHere)` | Just specifying UTF-8 in the header is not enough. I'd bet you haven't saved your file as UTF-8. Any reasonably advanced text editor will have this option. Try that and I'm sure it'll work! |
60,874 | <p>I know a few advanced ways, to change directories. <code>pushd</code> and <code>popd</code> (directory stack) or <code>cd -</code> (change to last directory).</p>
<p>But I am looking for quick way to achieve the following:</p>
<p>Say, I am in a rather deep dir:</p>
<pre><code>/this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names
</code></pre>
<p>and I want to switch to </p>
<pre><code>/this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names
</code></pre>
<p>Is there a cool/quick/geeky way to do it (without the mouse)?</p>
| [
{
"answer_id": 60887,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "<p>Do you mean that the path names are the same, and only one directory name changes (\"a\" becomes \"another\")? In that case:</p... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] | I know a few advanced ways, to change directories. `pushd` and `popd` (directory stack) or `cd -` (change to last directory).
But I am looking for quick way to achieve the following:
Say, I am in a rather deep dir:
```
/this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names
```
and I want to switch to
```
/this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names
```
Is there a cool/quick/geeky way to do it (without the mouse)? | Do you mean that the path names are the same, and only one directory name changes ("a" becomes "another")? In that case:
```
cd ${PWD/a/another}
```
will switch to the other directory. `$PWD` holds your current directory, and `${var/foo/bar}` gives you `$var` with the string 'foo' replaced by 'bar'. |
60,877 | <p>I have a query where I wish to retrieve the oldest X records. At present my query is something like the following:</p>
<pre><code>SELECT Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate DESC
</code></pre>
<p>I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first.</p>
<p>So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first. I should also add that my database exists on SQL Server 2005.</p>
| [
{
"answer_id": 60882,
"author": "Jason Punyon",
"author_id": 6212,
"author_profile": "https://Stackoverflow.com/users/6212",
"pm_score": 6,
"selected": true,
"text": "<p>Why not just use a subquery?</p>\n\n<pre><code>SELECT T1.* \nFROM\n(SELECT TOP X Id, Title, Comments, CreatedDate\nFRO... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5086/"
] | I have a query where I wish to retrieve the oldest X records. At present my query is something like the following:
```
SELECT Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate DESC
```
I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first.
So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first. I should also add that my database exists on SQL Server 2005. | Why not just use a subquery?
```
SELECT T1.*
FROM
(SELECT TOP X Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate) T1
ORDER BY CreatedDate DESC
``` |
60,893 | <p>In my application I have <code>TextBox</code> in a <code>FormView</code> bound to a <code>LinqDataSource</code> like so:</p>
<pre><code><asp:TextBox ID="MyTextBox" runat="server"
Text='<%# Bind("MyValue") %>' AutoPostBack="True"
ontextchanged="MyTextBox_TextChanged" />
protected void MyTextBox_TextChanged(object sender, EventArgs e)
{
MyFormView.UpdateItem(false);
}
</code></pre>
<p>This is inside an <code>UpdatePanel</code> so any change to the field is immediately persisted. Also, the value of <code>MyValue</code> is <code>decimal?</code>. This works fine unless I enter any string which cannot be converted to decimal into the field. In that case, the <code>UpdateItem</code> call throws: </p>
<blockquote>
<p><strong>LinqDataSourceValidationException</strong> -
Failed to set one or more properties on type MyType. asdf is not a valid value for Decimal.</p>
</blockquote>
<p>I understand the problem, ASP.NET does not know how to convert from 'asdf' to decimal?. What I would like it to do is convert all these invalid values to null. What is the best way to do this?</p>
| [
{
"answer_id": 60902,
"author": "maccullt",
"author_id": 4945,
"author_profile": "https://Stackoverflow.com/users/4945",
"pm_score": 1,
"selected": false,
"text": "<p>I find Robert Martin's <a href=\"http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd\" rel=\"nofollow noreferrer\... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | In my application I have `TextBox` in a `FormView` bound to a `LinqDataSource` like so:
```
<asp:TextBox ID="MyTextBox" runat="server"
Text='<%# Bind("MyValue") %>' AutoPostBack="True"
ontextchanged="MyTextBox_TextChanged" />
protected void MyTextBox_TextChanged(object sender, EventArgs e)
{
MyFormView.UpdateItem(false);
}
```
This is inside an `UpdatePanel` so any change to the field is immediately persisted. Also, the value of `MyValue` is `decimal?`. This works fine unless I enter any string which cannot be converted to decimal into the field. In that case, the `UpdateItem` call throws:
>
> **LinqDataSourceValidationException** -
> Failed to set one or more properties on type MyType. asdf is not a valid value for Decimal.
>
>
>
I understand the problem, ASP.NET does not know how to convert from 'asdf' to decimal?. What I would like it to do is convert all these invalid values to null. What is the best way to do this? | There was an interesting discussion of Technical Debt based on your definition of done on HanselMinutes a couple of weeks ago -- [What is Done](http://www.hanselminutes.com/default.aspx?showID=137). The basics of the show were that if you re-define 'Done' to increase perceived velocity, then you will amass Technical Debt. The corollary of this is that if you do not have a proper definition of 'Done' then you most likely are acquiring a list of items that will need to be finished before release irrespective of the design methodology. |
60,910 | <p>I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change. </p>
| [
{
"answer_id": 60940,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": false,
"text": "<p>From the <a href=\"http://www.emacswiki.org/cgi-bin/wiki/AquamacsFAQ#toc7\" rel=\"noreferrer\">EmacsWiki Aquamacs FAQ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change. | This is what I have in my .emacs for OS X:
```
(set-default-font "-apple-bitstream vera sans mono-medium-r-normal--0-0-0-0-m-0-mac-roman")
```
Now, I'm not sure Bitstream Vera comes standard on OS X, so you may have to either download it or choose a different font. You can search the X font names by running `(x-list-fonts "searchterm")` in an ELisp buffer (e.g. `*scratch*` - to run it, type it in and then type `C-j` on the same line). |
60,919 | <p>Can I use this approach efficiently?</p>
<pre><code>using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString))
{
cmd.Connection.Open();
// set up parameters and CommandType to StoredProcedure etc. etc.
cmd.ExecuteNonQuery();
}
</code></pre>
<p>My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?</p>
| [
{
"answer_id": 60934,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 8,
"selected": true,
"text": "<p>No, Disposing of the <code>SqlCommand</code> will not effect the Connection. A better approach would be to also wrap th... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796/"
] | Can I use this approach efficiently?
```
using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString))
{
cmd.Connection.Open();
// set up parameters and CommandType to StoredProcedure etc. etc.
cmd.ExecuteNonQuery();
}
```
My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not? | No, Disposing of the `SqlCommand` will not effect the Connection. A better approach would be to also wrap the `SqlConnection` in a using block as well:
```
using (SqlConnection conn = new SqlConnection(connstring))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(cmdstring, conn))
{
cmd.ExecuteNonQuery();
}
}
```
Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should
be disposed of as well, and likely more important to dispose of than a command.
**EDIT:**
I just tested this:
```
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn))
{
Console.WriteLine(cmd.ExecuteScalar().ToString());
}
using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn))
{
Console.WriteLine(cmd.ExecuteScalar().ToString());
}
conn.Dispose();
```
The first command was disposed when the using block was exited. The connection was still open and good for the second command.
***So, disposing of the command definitely does not dispose of the connection it was using.*** |
60,942 | <p>I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3:</p>
<pre><code> proc2 -> stdout
/
proc1
\
proc3 -> stdout
</code></pre>
<p>I tried</p>
<pre><code> proc1 | (proc2 & proc3)
</code></pre>
<p>but it doesn't seem to work, i.e.</p>
<pre><code> echo 123 | (tr 1 a & tr 1 b)
</code></pre>
<p>writes</p>
<pre><code> b23
</code></pre>
<p>to stdout instead of </p>
<pre><code> a23
b23
</code></pre>
| [
{
"answer_id": 60955,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 8,
"selected": true,
"text": "<p><sup><em>Editor's note</em>:<br>\n - <code>>(…)</code> is a <a href=\"http://mywiki.wooledge.org/ProcessSubstitution\" rel=\... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4085/"
] | I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3:
```
proc2 -> stdout
/
proc1
\
proc3 -> stdout
```
I tried
```
proc1 | (proc2 & proc3)
```
but it doesn't seem to work, i.e.
```
echo 123 | (tr 1 a & tr 1 b)
```
writes
```
b23
```
to stdout instead of
```
a23
b23
``` | *Editor's note*:
- `>(…)` is a [*process substitution*](http://mywiki.wooledge.org/ProcessSubstitution) that is a *nonstandard shell feature* of *some* POSIX-compatible shells: `bash`, `ksh`, `zsh`.
- This answer accidentally sends the output process substitution's output through the pipeline *too*: `echo 123 | tee >(tr 1 a) | tr 1 b`.
- Output from the process substitutions will be unpredictably interleaved, and, except in `zsh`, the pipeline may terminate before the commands inside `>(…)` do.
In unix (or on a mac), use the [`tee` command](http://en.wikipedia.org/wiki/Tee_(command)):
```
$ echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null
b23
a23
```
Usually you would use `tee` to redirect output to multiple files, but using >(...) you can
redirect to another process. So, in general,
```
$ proc1 | tee >(proc2) ... >(procN-1) >(procN) >/dev/null
```
will do what you want.
Under windows, I don't think the built-in shell has an equivalent. Microsoft's [Windows PowerShell](http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx) has a `tee` command though. |
60,944 | <p>The below HTML/CSS/Javascript (jQuery) code displays the <code>#makes</code> select box. Selecting an option displays the <code>#models</code> select box with relevant options. The <code>#makes</code> select box sits off-center and the <code>#models</code> select box fills the empty space when it is displayed. </p>
<p>How do you style the form so that the <code>#makes</code> select box is centered when it is the only form element displayed, but when both select boxes are displayed, they are both centered within the container?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var cars = [
{
"makes" : "Honda",
"models" : ['Accord','CRV','Pilot']
},
{
"makes" :"Toyota",
"models" : ['Prius','Camry','Corolla']
}
];
$(function() {
vehicles = [] ;
for(var i = 0; i < cars.length; i++) {
vehicles[cars[i].makes] = cars[i].models ;
}
var options = '';
for (var i = 0; i < cars.length; i++) {
options += '<option value="' + cars[i].makes + '">' + cars[i].makes + '</option>';
}
$("#make").html(options); // populate select box with array
$("#make").bind("click", function() {
$("#model").children().remove() ; // clear select box
var options = '';
for (var i = 0; i < vehicles[this.value].length; i++) {
options += '<option value="' + vehicles[this.value][i] + '">' +
vehicles[this.value][i] +
'</option>';
}
$("#model").html(options); // populate select box with array
$("#models").addClass("show");
}); // bind end
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide {
display: none;
}
.show {
display: inline;
}
fieldset {
border: #206ba4 1px solid;
}
fieldset legend {
margin-top: -.4em;
font-size: 20px;
font-weight: bold;
color: #206ba4;
}
fieldset fieldset {
position: relative;
margin-top: 25px;
padding-top: .75em;
background-color: #ebf4fa;
}
body {
margin: 0;
padding: 0;
font-family: Verdana;
font-size: 12px;
text-align: center;
}
#wrapper {
margin: 40px auto 0;
}
#myFieldset {
width: 213px;
}
#area {
margin: 20px;
}
#area select {
width: 75px;
float: left;
}
#area label {
display: block;
font-size: 1.1em;
font-weight: bold;
color: #000;
}
#area #selection {
display: block;
}
#makes {
margin: 5px;
}
#models {
margin: 5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="wrapper">
<fieldset id="myFieldset">
<legend>Cars</legend>
<fieldset id="area">
<label>Select Make:</label>
<div id="selection">
<div id="makes">
<select id="make"size="2"></select>
</div>
<div class="hide" id="models">
<select id="model" size="3"></select>
</div>
</div>
</fieldset>
</fieldset>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 61009,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Floating the select boxes changes their display properties to \"block\". If you have no reason to float them, simply remove ... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] | The below HTML/CSS/Javascript (jQuery) code displays the `#makes` select box. Selecting an option displays the `#models` select box with relevant options. The `#makes` select box sits off-center and the `#models` select box fills the empty space when it is displayed.
How do you style the form so that the `#makes` select box is centered when it is the only form element displayed, but when both select boxes are displayed, they are both centered within the container?
```js
var cars = [
{
"makes" : "Honda",
"models" : ['Accord','CRV','Pilot']
},
{
"makes" :"Toyota",
"models" : ['Prius','Camry','Corolla']
}
];
$(function() {
vehicles = [] ;
for(var i = 0; i < cars.length; i++) {
vehicles[cars[i].makes] = cars[i].models ;
}
var options = '';
for (var i = 0; i < cars.length; i++) {
options += '<option value="' + cars[i].makes + '">' + cars[i].makes + '</option>';
}
$("#make").html(options); // populate select box with array
$("#make").bind("click", function() {
$("#model").children().remove() ; // clear select box
var options = '';
for (var i = 0; i < vehicles[this.value].length; i++) {
options += '<option value="' + vehicles[this.value][i] + '">' +
vehicles[this.value][i] +
'</option>';
}
$("#model").html(options); // populate select box with array
$("#models").addClass("show");
}); // bind end
});
```
```css
.hide {
display: none;
}
.show {
display: inline;
}
fieldset {
border: #206ba4 1px solid;
}
fieldset legend {
margin-top: -.4em;
font-size: 20px;
font-weight: bold;
color: #206ba4;
}
fieldset fieldset {
position: relative;
margin-top: 25px;
padding-top: .75em;
background-color: #ebf4fa;
}
body {
margin: 0;
padding: 0;
font-family: Verdana;
font-size: 12px;
text-align: center;
}
#wrapper {
margin: 40px auto 0;
}
#myFieldset {
width: 213px;
}
#area {
margin: 20px;
}
#area select {
width: 75px;
float: left;
}
#area label {
display: block;
font-size: 1.1em;
font-weight: bold;
color: #000;
}
#area #selection {
display: block;
}
#makes {
margin: 5px;
}
#models {
margin: 5px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="wrapper">
<fieldset id="myFieldset">
<legend>Cars</legend>
<fieldset id="area">
<label>Select Make:</label>
<div id="selection">
<div id="makes">
<select id="make"size="2"></select>
</div>
<div class="hide" id="models">
<select id="model" size="3"></select>
</div>
</div>
</fieldset>
</fieldset>
</div>
``` | It's not entirely clear from your question what layout you're trying to achieve, but judging by that fact that you have applied "float:left" to the select elements, it looks like you want the select elements to appear side by side. If this is the case, you can achieve this by doing the following:
* To centrally align elements you need to add "text-align:center" to the containing block level element, in this case #selection.
* The position of elements that are floating is not affected by "text-align" declarations, so remove the "float:left" declaration from the select elements.
* In order for the #make and #model divs to sit side by side with out the use of floats they must be displayed as inline elements, so add "display:inline" to both #make and #model (note that this will lose the vertical margin on those elements, so you might need to make some other changes to get the exact layout you want).
As select elements are displayed inline by default, an alternative to the last step is to remove the #make and #model divs and and apply the "show" and "hide" classes to the model select element directly. |
60,977 | <p>Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time.</p>
<p>Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the future. Each subsequent recompile has the same problem.</p>
<p>Solution that I know are:</p>
<p>a) Find the file that has the future time and re-save it. This method is not ideal because the project is very big and it takes time even for windows advanced search to find the files that are changed.</p>
<p>b) Delete the whole project and re-check it out from svn.</p>
<p>Does anyone know how I can get around this problem?</p>
<p>Is there perhaps a setting in visual studio that will allow me to tell the compiler to use the archive bit instead of the last modification date to detect source file changes?</p>
<p>Or perhaps there is a recursive modification date reset tool that can be used in this situation?</p>
| [
{
"answer_id": 60984,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 0,
"selected": false,
"text": "<p>I don't use windows - but surely there is something like awk or grep that you can use to find the \"future\" timestamp... | 2008/09/13 | [
"https://Stackoverflow.com/questions/60977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] | Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time.
Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the future. Each subsequent recompile has the same problem.
Solution that I know are:
a) Find the file that has the future time and re-save it. This method is not ideal because the project is very big and it takes time even for windows advanced search to find the files that are changed.
b) Delete the whole project and re-check it out from svn.
Does anyone know how I can get around this problem?
Is there perhaps a setting in visual studio that will allow me to tell the compiler to use the archive bit instead of the last modification date to detect source file changes?
Or perhaps there is a recursive modification date reset tool that can be used in this situation? | If this was my problem, I'd look for ways to avoid mucking with the system time. Isolating the code under unit tests, or a virtual machine, or something.
However, because I love [PowerShell](https://stackoverflow.com/questions/52487/the-most-amazing-pieces-of-software-in-the-world#53414):
```
Get-ChildItem -r . |
? { $_.LastWriteTime -gt ([DateTime]::Now) } |
Set-ItemProperty -Name "LastWriteTime" -Value ([DateTime]::Now)
``` |
61,000 | <p>I am wondering what directory structure are commonly used in development projects. I mean with the idea of facilitating builds, deploys release, and etc.</p>
<p>I recently used a <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="nofollow noreferrer">Maven structure</a> for a java project, but I am not sure it's the best structure for a non-maven driven project.</p>
<p>So, I have two questions: When you guys start new projects, what structure you use? And: What if you need to integrate two different languages, like for example java classes into a PHP application; PHP files are source files, web files, you you use a /src, /classes, webapps/php ? What are your choices in such scenarios. </p>
<p>As a note: I am wondering also what are you choices for directories names. I like the 3-letters names (src, lib, bin, web, img, css, xml, cfg) but what are your opinions about descriptive names like libraris, sources or htdocs/public_html ?</p>
| [
{
"answer_id": 61003,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 0,
"selected": false,
"text": "<p>I just found a interesting document about Directory structures on Zend website:<br>\n<a href=\"http://framework.... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I am wondering what directory structure are commonly used in development projects. I mean with the idea of facilitating builds, deploys release, and etc.
I recently used a [Maven structure](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html) for a java project, but I am not sure it's the best structure for a non-maven driven project.
So, I have two questions: When you guys start new projects, what structure you use? And: What if you need to integrate two different languages, like for example java classes into a PHP application; PHP files are source files, web files, you you use a /src, /classes, webapps/php ? What are your choices in such scenarios.
As a note: I am wondering also what are you choices for directories names. I like the 3-letters names (src, lib, bin, web, img, css, xml, cfg) but what are your opinions about descriptive names like libraris, sources or htdocs/public\_html ? | After a couple years working with different structures I recently found a structure that hols most variations for me:
```
/project_name (everything goes here)
/web (htdocs)
/img
/css
/app (usually some framework or sensitive code)
/lib (externa libs)
/vendor_1
/vendor_2
/tmp
/cache
/sql (sql scripts usually with maybe diagrams)
/scripts
/doc (usually an empty directory)
``` |
61,002 | <p>I'd like to script, preferably in rake, the following actions into a single command:</p>
<ol>
<li>Get the version of my local git repository.</li>
<li>Git pull the latest code.</li>
<li>Git diff from the version I extracted in step #1 to what is now in my local repository.</li>
</ol>
<p>In other words, I want to get the latest code form the central repository and immediately generate a diff of what's changed since the last time I pulled.</p>
| [
{
"answer_id": 61004,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>This is very similar to a question I asked about <a href=\"https://stackoverflow.com/questions/53569/how-to-get-the-cha... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
] | I'd like to script, preferably in rake, the following actions into a single command:
1. Get the version of my local git repository.
2. Git pull the latest code.
3. Git diff from the version I extracted in step #1 to what is now in my local repository.
In other words, I want to get the latest code form the central repository and immediately generate a diff of what's changed since the last time I pulled. | You could do this fairly simply with refspecs.
```
git pull origin
git diff @{1}..
```
That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version:
```
current=`git rev-parse HEAD`
git pull origin
git diff $current..
```
I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch:
```
git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..
``` |
61,005 | <p>What are the best file permission settings for PHP scripts? Any suggestions on ways to figure out the minimum required permissions?</p>
| [
{
"answer_id": 61004,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>This is very similar to a question I asked about <a href=\"https://stackoverflow.com/questions/53569/how-to-get-the-cha... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | What are the best file permission settings for PHP scripts? Any suggestions on ways to figure out the minimum required permissions? | You could do this fairly simply with refspecs.
```
git pull origin
git diff @{1}..
```
That will give you a diff of the current branch as it existed before and after the pull. Note that if the pull doesn't actually update the current branch, the diff will give you the wrong results. Another option is to explicitly record the current version:
```
current=`git rev-parse HEAD`
git pull origin
git diff $current..
```
I personally use an alias that simply shows me a log, in reverse order (i.e. oldest to newest), sans merges, of all the commits since my last pull. I run this every time my pull updates the branch:
```
git config --global alias.lcrev 'log --reverse --no-merges --stat @{1}..
``` |
61,051 | <p>You can use more than one css class in an HTML tag in current web browsers, e.g.:</p>
<pre><code><div class="style1 style2 style3">foo bar</div>
</code></pre>
<p>This hasn't always worked; with which versions did the major browsers begin correctly supporting this feature?</p>
| [
{
"answer_id": 61053,
"author": "Wayne Kao",
"author_id": 3284,
"author_profile": "https://Stackoverflow.com/users/3284",
"pm_score": 1,
"selected": false,
"text": "<p>Apparently IE 6 doesn't handle these correctly if you have CSS selectors that contain multiple class names:\n<a href=\"h... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3283/"
] | You can use more than one css class in an HTML tag in current web browsers, e.g.:
```
<div class="style1 style2 style3">foo bar</div>
```
This hasn't always worked; with which versions did the major browsers begin correctly supporting this feature? | @Wayne Kao - IE6 has no problem reading more than one class name on an element, and applying styles that belong to each class. What the article is referring to is creating new styles based on the combination of class names.
```
<div class="bold italic">content</div>
.bold {
font-weight: 800;
}
.italic {
font-style: italic;
{
```
IE6 would apply both bold and italic styles to the div. However, say we wanted all elements that have bold and italic classes to also be purple. In Firefox (or possibly IE7, not sure), we could write something like this:
```
.bold.italic {
color: purple;
}
```
That would not work in IE6. |
61,084 | <p>I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g.</p>
<pre><code>XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
new XElement(ns + "urlset",
new XElement("url",
new XElement("loc", "http://www.example.com/page"),
new XElement("lastmod", "2008-09-14"))));
</code></pre>
<p>The result is ...</p>
<pre><code><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url xmlns="">
<loc>http://www.example.com/page</loc>
<lastmod>2008-09-14</lastmod>
</url>
</urlset>
</code></pre>
<p>I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way?</p>
| [
{
"answer_id": 61106,
"author": "Anheledir",
"author_id": 5703,
"author_profile": "https://Stackoverflow.com/users/5703",
"pm_score": 2,
"selected": false,
"text": "<p>If one element uses a namespace, they all must use one. In case you don't define one on your own the framework will add ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4449/"
] | I'm trying to create a sitemap using Linq to Xml, but am getting an empty namespace attribute, which I would like to get rid of. e.g.
```
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
new XElement(ns + "urlset",
new XElement("url",
new XElement("loc", "http://www.example.com/page"),
new XElement("lastmod", "2008-09-14"))));
```
The result is ...
```
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url xmlns="">
<loc>http://www.example.com/page</loc>
<lastmod>2008-09-14</lastmod>
</url>
</urlset>
```
I would rather not have the xmlns="" on the url element. I can strip it out using Replace on the final xdoc.ToString(), but is there a more correct way? | The "more correct way" would be:
```
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
new XElement(ns + "urlset",
new XElement(ns + "url",
new XElement(ns + "loc", "http://www.example.com/page"),
new XElement(ns + "lastmod", "2008-09-14"))));
```
Same as your code, but with the "ns +" before every element name that needs to be in the sitemap namespace. It's smart enough not to put any unnecessary namespace declarations in the resulting XML, so the result is:
```
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/page</loc>
<lastmod>2008-09-14</lastmod>
</url>
</urlset>
```
which is, if I'm not mistaken, what you want. |
61,085 | <p>I've been trying to use SQLite with the PDO wrapper in PHP with mixed success. I can read from the database fine, but none of my updates are being committed to the database when I view the page in the browser. Curiously, running the script from my shell does update the database. I suspected file permissions as the culprit, but even with the database providing full access (chmod 777) the problem persists. Should I try changing the file owner? If so, what to?</p>
<p>By the way, my machine is the standard Mac OS X Leopard install with PHP activated.</p>
<p>@Tom Martin</p>
<p>Thank you for your reply. I just ran your code and it looks like PHP runs as user _www. I then tried chowning the database to be owned by _www, but that didn't work either.</p>
<p>I should also note that PDO's errorInfo function doesn't indicate an error took place. Could this be a setting with PDO somehow opening the database for read-only? I've heard that SQLite performs write locks on the entire file. Is it possible that the database is locked by something else preventing the write?</p>
<p>I've decided to include the code in question. This is going to be more or less a port of <a href="https://stackoverflow.com/questions/6936/using-what-ive-learned-from-stackoverflow-html-scraper">Grant's script</a> to PHP. So far it's just the Questions section:</p>
<pre><code><?php
$db = new PDO('sqlite:test.db');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com/users/658/kyle");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIE, "shhsecret=1293706652");
$page = curl_exec($ch);
preg_match('/summarycount">.*?([,\d]+)<\/div>.*?Reputation/s', $page, $rep);
$rep = preg_replace("/,/", "", $rep[1]);
preg_match('/iv class="summarycount".{10,60} (\d+)<\/d.{10,140}Badges/s', $page, $badge);
$badge = $badge[1];
$qreg = '/question-summary narrow.*?vote-count-post"><strong.*?>(-?\d*).*?\/questions\/(\d*).*?>(.*?)<\/a>/s';
preg_match_all($qreg, $page, $questions, PREG_SET_ORDER);
$areg = '/(answer-summary"><a href="\/questions\/(\d*).*?votes.*?>(-?\d+).*?href.*?>(.*?)<.a)/s';
preg_match_all($areg, $page, $answers, PREG_SET_ORDER);
echo "<h3>Questions:</h3>\n";
echo "<table cellpadding=\"3\">\n";
foreach ($questions as $q)
{
$query = 'SELECT count(id), votes FROM Questions WHERE id = '.$q[2].' AND type=0;';
$dbitem = $db->query($query)->fetch(PDO::FETCH_ASSOC);
if ($dbitem['count(id)'] > 0)
{
$lastQ = $q[1] - $dbitem['votes'];
if ($lastQ == 0)
{
$lastQ = "";
}
$query = "UPDATE Questions SET votes = '$q[1]' WHERE id = '$q[2]'";
$db->exec($query);
}
else
{
$query = "INSERT INTO Questions VALUES('$q[3]', '$q[1]', 0, '$q[2]')";
echo "$query\n";
$db->exec($query);
$lastQ = "(NEW)";
}
echo "<tr><td>$lastQ</td><td align=\"right\">$q[1]</td><td>$q[3]</td></tr>\n";
}
echo "</table>";
?>
</code></pre>
| [
{
"answer_id": 61102,
"author": "Tom Martin",
"author_id": 5303,
"author_profile": "https://Stackoverflow.com/users/5303",
"pm_score": 1,
"selected": false,
"text": "<p>I think PHP commonly runs as the user \"nodody\". Not sure about on Mac though. If Mac has whoami you could try <code... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] | I've been trying to use SQLite with the PDO wrapper in PHP with mixed success. I can read from the database fine, but none of my updates are being committed to the database when I view the page in the browser. Curiously, running the script from my shell does update the database. I suspected file permissions as the culprit, but even with the database providing full access (chmod 777) the problem persists. Should I try changing the file owner? If so, what to?
By the way, my machine is the standard Mac OS X Leopard install with PHP activated.
@Tom Martin
Thank you for your reply. I just ran your code and it looks like PHP runs as user \_www. I then tried chowning the database to be owned by \_www, but that didn't work either.
I should also note that PDO's errorInfo function doesn't indicate an error took place. Could this be a setting with PDO somehow opening the database for read-only? I've heard that SQLite performs write locks on the entire file. Is it possible that the database is locked by something else preventing the write?
I've decided to include the code in question. This is going to be more or less a port of [Grant's script](https://stackoverflow.com/questions/6936/using-what-ive-learned-from-stackoverflow-html-scraper) to PHP. So far it's just the Questions section:
```
<?php
$db = new PDO('sqlite:test.db');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://stackoverflow.com/users/658/kyle");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIE, "shhsecret=1293706652");
$page = curl_exec($ch);
preg_match('/summarycount">.*?([,\d]+)<\/div>.*?Reputation/s', $page, $rep);
$rep = preg_replace("/,/", "", $rep[1]);
preg_match('/iv class="summarycount".{10,60} (\d+)<\/d.{10,140}Badges/s', $page, $badge);
$badge = $badge[1];
$qreg = '/question-summary narrow.*?vote-count-post"><strong.*?>(-?\d*).*?\/questions\/(\d*).*?>(.*?)<\/a>/s';
preg_match_all($qreg, $page, $questions, PREG_SET_ORDER);
$areg = '/(answer-summary"><a href="\/questions\/(\d*).*?votes.*?>(-?\d+).*?href.*?>(.*?)<.a)/s';
preg_match_all($areg, $page, $answers, PREG_SET_ORDER);
echo "<h3>Questions:</h3>\n";
echo "<table cellpadding=\"3\">\n";
foreach ($questions as $q)
{
$query = 'SELECT count(id), votes FROM Questions WHERE id = '.$q[2].' AND type=0;';
$dbitem = $db->query($query)->fetch(PDO::FETCH_ASSOC);
if ($dbitem['count(id)'] > 0)
{
$lastQ = $q[1] - $dbitem['votes'];
if ($lastQ == 0)
{
$lastQ = "";
}
$query = "UPDATE Questions SET votes = '$q[1]' WHERE id = '$q[2]'";
$db->exec($query);
}
else
{
$query = "INSERT INTO Questions VALUES('$q[3]', '$q[1]', 0, '$q[2]')";
echo "$query\n";
$db->exec($query);
$lastQ = "(NEW)";
}
echo "<tr><td>$lastQ</td><td align=\"right\">$q[1]</td><td>$q[3]</td></tr>\n";
}
echo "</table>";
?>
``` | Kyle, in order for PDO/Sqlite to work you need write permission to directory where your database resides.
Also, I see you perform multiple selects in loop. This may be ok if you are building something small and not heavy loaded. Otherwise I'd suggest building single query that returns multiple rows and process them in separate loop. |
61,088 | <p><strong>What "Hidden Features" of JavaScript do you think every programmer should know?</strong></p>
<p>After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/954327/">Hidden Features of HTML</a></li>
<li><a href="https://stackoverflow.com/questions/628407">Hidden Features of CSS</a></li>
<li><a href="https://stackoverflow.com/questions/61401/">Hidden Features of PHP</a></li>
<li><a href="https://stackoverflow.com/questions/54929/">Hidden Features of ASP.NET</a></li>
<li><a href="https://stackoverflow.com/questions/9033/">Hidden Features of C#</a></li>
<li><a href="https://stackoverflow.com/questions/15496/">Hidden Features of Java</a></li>
<li><a href="https://stackoverflow.com/questions/101268/">Hidden Features of Python</a></li>
</ul>
<p>Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.</p>
| [
{
"answer_id": 61094,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 8,
"selected": false,
"text": "<p>Functions are first class citizens in JavaScript:</p>\n\n<pre><code>var passFunAndApply = function (fn,x,y,z) { retur... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] | **What "Hidden Features" of JavaScript do you think every programmer should know?**
After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.
* [Hidden Features of HTML](https://stackoverflow.com/questions/954327/)
* [Hidden Features of CSS](https://stackoverflow.com/questions/628407)
* [Hidden Features of PHP](https://stackoverflow.com/questions/61401/)
* [Hidden Features of ASP.NET](https://stackoverflow.com/questions/54929/)
* [Hidden Features of C#](https://stackoverflow.com/questions/9033/)
* [Hidden Features of Java](https://stackoverflow.com/questions/15496/)
* [Hidden Features of Python](https://stackoverflow.com/questions/101268/)
Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is. | You don't need to define any parameters for a function. You can just use the function's `arguments` array-like object.
```
function sum() {
var retval = 0;
for (var i = 0, len = arguments.length; i < len; ++i) {
retval += arguments[i];
}
return retval;
}
sum(1, 2, 3) // returns 6
``` |
61,110 | <p>I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution.</p>
<p>The workaround I use while I don't find a cleaner approach is to subclass <code>TextWriter</code> overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this:</p>
<pre><code>public class DirtyWorkaround {
private class DirtyWriter : TextWriter {
private TextWriter stdoutWriter;
private StreamWriter fileWriter;
public DirtyWriter(string path, TextWriter stdoutWriter) {
this.stdoutWriter = stdoutWriter;
this.fileWriter = new StreamWriter(path);
}
override public void Write(string s) {
stdoutWriter.Write(s);
fileWriter.Write(s);
fileWriter.Flush();
}
// Same as above for WriteLine() and WriteLine(string),
// plus whatever methods I need to override to inherit
// from TextWriter (Encoding.Get I guess).
}
public static void Main(string[] args) {
using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) {
Console.SetOut(dw);
// Teh codez
}
}
}
</code></pre>
<p>See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer.</p>
<p>Also, excuse inaccuracies with the above code (had to write it <em>ad hoc</em>, sorry ;).</p>
| [
{
"answer_id": 61119,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think there's anything wrong with your approach.</p>\n\n<p>If you wanted reusable code, consider implementing ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4850/"
] | I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution.
The workaround I use while I don't find a cleaner approach is to subclass `TextWriter` overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this:
```
public class DirtyWorkaround {
private class DirtyWriter : TextWriter {
private TextWriter stdoutWriter;
private StreamWriter fileWriter;
public DirtyWriter(string path, TextWriter stdoutWriter) {
this.stdoutWriter = stdoutWriter;
this.fileWriter = new StreamWriter(path);
}
override public void Write(string s) {
stdoutWriter.Write(s);
fileWriter.Write(s);
fileWriter.Flush();
}
// Same as above for WriteLine() and WriteLine(string),
// plus whatever methods I need to override to inherit
// from TextWriter (Encoding.Get I guess).
}
public static void Main(string[] args) {
using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) {
Console.SetOut(dw);
// Teh codez
}
}
}
```
See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer.
Also, excuse inaccuracies with the above code (had to write it *ad hoc*, sorry ;). | The perfect solution for this is to use [log4net](http://logging.apache.org/log4net/) with a console appender and a file appender. There are many other appenders available as well. It also allows you to turn the different appenders off and on at runtime. |
61,143 | <p>Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#. </p>
| [
{
"answer_id": 61149,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming a mythical object TreeItem, that conatins a Children collection to represent your hierarchy.</p>\n\n<pre>... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5360/"
] | Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#. | Ok, I found some free time finally.
Here we go:
```
class TreeNode
{
public string Value { get; set;}
public List<TreeNode> Nodes { get; set;}
public TreeNode()
{
Nodes = new List<TreeNode>();
}
}
Action<TreeNode> traverse = null;
traverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);};
var root = new TreeNode { Value = "Root" };
root.Nodes.Add(new TreeNode { Value = "ChildA"} );
root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA1" });
root.Nodes[0].Nodes.Add(new TreeNode { Value = "ChildA2" });
root.Nodes.Add(new TreeNode { Value = "ChildB"} );
root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB1" });
root.Nodes[1].Nodes.Add(new TreeNode { Value = "ChildB2" });
traverse(root);
``` |
61,150 | <p>My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. </p>
<p>So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it <code>staticInit</code>. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock <code>staticInit</code> with <a href="https://jmockit.github.io/" rel="noreferrer">JMockit</a> to not do anything. Let's see this in example.</p>
<pre><code>public class ClassWithStaticInit {
static {
System.out.println("static initializer.");
}
}
</code></pre>
<p>Will be changed to</p>
<pre><code>public class ClassWithStaticInit {
static {
staticInit();
}
private static void staticInit() {
System.out.println("static initialized.");
}
}
</code></pre>
<p>So that we can do the following in a <a href="https://junit.org/junit5/" rel="noreferrer">JUnit</a>.</p>
<pre><code>public class DependentClassTest {
public static class MockClassWithStaticInit {
public static void staticInit() {
}
}
@BeforeClass
public static void setUpBeforeClass() {
Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class);
}
}
</code></pre>
<p>However this solution also comes with its own problems. You can't run <code>DependentClassTest</code> and <code>ClassWithStaticInitTest</code> on the same JVM since you actually want the static block to run for <code>ClassWithStaticInitTest</code>.</p>
<p>What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner?</p>
| [
{
"answer_id": 61153,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds to me like you are treating a symptom: poor design with dependencies on static initialization. Maybe some refa... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3087/"
] | My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes.
So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it `staticInit`. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock `staticInit` with [JMockit](https://jmockit.github.io/) to not do anything. Let's see this in example.
```
public class ClassWithStaticInit {
static {
System.out.println("static initializer.");
}
}
```
Will be changed to
```
public class ClassWithStaticInit {
static {
staticInit();
}
private static void staticInit() {
System.out.println("static initialized.");
}
}
```
So that we can do the following in a [JUnit](https://junit.org/junit5/).
```
public class DependentClassTest {
public static class MockClassWithStaticInit {
public static void staticInit() {
}
}
@BeforeClass
public static void setUpBeforeClass() {
Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class);
}
}
```
However this solution also comes with its own problems. You can't run `DependentClassTest` and `ClassWithStaticInitTest` on the same JVM since you actually want the static block to run for `ClassWithStaticInitTest`.
What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner? | When I run into this problem, I usually do the same thing you describe, except I make the static method protected so I can invoke it manually. On top of this, I make sure that the method can be invoked multiple times without problems (otherwise it is no better than the static initializer as far as the tests go).
This works reasonably well, and I can actually test that the static initializer method does what I expect/want it to do. Sometimes it is just easiest to have some static initialization code, and it just isn't worth it to build an overly complex system to replace it.
When I use this mechanism, I make sure to document that the protected method is only exposed for testing purposes, with the hopes that it won't be used by other developers. This of course may not be a viable solution, for example if the class' interface is externally visible (either as a sub-component of some kind for other teams, or as a public framework). It is a simple solution to the problem though, and doesn't require a third party library to set up (which I like). |
61,155 | <p>I'm trying to place this menu on the left hand side of the page:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="left-menu" style="left: 123px; top: 355px">
<ul>
<li> Categories </li>
<li> Weapons </li>
<li> Armor </li>
<li> Manuals </li>
<li> Sustenance </li>
<li> Test </li>
</ul>
</div></code></pre>
</div>
</div>
</p>
<p>The problem is that if I use absolute or fixed values, different screen sizes will render the navigation bar differently. I also have a second <code>div</code> that contains all the main content which also needs to be moved to the right, so far I'm using relative values which seems to work no matter the screen size.</p>
| [
{
"answer_id": 61157,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>I think you're supposed to use the <strong>float</strong> property for positioning things like that. <a href=\"http://cs... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298/"
] | I'm trying to place this menu on the left hand side of the page:
```html
<div class="left-menu" style="left: 123px; top: 355px">
<ul>
<li> Categories </li>
<li> Weapons </li>
<li> Armor </li>
<li> Manuals </li>
<li> Sustenance </li>
<li> Test </li>
</ul>
</div>
```
The problem is that if I use absolute or fixed values, different screen sizes will render the navigation bar differently. I also have a second `div` that contains all the main content which also needs to be moved to the right, so far I'm using relative values which seems to work no matter the screen size. | `float` is indeed the right property to achieve this. However, the example given by bmatthews68 can be improved. The most important thing about floating boxes is that they *must* specify an explicit width. This can be rather inconvenient but this is the way CSS works. However, notice that `px` is a unit of measure that has no place in the world of HTML/CSS, at least not to specify widths.
Always resort to measures that will work with different font sizes, i.e. either use `em` or `%`. Now, if the menu is implemented as a floating body, then this means that the main content floats “around” it. If the main content is higher than the menu, this might not be what you want:
[float1 http://page.mi.fu-berlin.de/krudolph/stuff/float1.png](http://page.mi.fu-berlin.de/krudolph/stuff/float1.png)
```
<div style="width: 10em; float: left;">Left</div>
<div>Right, spanning<br/> multiple lines</div>
```
You can correct this behaviour by giving the main content a `margin-left` equal to the width of the menu:
[float2 http://page.mi.fu-berlin.de/krudolph/stuff/float2.png](http://page.mi.fu-berlin.de/krudolph/stuff/float2.png)
```
<div style="width: 10em; float: left;">Left</div>
<div style="margin-left: 10em;">Right, spanning<br/> multiple lines</div>
```
In most cases you also want to give the main content a `padding-left` so it doesn't “stick” to the menu too closely.
By the way, it's trivial to change the above so that the menu is on the right side instead of the left: simply change every occurrence of the word “left” to “right”.
Ah, one last thing. If the menu's content is higher than the main content, it will render oddly because `float` does some odd things. In that case, you will have to clear the box that comes below the floating body, as in bmatthews68's example.
/EDIT: Damn, HTML doesn't work the way the preview showed it. Well, I've included pictures instead. |
61,176 | <p>I want to access messages in Gmail from a Java application using <a href="http://www.ing.iac.es/~docs/external/java/javamail/javadocs/index.html" rel="nofollow noreferrer">JavaMail</a> and <a href="https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol" rel="nofollow noreferrer">IMAP</a>. Why am I getting a <em><a href="https://docs.oracle.com/javase/7/docs/api/java/net/SocketTimeoutException.html" rel="nofollow noreferrer">SocketTimeoutException</a></em> ?</p>
<p>Here is my code:</p>
<pre><code>Properties props = System.getProperties();
props.setProperty("mail.imap.host", "imap.gmail.com");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.connectiontimeout", "5000");
props.setProperty("mail.imap.timeout", "5000");
try {
Session session = Session.getDefaultInstance(props, new MyAuthenticator());
URLName urlName = new URLName("imap://MYUSERNAME@gmail.com:MYPASSWORD@imap.gmail.com");
Store store = session.getStore(urlName);
if (!store.isConnected()) {
store.connect();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
</code></pre>
<p>I have set the timeout values so that it wouldn't take "forever" to timeout. Also, <em>MyAuthenticator</em> also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for <a href="https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol" rel="nofollow noreferrer">IMAP</a>.)</p>
| [
{
"answer_id": 61179,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 2,
"selected": false,
"text": "<p>You have to connect to GMail using SSL only. Setting the following properties will force that for you. </p>\n\n<pre... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2512222/"
] | I want to access messages in Gmail from a Java application using [JavaMail](http://www.ing.iac.es/~docs/external/java/javamail/javadocs/index.html) and [IMAP](https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol). Why am I getting a *[SocketTimeoutException](https://docs.oracle.com/javase/7/docs/api/java/net/SocketTimeoutException.html)* ?
Here is my code:
```
Properties props = System.getProperties();
props.setProperty("mail.imap.host", "imap.gmail.com");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.connectiontimeout", "5000");
props.setProperty("mail.imap.timeout", "5000");
try {
Session session = Session.getDefaultInstance(props, new MyAuthenticator());
URLName urlName = new URLName("imap://MYUSERNAME@gmail.com:MYPASSWORD@imap.gmail.com");
Store store = session.getStore(urlName);
if (!store.isConnected()) {
store.connect();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
```
I have set the timeout values so that it wouldn't take "forever" to timeout. Also, *MyAuthenticator* also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for [IMAP](https://en.wikipedia.org/wiki/Internet_Message_Access_Protocol).) | Using imaps was a great suggestion. Neither of the answers provided just worked for me, so I googled some more and found something that worked. Here's how my code looks now.
```
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>@gmail.com", "<password>");
...
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
```
This is nice because it takes the redundant Authenticator out of the picture. I'm glad this worked because the SSLNOTES.txt make my head spin. |
61,212 | <p>How do I delete untracked local files from the current working tree?</p>
| [
{
"answer_id": 61213,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-clean.html\" rel=\"noreferrer\">git-clean</a> is what you are l... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | How do I delete untracked local files from the current working tree? | >
> [git-clean](https://git-scm.com/docs/git-clean) - Remove untracked files from the working tree
> ----------------------------------------------------------------------------------------------
>
>
> ### Synopsis
>
>
>
> ```
> git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <path>…
>
> ```
>
> ### Description
>
>
> Cleans the working tree by recursively removing files that are not under version control, **starting from the current directory**.
>
>
> Normally, only files unknown to Git are removed, but if the `-x` option is specified, ignored files are also removed. This can, for example, be useful to remove all build products.
>
>
> If any optional `<path>...` arguments are given, only those paths are affected.
>
>
>
---
Step 1 is to show what will be deleted by using the `-n` option:
```
# Print out the list of files and directories which will be removed (dry run)
git clean -n -d
```
Clean Step - **beware: this will delete files**:
```
# Delete the files from the repository
git clean -f
```
* To remove directories, run `git clean -f -d` or `git clean -fd`
* To remove ignored files, run `git clean -f -X` or `git clean -fX`
* To remove ignored and non-ignored files, run `git clean -f -x` or `git clean -fx`
**Note** the case difference on the `X` for the two latter commands.
If `clean.requireForce` is set to "true" (the default) in your configuration, one needs to specify `-f` otherwise nothing will actually happen.
Again see the [`git-clean`](http://git-scm.com/docs/git-clean) docs for more information.
---
>
> ### Options
>
>
> **`-f`, `--force`**
>
>
> If the Git configuration variable clean.requireForce is not set to
> false, git clean will refuse to run unless given `-f`, `-n` or `-i`.
>
>
> **`-x`**
>
>
> Don’t use the standard ignore rules read from .gitignore (per
> directory) and `$GIT_DIR/info/exclude`, but do still use the ignore
> rules given with `-e` options. This allows removing all untracked files,
> including build products. This can be used (possibly in conjunction
> with git reset) to create a pristine working directory to test a clean
> build.
>
>
> **`-X`**
>
>
> Remove only files ignored by Git. This may be useful to rebuild
> everything from scratch, but keep manually created files.
>
>
> **`-n`, `--dry-run`**
>
>
> Don’t actually remove anything, just show what would be done.
>
>
> **`-d`**
>
>
> Remove untracked directories in addition to untracked files. If an
> untracked directory is managed by a different Git repository, it is
> not removed by default. Use `-f` option twice if you really want to
> remove such a directory.
>
>
> |
61,217 | <p>This question is a follow up to my <a href="https://stackoverflow.com/questions/56279/export-aspx-to-html">previous question</a> about getting the HTML from an ASPX page. I decided to try using the webclient object, but the problem is that I get the login page's HTML because login is required. I tried "logging in" using the webclient object:</p>
<pre><code>WebClient ww = new WebClient();
ww.DownloadString("Login.aspx?UserName=&Password=");
string html = ww.DownloadString("Internal.aspx");
</code></pre>
<p>But I still get the login page all the time. I know that the username info is not stored in a cookie. I must be doing something wrong or leaving out an important part. Does anyone know what it could be?</p>
| [
{
"answer_id": 61221,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 1,
"selected": false,
"text": "<p>Well does opening the page in a brower with \"Login.aspx?UserName=&Password=\" normaly work?<br>\nSome pages may n... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278/"
] | This question is a follow up to my [previous question](https://stackoverflow.com/questions/56279/export-aspx-to-html) about getting the HTML from an ASPX page. I decided to try using the webclient object, but the problem is that I get the login page's HTML because login is required. I tried "logging in" using the webclient object:
```
WebClient ww = new WebClient();
ww.DownloadString("Login.aspx?UserName=&Password=");
string html = ww.DownloadString("Internal.aspx");
```
But I still get the login page all the time. I know that the username info is not stored in a cookie. I must be doing something wrong or leaving out an important part. Does anyone know what it could be? | Just pass valid login parameters to a given URI. Should help you out.
**If you don't have login information you shouldn't be trying to circumvent it.**
```
public static string HttpPost( string URI, string Parameters )
{
System.Net.WebRequest req = System.Net.WebRequest.Create( URI );
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes( Parameters );
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write( bytes, 0, bytes.Length );
os.Close();
System.Net.WebResponse resp = req.GetResponse();
if ( resp == null ) return null;
System.IO.StreamReader sr = new System.IO.StreamReader( resp.GetResponseStream() );
return sr.ReadToEnd().Trim();
}
``` |
61,219 | <p>I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...).</p>
<p>He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.:</p>
<pre><code>Debug.Assert(i > 3, "i > 3", "This means I got a bad parameter");
</code></pre>
<p>Now, personally, it seems crazy to me that he so loves restating his test without an actual sensible 'business logic' comment, perhaps "i <= 3 must never happen because of the flobittyjam widgitification process".</p>
<p>So, I think I get Asserts as a kind-of low-level "Let's protect my assumptions" kind of thing... assuming that one feels this is a test one only needs to do in debug - i.e. you are protecting yourself against colleague and future programmers, and hoping that they actually test things.</p>
<p>But what I don't get is, he then goes on to say that you should use assertions in addition to normal error handling; now what I envisage is something like this:</p>
<pre><code>Debug.Assert(i > 3, "i must be greater than 3 because of the flibbity widgit status");
if (i <= 3)
{
throw new ArgumentOutOfRangeException("i", "i must be > 3 because... i=" + i.ToString());
}
</code></pre>
<p>What have I gained by the Debug.Assert repetition of the error condition test? I think I'd get it if we were talking about debug-only double-checking of a very important calculation...</p>
<pre><code>double interestAmount = loan.GetInterest();
Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc");
</code></pre>
<p>...but I don't get it for parameter tests which are surely worth checking (in both DEBUG and Release builds)... or not. What am I missing?</p>
| [
{
"answer_id": 61223,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>IMO it's a loss of development time only. Properly implemented exception gives you a clear picture of what happened. I saw <em... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6004/"
] | I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...).
He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.:
```
Debug.Assert(i > 3, "i > 3", "This means I got a bad parameter");
```
Now, personally, it seems crazy to me that he so loves restating his test without an actual sensible 'business logic' comment, perhaps "i <= 3 must never happen because of the flobittyjam widgitification process".
So, I think I get Asserts as a kind-of low-level "Let's protect my assumptions" kind of thing... assuming that one feels this is a test one only needs to do in debug - i.e. you are protecting yourself against colleague and future programmers, and hoping that they actually test things.
But what I don't get is, he then goes on to say that you should use assertions in addition to normal error handling; now what I envisage is something like this:
```
Debug.Assert(i > 3, "i must be greater than 3 because of the flibbity widgit status");
if (i <= 3)
{
throw new ArgumentOutOfRangeException("i", "i must be > 3 because... i=" + i.ToString());
}
```
What have I gained by the Debug.Assert repetition of the error condition test? I think I'd get it if we were talking about debug-only double-checking of a very important calculation...
```
double interestAmount = loan.GetInterest();
Debug.Assert(debugInterestDoubleCheck(loan) == interestAmount, "Mismatch on interest calc");
```
...but I don't get it for parameter tests which are surely worth checking (in both DEBUG and Release builds)... or not. What am I missing? | Assertions are not for parameter checking. Parameter checking should always be done (and precisely according to what pre-conditions are specified in your documentation and/or specification), and the `ArgumentOutOfRangeException` thrown as necessary.
Assertions are for testing for "impossible" situations, i.e., things that you (in your program logic) *assume* are true. The assertions are there to tell you if these assumptions are broken for any reason.
Hope this helps! |
61,227 | <p>If I have: </p>
<pre><code>signed char * p;
</code></pre>
<p>and I do a comparison:</p>
<pre><code>if ( *p == 0xFF )
break;
</code></pre>
<p>it will never catch 0XFF, but if I replace it with -1 it will:</p>
<pre><code>if ( *p == (signed char)0xFF )
break;
</code></pre>
<p>How can this happen? Is it something with the sign flag? I though that <code>0xFF == -1 == 255</code>.</p>
| [
{
"answer_id": 61229,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<p>The value <code>0xFF</code> is a signed int value. C will promote the <code>*p</code> to an <code>int</code> when doing ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] | If I have:
```
signed char * p;
```
and I do a comparison:
```
if ( *p == 0xFF )
break;
```
it will never catch 0XFF, but if I replace it with -1 it will:
```
if ( *p == (signed char)0xFF )
break;
```
How can this happen? Is it something with the sign flag? I though that `0xFF == -1 == 255`. | The value `0xFF` is a signed int value. C will promote the `*p` to an `int` when doing the comparison, so the first if statement is equivalent to:
```
if( -1 == 255 ) break;
```
which is of course false. By using `(signed char)0xFF` the statement is equivalent to:
```
if( -1 == -1 ) break;
```
which works as you expect. The key point here is that the comparison is done with `int` types instead of `signed char` types. |
61,233 | <p>What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:</p>
<pre><code>INSERT INTO some_table (column1, column2, column3)
SELECT
Rows.n.value('(@column1)[1]', 'varchar(20)'),
Rows.n.value('(@column2)[1]', 'nvarchar(100)'),
Rows.n.value('(@column3)[1]', 'int'),
FROM @xml.nodes('//Rows') Rows(n)
</code></pre>
<p>However I find that this is getting very slow for even moderate size xml data.</p>
| [
{
"answer_id": 61246,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure what is the best method. I used OPENXML construction:</p>\n\n<pre><code>INSERT INTO Test\nSELECT Id, Data \nFROM ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5769/"
] | What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:
```
INSERT INTO some_table (column1, column2, column3)
SELECT
Rows.n.value('(@column1)[1]', 'varchar(20)'),
Rows.n.value('(@column2)[1]', 'nvarchar(100)'),
Rows.n.value('(@column3)[1]', 'int'),
FROM @xml.nodes('//Rows') Rows(n)
```
However I find that this is getting very slow for even moderate size xml data. | Stumbled across this question whilst having a very similar problem, I'd been running a query processing a 7.5MB XML file (~approx 10,000 nodes) for around 3.5~4 hours before finally giving up.
However, after a little more research I found that having typed the XML using a schema and created an XML Index (I'd bulk inserted into a table) the same query completed in ~ 0.04ms.
How's that for a performance improvement!
Code to create a schema:
```
IF EXISTS ( SELECT * FROM sys.xml_schema_collections where [name] = 'MyXmlSchema')
DROP XML SCHEMA COLLECTION [MyXmlSchema]
GO
DECLARE @MySchema XML
SET @MySchema =
(
SELECT * FROM OPENROWSET
(
BULK 'C:\Path\To\Schema\MySchema.xsd', SINGLE_CLOB
) AS xmlData
)
CREATE XML SCHEMA COLLECTION [MyXmlSchema] AS @MySchema
GO
```
Code to create the table with a typed XML column:
```
CREATE TABLE [dbo].[XmlFiles] (
[Id] [uniqueidentifier] NOT NULL,
-- Data from CV element
[Data] xml(CONTENT dbo.[MyXmlSchema]) NOT NULL,
CONSTRAINT [PK_XmlFiles] PRIMARY KEY NONCLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
```
Code to create Index
```
CREATE PRIMARY XML INDEX PXML_Data
ON [dbo].[XmlFiles] (Data)
```
There are a few things to bear in mind though. SQL Server's implementation of Schema doesn't support xsd:include. This means that if you have a schema which references other schema, you'll have to copy all of these into a single schema and add that.
Also I would get an error:
```
XQuery [dbo.XmlFiles.Data.value()]: Cannot implicitly atomize or apply 'fn:data()' to complex content elements, found type 'xs:anyType' within inferred type 'element({http://www.mynamespace.fake/schemas}:SequenceNumber,xs:anyType) ?'.
```
if I tried to navigate above the node I had selected with the nodes function. E.g.
```
SELECT
,C.value('CVElementId[1]', 'INT') AS [CVElementId]
,C.value('../SequenceNumber[1]', 'INT') AS [Level]
FROM
[dbo].[XmlFiles]
CROSS APPLY
[Data].nodes('/CVSet/Level/CVElement') AS T(C)
```
Found that the best way to handle this was to use the OUTER APPLY to in effect perform an "outer join" on the XML.
```
SELECT
,C.value('CVElementId[1]', 'INT') AS [CVElementId]
,B.value('SequenceNumber[1]', 'INT') AS [Level]
FROM
[dbo].[XmlFiles]
CROSS APPLY
[Data].nodes('/CVSet/Level') AS T(B)
OUTER APPLY
B.nodes ('CVElement') AS S(C)
```
Hope that that helps someone as that's pretty much been my day. |
61,256 | <p>I have a problem with a little .Net web application which uses the Amazon webservice. With the integrated Visual Studio web server everything works fine. But after deploying it to the IIS on the same computer i get the following error message:</p>
<pre><code>Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach
einer bestimmten Zeitspanne nicht ordnungsgemäß reagiert hat, oder
die hergestellte Verbindung war fehlerhaft, da der verbundene Host
nicht reagiert hat 192.168.123.254:8080
</code></pre>
<p>Which roughly translates to "cant connect to 192.168.123.254:8080"</p>
<p>The computer is part of an Active Directory. The AD-Server was installed on a network which uses 192.168.123.254 as a proxy. Now it is not reachable and should not be used.</p>
<p><strong>How do I prevent the IIS from using a proxy?</strong></p>
<p>I think it has something to do with policy settings for the Internet Explorer. An "old" AD user has this setting, but a newly created user does not. I checked all the group policy settings and nowhere is a proxy defined.</p>
<p>The web server is running in the context of the anonymous internet user account on the local computer. Do local users get settings from the AD? If so how can I change that setting, if I cant login as this user?</p>
<p>What can I do, where else i could check?</p>
| [
{
"answer_id": 61296,
"author": "Brad Bruce",
"author_id": 5008,
"author_profile": "https://Stackoverflow.com/users/5008",
"pm_score": 0,
"selected": false,
"text": "<p>IIS is a destination. The configuration issue is in whatever is doing the call (acting like a client). If you are usi... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6297/"
] | I have a problem with a little .Net web application which uses the Amazon webservice. With the integrated Visual Studio web server everything works fine. But after deploying it to the IIS on the same computer i get the following error message:
```
Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach
einer bestimmten Zeitspanne nicht ordnungsgemäß reagiert hat, oder
die hergestellte Verbindung war fehlerhaft, da der verbundene Host
nicht reagiert hat 192.168.123.254:8080
```
Which roughly translates to "cant connect to 192.168.123.254:8080"
The computer is part of an Active Directory. The AD-Server was installed on a network which uses 192.168.123.254 as a proxy. Now it is not reachable and should not be used.
**How do I prevent the IIS from using a proxy?**
I think it has something to do with policy settings for the Internet Explorer. An "old" AD user has this setting, but a newly created user does not. I checked all the group policy settings and nowhere is a proxy defined.
The web server is running in the context of the anonymous internet user account on the local computer. Do local users get settings from the AD? If so how can I change that setting, if I cant login as this user?
What can I do, where else i could check? | Proxy use can be configured in the web.config.
The system.net/defaultProxy element will let you specify whether a proxy is used by default or provide a bypass list.
For more info see: [<http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx>](http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx) |
61,262 | <p>Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file.<br>
Now you want to create a class or use a symbol which is defined in multiple namespaces,
e.g. <code>System.Windows.Controls.Image</code> & <code>System.Drawing.Image</code></p>
<p>Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here?</p>
<p><em>(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)</em></p>
| [
{
"answer_id": 61264,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 6,
"selected": true,
"text": "<p>Use alias</p>\n<pre><code>using System.Windows.Controls;\nusing Drawing = System.Drawing;\n\n...\n\nImage img = ... //System.Wi... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
] | Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file.
Now you want to create a class or use a symbol which is defined in multiple namespaces,
e.g. `System.Windows.Controls.Image` & `System.Drawing.Image`
Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here?
*(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)* | Use alias
```
using System.Windows.Controls;
using Drawing = System.Drawing;
...
Image img = ... //System.Windows.Controls.Image
Drawing.Image img2 = ... //System.Drawing.Image
```
[C# using directive](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive) |
61,278 | <p>What method do you use when you want to get performance data about specific code paths?</p>
| [
{
"answer_id": 61279,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 5,
"selected": true,
"text": "<p>This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] | What method do you use when you want to get performance data about specific code paths? | This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
2. It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
3. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
---
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with [DbgView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)), including how many times the code was executed (and the average time spent of course)).
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>
namespace scope_timer {
class time_collector : boost::noncopyable {
__int64 total;
LARGE_INTEGER start;
size_t times;
const TCHAR* name;
double cpu_frequency()
{ // cache the CPU frequency, which doesn't change.
static double ret = 0; // store as double so devision later on is floating point and not truncating
if (ret == 0) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
ret = static_cast<double>(freq.QuadPart);
}
return ret;
}
bool in_use;
public:
time_collector(const TCHAR* n)
: times(0)
, name(n)
, total(0)
, start(LARGE_INTEGER())
, in_use(false)
{
}
~time_collector()
{
std::basic_ostringstream<TCHAR> msg;
msg << _T("scope_timer> ") << name << _T(" called: ");
double seconds = total / cpu_frequency();
double average = seconds / times;
msg << times << _T(" times total time: ") << seconds << _T(" seconds ")
<< _T(" (avg ") << average <<_T(")\n");
OutputDebugString(msg.str().c_str());
}
void add_time(__int64 ticks)
{
total += ticks;
++times;
in_use = false;
}
bool aquire()
{
if (in_use)
return false;
in_use = true;
return true;
}
};
class one_time : boost::noncopyable {
LARGE_INTEGER start;
time_collector* collector;
public:
one_time(time_collector& tc)
{
if (tc.aquire()) {
collector = &tc;
QueryPerformanceCounter(&start);
}
else
collector = 0;
}
~one_time()
{
if (collector) {
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
collector->add_time(end.QuadPart - start.QuadPart);
}
}
};
}
// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
scope_timer::one_time st_one_time_##name(st_time_collector_##name)
``` |
61,307 | <p>I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?</p>
| [
{
"answer_id": 61279,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 5,
"selected": true,
"text": "<p>This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let ... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2665/"
] | I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it? | This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
2. It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
3. Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
---
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with [DbgView](http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)), including how many times the code was executed (and the average time spent of course)).
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>
namespace scope_timer {
class time_collector : boost::noncopyable {
__int64 total;
LARGE_INTEGER start;
size_t times;
const TCHAR* name;
double cpu_frequency()
{ // cache the CPU frequency, which doesn't change.
static double ret = 0; // store as double so devision later on is floating point and not truncating
if (ret == 0) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
ret = static_cast<double>(freq.QuadPart);
}
return ret;
}
bool in_use;
public:
time_collector(const TCHAR* n)
: times(0)
, name(n)
, total(0)
, start(LARGE_INTEGER())
, in_use(false)
{
}
~time_collector()
{
std::basic_ostringstream<TCHAR> msg;
msg << _T("scope_timer> ") << name << _T(" called: ");
double seconds = total / cpu_frequency();
double average = seconds / times;
msg << times << _T(" times total time: ") << seconds << _T(" seconds ")
<< _T(" (avg ") << average <<_T(")\n");
OutputDebugString(msg.str().c_str());
}
void add_time(__int64 ticks)
{
total += ticks;
++times;
in_use = false;
}
bool aquire()
{
if (in_use)
return false;
in_use = true;
return true;
}
};
class one_time : boost::noncopyable {
LARGE_INTEGER start;
time_collector* collector;
public:
one_time(time_collector& tc)
{
if (tc.aquire()) {
collector = &tc;
QueryPerformanceCounter(&start);
}
else
collector = 0;
}
~one_time()
{
if (collector) {
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
collector->add_time(end.QuadPart - start.QuadPart);
}
}
};
}
// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
scope_timer::one_time st_one_time_##name(st_time_collector_##name)
``` |
61,339 | <p>I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how?</p>
| [
{
"answer_id": 61452,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Ah, You have to use the UserProfileManager class.\nMore information here: <a href=\"http://msdn.microsoft.com/en-us/library/... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how? | Here is a code snippet that should help get the job done for you. You may need to do some additional validation to avoid any exceptions (ensuring the profile actually exists, ensuring the image URL actually exists, etc...):
```
//get current profile manager
UserProfileManager objUserProfileManager = new UserProfileManager(PortalContext.Current);
//get current users profile
UserProfile profile = objUserProfileManager.GetUserProfile(true);
//get user image URL
string imageUrl = (string)profile[PropertyConstants.PictureUrl];
//do something here with imageUrl
``` |
61,341 | <p>I remember back in the day with the old borland DOS compiler you could do something like this:</p>
<pre><code>asm {
mov ax,ex
etc etc...
}
</code></pre>
<p>Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me.</p>
| [
{
"answer_id": 61344,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p>A good start would be reading this article which talk about inline assembly in C/C++:</p>\n\n<p><a href=\"http://www.codeproj... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6062/"
] | I remember back in the day with the old borland DOS compiler you could do something like this:
```
asm {
mov ax,ex
etc etc...
}
```
Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me. | Using [GCC](http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html)
```
__asm__("movl %edx, %eax\n\t"
"addl $2, %eax\n\t");
```
Using [VC++](http://msdn.microsoft.com/en-us/library/4ks26t93(VS.71).aspx)
```
__asm {
mov eax, edx
add eax, 2
}
``` |
61,357 | <p>Should I still be using tables anyway?</p>
<p>The table code I'd be replacing is:</p>
<pre><code><table>
<tr>
<td>Name</td><td>Value</td>
</tr>
...
</table>
</code></pre>
<p>From what I've been reading I should have something like</p>
<pre><code><label class="name">Name</label><label class="value">Value</value><br />
...
</code></pre>
<p>Ideas and links to online samples greatly appreciated. I'm a developer way out of my design depth.</p>
<p>EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form.</p>
| [
{
"answer_id": 61360,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p>I think tables are best used for tabular data, which it seems you have there.</p>\n\n<p>If you do not want to use tables, the... | 2008/09/14 | [
"https://Stackoverflow.com/questions/61357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122/"
] | Should I still be using tables anyway?
The table code I'd be replacing is:
```
<table>
<tr>
<td>Name</td><td>Value</td>
</tr>
...
</table>
```
From what I've been reading I should have something like
```
<label class="name">Name</label><label class="value">Value</value><br />
...
```
Ideas and links to online samples greatly appreciated. I'm a developer way out of my design depth.
EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form. | I think that definition lists are pretty close semantically to name/value pairs.
```
<dl>
<dt>Name</dt>
<dd>Value</dd>
</dl>
```
[Definition lists - misused or misunderstood?](http://www.maxdesign.com.au/presentation/definition) |