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 |
|---|---|---|---|---|---|---|
141,146 | <p>I want to know if my server is running Subversion 1.5.</p>
<p>How can I find that out?</p>
<p>Also would be nice to know my SVN client version number. <code>svn help</code> hasn't been helpful.</p>
<p><strong>Note:</strong> I don't want my <em>project's</em> revision number, etc. This question is about the <em>Subversion software</em> itself.</p>
| [
{
"answer_id": 141479,
"author": "PiedPiper",
"author_id": 19315,
"author_profile": "https://Stackoverflow.com/users/19315",
"pm_score": 5,
"selected": false,
"text": "<p>For an HTTP-based server there is a Python script to find the server version at:\n<a href=\"http://svn.apache.org/rep... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I want to know if my server is running Subversion 1.5.
How can I find that out?
Also would be nice to know my SVN client version number. `svn help` hasn't been helpful.
**Note:** I don't want my *project's* revision number, etc. This question is about the *Subversion software* itself. | To find the version of the subversion REPOSITORY you can:
1. Look to the repository on the web and on the bottom of the page it will say something like:
"Powered by Subversion version 1.5.2 (r32768)."
2. From the command line: <insert curl, grep oneliner here>
If not displayed, view source of the page
```
<svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/">
```
Now for the subversion CLIENT:
```
svn --version
```
will suffice |
141,154 | <p>I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.</p>
| [
{
"answer_id": 141166,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 6,
"selected": false,
"text": "<p>You could query this registry value to get the SQL version directly:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWAR... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] | I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance. | At a command line:
```
SQLCMD -L
```
or
```
OSQL -L
```
(Note: must be a capital L)
This will list all the sql servers installed on your network. There are configuration options you can set to prevent a SQL Server from showing in the list. To do this...
At command line:
```
svrnetcn
```
In the enabled protocols list, select 'TCP/IP', then click properties. There is a check box for 'Hide server'. |
141,162 | <p>I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution). It can be system dependent for Linux (specifically Debian and/or Ubuntu).</p>
<p>I already have the PID I am looking for, just need to see if it is currently running.</p>
<hr>
<p>UPDATE:</p>
<p>Thanks for all the responses everyone! I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have.</p>
| [
{
"answer_id": 141165,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"https://stackoverflow.com/questions/138097/how-do-i-find-my-pid-in-java-or-jruby-on-linux#138098\">my ans... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution). It can be system dependent for Linux (specifically Debian and/or Ubuntu).
I already have the PID I am looking for, just need to see if it is currently running.
---
UPDATE:
Thanks for all the responses everyone! I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have. | [Darron's comment](https://stackoverflow.com/questions/141162/how-can-i-determine-if-a-different-process-id-is-running-using-java-or-jruby-on#141731) was spot on, but rather than calling the "kill" binary, you can just use Ruby's Process.kill method with the 0 signal:
```
#!/usr/bin/ruby
pid = ARGV[0].to_i
begin
Process.kill(0, pid)
puts "#{pid} is running"
rescue Errno::EPERM # changed uid
puts "No permission to query #{pid}!";
rescue Errno::ESRCH
puts "#{pid} is NOT running."; # or zombied
rescue
puts "Unable to determine status for #{pid} : #{$!}"
end
```
>
> [user@host user]$ ./is\_running.rb 14302
>
> 14302 is running
>
>
> [user@host user]$ ./is\_running.rb 99999
>
> 99999 is NOT running.
>
>
> [user@host user]$ ./is\_running.rb 37
>
> No permission to query 37!
>
>
> [user@host user]$ sudo ./is\_running.rb 37
>
> 37 is running
>
>
>
Reference: <http://pleac.sourceforge.net/pleac_ruby/processmanagementetc.html> |
141,169 | <p>So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page.</p>
<p>The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed.</p>
<p>I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this?</p>
<p>Thanks!</p>
| [
{
"answer_id": 141195,
"author": "Mike J",
"author_id": 4443,
"author_profile": "https://Stackoverflow.com/users/4443",
"pm_score": 1,
"selected": false,
"text": "<p>You need to re-add the dynamically created controls, in the onload, so that they can be in the page hierarchy and fire the... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19086/"
] | So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page.
The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed.
I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this?
Thanks! | This is my favorite trick :)
Our scenario is to first render a control. Then using some input from the user, render further controls and have them respond to events.
The key here is state - you need to know the state of the control when it arrives at PostBack - so we use ViewState. The issue becomes then a chicken-and-egg problem; ViewState isn't available until after the `LoadViewState()` call, but you must create the controls before that call to have the events fired correctly.
The trick is to override `LoadViewState()` and `SaveViewState()` so we can control things.
*(note that the code below is rough, from memory and probably has issues)*
```
private string searchQuery = null;
private void SearchButton(object sender, EventArgs e)
{
searchQuery = searchBox.Text;
var results = DataLayer.PerformSearch(searchQuery);
CreateLinkButtonControls(results);
}
// We save both the base state object, plus our query string. Everything here must be serializable.
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
return new object[] { baseState, searchQuery };
}
// The parameter to this method is the exact object we returned from SaveViewState().
protected override void LoadViewState(object savedState)
{
object[] stateArray = (object[])savedState;
searchQuery = stateArray[1] as string;
// Re-run the query
var results = DataLayer.PerformSearch(searchQuery);
// Re-create the exact same control tree as at the point of SaveViewState above. It must be the same otherwise things will break.
CreateLinkButtonControls(results);
// Very important - load the rest of the ViewState, including our controls above.
base.LoadViewState(stateArray[0]);
}
``` |
141,201 | <p>I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well.</p>
<p>I understand that establish_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work:</p>
<pre><code>class Foo < ActiveRecord::Base
establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end
</code></pre>
| [
{
"answer_id": 141314,
"author": "Terry G Lorber",
"author_id": 809,
"author_profile": "https://Stackoverflow.com/users/809",
"pm_score": 3,
"selected": false,
"text": "<p>Heh. I was right! More cleanly:</p>\n\n<pre><code>class Foo < ActiveRecord::Base\n establish_connection \"fo... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809/"
] | I'd like the canonical way to do this. My Google searches have come up short. I have one ActiveRecord model that should map to a different database than the rest of the application. I would like to store the new configurations in the database.yml file as well.
I understand that establish\_connection should be called, but it's not clear where. Here's what I got so far, and it doesn't work:
```
class Foo < ActiveRecord::Base
establish_connection(('foo_' + ENV['RAILS_ENV']).intern)
end
``` | Also, it is a good idea to subclass your model that uses different database, such as:
```
class AnotherBase < ActiveRecord::Base
self.abstract_class = true
establish_connection "anotherbase_#{RAILS_ENV}"
end
```
And in your model
```
class Foo < AnotherBase
end
```
It is useful when you need to add subsequent models that access the same, another database. |
141,203 | <p>I'm trying to grok the purpose of .NET's SecureString. From MSDN:</p>
<blockquote>
<p>An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.</p>
<p>A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.</p>
<p>The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.</p>
</blockquote>
<p>Is the automatic encryption the big payoff?</p>
<p>And why can't I just say:</p>
<pre><code>SecureString password = new SecureString("password");
</code></pre>
<p>instead of</p>
<pre><code>SecureString pass = new SecureString();
foreach (char c in "password".ToCharArray())
pass.AppendChar(c);
</code></pre>
<p>What aspect of SecureString am I missing?</p>
| [
{
"answer_id": 141213,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 2,
"selected": false,
"text": "<p>I guess it's because the string is meant to be secure, i.e. a hacker should not be able to read it. If you initiali... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2258/"
] | I'm trying to grok the purpose of .NET's SecureString. From MSDN:
>
> An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory.
>
>
> A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.
>
>
> The value of an instance of SecureString is automatically encrypted when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the MakeReadOnly method.
>
>
>
Is the automatic encryption the big payoff?
And why can't I just say:
```
SecureString password = new SecureString("password");
```
instead of
```
SecureString pass = new SecureString();
foreach (char c in "password".ToCharArray())
pass.AppendChar(c);
```
What aspect of SecureString am I missing? | I would stop using SecureString . Looks like PG guys are dropping support for it. Possibly even pull it in the future - <https://github.com/dotnet/apireviews/tree/master/2015-07-14-securestring> .
>
> We should remove encryption from SecureString across all platforms in .NET Core - We should obsolete SecureString - We probably shouldn't expose SecureString in .NET Core
>
>
> |
141,204 | <p>I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here.</p>
<p>Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately?</p>
<pre><code>public class SomeDataClass : IDisposable
{
private SqlConnection _conn;
//constructors and methods
private DoSomethingWithTheSqlConnection()
{
//some code excluded for brevity
try
{
using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
finally
{
//is this the best way?
if (_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//some code excluded for brevity
}
public Dispose()
{
_conn.Dispose();
}
}
</code></pre>
| [
{
"answer_id": 141215,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 7,
"selected": true,
"text": "<p>Wrap your database handling code inside a \"using\"</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection (...))... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] | I use a pattern that looks something like this often. I'm wondering if this is alright or if there is a best practice that I am not applying here.
Specifically I'm wondering; in the case that an exception is thrown is the code that I have in the finally block enough to ensure that the connection is closed appropriately?
```
public class SomeDataClass : IDisposable
{
private SqlConnection _conn;
//constructors and methods
private DoSomethingWithTheSqlConnection()
{
//some code excluded for brevity
try
{
using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
{
_SqlConnection.Open();
countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
}
}
finally
{
//is this the best way?
if (_SqlConnection.State == ConnectionState.Closed)
_SqlConnection.Close();
}
//some code excluded for brevity
}
public Dispose()
{
_conn.Dispose();
}
}
``` | Wrap your database handling code inside a "using"
```
using (SqlConnection conn = new SqlConnection (...))
{
// Whatever happens in here, the connection is
// disposed of (closed) at the end.
}
``` |
141,241 | <p>I've seen reference in some C# posted questions to a "using" clause.
Does java have the equivalent?</p>
| [
{
"answer_id": 141267,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 6,
"selected": true,
"text": "<p>Yes. Java 1.7 introduced the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] | I've seen reference in some C# posted questions to a "using" clause.
Does java have the equivalent? | Yes. Java 1.7 introduced the [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) construct allowing you to write:
```
try(InputStream is1 = new FileInputStream("/tmp/foo");
InputStream is2 = new FileInputStream("/tmp/bar")) {
/* do stuff with is1 and is2 */
}
```
... just like a `using` statement.
Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:
```
InputStream is1 = new FileInputStream("/tmp/foo");
try{
InputStream is2 = new FileInputStream("/tmp/bar");
try{
/* do stuff with is1 and is 2 */
} finally {
is2.close();
}
} finally {
is1.close();
}
``` |
141,251 | <p>This is really annoying, we've switched our client downloads page to a different site and want to send a link out with our installer. When the link is created and overwrites the existing file, the metadata in windows XP still points to the same place even though the contents of the .url shows the correct address. I can change that URL property to google.com and it points to the same place when I copy over the file. </p>
<pre>
[InternetShortcut]
URL=https://www.xxxx.com/?goto=clientlogon.php
IDList=
HotKey=0
</pre>
<p>It works if we rename our link .url file. But we expect that the directory will be reused and that would result in one bad link and one good link which is more confusing than it is cool. </p>
| [
{
"answer_id": 144213,
"author": "DougN",
"author_id": 7442,
"author_profile": "https://Stackoverflow.com/users/7442",
"pm_score": 1,
"selected": false,
"text": "<p>.URL files are wierd (are they documented anywhere?)</p>\n\n<p>Mine look like this and I don't seem to have that problem (m... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] | This is really annoying, we've switched our client downloads page to a different site and want to send a link out with our installer. When the link is created and overwrites the existing file, the metadata in windows XP still points to the same place even though the contents of the .url shows the correct address. I can change that URL property to google.com and it points to the same place when I copy over the file.
```
[InternetShortcut]
URL=https://www.xxxx.com/?goto=clientlogon.php
IDList=
HotKey=0
```
It works if we rename our link .url file. But we expect that the directory will be reused and that would result in one bad link and one good link which is more confusing than it is cool. | Take a look at here: <http://www.cyanwerks.com/file-format-url.html>
It explains there's a Modified field you can add to the .url file. It also explains how to interpret it. |
141,278 | <p>I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like:</p>
<pre><code>WHERE id IN (SELECT id FROM ...)
</code></pre>
<p><strong>The refactored query runs about 100x faster.</strong> (~50 seconds to ~0.3) I expected an improvement, but can anyone explain why it was so drastic? The columns used in the where clause were all indexed. Does SQL execute the query in the where clause once per row or something?</p>
<p><strong>Update</strong> - Explain results:</p>
<p>The difference is in the second part of the "where id in ()" query - </p>
<pre><code>2 DEPENDENT SUBQUERY submission_tags ref st_tag_id st_tag_id 4 const 2966 Using where
</code></pre>
<p>vs 1 indexed row with the join:</p>
<pre><code> SIMPLE s eq_ref PRIMARY PRIMARY 4 newsladder_production.st.submission_id 1 Using index
</code></pre>
| [
{
"answer_id": 141290,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "<p>Look at the query plan for each query.</p>\n\n<p><em>Where in</em> and <em>Join</em> can <strong>typically</strong> be impl... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521/"
] | I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like:
```
WHERE id IN (SELECT id FROM ...)
```
**The refactored query runs about 100x faster.** (~50 seconds to ~0.3) I expected an improvement, but can anyone explain why it was so drastic? The columns used in the where clause were all indexed. Does SQL execute the query in the where clause once per row or something?
**Update** - Explain results:
The difference is in the second part of the "where id in ()" query -
```
2 DEPENDENT SUBQUERY submission_tags ref st_tag_id st_tag_id 4 const 2966 Using where
```
vs 1 indexed row with the join:
```
SIMPLE s eq_ref PRIMARY PRIMARY 4 newsladder_production.st.submission_id 1 Using index
``` | A "correlated subquery" (i.e., one in which the where condition depends on values obtained from the rows of the containing query) will execute once for each row. A non-correlated subquery (one in which the where condition is independent of the containing query) will execute once at the beginning. The SQL engine makes this distinction automatically.
But, yeah, explain-plan will give you the dirty details. |
141,280 | <p>What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that. </p>
<p>Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive.</p>
| [
{
"answer_id": 141311,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 1,
"selected": false,
"text": "<p>Try to split you string on words and count the resulting words, then sort on the counts.</p>\n"
},
{
"answer_id... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] | What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't mind if you'd like to share code as well. If there are particular functions that would help, I'd also appreciate that.
Right now I think I'm at using the split() function to separate the string by spaces and then cleaning punctuation out with a regular expression. I'd also want it to be case-insensitive. | Cut, paste + execute demo:
```
var text = "Text to be examined to determine which n words are used the most";
// Find 'em!
var wordRegExp = /\w+(?:'\w{1,2})?/g;
var words = {};
var matches;
while ((matches = wordRegExp.exec(text)) != null)
{
var word = matches[0].toLowerCase();
if (typeof words[word] == "undefined")
{
words[word] = 1;
}
else
{
words[word]++;
}
}
// Sort 'em!
var wordList = [];
for (var word in words)
{
if (words.hasOwnProperty(word))
{
wordList.push([word, words[word]]);
}
}
wordList.sort(function(a, b) { return b[1] - a[1]; });
// Come back any time, straaanger!
var n = 10;
var message = ["The top " + n + " words are:"];
for (var i = 0; i < n; i++)
{
message.push(wordList[i][0] + " - " + wordList[i][1] + " occurance" +
(wordList[i][1] == 1 ? "" : "s"));
}
alert(message.join("\n"));
```
Reusable function:
```
function getTopNWords(text, n)
{
var wordRegExp = /\w+(?:'\w{1,2})?/g;
var words = {};
var matches;
while ((matches = wordRegExp.exec(text)) != null)
{
var word = matches[0].toLowerCase();
if (typeof words[word] == "undefined")
{
words[word] = 1;
}
else
{
words[word]++;
}
}
var wordList = [];
for (var word in words)
{
if (words.hasOwnProperty(word))
{
wordList.push([word, words[word]]);
}
}
wordList.sort(function(a, b) { return b[1] - a[1]; });
var topWords = [];
for (var i = 0; i < n; i++)
{
topWords.push(wordList[i][0]);
}
return topWords;
}
``` |
141,288 | <p>Is it possible to use the Flex Framework and Components, without using MXML? I know ActionScript pretty decently, and don't feel like messing around with some new XML language just to get some simple UI in there. Can anyone provide an example consisting of an .as file which can be compiled (ideally via FlashDevelop, though just telling how to do it with the Flex SDK is ok too) and uses the Flex Framework? For example, just showing a Flex button that pops open an Alert would be perfect.</p>
<p>If it's not possible, can someone provide a minimal MXML file which will bootstrap a custom AS class which then has access to the Flex SDK?</p>
| [
{
"answer_id": 141488,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you just need to include the flex swc in your classpath. You can find flex.swc in the flex sdk in frameoworks/lib/flex... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] | Is it possible to use the Flex Framework and Components, without using MXML? I know ActionScript pretty decently, and don't feel like messing around with some new XML language just to get some simple UI in there. Can anyone provide an example consisting of an .as file which can be compiled (ideally via FlashDevelop, though just telling how to do it with the Flex SDK is ok too) and uses the Flex Framework? For example, just showing a Flex button that pops open an Alert would be perfect.
If it's not possible, can someone provide a minimal MXML file which will bootstrap a custom AS class which then has access to the Flex SDK? | I did a simple bootstrap similar to Borek (see below). I would love to get rid of the mxml file, but if I don't have it, I don't get any of the standard themes that come with Flex (haloclassic.swc, etc). Does anybody know how to do what Theo suggests and still have the standard themes applied?
Here's my simplified bootstrapping method:
main.mxml
```
<?xml version="1.0" encoding="utf-8"?>
<custom:ApplicationClass xmlns:custom="components.*"/>
```
ApplicationClass.as
```
package components {
import mx.core.Application;
import mx.events.FlexEvent;
import flash.events.MouseEvent;
import mx.controls.Alert;
import mx.controls.Button;
public class ApplicationClass extends Application {
public function ApplicationClass () {
addEventListener (FlexEvent.CREATION_COMPLETE, handleComplete);
}
private function handleComplete( event : FlexEvent ) : void {
var button : Button = new Button();
button.label = "My favorite button";
button.styleName="halo"
button.addEventListener(MouseEvent.CLICK, handleClick);
addChild( button );
}
private function handleClick(e:MouseEvent):void {
Alert.show("You clicked on the button!", "Clickity");
}
}
}
```
---
Here are the necessary updates to use it with Flex 4:
main.mxml
```
<?xml version="1.0" encoding="utf-8"?>
<local:MyApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:local="components.*" />
```
MyApplication.as
```
package components {
import flash.events.MouseEvent;
import mx.controls.Alert;
import mx.events.FlexEvent;
import spark.components.Application;
import spark.components.Button;
public class MyApplication extends Application {
public function MyApplication() {
addEventListener(FlexEvent.CREATION_COMPLETE, creationHandler);
}
private function creationHandler(e:FlexEvent):void {
var button : Button = new Button();
button.label = "My favorite button";
button.styleName="halo"
button.addEventListener(MouseEvent.CLICK, handleClick);
addElement( button );
}
private function handleClick(e:MouseEvent):void {
Alert.show("You clicked it!", "Clickity!");
}
}
}
``` |
141,291 | <p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
| [
{
"answer_id": 141313,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 4,
"selected": false,
"text": "<pre><code>directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]\n</code></pre>\n"
},
{
"answer_id... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] | I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.
Let's see if an example helps. In the current directory we have:
```
>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
```
However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:
```
>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
```
However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much. | Filter the result using os.path.isdir() (and use os.path.join() to get the real path):
```
>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
``` |
141,302 | <p>Is there a way to check if a file has been opened by ReWrite in Delphi? </p>
<p>Code would go something like this:</p>
<pre><code>AssignFile(textfile, 'somefile.txt');
if not textFile.IsOpen then
Rewrite(textFile);
</code></pre>
| [
{
"answer_id": 141339,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 5,
"selected": true,
"text": "<p>You can get the filemode. (One moment, I'll create an example).</p>\n\n<p>TTextRec(txt).Mode gives you the mode:</p... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075/"
] | Is there a way to check if a file has been opened by ReWrite in Delphi?
Code would go something like this:
```
AssignFile(textfile, 'somefile.txt');
if not textFile.IsOpen then
Rewrite(textFile);
``` | You can get the filemode. (One moment, I'll create an example).
TTextRec(txt).Mode gives you the mode:
```
55216 = closed
55217 = open read
55218 = open write
fmClosed = $D7B0;
fmInput = $D7B1;
fmOutput = $D7B2;
fmInOut = $D7B3;
```
Search TTextRec in the system unit for more information. |
141,315 | <p>Is there a way to check to see if a date/time is valid you would think these would be easy to check:</p>
<pre><code>$date = '0000-00-00';
$time = '00:00:00';
$dateTime = $date . ' ' . $time;
if(strtotime($dateTime)) {
// why is this valid?
}
</code></pre>
<p>what really gets me is this:</p>
<pre><code>echo date('Y-m-d', strtotime($date));
</code></pre>
<p>results in: "1999-11-30",</p>
<p>huh? i went from 0000-00-00 to 1999-11-30 ???</p>
<p>I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?</p>
<p>Edit:
People are asking what i'm running:
Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux</p>
| [
{
"answer_id": 141341,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>echo date('Y-m-d', strtotime($date));</p>\n \n <p>results in: \"1999-11-30\"</p>\n</blockquote>\n\n<p>T... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] | Is there a way to check to see if a date/time is valid you would think these would be easy to check:
```
$date = '0000-00-00';
$time = '00:00:00';
$dateTime = $date . ' ' . $time;
if(strtotime($dateTime)) {
// why is this valid?
}
```
what really gets me is this:
```
echo date('Y-m-d', strtotime($date));
```
results in: "1999-11-30",
huh? i went from 0000-00-00 to 1999-11-30 ???
I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?
Edit:
People are asking what i'm running:
Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux | From [php.net](http://php.net/manual/en/function.checkdate.php#78362)
```
<?php
function isValidDateTime($dateTime)
{
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
?>
``` |
141,332 | <p>I'm writing some server code that talks to a client process via STDIN. I'm trying to write a snippet of perl code that asynchronously receives responses from the client's STDOUT. The blocking version of the code might look like this:</p>
<pre><code>sub _read_from_client
{
my ($file_handle) = @_;
while (my $line = <$file_handle>) {
print STDOUT $line;
}
return;
}
</code></pre>
<p>Importantly, the snippet needs to work in Win32 platform. There are many solutions for *nix platforms that I'm not interested in. I'm using ActivePerl 5.10.</p>
| [
{
"answer_id": 141770,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.perlmonks.org/?node_id=529812\" rel=\"nofollow noreferrer\">This thread</a> on <a href=\"http://www.per... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7045/"
] | I'm writing some server code that talks to a client process via STDIN. I'm trying to write a snippet of perl code that asynchronously receives responses from the client's STDOUT. The blocking version of the code might look like this:
```
sub _read_from_client
{
my ($file_handle) = @_;
while (my $line = <$file_handle>) {
print STDOUT $line;
}
return;
}
```
Importantly, the snippet needs to work in Win32 platform. There are many solutions for \*nix platforms that I'm not interested in. I'm using ActivePerl 5.10. | [This thread](http://www.perlmonks.org/?node_id=529812) on [Perlmonks](http://www.perlmonks.org) suggests you can make a socket nonblocking on Windows in Perl this way:
```
ioctl($socket, 0x8004667e, 1);
```
More details and resources in that thread |
141,344 | <p>How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one.</p>
<p>Is there a better way of doing this? Something like <a href="https://ss64.com/nt/find.html" rel="nofollow noreferrer">FIND</a> or <a href="https://ss64.com/nt/findstr.html" rel="nofollow noreferrer">FINDSTR</a> operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.</p>
<pre><code>FOR /F "delims=;" %%P IN ("%PATH%") DO (
@ECHO %%~P
)
</code></pre>
| [
{
"answer_id": 141385,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 5,
"selected": false,
"text": "<p>This may work:</p>\n<pre><code>echo ;%PATH%; | find /C /I ";<string>;"\n</code></pre>\n<p>It should give yo... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16605/"
] | How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one.
Is there a better way of doing this? Something like [FIND](https://ss64.com/nt/find.html) or [FINDSTR](https://ss64.com/nt/findstr.html) operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.
```
FOR /F "delims=;" %%P IN ("%PATH%") DO (
@ECHO %%~P
)
``` | First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.
For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.
From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:
1. **The trailing `\` is optional in a path**
Most paths work equally well both with and without the trailing `\`. The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing `\`. This is probably the most common practical issue when searching a PATH for a match.
* There is one exception: The relative path `C:` (meaning the current working directory of drive C) is very different than `C:\` (meaning the root directory of drive C)
2. **Some paths have alternate short names**
Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.
3. **Windows accepts both `/` and `\` as folder separators within a path.**
This is not seen very often, but a path can be specified using `/` instead of `\` and it will function just fine within PATH (as well as in many other Windows contexts)
4. **Windows treats consecutive folder separators as one logical separator.**
C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append `\` to a path without bothering to check if the trailing `\` already exists. But this obviously can cause problems if trying to perform an exact string match.
* Exceptions: Not only is `C:`, different than `C:\`, but `C:\` (a valid path), is different than `C:\\` (an invalid path).
5. **Windows trims trailing dots and spaces from file and directory names.**
`"C:\test. "` is equivalent to `"C:\test"`.
6. **The current `.\` and parent `..\` folder specifiers may appear within a path**
Unlikely to be seen in real life, but something like `C:\.\parent\child\..\.\child\` is equivalent to `C:\parent\child`
7. **A path can optionally be enclosed within double quotes.**
A path is often enclosed in quotes to protect against special characters like `<space>` `,` `;` `^` `&` `=`. Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a `;`, but the quotes may be present never-the-less.
8. **A path may be fully qualified or relative.**
A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths:
* **`D:`** is relative to the current working directory of volume D:
* **`\myPath`** is relative to the current working volume (could be C:, D: etc.)
* **`myPath`** is relative to the current working volume and directoryIt is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain `.\`. But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.
So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The `~s` modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 - 6, and partially addresses issue 7. The `~s` modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the `~s` modifier will not append the `\` to the path, nor will it convert the path into a valid 8.3 format.
The problem with `~s` is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with `<letter>:<separator>` but not `<letter>:<separator><separator>`, where <separator> is either `\` or `/`. UNC paths are always fully qualified and must start with `\\`. When comparing fully qualified paths we use the `~s` modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.
There are some additional issues that complicate this problem:
9) **Normal expansion is not reliable when dealing with a PATH that contains special characters.**
Special characters do not need to be quoted within PATH, but they could be. So a PATH like
`C:\THIS & THAT;"C:\& THE OTHER THING"` is perfectly valid, but it cannot be expanded safely using simple expansion because both `"%PATH%"` and `%PATH%` will fail.
10) **The path delimiter is also valid within a path name**
A `;` is used to delimit paths within PATH, but `;` can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.
jeb solved both issues 9 and 10 at ['Pretty print' windows %PATH% variable - how to split on ';' in CMD shell](https://stackoverflow.com/questions/5471556/pretty-print-windows-path-variable-how-to-split-on-in-cmd-shell/5472168#5472168)
So we can combine the `~s` modifier and path classification techniques along with my variation of jeb's PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.
```
@echo off
:inPath pathVar
::
:: Tests if the path stored within variable pathVar exists within PATH.
::
:: The result is returned as the ERRORLEVEL:
:: 0 if the pathVar path is found in PATH.
:: 1 if the pathVar path is not found in PATH.
:: 2 if pathVar is missing or undefined or if PATH is undefined.
::
:: If the pathVar path is fully qualified, then it is logically compared
:: to each fully qualified path within PATH. The path strings don't have
:: to match exactly, they just need to be logically equivalent.
::
:: If the pathVar path is relative, then it is strictly compared to each
:: relative path within PATH. Case differences and double quotes are
:: ignored, but otherwise the path strings must match exactly.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then do
:: proper comparison with pathVar.
:: Exit with ERRORLEVEL 0 if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
if "!!"=="" endlocal
for %%C in ("%%~B\") do (
echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
|| (if %abs%==0 if /i "%%~A"=="%%~C" exit /b 0)
)
)
:: No match was found so exit with ERRORLEVEL 1
exit /b 1
```
The function can be used like so (assuming the batch file is named inPath.bat):
```
set test=c:\mypath
call inPath test && (echo found) || (echo not found)
```
Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped `!` will corrupt the value if delayed expansion is enabled.
These problems are resolved using an amazing safe return technique that jeb invented here: <http://www.dostips.com/forum/viewtopic.php?p=6930#p6930>
```
@echo off
:addPath pathVar /B
::
:: Safely appends the path contained within variable pathVar to the end
:: of PATH if and only if the path does not already exist within PATH.
::
:: If the case insensitive /B option is specified, then the path is
:: inserted into the front (Beginning) of PATH instead.
::
:: If the pathVar path is fully qualified, then it is logically compared
:: to each fully qualified path within PATH. The path strings are
:: considered a match if they are logically equivalent.
::
:: If the pathVar path is relative, then it is strictly compared to each
:: relative path within PATH. Case differences and double quotes are
:: ignored, but otherwise the path strings must match exactly.
::
:: Before appending the pathVar path, all double quotes are stripped, and
:: then the path is enclosed in double quotes if and only if the path
:: contains at least one semicolon.
::
:: addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined
:: or if PATH is undefined.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Determine if function was called while delayed expansion was enabled
setlocal
set "NotDelayed=!"
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"^=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then
:: do proper comparison with pathVar. Exit if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
if "!!"=="" setlocal disableDelayedExpansion
for %%C in ("%%~B\") do (
echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
|| (if %abs%==0 if /i %%A==%%C exit /b 0)
)
)
::
:: Build the modified PATH, enclosing the added path in quotes
:: only if it contains ;
setlocal enableDelayedExpansion
if "!new:;=!" neq "!new!" set new="!new!"
if /i "%~2"=="/B" (set "rtn=!new!;!path!") else set "rtn=!path!;!new!"
::
:: rtn now contains the modified PATH. We need to safely pass the
:: value accross the ENDLOCAL barrier
::
:: Make rtn safe for assignment using normal expansion by replacing
:: % and " with not yet defined FOR variables
set "rtn=!rtn:%%=%%A!"
set "rtn=!rtn:"=%%B!"
::
:: Escape ^ and ! if function was called while delayed expansion was enabled.
:: The trailing ! in the second assignment is critical and must not be removed.
if not defined NotDelayed set "rtn=!rtn:^=^^^^!"
if not defined NotDelayed set "rtn=%rtn:!=^^^!%" !
::
:: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to
:: restore the % and " characters. Again the trailing ! is critical.
for /f "usebackq tokens=1,2" %%A in ('%%^ ^"') do (
endlocal & endlocal & endlocal & endlocal & endlocal
set "path=%rtn%" !
)
exit /b 0
``` |
141,345 | <p>I have a xsl file that is grabbing variables from xml and they seem to not be able to see each other. I know it is a scope issue, I just do not know what I am doing wrong.</p>
<pre><code><xsl:template match="one">
<xsl:variable name="varOne" select="@count" />
</xsl:template>
<xsl:template match="two">
<xsl:if test="$varOne = 'Y'">
<xsl:value-of select="varTwo"/>
</xsl:if>
</xsl:template>
</code></pre>
<p>This has been simplified for here.</p>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 141364,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 2,
"selected": false,
"text": "<p>I'm fairly certain that variables are scoped and therefore you can't declare a variable in one and then use it in th... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16354/"
] | I have a xsl file that is grabbing variables from xml and they seem to not be able to see each other. I know it is a scope issue, I just do not know what I am doing wrong.
```
<xsl:template match="one">
<xsl:variable name="varOne" select="@count" />
</xsl:template>
<xsl:template match="two">
<xsl:if test="$varOne = 'Y'">
<xsl:value-of select="varTwo"/>
</xsl:if>
</xsl:template>
```
This has been simplified for here.
Any help is appreciated. | Remembering that xsl variables are immutable...
```
<!-- You may want to use absolute path -->
<xsl:variable name="varOne" select="one/@count" />
<xsl:template match="one">
<!-- // do something -->
</xsl:template>
<xsl:template match="two">
<xsl:if test="$varOne = 'Y'">
<xsl:value-of select="varTwo"/>
</xsl:if>
</xsl:template>
``` |
141,348 | <p>I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript <code>Date()</code> object so I can easily perform comparisons and other things on it.</p>
<p>I tried the <code>parse()</code> method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same <code>Date()</code> object:</p>
<ul>
<li>1:00 pm</li>
<li>1:00 p.m.</li>
<li>1:00 p</li>
<li>1:00pm</li>
<li>1:00p.m.</li>
<li>1:00p</li>
<li>1 pm</li>
<li>1 p.m.</li>
<li>1 p</li>
<li>1pm</li>
<li>1p.m.</li>
<li>1p</li>
<li>13:00</li>
<li>13</li>
</ul>
<p>I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my <code>Date()</code> object. What is the best way to do this?</p>
| [
{
"answer_id": 141383,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 5,
"selected": false,
"text": "<p>Don't bother doing it yourself, just use <a href=\"http://www.datejs.com/\" rel=\"noreferrer\">datejs</a>.</p>\n"
},
{
... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18986/"
] | I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript `Date()` object so I can easily perform comparisons and other things on it.
I tried the `parse()` method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same `Date()` object:
* 1:00 pm
* 1:00 p.m.
* 1:00 p
* 1:00pm
* 1:00p.m.
* 1:00p
* 1 pm
* 1 p.m.
* 1 p
* 1pm
* 1p.m.
* 1p
* 13:00
* 13
I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my `Date()` object. What is the best way to do this? | A quick solution which works on the input that you've specified:
```js
function parseTime( t ) {
var d = new Date();
var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ );
d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) );
d.setMinutes( parseInt( time[2]) || 0 );
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
```
It should work for a few other varieties as well (even if a.m. is used, it'll still work - for example). Obviously this is pretty crude but it's also pretty lightweight (much cheaper to use that than a full library, for example).
>
> Warning: The code doe not work with 12:00 AM, etc.
>
>
> |
141,351 | <p>My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a <a href="https://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a> (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.</p>
<p>What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. <a href="https://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection">How do I get a core dump of a python process like this?</a> Once I have one, how do I do something useful with it?</p>
| [
{
"answer_id": 142138,
"author": "joeld",
"author_id": 19104,
"author_profile": "https://Stackoverflow.com/users/19104",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know how to dump an entire python interpreter state and restore it. It would be useful, I'll keep my eye on this ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9585/"
] | My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a [Python memory profiler](https://stackoverflow.com/questions/110259/python-memory-profiler) (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.
What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get\_objects), and then analyze it offline to see where it is using memory. [How do I get a core dump of a python process like this?](https://stackoverflow.com/questions/141802/how-do-i-dump-an-entire-python-process-for-later-debugging-inspection) Once I have one, how do I do something useful with it? | I will expand on Brett's answer from my recent experience. [Dozer package](https://pypi.org/project/Dozer/) is [well maintained](https://github.com/mgedmin/dozer), and despite advancements, like addition of `tracemalloc` to stdlib in Python 3.4, its `gc.get_objects` counting chart is my go-to tool to tackle memory leaks. Below I use `dozer > 0.7` which has not been released at the time of writing (well, because I contributed a couple of fixes there recently).
Example
=======
Let's look at a non-trivial memory leak. I'll use [Celery](http://www.celeryproject.org/) 4.4 here and will eventually uncover a feature which causes the leak (and because it's a bug/feature kind of thing, it can be called mere misconfiguration, cause by ignorance). So there's a Python 3.6 *venv* where I `pip install celery < 4.5`. And have the following module.
*demo.py*
```
import time
import celery
redis_dsn = 'redis://localhost'
app = celery.Celery('demo', broker=redis_dsn, backend=redis_dsn)
@app.task
def subtask():
pass
@app.task
def task():
for i in range(10_000):
subtask.delay()
time.sleep(0.01)
if __name__ == '__main__':
task.delay().get()
```
Basically a task which schedules a bunch of subtasks. What can go wrong?
I'll use [`procpath`](https://pypi.org/project/Procpath/) to analyse Celery node memory consumption. `pip install procpath`. I have 4 terminals:
1. `procpath record -d celery.sqlite -i1 "$..children[?('celery' in @.cmdline)]"` to record the Celery node's process tree stats
2. `docker run --rm -it -p 6379:6379 redis` to run Redis which will serve as Celery broker and result backend
3. `celery -A demo worker --concurrency 2` to run the node with 2 workers
4. `python demo.py` to finally run the example
(4) will finish under 2 minutes.
Then I use [sqliteviz](https://github.com/lana-k/sqliteviz) ([pre-built version](https://lana-k.github.io/sqliteviz/)) to visualise what `procpath` has recorder. I drop the `celery.sqlite` there and use this query:
```
SELECT datetime(ts, 'unixepoch', 'localtime') ts, stat_pid, stat_rss / 256.0 rss
FROM record
```
And in sqliteviz I create a line chart trace with `X=ts`, `Y=rss`, and add split transform `By=stat_pid`. The result chart is:
[](https://i.stack.imgur.com/US20P.png)
This shape is likely pretty familiar to anyone who fought with memory leaks.
Finding leaking objects
=======================
Now it's time for `dozer`. I'll show non-instrumented case (and you can instrument your code in similar way if you can). To inject Dozer server into target process I'll use [Pyrasite](https://pypi.org/project/pyrasite/). There are two things to know about it:
* To run it, [ptrace](http://man7.org/linux/man-pages/man2/ptrace.2.html) has to be configured as "classic ptrace permissions": `echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope`, which is may be a security risk
* There are non-zero chances that your target Python process will crash
With that caveat I:
* `pip install https://github.com/mgedmin/dozer/archive/3ca74bd8.zip` (that's to-be 0.8 I mentioned above)
* `pip install pillow` (which `dozer` uses for charting)
* `pip install pyrasite`
After that I can get Python shell in the target process:
```
pyrasite-shell 26572
```
And inject the following, which will run Dozer's WSGI application using stdlib's `wsgiref`'s server.
```
import threading
import wsgiref.simple_server
import dozer
def run_dozer():
app = dozer.Dozer(app=None, path='/')
with wsgiref.simple_server.make_server('', 8000, app) as httpd:
print('Serving Dozer on port 8000...')
httpd.serve_forever()
threading.Thread(target=run_dozer, daemon=True).start()
```
Opening `http://localhost:8000` in a browser there should see something like:
[](https://i.stack.imgur.com/5hDUb.png)
After that I run `python demo.py` from (4) again and wait for it to finish. Then in Dozer I set "Floor" to 5000, and here's what I see:
[](https://i.stack.imgur.com/VoTDD.png)
Two types related to Celery grow as the subtask are scheduled:
* `celery.result.AsyncResult`
* `vine.promises.promise`
`weakref.WeakMethod` has the same shape and numbers and must be caused by the same thing.
Finding root cause
==================
At this point from the leaking types and the trends it may be already clear what's going on in your case. If it's not, Dozer has "TRACE" link per type, which allows tracing (e.g. seeing object's attributes) chosen object's referrers (`gc.get_referrers`) and referents (`gc.get_referents`), and continue the process again traversing the graph.
But a picture says a thousand words, right? So I'll show how to use [`objgraph`](https://pypi.org/project/objgraph/) to render chosen object's dependency graph.
* `pip install objgraph`
* `apt-get install graphviz`
Then:
* I run `python demo.py` from (4) again
* in Dozer I set `floor=0`, `filter=AsyncResult`
* and click "TRACE" which should yield
[](https://i.stack.imgur.com/GRp77.png)
Then in Pyrasite shell run:
```
objgraph.show_backrefs([objgraph.at(140254427663376)], filename='backref.png')
```
The PNG file should contain:
[](https://i.stack.imgur.com/TrU1M.png)
Basically there's some `Context` object containing a `list` called `_children` that in turn is containing many instances of `celery.result.AsyncResult`, which leak. Changing `Filter=celery.*context` in Dozer here's what I see:
[](https://i.stack.imgur.com/sIplB.png)
So the culprit is `celery.app.task.Context`. Searching that type would certainly lead you to [Celery task page](https://docs.celeryproject.org/en/stable/reference/celery.app.task.html). Quickly searching for "children" there, here's what it says:
>
> `trail = True`
>
>
> If enabled the request will keep track of subtasks started by this task, and this information will be sent with the result (`result.children`).
>
>
>
Disabling the trail by setting `trail=False` like:
```
@app.task(trail=False)
def task():
for i in range(10_000):
subtask.delay()
time.sleep(0.01)
```
Then restarting the Celery node from (3) and `python demo.py` from (4) yet again, shows this memory consumption.
[](https://i.stack.imgur.com/CzTin.png)
Problem solved! |
141,368 | <p>Given two datetimes. What is the best way to calculate the number of working hours between them. Considering the working hours are Mon 8 - 5.30, and Tue-Fri 8.30 - 5.30, and that potentially any day could be a public holiday.</p>
<p>This is my effort, seem hideously inefficient but in terms of the number of iterations and that the IsWorkingDay method hits the DB to see if that datetime is a public holiday.</p>
<p>Can anyone suggest any optimizations or alternatives.</p>
<pre><code> public decimal ElapsedWorkingHours(DateTime start, DateTime finish)
{
decimal counter = 0;
while (start.CompareTo(finish) <= 0)
{
if (IsWorkingDay(start) && IsOfficeHours(start))
{
start = start.AddMinutes(1);
counter++;
}
else
{
start = start.AddMinutes(1);
}
}
decimal hours;
if (counter != 0)
{
hours = counter/60;
}
return hours;
}
</code></pre>
| [
{
"answer_id": 141384,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>especially considering the IsWorkingDay method hits the DB to see if that day is a public holiday</... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] | Given two datetimes. What is the best way to calculate the number of working hours between them. Considering the working hours are Mon 8 - 5.30, and Tue-Fri 8.30 - 5.30, and that potentially any day could be a public holiday.
This is my effort, seem hideously inefficient but in terms of the number of iterations and that the IsWorkingDay method hits the DB to see if that datetime is a public holiday.
Can anyone suggest any optimizations or alternatives.
```
public decimal ElapsedWorkingHours(DateTime start, DateTime finish)
{
decimal counter = 0;
while (start.CompareTo(finish) <= 0)
{
if (IsWorkingDay(start) && IsOfficeHours(start))
{
start = start.AddMinutes(1);
counter++;
}
else
{
start = start.AddMinutes(1);
}
}
decimal hours;
if (counter != 0)
{
hours = counter/60;
}
return hours;
}
``` | Before you start optimizing it, ask yourself two questions.
a) Does it work?
b) Is it too slow?
Only if the answer to both question is "yes" are you ready to start optimizing.
Apart from that
* you only need to worry about minutes and hours on the start day and end day. Intervening days will obviously be a full 9/9.5 hours, unless they are holidays or weekends
* No need to check a weekend day to see if it's a holiday
Here's how I'd do it
```
// Normalise start and end
while start.day is weekend or holiday, start.day++, start.time = 0.00am
if start.day is monday,
start.time = max(start.time, 8am)
else
start.time = max(start.time, 8.30am)
while end.day is weekend or holiday, end.day--, end.time = 11.59pm
end.time = min(end.time, 5.30pm)
// Now we've normalised, is there any time left?
if start > end
return 0
// Calculate time in first day
timediff = 5.30pm - start.time
day = start.day + 1
// Add time on all intervening days
while(day < end.day)
// returns 9 or 9.30hrs or 0 as appropriate, could be optimised to grab all records
// from the database in 1 or 2 hits, by counting all intervening mondays, and all
// intervening tue-fris (non-holidays)
timediff += duration(day)
// Add time on last day
timediff += end.time - 08.30am
if end.day is Monday then
timediff += end.time - 08.00am
else
timediff += end.time - 08.30am
return timediff
```
You could do something like
SELECT COUNT(DAY) FROM HOLIDAY WHERE HOLIDAY BETWEEN @Start AND @End GROUP BY DAY
to count the number of holidays falling on Monday, Tuesday, Wednesday, and so forth. Probably a way of getting SQL to count just Mondays and non-Mondays, though can't think of anything at the moment. |
141,370 | <p>What is the best way to specify a property name when using INotifyPropertyChanged? </p>
<p>Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead.</p>
| [
{
"answer_id": 141379,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 4,
"selected": false,
"text": "<p>The reflection overhead here is pretty much overkill especially since INotifyPropertyChanged gets called <strong>a l... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22813/"
] | What is the best way to specify a property name when using INotifyPropertyChanged?
Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead. | Don't forget one thing : `PropertyChanged` event is mainly consumed by components that will **use reflection** to get the value of the named property.
The most obvious example is databinding.
When you fire `PropertyChanged` event, passing the name of the property as a parameter, you should know that *the subscriber of this event is likely to use reflection* by calling, for instance, `GetProperty` (at least the first time if it uses a cache of `PropertyInfo`), then `GetValue`. This last call is a dynamic invocation (MethodInfo.Invoke) of the property getter method, which costs more than the `GetProperty` which only queries meta data. (Note that data binding relies on the whole [TypeDescriptor](http://msdn.microsoft.com/en-us/library/ms171819.aspx) thing -- but the default implementation uses reflection.)
So, of course using hard code property names when firing PropertyChanged is more efficient than using reflection for dynamically getting the name of the property, but IMHO, it is important to balance your thoughts. In some cases, the performance overhead is not that critical, and you could benefit from some kind on strongly typed event firing mechanism.
Here is what I use sometimes in C# 3.0, when performances would not be a concern :
```
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return this.name; }
set
{
this.name = value;
FirePropertyChanged(p => p.Name);
}
}
private void FirePropertyChanged<TValue>(Expression<Func<Person, TValue>> propertySelector)
{
if (PropertyChanged == null)
return;
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
```
Notice the use of the expression tree to get the name of the property, and the use of the lambda expression as an `Expression` :
```
FirePropertyChanged(p => p.Name);
``` |
141,372 | <p>Emacs has a useful <code>transpose-words</code> command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.</p>
<p>For example, ‘<code>stack |overflow</code>’ + M-t = ‘<code>overflow stack|</code>’ (‘<code>|</code>’ is the cursor position).</p>
<p><code><a>|<p></code> becomes <code><p><a|></code>.</p>
<p>Is it possible to emulate it in Vim? I know I can use <code>dwwP</code>, but it doesn’t work well with punctuation.</p>
<p><em>Update:</em> No, <code>dwwP</code> is <em>really</em> not a solution. Imagine:</p>
<pre><code>SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) )
// with cursor here ^
</code></pre>
<p>Emacs’ M-t would have exchanged <code>b</code> and <code>c</code>, resulting in <code>(a)(c)(b)</code>.</p>
<p>What works is <code>/\w
yiwNviwpnviwgp</code>. But it spoils <code>""</code> and <code>"/</code>. Is there a cleaner solution?</p>
<p><em>Update²:</em></p>
<h1>Solved</h1>
<pre><code>:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,<CR>kgJ:nohl<CR>
</code></pre>
<p>Imperfect, but works.</p>
<p>Thanks Camflan for bringing the <code>%#</code> item to my attention. Of course, it’s all on the <a href="http://vim.wikia.com/wiki/VimTip47" rel="noreferrer">wiki</a>, but I didn’t realize it could solve the problem of <em>exact</em> (Emacs got it completely right) duplication of the <code>transpose-words</code> feature.</p>
| [
{
"answer_id": 141447,
"author": "Sam Martin",
"author_id": 19088,
"author_profile": "https://Stackoverflow.com/users/19088",
"pm_score": 3,
"selected": false,
"text": "<p>Depending on the situation, you can use the W or B commands, as in dWwP. The \"capital\" versions skip to the next/... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21055/"
] | Emacs has a useful `transpose-words` command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.
For example, ‘`stack |overflow`’ + M-t = ‘`overflow stack|`’ (‘`|`’ is the cursor position).
`<a>|<p>` becomes `<p><a|>`.
Is it possible to emulate it in Vim? I know I can use `dwwP`, but it doesn’t work well with punctuation.
*Update:* No, `dwwP` is *really* not a solution. Imagine:
```
SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) )
// with cursor here ^
```
Emacs’ M-t would have exchanged `b` and `c`, resulting in `(a)(c)(b)`.
What works is `/\w
yiwNviwpnviwgp`. But it spoils `""` and `"/`. Is there a cleaner solution?
*Update²:*
Solved
======
```
:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,<CR>kgJ:nohl<CR>
```
Imperfect, but works.
Thanks Camflan for bringing the `%#` item to my attention. Of course, it’s all on the [wiki](http://vim.wikia.com/wiki/VimTip47), but I didn’t realize it could solve the problem of *exact* (Emacs got it completely right) duplication of the `transpose-words` feature. | These are from my .vimrc and work well for me.
```
" swap two words
:vnoremap <C-X> <Esc>`.``gvP``P
" Swap word with next word
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> *N*
``` |
141,388 | <p>Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine:</p>
<pre><code><ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}"
dataProvider="{_data.staticData.dead_reason}"
labelField="@label" width="300"/>
</code></pre>
<p>The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons?</p>
| [
{
"answer_id": 141408,
"author": "bill d",
"author_id": 1798,
"author_profile": "https://Stackoverflow.com/users/1798",
"pm_score": 2,
"selected": false,
"text": "<p>Try using an <mx:Repeater> Something like:</p>\n\n<pre><code><mx:Repeater dataProvider=\"{_data.staticData.dead_... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine:
```
<ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}"
dataProvider="{_data.staticData.dead_reason}"
labelField="@label" width="300"/>
```
The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons? | Try using an <mx:Repeater> Something like:
```
<mx:Repeater dataProvider="{_data.staticData.dead_reason}">
<mx:RadioButton groupName="reasons" ...>
</mx:Repeater>
``` |
141,422 | <p>Using assorted matrix math, I've solved a system of equations resulting in coefficients for a polynomial of degree 'n'</p>
<pre><code>Ax^(n-1) + Bx^(n-2) + ... + Z
</code></pre>
<p>I then evaulate the polynomial over a given x range, essentially I'm rendering the polynomial curve. Now here's the catch. I've done this work in one coordinate system we'll call "data space". Now I need to present the same curve in another coordinate space. It is easy to transform input/output to and from the coordinate spaces, but the end user is only interested in the coefficients [A,B,....,Z] since they can reconstruct the polynomial on their own. How can I present a second set of coefficients [A',B',....,Z'] which represent the same shaped curve in a different coordinate system.</p>
<p>If it helps, I'm working in 2D space. Plain old x's and y's. I also feel like this may involve multiplying the coefficients by a transformation matrix? Would it some incorporate the scale/translation factor between the coordinate systems? Would it be the inverse of this matrix? I feel like I'm headed in the right direction...</p>
<p>Update: Coordinate systems are linearly related. Would have been useful info eh?</p>
| [
{
"answer_id": 141493,
"author": "Laplie Anderson",
"author_id": 14204,
"author_profile": "https://Stackoverflow.com/users/14204",
"pm_score": 0,
"selected": false,
"text": "<p>You have the equation:</p>\n\n<pre><code>y = Ax^(n-1) + Bx^(n-2) + ... + Z\n</code></pre>\n\n<p>In xy space, an... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287/"
] | Using assorted matrix math, I've solved a system of equations resulting in coefficients for a polynomial of degree 'n'
```
Ax^(n-1) + Bx^(n-2) + ... + Z
```
I then evaulate the polynomial over a given x range, essentially I'm rendering the polynomial curve. Now here's the catch. I've done this work in one coordinate system we'll call "data space". Now I need to present the same curve in another coordinate space. It is easy to transform input/output to and from the coordinate spaces, but the end user is only interested in the coefficients [A,B,....,Z] since they can reconstruct the polynomial on their own. How can I present a second set of coefficients [A',B',....,Z'] which represent the same shaped curve in a different coordinate system.
If it helps, I'm working in 2D space. Plain old x's and y's. I also feel like this may involve multiplying the coefficients by a transformation matrix? Would it some incorporate the scale/translation factor between the coordinate systems? Would it be the inverse of this matrix? I feel like I'm headed in the right direction...
Update: Coordinate systems are linearly related. Would have been useful info eh? | The problem statement is slightly unclear, so first I will clarify my own interpretation of it:
You have a polynomial function
**f(x) = Cnxn + Cn-1xn-1 + ... + C0**
[I changed A, B, ... Z into Cn, Cn-1, ..., C0 to more easily work with linear algebra below.]
Then you also have a transformation such as: **z = ax + b** that you want to use to find coefficients for the *same* polynomial, but in terms of *z*:
**f(z) = Dnzn + Dn-1zn-1 + ... + D0**
This can be done pretty easily with some linear algebra. In particular, you can define an (n+1)×(n+1) matrix *T* which allows us to do the matrix multiplication
***d* = *T* \* *c*** ,
where *d* is a column vector with top entry *D0*, to last entry *Dn*, column vector *c* is similar for the *Ci* coefficients, and matrix *T* has (i,j)-th [ith row, jth column] entry *tij* given by
***tij* = (*j* choose *i*) *ai* *bj-i***.
Where (*j* choose *i*) is the binomial coefficient, and = 0 when *i* > *j*. Also, unlike standard matrices, I'm thinking that i,j each range from 0 to n (usually you start at 1).
This is basically a nice way to write out the expansion and re-compression of the polynomial when you plug in z=ax+b by hand and use the [binomial theorem](http://en.wikipedia.org/wiki/Binomial_theorem). |
141,432 | <p>I have created a brand new project in XCode and have the following in my AppDelegate.py file:</p>
<pre><code>from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setTitle_(u"12%")
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
</code></pre>
<p>However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.</p>
| [
{
"answer_id": 142162,
"author": "Chris Lundie",
"author_id": 20685,
"author_profile": "https://Stackoverflow.com/users/20685",
"pm_score": 4,
"selected": true,
"text": "<p>I had to do this to make it work:</p>\n\n<ol>\n<li><p>Open MainMenu.xib. Make sure the class of the app delegate is... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] | I have created a brand new project in XCode and have the following in my AppDelegate.py file:
```
from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setTitle_(u"12%")
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
```
However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default. | I had to do this to make it work:
1. Open MainMenu.xib. Make sure the class of the app delegate is `MyApplicationAppDelegate`. I'm not sure if you will have to do this, but I did. It was wrong and so the app delegate never got called in the first place.
2. Add `statusItem.retain()` because it gets autoreleased right away. |
141,441 | <p>In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?</p>
<pre><code>try{
if(myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip) {
this.setAddress(newInfo);
}
} catch(e) {} // ignore missing args
</code></pre>
| [
{
"answer_id": 141474,
"author": "pdavis",
"author_id": 7819,
"author_profile": "https://Stackoverflow.com/users/7819",
"pm_score": -1,
"selected": false,
"text": "<p>For the example given I would say it was bad practice. There are instances however where it may be more <strong>efficient... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22816/"
] | In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?
```
try{
if(myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip) {
this.setAddress(newInfo);
}
} catch(e) {} // ignore missing args
``` | Yes. For one, an exception could be thrown for any number of reasons besides missing arguments. The catch-all would hide those cases which probably isn't desired. |
141,449 | <p>How do I create a file-like object (same duck type as File) with the contents of a string?</p>
| [
{
"answer_id": 141451,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 8,
"selected": true,
"text": "<p>For Python 2.x, use the <a href=\"https://docs.python.org/2/library/stringio.html\" rel=\"noreferrer\">StringIO</a> ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] | How do I create a file-like object (same duck type as File) with the contents of a string? | For Python 2.x, use the [StringIO](https://docs.python.org/2/library/stringio.html) module. For example:
```
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
```
I use cStringIO (which is faster), but note that it doesn't [accept Unicode strings that cannot be encoded as plain ASCII strings](http://docs.python.org/lib/module-cStringIO.html). (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)
For Python 3.x, use the [`io`](https://docs.python.org/3/library/io.html#text-i-o) module.
```
f = io.StringIO('foo')
``` |
141,450 | <p>I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:</p>
<ul>
<li>Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.</li>
<li>Change events, but these only are triggered when the select box's value changes.</li>
</ul>
<p>Ideas?</p>
| [
{
"answer_id": 141535,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think there's direct support. You could also sit on the onblur of the select -- it gets called when the selec... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10290/"
] | I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:
* Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.
* Change events, but these only are triggered when the select box's value changes.
Ideas? | Conditional-content, which is what you're asking about, isn't that difficult. The in the following example, I'll use [jQuery](http://www.jquery.com) to accomplish our goal:
```
<select id="theSelectId">
<option value="dogs">Dogs</option>
<option value="birds">Birds</option>
<option value="cats">Cats</option>
<option value="horses">Horses</option>
</select>
<div id="myDiv" style="width:300px;height:100px;background:#cc0000"></div>
```
We'll tie a couple events to show/hide #myDiv based upon the selected value of #theSelectId
```
$("#theSelectId").change(function(){
if ($(this).val() != "dogs")
$("#myDiv").fadeOut();
else
$("#myDiv").fadeIn();
});
``` |
141,467 | <p>I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas?</p>
<p>Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.</p>
| [
{
"answer_id": 141495,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 0,
"selected": false,
"text": "<pre><code>static class EnumerableExtensions\n{\n public static IEnumerable<T> Flatten<T>(this ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18049/"
] | I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas?
Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm. | Hmm... I'm not sure *exactly* what you want here, but here's a "one level" option:
```
public static IEnumerable<TElement> Flatten<TElement,TSequence> (this IEnumerable<TSequence> sequences)
where TSequence : IEnumerable<TElement>
{
foreach (TSequence sequence in sequences)
{
foreach(TElement element in sequence)
{
yield return element;
}
}
}
```
If that's not what you want, could you provide the signature of what you do want? If you don't need a generic form, and you just want to do the kind of thing that LINQ to XML constructors do, that's reasonably simple - although the recursive use of iterator blocks is relatively inefficient. Something like:
```
static IEnumerable Flatten(params object[] objects)
{
// Can't easily get varargs behaviour with IEnumerable
return Flatten((IEnumerable) objects);
}
static IEnumerable Flatten(IEnumerable enumerable)
{
foreach (object element in enumerable)
{
IEnumerable candidate = element as IEnumerable;
if (candidate != null)
{
foreach (object nested in candidate)
{
yield return nested;
}
}
else
{
yield return element;
}
}
}
```
Note that that will treat a string as a sequence of chars, however - you may want to special-case strings to be individual elements instead of flattening them, depending on your use case.
Does that help? |
141,484 | <p>I'm looking to write a config file that allows for RESTful services in WCF, but I still want the ability to 'tap into' the membership provider for username/password authentication.</p>
<p>The below is part of my current config using basicHttp binding or wsHttp w/out WS Security, how will this change w/ REST based services?</p>
<pre><code> <bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="false"/>
</security>
</binding>
</wsHttpBinding>
<basicHttpBinding>
<binding name="basicHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="NorthwindBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</code></pre>
| [
{
"answer_id": 143738,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 1,
"selected": false,
"text": "<p>Before you continue down this path of fighting to implement REST over WCF, I suggest you read <a href=\"http://www.... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] | I'm looking to write a config file that allows for RESTful services in WCF, but I still want the ability to 'tap into' the membership provider for username/password authentication.
The below is part of my current config using basicHttp binding or wsHttp w/out WS Security, how will this change w/ REST based services?
```
<bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="false"/>
</security>
</binding>
</wsHttpBinding>
<basicHttpBinding>
<binding name="basicHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="NorthwindBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
``` | **UPDATE 01/23/2012**
Since I wrote this question I've seen a much better approach to securing REST like web services in the wild. It sounded complex when I first heard about it but the idea is simple and all over the web for both web services and other secure communication.
It requires the use of public/private keys.
1.) each user (customer) of the endpoint will need to register with your REST web service
* a.) you give this user a private key that should not be shared with
anyone
* b.) you also generate a public key that can go over the wire
in plain text if need be (this will also be used to identify the client)
2.) each request from the user needs to generate a hash to sign the request
* a.) One example of this might look like: private key + a timestamp + encoded payload (if small enough like a simple user info to be updated for example)
* b.) you take these 3 (or whatever you decided on) and generate a 1 way hash (using hmac for example)
* c.) in the request being sent over the wire you include the public key (so the server side knows who is attempting to send this request), the hash that was generated w/ the private key, and the timestamp.
3.) the server endpoint (your REST method) will need to generate a hash using the same inputs used on the client. This step will prove that both client and server knew a private key that matched the public key passed along with the request. (this in turn means that the user sending the request is legit as no one else could know the private key)
* a.) lookup the customers private key by the public key being passed along during the request
* b.) take the other params (timestamp and the encoded payload) along with the private key you found in the previous step and use the same algorithm to generate a 1 way hash (again hmac is what I've seen used in the real world)
* c.) the resulting 1 way hash needs to match the hash sent over the wire, if not send back a 400 (or whatever http code you deem to be a "bad request") |
141,487 | <pre><code>class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
</code></pre>
<p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
| [
{
"answer_id": 141505,
"author": "Nick Sergeant",
"author_id": 22468,
"author_profile": "https://Stackoverflow.com/users/22468",
"pm_score": 2,
"selected": false,
"text": "<p>For pre-1.0:</p>\n\n<pre><code>slug = models.SlugField(prepopulate_from=('title',))\n</code></pre>\n\n<p>should w... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22306/"
] | ```
class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
```
Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin. | for Admin in Django 1.0 and up, you'd need to use
```
prepopulated_fields = {'slug': ('title',), }
```
in your admin.py
Your key in the prepopulated\_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.
Outside of admin, you can use the `slugify` function in your views. In templates, you can use the `|slugify` filter.
There is also this package which will take care of this automatically: <https://pypi.python.org/pypi/django-autoslug> |
141,519 | <p>We have a pair of applications. One is written in C# and uses something like:</p>
<pre><code> string s = "alpha\r\nbeta\r\ngamma\r\ndelta";
// Actually there's wrapper code here to make sure this works.
System.Windows.Forms.Clipboard.SetDataObject(s, true);
</code></pre>
<p>To put a list of items onto the clipboard. Another application (in WinBatch) then picks up the list using a ClipGet() function. (We use the clipboard functions to give people the option of editing the list in notepad or something, without having to actually cut-and-paste every time.)</p>
<p>In this particular environment, we have many users on one system via Citrix. Many using these pairs of programs.</p>
<p>Just <em>one</em> user is having the problem where the line delimiters in the text are getting switched from CRLF to LF somewhere between the SetDataObject() and the CLipGet(). I could explain this in a mixed Unix/Windows environment, but there is no Unix here. No unix-y utilities anywhere near this system either. Other users on the same server, no problems at all. It's like something in Windows/Citrix is being "helpful" when we really don't want it, but just for this one guy.</p>
<p>Ideas?</p>
| [
{
"answer_id": 141516,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": false,
"text": "<p>I use <code>print_r()</code> because I like the pretty array structure... but <code>var_dump</code> does give you a bit more... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173/"
] | We have a pair of applications. One is written in C# and uses something like:
```
string s = "alpha\r\nbeta\r\ngamma\r\ndelta";
// Actually there's wrapper code here to make sure this works.
System.Windows.Forms.Clipboard.SetDataObject(s, true);
```
To put a list of items onto the clipboard. Another application (in WinBatch) then picks up the list using a ClipGet() function. (We use the clipboard functions to give people the option of editing the list in notepad or something, without having to actually cut-and-paste every time.)
In this particular environment, we have many users on one system via Citrix. Many using these pairs of programs.
Just *one* user is having the problem where the line delimiters in the text are getting switched from CRLF to LF somewhere between the SetDataObject() and the CLipGet(). I could explain this in a mixed Unix/Windows environment, but there is no Unix here. No unix-y utilities anywhere near this system either. Other users on the same server, no problems at all. It's like something in Windows/Citrix is being "helpful" when we really don't want it, but just for this one guy.
Ideas? | I always use the Xdebug extended var\_dump. It gives out a lot of verbose output.
See: <http://xdebug.org/docs/display> for more details. |
141,525 | <p>I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...</p>
<p>At a core level, what does bit-shifting (<code><<</code>, <code>>></code>, <code>>>></code>) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.</p>
| [
{
"answer_id": 141576,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 8,
"selected": false,
"text": "<p>Let's say we have a single byte:</p>\n\n<pre><code>0110110\n</code></pre>\n\n<p>Applying a single left bitshift gets us:<... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
] | I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...
At a core level, what does bit-shifting (`<<`, `>>`, `>>>`) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness. | The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators.
The Operators
-------------
* `>>` is the arithmetic (or signed) right shift operator.
* `>>>` is the logical (or unsigned) right shift operator.
* `<<` is the left shift operator, and meets the needs of both logical and arithmetic shifts.
All of these operators can be applied to integer values (`int`, `long`, possibly `short` and `byte` or `char`). In some languages, applying the shift operators to any datatype smaller than `int` automatically resizes the operand to be an `int`.
Note that `<<<` is not an operator, because it would be redundant.
Also note that **C and C++ do not distinguish between the right shift operators**. They provide only the `>>` operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators.
(In all mainstream C and C++ implementations including GCC and Clang/LLVM, `>>` on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not *undefined*, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers *is* undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.)
---
Left shift (<<)
---------------
Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit `int` would be:
```
00000000 00000000 00000000 00000110
```
Shifting this bit pattern to the left one position (`6 << 1`) would result in the number 12:
```
00000000 00000000 00000000 00001100
```
As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So `6 << 1` is equivalent to `6 * 2`, and `6 << 3` is equivalent to `6 * 8`. A good optimizing compiler will replace multiplications with shifts when possible.
### Non-circular shifting
Please note that these are *not* circular shifts. Shifting this value to the left by one position (`3,758,096,384 << 1`):
```
11100000 00000000 00000000 00000000
```
results in 3,221,225,472:
```
11000000 00000000 00000000 00000000
```
The digit that gets shifted "off the end" is lost. It does not wrap around.
---
Logical right shift (>>>)
-------------------------
A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:
```
00000000 00000000 00000000 00001100
```
to the right by one position (`12 >>> 1`) will get back our original 6:
```
00000000 00000000 00000000 00000110
```
So we see that shifting to the right is equivalent to division by powers of 2.
### Lost bits are gone
However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern:
```
00111000 00000000 00000000 00000110
```
to the left 4 positions (`939,524,102 << 4`), we get 2,147,483,744:
```
10000000 00000000 00000000 01100000
```
and then shifting back (`(939,524,102 << 4) >>> 4`) we get 134,217,734:
```
00001000 00000000 00000000 00000110
```
We cannot get back our original value once we have lost bits.
---
Arithmetic right shift (>>)
===========================
The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the *sign* bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.
For example, if we interpret this bit pattern as a negative number:
```
10000000 00000000 00000000 01100000
```
we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us:
```
11111000 00000000 00000000 00000110
```
or the number -134,217,722.
So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2. |
141,545 | <p>Let's say I have a class that has a member called data which is a list. </p>
<p>I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.</p>
<p>What's your technique for doing this?</p>
<p>Do you just check the type by looking at <code>__class__</code>?</p>
<p>Is there some trick I might be missing?</p>
<p>I'm used to C++ where overloading by argument type is easy. </p>
| [
{
"answer_id": 141565,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>A better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:</p>\n\n... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1179/"
] | Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type by looking at `__class__`?
Is there some trick I might be missing?
I'm used to C++ where overloading by argument type is easy. | A much neater way to get 'alternate constructors' is to use classmethods. For instance:
```
>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyData from a file"
... data = open(filename).readlines()
... return cls(data)
...
... @classmethod
... def fromdict(cls, datadict):
... "Initialize MyData from a dict's items"
... return cls(datadict.items())
...
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]
```
The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with `isinstance(x, basestring)` is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code. |
141,560 | <p>I have a loop that looks something like this:</p>
<pre><code>for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
</code></pre>
<p>This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return <code>null</code> if there is an error, so I put the loop inside a <code>try...catch</code> block, like this:</p>
<pre><code>try {
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
} catch (NumberFormatException ex) {
return null;
}
</code></pre>
<p>But then I also thought of putting the <code>try...catch</code> block inside the loop, like this:</p>
<pre><code>for (int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
} catch (NumberFormatException ex) {
return null;
}
myFloats[i] = myNum;
}
</code></pre>
<p>Is there any reason, performance or otherwise, to prefer one over the other?</p>
<hr>
<p><strong>Edit:</strong> The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?</p>
| [
{
"answer_id": 141577,
"author": "Jamie",
"author_id": 22748,
"author_profile": "https://Stackoverflow.com/users/22748",
"pm_score": 2,
"selected": false,
"text": "<p>In your examples there is no functional difference. I find your first example more readable.</p>\n"
},
{
"answer... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13531/"
] | I have a loop that looks something like this:
```
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
```
This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return `null` if there is an error, so I put the loop inside a `try...catch` block, like this:
```
try {
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
} catch (NumberFormatException ex) {
return null;
}
```
But then I also thought of putting the `try...catch` block inside the loop, like this:
```
for (int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
} catch (NumberFormatException ex) {
return null;
}
myFloats[i] = myNum;
}
```
Is there any reason, performance or otherwise, to prefer one over the other?
---
**Edit:** The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer? | All right, after [Jeffrey L Whitledge said](https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141652) that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:
```
public class Main {
private static final int NUM_TESTS = 100;
private static int ITERATIONS = 1000000;
// time counters
private static long inTime = 0L;
private static long aroundTime = 0L;
public static void main(String[] args) {
for (int i = 0; i < NUM_TESTS; i++) {
test();
ITERATIONS += 1; // so the tests don't always return the same number
}
System.out.println("Inside loop: " + (inTime/1000000.0) + " ms.");
System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms.");
}
public static void test() {
aroundTime += testAround();
inTime += testIn();
}
public static long testIn() {
long start = System.nanoTime();
Integer i = tryInLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static long testAround() {
long start = System.nanoTime();
Integer i = tryAroundLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static Integer tryInLoop() {
int count = 0;
for (int i = 0; i < ITERATIONS; i++) {
try {
count = Integer.parseInt(Integer.toString(count)) + 1;
} catch (NumberFormatException ex) {
return null;
}
}
return count;
}
public static Integer tryAroundLoop() {
int count = 0;
try {
for (int i = 0; i < ITERATIONS; i++) {
count = Integer.parseInt(Integer.toString(count)) + 1;
}
return count;
} catch (NumberFormatException ex) {
return null;
}
}
}
```
I checked the resulting bytecode using javap to make sure that nothing got inlined.
The results showed that, assuming insignificant JIT optimizations, **Jeffrey is correct**; there is absolutely **no performance difference on Java 6, Sun client VM** (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.
Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or [Ray Hayes's way](https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141589). |
141,562 | <p>I can select all the distinct values in a column in the following ways:</p>
<ul>
<li><code>SELECT DISTINCT column_name FROM table_name;</code></li>
<li><code>SELECT column_name FROM table_name GROUP BY column_name;</code></li>
</ul>
<p>But how do I get the row count from that query? Is a subquery required?</p>
| [
{
"answer_id": 141573,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 4,
"selected": false,
"text": "<pre><code>select Count(distinct columnName) as columnNameCount from tableName \n</code></pre>\n"
},
{
"answer_id": 14... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] | I can select all the distinct values in a column in the following ways:
* `SELECT DISTINCT column_name FROM table_name;`
* `SELECT column_name FROM table_name GROUP BY column_name;`
But how do I get the row count from that query? Is a subquery required? | You can use the `DISTINCT` keyword within the [`COUNT`](http://technet.microsoft.com/en-us/library/ms175997%28v=sql.90%29.aspx) aggregate function:
```
SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name
```
This will count only the distinct values for that column. |
141,598 | <p>I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: <code>School</code>, <code>Course</code>, and <code>Student</code>, which are defined as follows:</p>
<pre><code>class School
{
List<Course> Courses;
List<Student> Students;
}
class Course
{
string Number;
string Description;
}
class Student
{
string Name;
List<Course> EnrolledIn;
}
</code></pre>
<p>I would store such a data structure in XML like so:</p>
<pre><code><School>
<Courses>
<Course Number="ENGL 101" Description="English I" />
<Course Number="CHEM 102" Description="General Inorganic Chemistry" />
<Course Number="MATH 103" Description="Trigonometry" />
</Courses>
<Students>
<Student Name="Jack">
<EnrolledIn>
<Course Number="CHEM 102" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
<Student Name="Jill">
<EnrolledIn>
<Course Number="ENGL 101" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
</Students>
</School>
</code></pre>
<p>With the XML ordered this way, I can parse <code>Courses</code> first. Then, when I parse <code>Students</code>, I can look up each <code>Course</code> listed in <code>EnrolledIn</code> (by its <code>Number</code>) in the <code>School.Courses</code> list. This will give me an object reference to add to the <code>EnrolledIn</code> list in <code>Student</code>. If <code>Students</code>, however, comes <em>before</em> <code>Courses</code>, such a lookup to get a object reference is not possible. (Since <code>School.Courses</code> has not yet been populated.)</p>
<p>So what are the best practices for storing relational data in XML?
- Should I enforce that <code>Courses</code> must always come before <code>Students</code>?
- Should I tolerate any ordering and create a stub <code>Course</code> object whenever I encounter one I have not yet seen? (To be expanded when the definition of the <code>Course</code> is eventually reached later.)
- Is there some other way I should be persisting/loading my objects to/from XML? (I am currently implementing <code>Save</code> and <code>Load</code> methods on all my business objects and doing all this manually using <code>System.Xml.XmlDocument</code> and its associated classes.)</p>
<p>I am used to working with relational data out of SQL, but this is my first experience trying to store a non-trivial relational data structure in XML. Any advice you can provide as to how I should proceed would be greatly appreciated.</p>
| [
{
"answer_id": 141624,
"author": "Instantsoup",
"author_id": 9861,
"author_profile": "https://Stackoverflow.com/users/9861",
"pm_score": 0,
"selected": false,
"text": "<p>From experience, XML isn't the best to store relational data. Have you investigated <a href=\"http://www.yaml.org/\" ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: `School`, `Course`, and `Student`, which are defined as follows:
```
class School
{
List<Course> Courses;
List<Student> Students;
}
class Course
{
string Number;
string Description;
}
class Student
{
string Name;
List<Course> EnrolledIn;
}
```
I would store such a data structure in XML like so:
```
<School>
<Courses>
<Course Number="ENGL 101" Description="English I" />
<Course Number="CHEM 102" Description="General Inorganic Chemistry" />
<Course Number="MATH 103" Description="Trigonometry" />
</Courses>
<Students>
<Student Name="Jack">
<EnrolledIn>
<Course Number="CHEM 102" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
<Student Name="Jill">
<EnrolledIn>
<Course Number="ENGL 101" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
</Students>
</School>
```
With the XML ordered this way, I can parse `Courses` first. Then, when I parse `Students`, I can look up each `Course` listed in `EnrolledIn` (by its `Number`) in the `School.Courses` list. This will give me an object reference to add to the `EnrolledIn` list in `Student`. If `Students`, however, comes *before* `Courses`, such a lookup to get a object reference is not possible. (Since `School.Courses` has not yet been populated.)
So what are the best practices for storing relational data in XML?
- Should I enforce that `Courses` must always come before `Students`?
- Should I tolerate any ordering and create a stub `Course` object whenever I encounter one I have not yet seen? (To be expanded when the definition of the `Course` is eventually reached later.)
- Is there some other way I should be persisting/loading my objects to/from XML? (I am currently implementing `Save` and `Load` methods on all my business objects and doing all this manually using `System.Xml.XmlDocument` and its associated classes.)
I am used to working with relational data out of SQL, but this is my first experience trying to store a non-trivial relational data structure in XML. Any advice you can provide as to how I should proceed would be greatly appreciated. | Don't think in SQL or relational when working with XML, because there are no order constraints.
You can however query using XPath to any portion of the XML document at any time. You want the courses first, then "//Courses/Course". You want the students enrollments next, then "//Students/Student/EnrolledIn/Course".
The bottom line being... just because XML is stored in a file, don't get caught thinking all your accesses are serial.
---
I posted a separate question, ["Can XPath do a foreign key lookup across two subtrees of an XML?"](https://stackoverflow.com/questions/142010/can-xpath-do-a-foreign-key-lookup-across-two-subtrees-of-an-xml), in order to clarify my position. The solution shows how you can use XPath to make relational queries against XML data. |
141,599 | <p>What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'. </p>
<p>Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?</p>
<p>Example:</p>
<pre><code>svn -v log -d 2008-9-23:2008-9:24 > report.txt
</code></pre>
| [
{
"answer_id": 141619,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 7,
"selected": true,
"text": "<p>Very first hit by google for \"svn log date range\": <a href=\"http://svn.haxx.se/users/archive-2006-08/0737.shtml... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] | What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'.
Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?
Example:
```
svn -v log -d 2008-9-23:2008-9:24 > report.txt
``` | Very first hit by google for "svn log date range": <http://svn.haxx.se/users/archive-2006-08/0737.shtml>
>
> So `svn log <url> -r
> {2008-09-19}:{2008-09-26}` will get
> all changes for the past week,
> including today.
>
>
>
And if you want to generate reports for a repo, there's a solution: [Statsvn](http://statsvn.org/index.html).
HTH |
141,606 | <p>Say that I write an article or document about a certain topic, but the content is meant for readers with certain prior knowledge about the topic. To help people who don't have the "required" background information, I would like to add a note to the top of the page with an explanation and possibly a link to some reference material.</p>
<p>Here's an example:</p>
<blockquote>
<p><strong>Using The Best Product in the World to Create World Peace</strong></p>
<p><em>Note: This article assumes you are already familiar with The Best Product in the World. To learn more about The Best Product in the World, please see the official web site.</em></p>
<p>
The Best Product in the World ...
</p>
</blockquote>
<p>Now, I don't want the note to show up in <strike>Google</strike> search engine results, only the title and the content that follows the note. Is there any way I can achieve this?</p>
<p>Also, is it possible to do this without direct control over the entire HTML file and/or HTTP response, i.e. on blog hosted by a third party, like <a href="http://www.wordpress.com" rel="nofollow noreferrer">Wordpress.com</a>?</p>
<p><strong>Update</strong></p>
<p>Unfortunately, both the JavaScript solution and the HTML meta tag approach does not work on hosted Wordpress.com blogs, since they don't allow JavaScript in posts and they don't provide access to edit the HTML meta tags directly.</p>
| [
{
"answer_id": 141613,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "<p>I just came to think of something. I guess I could render the note with JavaScript once the page is loaded?</p>\n"... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709/"
] | Say that I write an article or document about a certain topic, but the content is meant for readers with certain prior knowledge about the topic. To help people who don't have the "required" background information, I would like to add a note to the top of the page with an explanation and possibly a link to some reference material.
Here's an example:
>
> **Using The Best Product in the World to Create World Peace**
>
>
> *Note: This article assumes you are already familiar with The Best Product in the World. To learn more about The Best Product in the World, please see the official web site.*
>
>
>
> The Best Product in the World ...
>
>
>
>
Now, I don't want the note to show up in Google search engine results, only the title and the content that follows the note. Is there any way I can achieve this?
Also, is it possible to do this without direct control over the entire HTML file and/or HTTP response, i.e. on blog hosted by a third party, like [Wordpress.com](http://www.wordpress.com)?
**Update**
Unfortunately, both the JavaScript solution and the HTML meta tag approach does not work on hosted Wordpress.com blogs, since they don't allow JavaScript in posts and they don't provide access to edit the HTML meta tags directly. | You can build that portion of the content dynamically using Javascript.
For example:
```
<html>
<body>
<div id="dynContent">
</div>
Rest of the content here.
</body>
<script language='javascript' type='text/javascript'>
var dyn = document.getElementById('dynContent');
dyn.innerHTML = "Put the dynamic content here";
</script>
</html>
```
If you're really stuck, you can just go old school and reference an image that has your text as part of it. It's not particularly "accessibility-friendly" though. |
141,611 | <p>I have an Enum like this</p>
<pre><code>package com.example;
public enum CoverageEnum {
COUNTRY,
REGIONAL,
COUNTY
}
</code></pre>
<p>I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:</p>
<pre><code><c:forEach var="type" items="<%= com.example.CoverageEnum.values() %>">
${type}
</c:forEach>
</code></pre>
<p>But can I achieve the same thing without scriptlets?</p>
<p>Cheers,
Don</p>
| [
{
"answer_id": 141658,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] | I have an Enum like this
```
package com.example;
public enum CoverageEnum {
COUNTRY,
REGIONAL,
COUNTY
}
```
I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:
```
<c:forEach var="type" items="<%= com.example.CoverageEnum.values() %>">
${type}
</c:forEach>
```
But can I achieve the same thing without scriptlets?
Cheers,
Don | If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become:
```
<c:forEach var="type" items="${myprefix:getValues()}">
```
EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this:
```
public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {
try {
Method m = klass.getMethod("values", null);
Object obj = m.invoke(null, null);
return (Enum<T>[])obj;
} catch(Exception ex) {
//shouldn't happen...
return null;
}
}
``` |
141,612 | <p>I'm working on database designs for a project management system as personal project and I've hit a snag.</p>
<p>I want to implement a ticket system and I want the tickets to look like the <a href="http://trac.edgewall.org/ticket/6436" rel="noreferrer">tickets in Trac</a>. What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing)</p>
<p>Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again. </p>
<p><strong>Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.</strong> </p>
| [
{
"answer_id": 141621,
"author": "Pete Karl II",
"author_id": 22491,
"author_profile": "https://Stackoverflow.com/users/22491",
"pm_score": 1,
"selected": false,
"text": "<p>I'd say create some kind of event listening class that you ping every time something happens within your system &a... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16204/"
] | I'm working on database designs for a project management system as personal project and I've hit a snag.
I want to implement a ticket system and I want the tickets to look like the [tickets in Trac](http://trac.edgewall.org/ticket/6436). What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing)
Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again.
**Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.** | I have implemented pure record change data using a "thin" design:
```
RecordID Table Column OldValue NewValue
-------- ----- ------ -------- --------
```
You may not want to use "Table" and "Column", but rather "Object" and "Property", and so forth, depending on your design.
This has the advantage of flexibility and simplicity, at the cost of query speed -- clustered indexes on the "Table" and "Column" columns can speed up queries and filters. But if you are going to be viewing the change log online frequently at a Table or object level, you may want to design something flatter.
**EDIT**: several people have rightly pointed out that with this solution you could not pull together a change set. I forgot this in the table above -- the implementation I worked with also had a "Transaction" table with a datetime, user and other info, and a "TransactionID" column, so the design would look like this:
```
CHANGE LOG TABLE:
RecordID Table Column OldValue NewValue TransactionID
-------- ----- ------ -------- -------- -------------
TRANSACTION LOG TABLE:
TransactionID UserID TransactionDate
------------- ------ ---------------
``` |
141,620 | <p>i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before_filter to check that the user of the user in the session has a 'can_access_admin' flag.</p>
<p>i have this code in the application.rb:</p>
<p>def check_role
@user = session[:user]</p>
<p>if @user.role.can_access_admin.nil? || !@user.role.can_access_admin
render :text => "your current role does not allow access to the administration area."
return
end
end</p>
<p>and then i have this code inside one of the admin controllers:</p>
<p>class Admin::BlogsController < ApplicationController
before_filter :check_role</p>
<p>def list
@blogList = Blog.find(:all)
end
end</p>
<p>and when i try to view the list action i get this error:</p>
<p>undefined method 'role' for user...</p>
<p>anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)</p>
| [
{
"answer_id": 141721,
"author": "MatthewFord",
"author_id": 21596,
"author_profile": "https://Stackoverflow.com/users/21596",
"pm_score": 4,
"selected": true,
"text": "<p>just a guess but it seems that your session[:user] is just storing the id, you need to do:</p>\n\n<pre><code>@user =... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] | i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before\_filter to check that the user of the user in the session has a 'can\_access\_admin' flag.
i have this code in the application.rb:
def check\_role
@user = session[:user]
if @user.role.can\_access\_admin.nil? || !@user.role.can\_access\_admin
render :text => "your current role does not allow access to the administration area."
return
end
end
and then i have this code inside one of the admin controllers:
class Admin::BlogsController < ApplicationController
before\_filter :check\_role
def list
@blogList = Blog.find(:all)
end
end
and when i try to view the list action i get this error:
undefined method 'role' for user...
anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it) | just a guess but it seems that your session[:user] is just storing the id, you need to do:
```
@user = User.find(session[:user])
```
or something along those lines to fetch the user from the database (along with its associations).
It's good to do the above in a before filter too. |
141,626 | <p>I've got a windows form in Visual Studio 2008 using .NET 3.5 which has a WebBrowser control on it. I need to analyse the form's PostData in the Navigating event handler before the request is sent. Is there a way to get to it?</p>
<p>The old win32 browser control had a Before_Navigate event which had PostData as one of its arguments. Not so with the new .NET WebBrowser control.</p>
| [
{
"answer_id": 144354,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 4,
"selected": true,
"text": "<p>That functionality isn't exposed by the .NET WebBrowser control. Fortunately, that control is mostly a wrapper around the 'old... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've got a windows form in Visual Studio 2008 using .NET 3.5 which has a WebBrowser control on it. I need to analyse the form's PostData in the Navigating event handler before the request is sent. Is there a way to get to it?
The old win32 browser control had a Before\_Navigate event which had PostData as one of its arguments. Not so with the new .NET WebBrowser control. | That functionality isn't exposed by the .NET WebBrowser control. Fortunately, that control is mostly a wrapper around the 'old' control. This means you can subscribe to the BeforeNavigate2 event you know and love(?) using something like the following (after adding a reference to SHDocVw to your project):
```
Dim ie = DirectCast(WebBrowser1.ActiveXInstance, SHDocVw.InternetExplorer)
AddHandler ie.BeforeNavigate2, AddressOf WebBrowser_BeforeNavigate2
```
...and do whatever you want to the PostData inside that event:
```
Private Sub WebBrowser_BeforeNavigate2(ByVal pDisp As Object, ByRef URL As Object, _
ByRef Flags As Object, ByRef TargetFrameName As Object, _
ByRef PostData As Object, ByRef Headers As Object, ByRef Cancel As Boolean)
Dim PostDataText = System.Text.Encoding.ASCII.GetString(PostData)
End Sub
```
One important caveat: the [documentation for the WebBrowser.ActiveXInstance property](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowserbase.activexinstance.aspx) states that "This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.". In other words: your use of the property may break your app at any point in the future, for example when the Framework people decide to implement their own browser component, instead of wrapping the existing SHDocVw COM one.
So, you'll not want to put this code in anything you ship to a lot of people and/or anything that should remain working for many Framework versions to come... |
141,630 | <p>If I drag and drop a selection of a webpage from Firefox to HTML-Kit, HTML-Kit asks me whether I want to paste as text or HTML. If I select "text," I get this:</p>
<pre><code>Version:0.9
StartHTML:00000147
EndHTML:00000516
StartFragment:00000181
EndFragment:00000480
SourceURL:http://en.wikipedia.org/wiki/Herodotus
<html><body>
<!--StartFragment-->Additional details have been garnered from the <i><a href="http://en.wikipedia.org/wiki/Suda" title="Suda">Suda</a></i>, an 11th-century encyclopaedia of the <a href="http://en.wikipedia.org/wiki/Byzantium" title="Byzantium">Byzantium</a> which likely took its information from traditional accounts.<!--EndFragment-->
</body>
</html>
</code></pre>
<p><a href="https://learn.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format" rel="nofollow noreferrer">According to MSDN</a>, this is "CF_HTML" formatted clipboard data. Is it the same on OS X and Linux systems? </p>
<p>Is there any way to access this kind of detailed information (as opposed to just the plain clip fragment) in a webpage-to-webpage drag and drop operation? What about to a C# WinForms desktop application?</p>
| [
{
"answer_id": 141727,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>It is Microsoft specific, don't expect to see the same information in other OSes.<br>\nNote that you get the same format... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4965/"
] | If I drag and drop a selection of a webpage from Firefox to HTML-Kit, HTML-Kit asks me whether I want to paste as text or HTML. If I select "text," I get this:
```
Version:0.9
StartHTML:00000147
EndHTML:00000516
StartFragment:00000181
EndFragment:00000480
SourceURL:http://en.wikipedia.org/wiki/Herodotus
<html><body>
<!--StartFragment-->Additional details have been garnered from the <i><a href="http://en.wikipedia.org/wiki/Suda" title="Suda">Suda</a></i>, an 11th-century encyclopaedia of the <a href="http://en.wikipedia.org/wiki/Byzantium" title="Byzantium">Byzantium</a> which likely took its information from traditional accounts.<!--EndFragment-->
</body>
</html>
```
[According to MSDN](https://learn.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format), this is "CF\_HTML" formatted clipboard data. Is it the same on OS X and Linux systems?
Is there any way to access this kind of detailed information (as opposed to just the plain clip fragment) in a webpage-to-webpage drag and drop operation? What about to a C# WinForms desktop application? | For completeness, here is the P/Invoke Win32 API code to get RAW clipboard data
```
using System;
using System.Runtime.InteropServices;
using System.Text;
//--------------------------------------------------------------------------------
http://metadataconsulting.blogspot.com/2019/06/How-to-get-HTML-from-the-Windows-system-clipboard-directly-using-PInvoke-Win32-Native-methods-avoiding-bad-funny-characters.html
//--------------------------------------------------------------------------------
public class ClipboardHelper
{
#region Win32 Native PInvoke
[DllImport("User32.dll", SetLastError = true)]
private static extern uint RegisterClipboardFormat(string lpszFormat);
//or specifically - private static extern uint RegisterClipboardFormatA(string lpszFormat);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsClipboardFormatAvailable(uint format);
[DllImport("User32.dll", SetLastError = true)]
private static extern IntPtr GetClipboardData(uint uFormat);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseClipboard();
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("Kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern int GlobalSize(IntPtr hMem);
#endregion
public static string GetHTMLWin32Native()
{
string strHTMLUTF8 = string.Empty;
uint CF_HTML = RegisterClipboardFormatA("HTML Format");
if (CF_HTML != null || CF_HTML == 0)
return null;
if (!IsClipboardFormatAvailable(CF_HTML))
return null;
try
{
if (!OpenClipboard(IntPtr.Zero))
return null;
IntPtr handle = GetClipboardData(CF_HTML);
if (handle == IntPtr.Zero)
return null;
IntPtr pointer = IntPtr.Zero;
try
{
pointer = GlobalLock(handle);
if (pointer == IntPtr.Zero)
return null;
uint size = GlobalSize(handle);
byte[] buff = new byte[size];
Marshal.Copy(pointer, buff, 0, (int)size);
strHTMLUTF8 = System.Text.Encoding.UTF8.GetString(buff);
}
finally
{
if (pointer != IntPtr.Zero)
GlobalUnlock(handle);
}
}
finally
{
CloseClipboard();
}
return strHTMLUTF8;
}
}
``` |
141,637 | <p>I have this code:</p>
<pre><code>@PersistenceContext(name="persistence/monkey", unitName="deltaflow-pu")
...
@Stateless
public class GahBean implements GahRemote {
</code></pre>
<p>But when I use this:</p>
<pre><code>try{
InitialContext ic = new InitialContext();
System.out.println("Pissing me off * " + ic.lookup("java:comp/env/persistent/monkey"));
Iterator e = ic.getEnvironment().values().iterator();
while ( e.hasNext() )
System.out.println("rem - " + e.next());
}catch(Exception a){ a.printStackTrace();}
</code></pre>
<p>I get this exception:</p>
<pre><code>javax.naming.NameNotFoundException: No object bound to name java:comp/env/persistent/monkey
</code></pre>
<p>If I remove the lookup the iterator doesn't have anything close to it either. What could be the problem?</p>
| [
{
"answer_id": 141706,
"author": "arinte",
"author_id": 22763,
"author_profile": "https://Stackoverflow.com/users/22763",
"pm_score": 0,
"selected": false,
"text": "<p>If I inject it by the way it works fine, but everywhere I read about that they say it isn't threadsafe to do it that way... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22763/"
] | I have this code:
```
@PersistenceContext(name="persistence/monkey", unitName="deltaflow-pu")
...
@Stateless
public class GahBean implements GahRemote {
```
But when I use this:
```
try{
InitialContext ic = new InitialContext();
System.out.println("Pissing me off * " + ic.lookup("java:comp/env/persistent/monkey"));
Iterator e = ic.getEnvironment().values().iterator();
while ( e.hasNext() )
System.out.println("rem - " + e.next());
}catch(Exception a){ a.printStackTrace();}
```
I get this exception:
```
javax.naming.NameNotFoundException: No object bound to name java:comp/env/persistent/monkey
```
If I remove the lookup the iterator doesn't have anything close to it either. What could be the problem? | This could be my ignorance about JPA showing, but you appear to have "persistence" in some places and "persistent" in others. I'd start by making sure the names match. |
141,642 | <p>Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. </p>
<p>Some limitations are mentioned in the <a href="http://ivan.truemesh.com/archives/000411.html" rel="noreferrer">Closures in Python</a> (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.</p>
<p>Seeing a code example for a concrete limitation would be great.</p>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python">Can you explain closures (as they relate to Python)?</a></li>
<li><a href="https://stackoverflow.com/questions/36636/what-is-a-closure">What is a ‘Closure’?</a></li>
<li><a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How does a javascript closure work ?</a></li>
</ul>
| [
{
"answer_id": 141670,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>The only difficulty I've seen people encounter with Python's in particular is when they try to mix non-functional f... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
] | Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures.
Some limitations are mentioned in the [Closures in Python](http://ivan.truemesh.com/archives/000411.html) (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.
Seeing a code example for a concrete limitation would be great.
**Related questions**:
* [Can you explain closures (as they relate to Python)?](https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python)
* [What is a ‘Closure’?](https://stackoverflow.com/questions/36636/what-is-a-closure)
* [How does a javascript closure work ?](https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work) | The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:
```
>>> def outer(x):
... def inner_reads():
... # Will return outer's 'x'.
... return x
... def inner_writes(y):
... # Will assign to a local 'x', not the outer 'x'
... x = y
... def inner_error(y):
... # Will produce an error: 'x' is local because of the assignment,
... # but we use it before it is assigned to.
... tmp = x
... x = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
5
>>> inner_error(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in inner_error
UnboundLocalError: local variable 'x' referenced before assignment
```
A name that gets assigned to in a local scope (a function) is always local, unless declared otherwise. While there is the 'global' declaration to declare a variable global even when it is assigned to, there is no such declaration for enclosed variables -- yet. In Python 3.0, there is (will be) the 'nonlocal' declaration that does just that.
You can work around this limitation in the mean time by using a mutable container type:
```
>>> def outer(x):
... x = [x]
... def inner_reads():
... # Will return outer's x's first (and only) element.
... return x[0]
... def inner_writes(y):
... # Will look up outer's x, then mutate it.
... x[0] = y
... def inner_error(y):
... # Will now work, because 'x' is not assigned to, just referenced.
... tmp = x[0]
... x[0] = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
10
>>> inner_error(15)
10
>>> inner_reads()
15
``` |
141,650 | <p>I've seen <a href="https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function">the other post about this</a>, but is there a clean way of doing this in Haskell?</p>
<p>As a 2nd part, can it also be done without making the function monadic?</p>
| [
{
"answer_id": 142269,
"author": "mattiast",
"author_id": 8272,
"author_profile": "https://Stackoverflow.com/users/8272",
"pm_score": 1,
"selected": false,
"text": "<p>If your arguments are going to be natural numbers, you can do simply:</p>\n\n<pre><code>memo f = let values = map f [0..... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12887/"
] | I've seen [the other post about this](https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function), but is there a clean way of doing this in Haskell?
As a 2nd part, can it also be done without making the function monadic? | This largely follows <http://www.haskell.org/haskellwiki/Memoization>.
You want a function of type (a -> b). If it doesn't call itself, then
you can just write a simple wrapper that caches the return values. The
best way to store this mapping depends on what properties of a you can
exploit. Ordering is pretty much a minimum. With integers
you can construct an infinite lazy list or tree holding the values.
```
type Cacher a b = (a -> b) -> a -> b
positive_list_cacher :: Cacher Int b
positive_list_cacher f n = (map f [0..]) !! n
```
or
```
integer_list_cacher :: Cacher Int b
integer_list_cacher f n = (map f (interleave [0..] [-1, -2, ..]) !!
index n where
index n | n < 0 = 2*abs(n) - 1
index n | n >= 0 = 2 * n
```
So, suppose it is recursive. Then you need it to call not itself, but
the memoized version, so you pass that in instead:
```
f_with_memo :: (a -> b) -> a -> b
f_with_memo memoed base = base_answer
f_with_memo memoed arg = calc (memoed (simpler arg))
```
The memoized version is, of course, what we're trying to define.
But we can start by creating a function that caches its inputs:
We could construct one level by passing in a function that creates a
structure that caches values. Except we need to create the version of f
that *already has* the cached function passed in.
Thanks to laziness, this is no problem:
```
memoize cacher f = cached where
cached = cacher (f cached)
```
then all we need is to use it:
```
exposed_f = memoize cacher_for_f f
```
The article gives hints as to how to use a type class selecting on the
input to the function to do the above, rather than choosing an explicit
caching function. This can be really nice -- rather than explicitly
constructing a cache for each combination of input types, we can implicitly
combine caches for types a and b into a cache for a function taking a and b.
One final caveat: using this lazy technique means the cache never shrinks,
it only grows. If you instead use the IO monad, you can manage this, but
doing it wisely depends on usage patterns. |
141,682 | <p>I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION_SCHEMA.</p>
<p>I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere.</p>
<p>Are they not there? (I'm using MS SQL Server 2000).</p>
<p>EDIT: I'm looking to get by the name of the constraint.</p>
| [
{
"answer_id": 141825,
"author": "user12861",
"author_id": 12861,
"author_profile": "https://Stackoverflow.com/users/12861",
"pm_score": 2,
"selected": false,
"text": "<p>Is the COLUMN_DEFAULT column of INFORMATION_SCHEMA.COLUMNS what you are looking for?</p>\n"
},
{
"answer_id":... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9052/"
] | I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION\_SCHEMA.
I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere.
Are they not there? (I'm using MS SQL Server 2000).
EDIT: I'm looking to get by the name of the constraint. | As I understand it, default value constraints aren't part of the ISO standard, so they don't appear in INFORMATION\_SCHEMA. INFORMATION\_SCHEMA seems like the best choice for this kind of task because it is cross-platform, but if the information isn't available one should use the object catalog views (sys.\*) instead of system table views, which are deprecated in SQL Server 2005 and later.
Below is pretty much the same as @user186476's answer. It returns the name of the default value constraint for a given column. (For non-SQL Server users, you need the name of the default in order to drop it, and if you don't name the default constraint yourself, SQL Server creates some crazy name like "DF\_TableN\_Colum\_95AFE4B5". To make it easier to change your schema in the future, always explicitly name your constraints!)
```
-- returns name of a column's default value constraint
SELECT
default_constraints.name
FROM
sys.all_columns
INNER JOIN
sys.tables
ON all_columns.object_id = tables.object_id
INNER JOIN
sys.schemas
ON tables.schema_id = schemas.schema_id
INNER JOIN
sys.default_constraints
ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = 'dbo'
AND tables.name = 'tablename'
AND all_columns.name = 'columnname'
``` |
141,734 | <p>If I do not specify the following in my web.xml file:</p>
<pre><code><session-config>
<session-timeout>10</session-timeout>
</session-config>
</code></pre>
<p>What will be my default session timeout? (I am running Tomcat 6.0)</p>
| [
{
"answer_id": 141742,
"author": "JavadocMD",
"author_id": 9304,
"author_profile": "https://Stackoverflow.com/users/9304",
"pm_score": 3,
"selected": false,
"text": "<p>I'm sure it depends on your container. Tomcat is 30 minutes.</p>\n"
},
{
"answer_id": 141755,
"author": "Hu... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318/"
] | If I do not specify the following in my web.xml file:
```
<session-config>
<session-timeout>10</session-timeout>
</session-config>
```
What will be my default session timeout? (I am running Tomcat 6.0) | If you're using Tomcat, it's 30 minutes. You can read more about it [here](http://forums.sun.com/thread.jspa?threadID=565341&messageID=2788327). |
141,752 | <p>My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values are different about 1/2 of the cases.</p>
<p>Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug.</p>
<p>For example:</p>
<pre><code>LEFTPOS and SPACING are defined floating point values.
float def_x;
int xpos;
def_x = LEFTPOS + (xpos * (SPACING / 2));
</code></pre>
<p>The issue is in regards to the X360 compiler.</p>
| [
{
"answer_id": 141771,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": 2,
"selected": false,
"text": "<p>It's not a bug. Any floating point uperation has a certain imprecision. In Release mode, optimization will change the or... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] | My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values are different about 1/2 of the cases.
Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug.
For example:
```
LEFTPOS and SPACING are defined floating point values.
float def_x;
int xpos;
def_x = LEFTPOS + (xpos * (SPACING / 2));
```
The issue is in regards to the X360 compiler. | Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes. |
141,779 | <p>The problem/comic in question: <a href="http://xkcd.com/287/" rel="nofollow noreferrer">http://xkcd.com/287/</a></p>
<p><img src="https://imgs.xkcd.com/comics/np_complete.png" alt="General solutions get you a 50% tip"></p>
<p>I'm not sure this is the best way to do it, but here's what I've come up with so far. I'm using CFML, but it should be readable by anyone.</p>
<pre><code><cffunction name="testCombo" returntype="boolean">
<cfargument name="currentCombo" type="string" required="true" />
<cfargument name="currentTotal" type="numeric" required="true" />
<cfargument name="apps" type="array" required="true" />
<cfset var a = 0 />
<cfset var found = false />
<cfloop from="1" to="#arrayLen(arguments.apps)#" index="a">
<cfset arguments.currentCombo = listAppend(arguments.currentCombo, arguments.apps[a].name) />
<cfset arguments.currentTotal = arguments.currentTotal + arguments.apps[a].cost />
<cfif arguments.currentTotal eq 15.05>
<!--- print current combo --->
<cfoutput><strong>#arguments.currentCombo# = 15.05</strong></cfoutput><br />
<cfreturn true />
<cfelseif arguments.currentTotal gt 15.05>
<cfoutput>#arguments.currentCombo# > 15.05 (aborting)</cfoutput><br />
<cfreturn false />
<cfelse>
<!--- less than 15.05 --->
<cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br />
<cfset found = testCombo(arguments.currentCombo, arguments.currentTotal, arguments.apps) />
</cfif>
</cfloop>
</cffunction>
<cfset mf = {name="Mixed Fruit", cost=2.15} />
<cfset ff = {name="French Fries", cost=2.75} />
<cfset ss = {name="side salad", cost=3.35} />
<cfset hw = {name="hot wings", cost=3.55} />
<cfset ms = {name="moz sticks", cost=4.20} />
<cfset sp = {name="sampler plate", cost=5.80} />
<cfset apps = [ mf, ff, ss, hw, ms, sp ] />
<cfloop from="1" to="6" index="b">
<cfoutput>#testCombo(apps[b].name, apps[b].cost, apps)#</cfoutput>
</cfloop>
</code></pre>
<p>The above code tells me that the only combination that adds up to $15.05 is 7 orders of Mixed Fruit, and it takes 232 executions of my testCombo function to complete.</p>
<p>Is there a better algorithm to come to the correct solution? Did I come to the correct solution?</p>
| [
{
"answer_id": 141858,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>Read up on the <a href=\"http://en.wikipedia.org/wiki/Knapsack_problem\" rel=\"nofollow noreferrer\">Knapsack Pro... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] | The problem/comic in question: <http://xkcd.com/287/>

I'm not sure this is the best way to do it, but here's what I've come up with so far. I'm using CFML, but it should be readable by anyone.
```
<cffunction name="testCombo" returntype="boolean">
<cfargument name="currentCombo" type="string" required="true" />
<cfargument name="currentTotal" type="numeric" required="true" />
<cfargument name="apps" type="array" required="true" />
<cfset var a = 0 />
<cfset var found = false />
<cfloop from="1" to="#arrayLen(arguments.apps)#" index="a">
<cfset arguments.currentCombo = listAppend(arguments.currentCombo, arguments.apps[a].name) />
<cfset arguments.currentTotal = arguments.currentTotal + arguments.apps[a].cost />
<cfif arguments.currentTotal eq 15.05>
<!--- print current combo --->
<cfoutput><strong>#arguments.currentCombo# = 15.05</strong></cfoutput><br />
<cfreturn true />
<cfelseif arguments.currentTotal gt 15.05>
<cfoutput>#arguments.currentCombo# > 15.05 (aborting)</cfoutput><br />
<cfreturn false />
<cfelse>
<!--- less than 15.05 --->
<cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br />
<cfset found = testCombo(arguments.currentCombo, arguments.currentTotal, arguments.apps) />
</cfif>
</cfloop>
</cffunction>
<cfset mf = {name="Mixed Fruit", cost=2.15} />
<cfset ff = {name="French Fries", cost=2.75} />
<cfset ss = {name="side salad", cost=3.35} />
<cfset hw = {name="hot wings", cost=3.55} />
<cfset ms = {name="moz sticks", cost=4.20} />
<cfset sp = {name="sampler plate", cost=5.80} />
<cfset apps = [ mf, ff, ss, hw, ms, sp ] />
<cfloop from="1" to="6" index="b">
<cfoutput>#testCombo(apps[b].name, apps[b].cost, apps)#</cfoutput>
</cfloop>
```
The above code tells me that the only combination that adds up to $15.05 is 7 orders of Mixed Fruit, and it takes 232 executions of my testCombo function to complete.
Is there a better algorithm to come to the correct solution? Did I come to the correct solution? | The point about an NP-complete problem is not that it's tricky on a small data set, but that the amount of work to solve it grows at a rate greater than polynomial, i.e. there is no O(n^x) algorithm.
If the time complexity is O(n!), as in (I believe) the two problems mentioned above, that is in NP. |
141,807 | <p>I've got a really large project I made for myself and rece3ntly a client asked for their own version of it with some modifications. The project name was rather silly and my client wants the source so I figured it'd be best if I renamed all my files from</p>
<pre><code>sillyname.h
sillyname.cpp
sillyname.dsp
</code></pre>
<p>etc..
Unfortunatly after I added everything back together I can't see any way to change the project name itself. Plus now I'm getting this error on compilation.</p>
<pre><code>main.obj : error LNK2001: unresolved external symbol __imp__InitCommonControls@0
Debug/New_Name_Thats_not_so_silly.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
</code></pre>
<p>There has to be an easier way to change all this, right?</p>
| [
{
"answer_id": 141839,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply rename the .vcproj or .dsp file and then either create a new workspace (sln dsw) and include the ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've got a really large project I made for myself and rece3ntly a client asked for their own version of it with some modifications. The project name was rather silly and my client wants the source so I figured it'd be best if I renamed all my files from
```
sillyname.h
sillyname.cpp
sillyname.dsp
```
etc..
Unfortunatly after I added everything back together I can't see any way to change the project name itself. Plus now I'm getting this error on compilation.
```
main.obj : error LNK2001: unresolved external symbol __imp__InitCommonControls@0
Debug/New_Name_Thats_not_so_silly.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
```
There has to be an easier way to change all this, right? | Here is a [Step by Step](http://www.platinumbay.com/blogs/dotneticated/archive/2008/01/01/renaming-and-copying-projects-and-solutions.aspx) on Steve Andrews' blog (he works on Visual Studio at Microsoft) |
141,808 | <p>I have a micro-mini-search engine that highlights the search terms in my rails app. The search ignores accents and the highlight is case insensitive. Almost perfect.
But, for instance if I have a record with the text "pão de queijo" and searches for "pao de queijo" the record <strong>is</strong> returned but the iext <strong>is not</strong> highlighted. Similarly, if I search for "pÃo de queijo" the record is returned but not highlighted properly.</p>
<p>My code is as simple as:</p>
<pre><code><%= highlight(result_pessoa.observacoes, search_string, '<span style="background-color: yellow;">\1</span>') %>
</code></pre>
| [
{
"answer_id": 141823,
"author": "Kolten",
"author_id": 13959,
"author_profile": "https://Stackoverflow.com/users/13959",
"pm_score": 0,
"selected": false,
"text": "<p>it sounds like you are using two different methods for deciding whether a match has occured or not: one for your search,... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] | I have a micro-mini-search engine that highlights the search terms in my rails app. The search ignores accents and the highlight is case insensitive. Almost perfect.
But, for instance if I have a record with the text "pão de queijo" and searches for "pao de queijo" the record **is** returned but the iext **is not** highlighted. Similarly, if I search for "pÃo de queijo" the record is returned but not highlighted properly.
My code is as simple as:
```
<%= highlight(result_pessoa.observacoes, search_string, '<span style="background-color: yellow;">\1</span>') %>
``` | I've just submitted a patch to Rails thats solves this.
<http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3593-patch-support-for-highlighting-with-ignoring-special-chars>
```
# Highlights one or more +phrases+ everywhere in +text+ by inserting it into
# a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
# as a single-quoted string with \1 where the phrase is to be inserted (defaults to
# '<strong class="highlight">\1</strong>')
#
# ==== Examples
# highlight('You searched for: rails', 'rails')
# # => You searched for: <strong class="highlight">rails</strong>
#
# highlight('You searched for: ruby, rails, dhh', 'actionpack')
# # => You searched for: ruby, rails, dhh
#
# highlight('You searched for: rails', ['for', 'rails'], :highlighter => '<em>\1</em>')
# # => You searched <em>for</em>: <em>rails</em>
#
# highlight('You searched for: rails', 'rails', :highlighter => '<a href="search?q=\1">\1</a>')
# # => You searched for: <a href="search?q=rails">rails</a>
#
# highlight('Šumné dievčatá', ['šumňe', 'dievca'], :ignore_special_chars => true)
# # => <strong class="highlight">Šumné</strong> <strong class="highlight">dievča</strong>tá
#
# You can still use <tt>highlight</tt> with the old API that accepts the
# +highlighter+ as its optional third parameter:
# highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a>
def highlight(text, phrases, *args)
options = args.extract_options!
unless args.empty?
options[:highlighter] = args[0] || '<strong class="highlight">\1</strong>'
end
options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>')
if text.blank? || phrases.blank?
text
else
haystack = text.clone
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
if options[:ignore_special_chars]
haystack = haystack.mb_chars.normalize(:kd)
match = match.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]+/n, '').gsub(/\w/, '\0[^\x00-\x7F]*')
end
highlighted = haystack.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter])
highlighted = highlighted.mb_chars.normalize(:kc) if options[:ignore_special_chars]
highlighted
end
end
``` |
141,864 | <p>I need help understanding some C++ operator overload statements. The class is declared like this: </p>
<pre><code>template <class key_t, class ipdc_t>
class ipdc_map_template_t : public ipdc_lockable_t
{
...
typedef map<key_t,
ipdc_t*,
less<key_t>> map_t;
...
</code></pre>
<p>The creator of the class has created an iterator for the internal map structure:</p>
<pre><code>struct iterator : public map_t::iterator
{
iterator() {}
iterator(const map_t::iterator & it)
: map_t::iterator(it) {}
iterator(const iterator & it)
: map_t::iterator(
*static_cast<const map_t::iterator *>(&it)) {}
operator key_t() {return ((this->operator*()).first);} // I don't understand this.
operator ipdc_t*() const {return ((this->operator*()).second);} // or this.
};
</code></pre>
<p>And begin() and end() return the begin() and end() of the map:</p>
<pre><code>iterator begin() {IT_ASSERT(is_owner()); return map.begin();}
iterator end() {return map.end();}
</code></pre>
<p>My question is, if I have an iterator, how do I use those overloads to get the key and the value?</p>
<pre><code>ipdc_map_template_t::iterator iter;
for( iter = my_instance.begin();
iter != my_instance.end();
++iter )
{
key_t my_key = ??????;
ipdc_t *my_value = ??????;
}
</code></pre>
| [
{
"answer_id": 141893,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>The creator of the class has overridden the cast operators.\nSo by just assigning the iter to an object of the corr... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19719/"
] | I need help understanding some C++ operator overload statements. The class is declared like this:
```
template <class key_t, class ipdc_t>
class ipdc_map_template_t : public ipdc_lockable_t
{
...
typedef map<key_t,
ipdc_t*,
less<key_t>> map_t;
...
```
The creator of the class has created an iterator for the internal map structure:
```
struct iterator : public map_t::iterator
{
iterator() {}
iterator(const map_t::iterator & it)
: map_t::iterator(it) {}
iterator(const iterator & it)
: map_t::iterator(
*static_cast<const map_t::iterator *>(&it)) {}
operator key_t() {return ((this->operator*()).first);} // I don't understand this.
operator ipdc_t*() const {return ((this->operator*()).second);} // or this.
};
```
And begin() and end() return the begin() and end() of the map:
```
iterator begin() {IT_ASSERT(is_owner()); return map.begin();}
iterator end() {return map.end();}
```
My question is, if I have an iterator, how do I use those overloads to get the key and the value?
```
ipdc_map_template_t::iterator iter;
for( iter = my_instance.begin();
iter != my_instance.end();
++iter )
{
key_t my_key = ??????;
ipdc_t *my_value = ??????;
}
``` | These are typecast operators, so you can do this:
```
{
key_t key = iter;
ipdc_t *val = iter;
}
```
Or, since `ipdc_map_template::iterator` is a subclass of `std::map::iterator`, you can still use the original accessors (which I find more readable):
```
{
key_t key = (*iter).first;
ipdc_t *val = (*iter).second;
// or, equivalently
key_t key = iter->first;
ipdc_t *val = iter->second;
}
``` |
141,875 | <p>What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:</p>
<pre><code>number: (MONTH|INT);
</code></pre>
<p>It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:</p>
<pre><code>date: month '/' day ( '/' year )? -> ^('DATE' year month day);
</code></pre>
<p>I don't care if month,day & year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:</p>
<pre><code>foo: STRING OP number -> ^(OP STRING number);
STRING: ('a'..'z')+;
OP: ('<'|'>');
</code></pre>
| [
{
"answer_id": 142009,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your p... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12034/"
] | What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:
```
number: (MONTH|INT);
```
It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:
```
date: month '/' day ( '/' year )? -> ^('DATE' year month day);
```
I don't care if month,day & year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:
```
foo: STRING OP number -> ^(OP STRING number);
STRING: ('a'..'z')+;
OP: ('<'|'>');
``` | The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your parser. It's a common mistake, and something that is only possible in very simple languages.
What you really need to do is accept more broadly in the lexer and parser, and then perform semantic checks. How strict you are in your lexing is up to you, but you have two basic options, depending on whether or not you need to accept zeroes preceding your days of the month: 1) Be really accepting for your INTs, 2) define DATENUM to only accept those tokens that are valid days, yet not valid INTs. I recommend the second because there will be less semantic checks necessary later in the code (since INTs will then be verifiable at the syntax level and you'll only need to perform semantic checks on your dates. The first approach:
```
INT: '0'..'9'+;
```
The second approach:
```
DATENUM: '0' '1'..'9';
INT: '0' | SIGN? '1'..'9' '0'..'9'*;
```
After accepting using these rules in the lexer, your date field would be either:
```
date: INT '/' INT ( '/' INT )?
```
or:
```
date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )?
```
After that, you would perform a semantic run over your AST to make sure that your dates are valid.
If you're dead set on performing semantic checks in your grammar, however, ANTLR allows semantic predicates in the parser, so you could make a date field that checks the values like this:
```
date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)}
```
When you do this, however, you are embedding language specific code in your grammar, and it won't be portable across targets. |
141,876 | <p>Platform: Windows XP
Development Platform: VB6</p>
<p>When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed.</p>
<p>Does anyone have a workaround or fix for this? </p>
<hr>
<p>Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) . </p>
<p>Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string. </p>
<p>I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB. </p>
| [
{
"answer_id": 142183,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "<p>It appears that VB6 limits the App.Title property to 40 characters. Unfortunately, I can't locate any documentation o... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820/"
] | Platform: Windows XP
Development Platform: VB6
When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed.
Does anyone have a workaround or fix for this?
---
Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) .
Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string.
I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB. | One solution using the Windows API
----------------------------------
**Disclaimer**: *IMHO this seems like overkill just to meet the requirement stated in the question, but in the spirit of giving a (hopefully) complete answer to the problem, here goes nothing...*
Here is a working version I came up with after looking around in MSDN for awhile, until I finally came upon an article on vbAccelerator that got my wheels turning.
* See the [vbAccelerator](http://www.vbaccelerator.com/home/VB/Tips/Get_System_Display_Fonts_and_Non-Client_Area_Sizes/article.asp) page for the original article (not directly related to the question, but there was enough there for me to formulate an answer)
The basic premise is to first calculate the width of the form's caption text and then to use **GetSystemMetrics** to get the width of various bits of the window, such as the border and window frame width, the width of the Minimize, Maximize, and Close buttons, and so on (I split these into their own functions for readibility/clarity). We need to account for these parts of the window in order to calculate an accurate new width for the form.
In order to accurately calculate the width ("extent") of the form's caption, we need to get the system caption font, hence the **SystemParametersInfo** and **CreateFontIndirect** calls and related goodness.
The end result all this effort is the **GetRecommendedWidth** function, which calculates all of these values and adds them together, plus a bit of extra padding so that there is some space between the last character of the caption and the control buttons. If this new width is greater than the form's current width, GetRecommendedWidth will return this (larger) width, otherwise, it will return the Form's current width.
I only tested it briefly, but it appears to work fine. Since it uses Windows API functions, however, you may want to exercise caution, especially since it's copying memory around. I didn't add robust error-handling, either.
By the way, if someone has a cleaner, less-involved way of doing this, or if I missed something in my own code, please let me know.
**To try it out, paste the following code into a new module**
```
Option Explicit
Private Type SIZE
cx As Long
cy As Long
End Type
Private Const LF_FACESIZE = 32
'NMLOGFONT: This declaration came from vbAccelerator (here is what he says about it):'
' '
' For some bizarre reason, maybe to do with byte '
' alignment, the LOGFONT structure we must apply '
' to NONCLIENTMETRICS seems to require an LF_FACESIZE '
' 4 bytes smaller than normal: '
Private Type NMLOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE - 4) As Byte
End Type
Private Type LOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE) As Byte
End Type
Private Type NONCLIENTMETRICS
cbSize As Long
iBorderWidth As Long
iScrollWidth As Long
iScrollHeight As Long
iCaptionWidth As Long
iCaptionHeight As Long
lfCaptionFont As NMLOGFONT
iSMCaptionWidth As Long
iSMCaptionHeight As Long
lfSMCaptionFont As NMLOGFONT
iMenuWidth As Long
iMenuHeight As Long
lfMenuFont As NMLOGFONT
lfStatusFont As NMLOGFONT
lfMessageFont As NMLOGFONT
End Type
Private Enum SystemMetrics
SM_CXBORDER = 5
SM_CXDLGFRAME = 7
SM_CXFRAME = 32
SM_CXSCREEN = 0
SM_CXICON = 11
SM_CXICONSPACING = 38
SM_CXSIZE = 30
SM_CXEDGE = 45
SM_CXSMICON = 49
SM_CXSMSIZE = 52
End Enum
Private Const SPI_GETNONCLIENTMETRICS = 41
Private Const SPI_SETNONCLIENTMETRICS = 42
Private Declare Function GetTextExtentPoint32 Lib "gdi32" Alias "GetTextExtentPoint32A" _
(ByVal hdc As Long, _
ByVal lpszString As String, _
ByVal cbString As Long, _
lpSize As SIZE) As Long
Private Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As SystemMetrics) As Long
Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" ( _
ByVal uAction As Long, _
ByVal uParam As Long, _
lpvParam As Any, _
ByVal fuWinIni As Long) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
Private Declare Function CreateFontIndirect Lib "gdi32" Alias "CreateFontIndirectA" (lpLogFont As LOGFONT) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Function GetCaptionTextWidth(ByVal frm As Form) As Long
'-----------------------------------------------'
' This function does the following: '
' '
' 1. Get the font used for the forms caption '
' 2. Call GetTextExtent32 to get the width in '
' pixels of the forms caption '
' 3. Convert the width from pixels into '
' the scaling mode being used by the form '
' '
'-----------------------------------------------'
Dim sz As SIZE
Dim hOldFont As Long
Dim hCaptionFont As Long
Dim CaptionFont As LOGFONT
Dim ncm As NONCLIENTMETRICS
ncm.cbSize = LenB(ncm)
If SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, ncm, 0) = 0 Then
' What should we do if we the call fails? Change as needed for your app,'
' but this call is unlikely to fail anyway'
Exit Function
End If
CopyMemory CaptionFont, ncm.lfCaptionFont, LenB(CaptionFont)
hCaptionFont = CreateFontIndirect(CaptionFont)
hOldFont = SelectObject(frm.hdc, hCaptionFont)
GetTextExtentPoint32 frm.hdc, frm.Caption, Len(frm.Caption), sz
GetCaptionTextWidth = frm.ScaleX(sz.cx, vbPixels, frm.ScaleMode)
'clean up, otherwise bad things will happen...'
DeleteObject (SelectObject(frm.hdc, hOldFont))
End Function
Private Function GetControlBoxWidth(ByVal frm As Form) As Long
Dim nButtonWidth As Long
Dim nButtonCount As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
nButtonCount = 1 'close button is always present'
nButtonWidth = GetSystemMetrics(SM_CXSIZE) 'get width of a single button in the titlebar'
' account for min and max buttons if they are visible'
If frm.MinButton Then nButtonCount = nButtonCount + 1
If frm.MaxButton Then nButtonCount = nButtonCount + 1
nFinalWidth = nButtonWidth * nButtonCount
End If
'convert to whatever scale the form is using'
GetControlBoxWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetIconWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog, vbSizable:
'we have an icon, gets its width'
nFinalWidth = GetSystemMetrics(SM_CXSMICON)
Case Else:
'no icon present, so report zero width'
nFinalWidth = 0
End Select
End If
'convert to whatever scale the form is using'
GetIconWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetFrameWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog:
nFinalWidth = GetSystemMetrics(SM_CXDLGFRAME)
Case vbSizable:
nFinalWidth = GetSystemMetrics(SM_CXFRAME)
End Select
End If
'convert to whatever scale the form is using'
GetFrameWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetBorderWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.Appearance
Case 0 'flat'
nFinalWidth = GetSystemMetrics(SM_CXBORDER)
Case 1 '3D'
nFinalWidth = GetSystemMetrics(SM_CXEDGE)
End Select
End If
'convert to whatever scale the form is using'
GetBorderWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Public Function GetRecommendedWidth(ByVal frm As Form) As Long
Dim nNewWidth As Long
' An abitrary amount of extra padding so that the caption text '
' is not scrunched up against the min/max/close buttons '
Const PADDING_TWIPS = 120
nNewWidth = _
GetCaptionTextWidth(frm) _
+ GetControlBoxWidth(frm) _
+ GetIconWidth(frm) _
+ GetFrameWidth(frm) * 2 _
+ GetBorderWidth(frm) * 2 _
+ PADDING_TWIPS
If nNewWidth > frm.Width Then
GetRecommendedWidth = nNewWidth
Else
GetRecommendedWidth = frm.Width
End If
End Function
```
**Then place the following in your Form\_Load event**
```
Private Sub Form_Load()
Me.Caption = String(100, "x") 'replace this with your caption'
Me.Width = GetRecommendedWidth(Me)
End Sub
``` |
141,878 | <p>The following snippet is supposed to take the value of PROJECT (defined in the Makefile)
and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR</p>
<p>I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?</p>
<pre><code>#define PROJECT classifier
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)
#include PROJECTINCSTR
</code></pre>
<p>Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.</p>
| [
{
"answer_id": 141919,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 0,
"selected": false,
"text": "<p>That barebone example works with gcc (v4.1.2) and tries to include \"PROJECT_ir.h\"</p>\n"
},
{
"answer_id": 14... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22781/"
] | The following snippet is supposed to take the value of PROJECT (defined in the Makefile)
and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier\_ir.h for PROJECTINCSTR
I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?
```
#define PROJECT classifier
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)
#include PROJECTINCSTR
```
Edit: The compiler should try to include classifier\_ir.h, not PROJECT\_ir.h. | ```
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define SMASH(x,y) x##y
#define MAKEINC(x) SMASH(x,_ir.h)
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)
``` |
141,913 | <p>I'm parsing XML results from an API call using PHP and xpath. </p>
<pre><code> $dom = new DOMDocument();
$dom->loadXML($response->getBody());
$xpath = new DOMXPath($dom);
$xpath->registerNamespace("a", "http://www.example.com");
$hrefs = $xpath->query('//a:Books/text()', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookTitle[$i] = $hrefs->item($i)->data;
}
$hrefs = $xpath->query('//a:Books', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
}
</code></pre>
<p>This works but is there a way I can access both the text and the attribute from one query? And if so how do you get to those items once query is executed?</p>
| [
{
"answer_id": 141933,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>Could you query for the concatenation?</p>\n\n<pre><code>$xpath->query('concat(//a:Books/text(), //a:Books/@DeweyDe... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2863/"
] | I'm parsing XML results from an API call using PHP and xpath.
```
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
$xpath = new DOMXPath($dom);
$xpath->registerNamespace("a", "http://www.example.com");
$hrefs = $xpath->query('//a:Books/text()', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookTitle[$i] = $hrefs->item($i)->data;
}
$hrefs = $xpath->query('//a:Books', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
}
```
This works but is there a way I can access both the text and the attribute from one query? And if so how do you get to those items once query is executed? | After doing some looking around I came across this solution. This way I can get the element text and access any attributes of the node.
```
$hrefs = $xpath->query('//a:Books', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookTitle[$i] = $hrefs->item($i)->nodeValue;
$arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
}
``` |
141,939 | <p>I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting </p>
<pre><code>./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj
</code></pre>
<p>Which c++filt describes as </p>
<pre><code>std::_Rb_tree<unsigned int, unsigned int, std::_Identity<unsigned int>, std::less<unsigned int>, std::allocator<unsigned int> >::insert_unique(unsigned int const&)
</code></pre>
<p>I thought this might have come from using hash_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including <code>-lstdc++</code>.</p>
<p>Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?</p>
<p><em>EDIT:</em> After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.</p>
| [
{
"answer_id": 141957,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": 1,
"selected": false,
"text": "<p><code>std::_Rb_Tree</code> might be a red-black tree, which would most likely be from using <code>map</code>. It should ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17209/"
] | I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting
```
./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj
```
Which c++filt describes as
```
std::_Rb_tree<unsigned int, unsigned int, std::_Identity<unsigned int>, std::less<unsigned int>, std::allocator<unsigned int> >::insert_unique(unsigned int const&)
```
I thought this might have come from using hash\_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including `-lstdc++`.
Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?
*EDIT:* After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug. | `std::_Rb_Tree` might be a red-black tree, which would most likely be from using `map`. It should be part of `libstdc++`, unless your library is linking against a different version of `libstdc++` than the application, which from what you've said so far seems unlikely.
EDIT: Just to clarify, the red-black tree is the underlying data structure in `map`. All that `hash_map` does is hash the key before using it, rather than using the raw value. |
141,970 | <p>I'm experimenting with generics and I'm trying to create structure similar to Dataset class.<br>
I have following code</p>
<pre><code>public struct Column<T>
{
T value;
T originalValue;
public bool HasChanges
{
get { return !value.Equals(originalValue); }
}
public void AcceptChanges()
{
originalValue = value;
}
}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
public bool HasChanges
{
get
{
return id.HasChanges | name.HasChanges | someDate.HasChanges | someInt.HasChanges;
}
}
public void AcceptChanges()
{
id.AcceptChanges();
name.AcceptChanges();
someDate.AcceptChanges();
someInt.AcceptChanges();
}
}
</code></pre>
<p>Problem I have is that when I add new column I need to add it also in HasChanges property and AcceptChanges() method. This just asks for some refactoring.<br>
So first solution that cames to my mind was something like this:</p>
<pre><code>public interface IColumn
{
bool HasChanges { get; }
void AcceptChanges();
}
public struct Column<T> : IColumn {...}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
IColumn[] Columns { get { return new IColumn[] {id, name, someDate, someInt}; }}
public bool HasChanges
{
get
{
bool has = false;
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
has |= columns[i].HasChanges;
return has;
}
}
public void AcceptChanges()
{
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
columns[i].AcceptChanges(); //Here we are changing clone
}
}
</code></pre>
<p>As you can see from comments we have few problems here with struct cloning. Simple solution to this is to change Column to class, but from my tests it seems that it increases memory usage by ~40% (because of each object metadata) which is not acceptable for me.
<br>
<br>
So my question is: does anyone have any other ideas how to create methods that can work on different structured objects/records? Maybe someone from F# community can suggest how such problems are solved in functional languages and how it impacts performance and memory usage.
<br>
<br>
<strong>Edit:</strong><br>
sfg thanks for suggestion about macros.<br>
In Visual Studio 2008 there is built-in (but not so known) template engine called T4. Tha whole point is to add '.tt' file to my project and create a template that will search all my classes, recognize somehow the ones that are records (for example by some interface they implement) and produce partial classes with HasChanges and AcceptChanges() that will call only Columns the class contain.<br><br>
Some usefull links:<br>
<a href="http://www.t4editor.net/" rel="nofollow noreferrer" title="T4 Editor for VS">T4 Editor for VS</a><br>
<a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/" rel="nofollow noreferrer" title="Blog with links and tutorials about T4">Blog with links and tutorials about T4</a><br>
<a href="http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/" rel="nofollow noreferrer" title="Blog entry with example that uses EnvDTE to read project files">Blog entry with example that uses EnvDTE to read project files</a></p>
| [
{
"answer_id": 142115,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>You could use reflection to iterate over the members and invoke HasChanges and AcceptChanges. The Record class could ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22569/"
] | I'm experimenting with generics and I'm trying to create structure similar to Dataset class.
I have following code
```
public struct Column<T>
{
T value;
T originalValue;
public bool HasChanges
{
get { return !value.Equals(originalValue); }
}
public void AcceptChanges()
{
originalValue = value;
}
}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
public bool HasChanges
{
get
{
return id.HasChanges | name.HasChanges | someDate.HasChanges | someInt.HasChanges;
}
}
public void AcceptChanges()
{
id.AcceptChanges();
name.AcceptChanges();
someDate.AcceptChanges();
someInt.AcceptChanges();
}
}
```
Problem I have is that when I add new column I need to add it also in HasChanges property and AcceptChanges() method. This just asks for some refactoring.
So first solution that cames to my mind was something like this:
```
public interface IColumn
{
bool HasChanges { get; }
void AcceptChanges();
}
public struct Column<T> : IColumn {...}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
IColumn[] Columns { get { return new IColumn[] {id, name, someDate, someInt}; }}
public bool HasChanges
{
get
{
bool has = false;
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
has |= columns[i].HasChanges;
return has;
}
}
public void AcceptChanges()
{
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
columns[i].AcceptChanges(); //Here we are changing clone
}
}
```
As you can see from comments we have few problems here with struct cloning. Simple solution to this is to change Column to class, but from my tests it seems that it increases memory usage by ~40% (because of each object metadata) which is not acceptable for me.
So my question is: does anyone have any other ideas how to create methods that can work on different structured objects/records? Maybe someone from F# community can suggest how such problems are solved in functional languages and how it impacts performance and memory usage.
**Edit:**
sfg thanks for suggestion about macros.
In Visual Studio 2008 there is built-in (but not so known) template engine called T4. Tha whole point is to add '.tt' file to my project and create a template that will search all my classes, recognize somehow the ones that are records (for example by some interface they implement) and produce partial classes with HasChanges and AcceptChanges() that will call only Columns the class contain.
Some usefull links:
[T4 Editor for VS](http://www.t4editor.net/ "T4 Editor for VS")
[Blog with links and tutorials about T4](http://www.olegsych.com/2007/12/text-template-transformation-toolkit/ "Blog with links and tutorials about T4")
[Blog entry with example that uses EnvDTE to read project files](http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/ "Blog entry with example that uses EnvDTE to read project files") | As you asked for examples from functional languages; in lisp you could prevent the writing of all that code upon each addition of a column by using a macro to crank the code out for you. Sadly, I do not think that is possible in C#.
In terms of performance: the macro would be evaluated at compile time (thus slowing compilation a tiny amount), but would cause no slow-down at run-time as the run-time code would be the same as what you would write manually.
I think you might have to accept your original AcceptChanges() as you need to access the structs directly by their identifiers if you want to avoid writing to cloned versions.
In other words: you need a program to write the program for you, and I do not know how to do that in C# without going to extraordinary lengths or losing more in performance than you ever would by switching the structs to classes (e.g. reflection). |
141,973 | <p>Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.</p>
<p>EDIT: Here is what I have unsuccessfully tried:</p>
<pre><code>class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return self._series
</code></pre>
<p>And in my template:</p>
<pre><code><a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>
</code></pre>
<p>The result:</p>
<pre><code><a href="games/view-series.html?series=#comm59">more</a>
</code></pre>
| [
{
"answer_id": 142106,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 1,
"selected": false,
"text": "<p>You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it di... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
] | Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an \_, but I have been unable to get any code working. Examples would be much appreciated. Thanks.
EDIT: Here is what I have unsuccessfully tried:
```
class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return self._series
```
And in my template:
```
<a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>
```
The result:
```
<a href="games/view-series.html?series=#comm59">more</a>
``` | Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '\_' in python are generally accepted to be "protected" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes.
However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example:
```
class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return Comment.series.get_value_for_datastore(self)
```
When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values. |
141,993 | <p>I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.</p>
<p>When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)</p>
<p>I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage. </p>
<p>So, boiled down, the question is:</p>
<p>Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.</p>
| [
{
"answer_id": 142004,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://xom.nu\" rel=\"noreferrer\">Xom</a> has a Canonicalizer utility which turns your DOMs into a regular ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/141993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247/"
] | I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.
When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)
I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage.
So, boiled down, the question is:
Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are. | Sounds like a job for XMLUnit
* <http://www.xmlunit.org/>
* <https://github.com/xmlunit>
Example:
```
public class SomeTest extends XMLTestCase {
@Test
public void test() {
String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences
// can also compare xml Documents, InputSources, Readers, Diffs
assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase
}
}
``` |
142,000 | <p>I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with <code>e.preventDefault()</code> and runs an AJAX command. This works fine when the submit button is clicked but when a link with <code>onclick='document.formName.submit();'</code> is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?</p>
| [
{
"answer_id": 142021,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using jQuery, you should be attaching events via it's own <a href=\"http://docs.jquery.com/Events\" re... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16624/"
] | I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with `e.preventDefault()` and runs an AJAX command. This works fine when the submit button is clicked but when a link with `onclick='document.formName.submit();'` is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements? | A couple of suggestions:
* Overwrite the submit function to do your evil bidding
```
var oldSubmit = form.submit;
form.submit = function() {
$(form).trigger("submit");
oldSubmit.call(form, arguments);
}
```
* Why not bind to all the <a> tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag):
```
$("form a").click(function() {
$(this).parents().filter("form").trigger("submit");
});
``` |
142,003 | <p>I have a scenario. (Windows Forms, C#, .NET)</p>
<ol>
<li>There is a main form which hosts some user control.</li>
<li>The user control does some heavy data operation, such that if I directly call the <code>UserControl_Load</code> method the UI become nonresponsive for the duration for load method execution.</li>
<li>To overcome this I load data on different thread (trying to change existing code as little as I can)</li>
<li>I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.</li>
<li>Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.</li>
</ol>
<p>The pseudocode would look like this:</p>
<p><strong>CODE 1</strong></p>
<pre><code>UserContrl1_LoadDataMethod()
{
if (textbox1.text == "MyName") // This gives exception
{
//Load data corresponding to "MyName".
//Populate a globale variable List<string> which will be binded to grid at some later stage.
}
}
</code></pre>
<p>The Exception it gave was</p>
<blockquote>
<p>Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.</p>
</blockquote>
<p>To know more about this I did some googling and a suggestion came up like using the following code</p>
<p><strong>CODE 2</strong></p>
<pre><code>UserContrl1_LoadDataMethod()
{
if (InvokeRequired) // Line #1
{
this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));
return;
}
if (textbox1.text == "MyName") // Now it won't give an exception
{
//Load data correspondin to "MyName"
//Populate a globale variable List<string> which will be binded to grid at some later stage
}
}
</code></pre>
<p>But it still seems that I've come back to square one. The Application again
becomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.</p>
<p>I don't know whether I perceived this right or wrong. I'm new to threading.</p>
<p>How do I resolve this and also what is the effect of execution of Line#1 if block?</p>
<p><strong>The situation is this</strong>: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.</p>
<p>So only accessing the value so that the corresponding data can be fetched from the database.</p>
| [
{
"answer_id": 142053,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<p>Controls in .NET are not generally thread safe. That means you shouldn't access a control from a thread other than... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22858/"
] | I have a scenario. (Windows Forms, C#, .NET)
1. There is a main form which hosts some user control.
2. The user control does some heavy data operation, such that if I directly call the `UserControl_Load` method the UI become nonresponsive for the duration for load method execution.
3. To overcome this I load data on different thread (trying to change existing code as little as I can)
4. I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.
5. Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.
The pseudocode would look like this:
**CODE 1**
```
UserContrl1_LoadDataMethod()
{
if (textbox1.text == "MyName") // This gives exception
{
//Load data corresponding to "MyName".
//Populate a globale variable List<string> which will be binded to grid at some later stage.
}
}
```
The Exception it gave was
>
> Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.
>
>
>
To know more about this I did some googling and a suggestion came up like using the following code
**CODE 2**
```
UserContrl1_LoadDataMethod()
{
if (InvokeRequired) // Line #1
{
this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));
return;
}
if (textbox1.text == "MyName") // Now it won't give an exception
{
//Load data correspondin to "MyName"
//Populate a globale variable List<string> which will be binded to grid at some later stage
}
}
```
But it still seems that I've come back to square one. The Application again
becomes unresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.
I don't know whether I perceived this right or wrong. I'm new to threading.
How do I resolve this and also what is the effect of execution of Line#1 if block?
**The situation is this**: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.
So only accessing the value so that the corresponding data can be fetched from the database. | As per [Prerak K's update comment](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the#142108) (since deleted):
>
> I guess I have not presented the question properly.
>
>
> Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.
>
>
> So only accessing the value so that corresponding data can be fetched from the database.
>
>
>
The solution you want then should look like:
```
UserContrl1_LOadDataMethod()
{
string name = "";
if(textbox1.InvokeRequired)
{
textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));
}
if(name == "MyName")
{
// do whatever
}
}
```
Do your serious processing in the separate thread *before* you attempt to switch back to the control's thread. For example:
```
UserContrl1_LOadDataMethod()
{
if(textbox1.text=="MyName") //<<======Now it wont give exception**
{
//Load data correspondin to "MyName"
//Populate a globale variable List<string> which will be
//bound to grid at some later stage
if(InvokeRequired)
{
// after we've done all the processing,
this.Invoke(new MethodInvoker(delegate {
// load the control with the appropriate data
}));
return;
}
}
}
``` |
142,010 | <p>Say I have the following XML...</p>
<pre><code><root>
<base>
<tent key="1" color="red"/>
<tent key="2" color="yellow"/>
<tent key="3" color="blue"/>
</base>
<bucket>
<tent key="1"/>
<tent key="3"/>
</bucket>
</root>
</code></pre>
<p>...what would the XPath be that returns that the "bucket" contains "red" and "blue"?</p>
| [
{
"answer_id": 142067,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 2,
"selected": false,
"text": "<p>I think this will work:</p>\n\n<pre><code>/root/base/tent[/root/bucket/tent/@key = @key ]/@color\n</code></pr... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] | Say I have the following XML...
```
<root>
<base>
<tent key="1" color="red"/>
<tent key="2" color="yellow"/>
<tent key="3" color="blue"/>
</base>
<bucket>
<tent key="1"/>
<tent key="3"/>
</bucket>
</root>
```
...what would the XPath be that returns that the "bucket" contains "red" and "blue"? | If you're using XSLT, I'd recommend setting up a key:
```
<xsl:key name="tents" match="base/tent" use="@key" />
```
You can then get the `<tent>` within `<base>` with a particular `key` using
```
key('tents', $id)
```
Then you can do
```
key('tents', /root/bucket/tent/@key)/@color
```
or, if `$bucket` is a particular `<bucket>` element,
```
key('tents', $bucket/tent/@key)/@color
``` |
142,016 | <p>I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.</p>
<p>IE: given</p>
<pre><code>struct mstct {
int myfield;
int myfield2;
};
</code></pre>
<p>I could write:</p>
<pre><code>mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));
</code></pre>
<p>And get <code>offset 4</code> for the output. How can I do it without that <code>mstct thing</code> declaration/allocating one?</p>
<p>I know that <code>&<struct></code> does not always point at the first byte of the first field of the structure, I can account for that later.</p>
| [
{
"answer_id": 142023,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 7,
"selected": true,
"text": "<p>How about the standard offsetof() macro (in stddef.h)?</p>\n\n<p>Edit: for people who might not have the offsetof()... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4777/"
] | I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.
IE: given
```
struct mstct {
int myfield;
int myfield2;
};
```
I could write:
```
mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));
```
And get `offset 4` for the output. How can I do it without that `mstct thing` declaration/allocating one?
I know that `&<struct>` does not always point at the first byte of the first field of the structure, I can account for that later. | How about the standard offsetof() macro (in stddef.h)?
Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:
```
#define OFFSETOF(type, field) ((unsigned long) &(((type *) 0)->field))
``` |
142,042 | <p>I want to attach an xslt stylesheet to an XML document that I build with XMLBuilder. This is done with a Processing Instruction that looks like</p>
<pre><code><?xml-stylesheet type='text/xsl' href='/stylesheets/style.xslt' ?>
</code></pre>
<p>Normally, I'd use the <code>instruct!</code> method, but <code>:xml-stylesheet</code> is not a valid Ruby symbol.</p>
<p>XMLBuilder has a solution for this case for elements using <code>tag!</code> method, but I don't see the equivalent for Processing Instructions.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 142077,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not sure this will solve your problem since I don't know the instruct! method of that object, but :'xml-stylesheet... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10026/"
] | I want to attach an xslt stylesheet to an XML document that I build with XMLBuilder. This is done with a Processing Instruction that looks like
```
<?xml-stylesheet type='text/xsl' href='/stylesheets/style.xslt' ?>
```
Normally, I'd use the `instruct!` method, but `:xml-stylesheet` is not a valid Ruby symbol.
XMLBuilder has a solution for this case for elements using `tag!` method, but I don't see the equivalent for Processing Instructions.
Any ideas? | I'm not sure this will solve your problem since I don't know the instruct! method of that object, but :'xml-stylesheet' is a valid ruby symbol. |
142,090 | <p>I'm looking to create an ValidationRule class that validates properties on an entity type object. I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method. Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property?</p>
<p>Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear.</p>
| [
{
"answer_id": 142112,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class ValidationRule {\n public delegate bool Validator();\n\n private Validator _v;\n\n public Vali... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | I'm looking to create an ValidationRule class that validates properties on an entity type object. I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method. Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property?
Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear. | Really, what you want to use is `Func<T,bool>` where T is the type of the item you want to validate. Then you would do something like this
```
validator.AddValidation(item => (item.HasEnoughInformation() || item.IsEmpty());
```
you could store them in a `List<Func<T,bool>>`. |
142,110 | <p>Basically I want to know how to set center alignment for a cell using VBScript...</p>
<p>I've been googling it and can't seem to find anything that helps.</p>
| [
{
"answer_id": 142170,
"author": "mistrmark",
"author_id": 19242,
"author_profile": "https://Stackoverflow.com/users/19242",
"pm_score": 1,
"selected": false,
"text": "<p>There are many ways to select a cell or a range of cells, but the following will work for a single cell.</p>\n\n<pre>... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Basically I want to know how to set center alignment for a cell using VBScript...
I've been googling it and can't seem to find anything that helps. | ```
Set excel = CreateObject("Excel.Application")
excel.Workbooks.Add() ' create blank workbook
Set workbook = excel.Workbooks(1)
' set A1 to be centered.
workbook.Sheets(1).Cells(1,1).HorizontalAlignment = -4108 ' xlCenter constant.
workbook.SaveAs("C:\NewFile.xls")
excel.Quit()
set excel = nothing
'If the script errors, it'll give you an orphaned excel process, so be warned.
```
Save that as a .vbs and run it using the command prompt or double clicking. |
142,121 | <p>I have a class that processes a 2 xml files and produces a text file. </p>
<p>I would like to write a bunch of unit / integration tests that can individually pass or fail for this class that do the following:</p>
<ol>
<li>For input A and B, generate the output.</li>
<li>Compare the contents of the generated file to the contents expected output</li>
<li>When the actual contents differ from the expected contents, fail and display some <strong>useful</strong> information about the differences.</li>
</ol>
<p>Below is the prototype for the class along with my first stab at unit tests.</p>
<p><strong>Is there a pattern I should be using for this sort of testing, or do people tend to write zillions of TestX() functions?</strong></p>
<p><strong>Is there a better way to coax text-file differences from NUnit?</strong> Should I embed a textfile diff algorithm?</p>
<hr>
<pre><code>class ReportGenerator
{
string Generate(string inputPathA, string inputPathB)
{
//do stuff
}
}
</code></pre>
<hr>
<pre><code>[TextFixture]
public class ReportGeneratorTests
{
static Diff(string pathToExpectedResult, string pathToActualResult)
{
using (StreamReader rs1 = File.OpenText(pathToExpectedResult))
{
using (StreamReader rs2 = File.OpenText(pathToActualResult))
{
string actualContents = rs2.ReadToEnd();
string expectedContents = rs1.ReadToEnd();
//this works, but the output could be a LOT more useful.
Assert.AreEqual(expectedContents, actualContents);
}
}
}
static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
{
ReportGenerator obj = new ReportGenerator();
string pathToResult = obj.Generate(pathToInputA, pathToInputB);
Diff(pathToExpectedResult, pathToResult);
}
[Test]
public void TestX()
{
TestGenerate("x1.xml", "x2.xml", "x-expected.txt");
}
[Test]
public void TestY()
{
TestGenerate("y1.xml", "y2.xml", "y-expected.txt");
}
//etc...
}
</code></pre>
<hr>
<h2>Update</h2>
<p>I'm not interested in testing the diff functionality. I just want to use it to produce more readable failures.</p>
| [
{
"answer_id": 142169,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than call .AreEqual you could parse the two input streams yourself, keep a count of line and column and compare ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] | I have a class that processes a 2 xml files and produces a text file.
I would like to write a bunch of unit / integration tests that can individually pass or fail for this class that do the following:
1. For input A and B, generate the output.
2. Compare the contents of the generated file to the contents expected output
3. When the actual contents differ from the expected contents, fail and display some **useful** information about the differences.
Below is the prototype for the class along with my first stab at unit tests.
**Is there a pattern I should be using for this sort of testing, or do people tend to write zillions of TestX() functions?**
**Is there a better way to coax text-file differences from NUnit?** Should I embed a textfile diff algorithm?
---
```
class ReportGenerator
{
string Generate(string inputPathA, string inputPathB)
{
//do stuff
}
}
```
---
```
[TextFixture]
public class ReportGeneratorTests
{
static Diff(string pathToExpectedResult, string pathToActualResult)
{
using (StreamReader rs1 = File.OpenText(pathToExpectedResult))
{
using (StreamReader rs2 = File.OpenText(pathToActualResult))
{
string actualContents = rs2.ReadToEnd();
string expectedContents = rs1.ReadToEnd();
//this works, but the output could be a LOT more useful.
Assert.AreEqual(expectedContents, actualContents);
}
}
}
static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
{
ReportGenerator obj = new ReportGenerator();
string pathToResult = obj.Generate(pathToInputA, pathToInputB);
Diff(pathToExpectedResult, pathToResult);
}
[Test]
public void TestX()
{
TestGenerate("x1.xml", "x2.xml", "x-expected.txt");
}
[Test]
public void TestY()
{
TestGenerate("y1.xml", "y2.xml", "y-expected.txt");
}
//etc...
}
```
---
Update
------
I'm not interested in testing the diff functionality. I just want to use it to produce more readable failures. | As for the multiple tests with different data, use the NUnit RowTest extension:
```
using NUnit.Framework.Extensions;
[RowTest]
[Row("x1.xml", "x2.xml", "x-expected.xml")]
[Row("y1.xml", "y2.xml", "y-expected.xml")]
public void TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
{
ReportGenerator obj = new ReportGenerator();
string pathToResult = obj.Generate(pathToInputA, pathToInputB);
Diff(pathToExpectedResult, pathToResult);
}
``` |
142,142 | <p>Is there a query in SQL Server 2005 I can use to get the server's IP or name?</p>
| [
{
"answer_id": 142144,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select @@servername\n</code></pre>\n"
},
{
"answer_id": 142146,
"author": "Michał Piaskowski... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | Is there a query in SQL Server 2005 I can use to get the server's IP or name? | ```
SELECT
CONNECTIONPROPERTY('net_transport') AS net_transport,
CONNECTIONPROPERTY('protocol_type') AS protocol_type,
CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
CONNECTIONPROPERTY('local_net_address') AS local_net_address,
CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
CONNECTIONPROPERTY('client_net_address') AS client_net_address
```
The code here Will give you the IP Address;
This will work for a remote client request to SQL 2008 and newer.
If you have Shared Memory connections allowed, then running above on the server itself will give you
* "Shared Memory" as the value for 'net\_transport', and
* NULL for 'local\_net\_address', and
* '`<local machine>`' will be shown in 'client\_net\_address'.
'client\_net\_address' is the address of the computer that the request originated from, whereas 'local\_net\_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.
I advice strongly against using [this answer](https://stackoverflow.com/a/142157/578411). Enabling the shell out is a very bad idea on a production SQL Server. |
142,147 | <p>I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3.</p>
<p>When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1.</p>
<p>Why does the scope of the 'ii' variable continue between loops?</p>
<pre><code>var fs:Array = new Array();
for (var i = 0; i < 3; i++){
var ii = i + 1;
fs[i] = function(){
trace(ii);
}
}
fs[0]();
</code></pre>
| [
{
"answer_id": 142224,
"author": "gltovar",
"author_id": 2855,
"author_profile": "https://Stackoverflow.com/users/2855",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately Actionscript 2.0 does not have a strong scope... especially on the time line.</p>\n\n<pre><code>var fs:Arra... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3.
When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1.
Why does the scope of the 'ii' variable continue between loops?
```
var fs:Array = new Array();
for (var i = 0; i < 3; i++){
var ii = i + 1;
fs[i] = function(){
trace(ii);
}
}
fs[0]();
``` | Unfortunately, AS2 is not that kind of language; it doesn't have that kind of closure. Functions aren't exactly first-class citizens in AS2, and one of the results of that is that a function doesn't retain its own scope, it has to be associated with some scope when it's called (usually the same scope where the function itself is defined, unless you use a function's `call` or `apply` methods).
Then when the function is executed, the scope of variables inside it is just the scope of wherever it happened to be called - in your case, the scope outside your loop. This is also why you can do things like this:
```
function foo() {
trace( this.value );
}
objA = { value:"A" };
objB = { value:"B" };
foo.apply( objA ); // A
foo.apply( objB ); // B
objA.foo = foo;
objB.foo = foo;
objA.foo(); // A
objB.foo(); // B
```
If you're used to true OO languages that looks very strange, and the reason is that AS2 is ultimately a [prototyped language](http://en.wikipedia.org/wiki/Prototype-based_programming). Everything that looks object-oriented is just a coincidence. ;D |
142,240 | <p>Out of order execution in CPUs means that a CPU can reorder instructions to gain better performance and it means the CPU is having to do some very nifty bookkeeping and such. There are other processor approaches too, such as hyper-threading.</p>
<p>Some fancy compilers understand the (un)interrelatedness of instructions to a limited extent, and will automatically interleave instruction flows (probably over a longer window than the CPU sees) to better utilise the processor. Deliberate compile-time interleaving of floating and integer instructions is another example of this.</p>
<p>Now I have highly-parallel task. And I typically have an ageing single-core x86 processor without hyper-threading.</p>
<p>Is there a straight-forward way to get my the body of my 'for' loop for this highly-parallel task to be interleaved so that two (or more) iterations are being done together? (This is slightly different from 'loop unwinding' as I understand it.)</p>
<p>My task is a 'virtual machine' running through a set of instructions, which I'll really simplify for illustration as:</p>
<pre>void run(int num) {
for(int n=0; n<num; n++) {
vm_t data(n);
for(int i=0; i<data.len(); i++) {
data.insn(i).parse();
data.insn(i).eval();
}
}
}</pre>
<p>So the execution trail might look like this:</p>
<pre>data(1) insn(0) parse
data(1) insn(0) eval
data(1) insn(1) parse
...
data(2) insn(1) eval
data(2) insn(2) parse
data(2) insn(2) eval</pre>
<p>Now, what I'd like is to be able to do two (or more) iterations explicitly in parallel:</p>
<pre>data(1) insn(0) parse
data(2) insn(0) parse \ processor can do OOO as these two flow in
data(1) insn(0) eval /
data(2) insn(0) eval \ OOO opportunity here too
data(1) insn(1) parse /
data(2) insn(1) parse</pre>
<p>I know, from profiling, (e.g. using Callgrind with --simulate-cache=yes), that parsing is about random memory accesses (cache missing) and eval is about doing ops in registers and then writing results back. Each step is several thousand instructions long. So if I can intermingle the two steps for two iterations at once, the processor will hopefully have something to do whilst the cache misses of the parse step are occurring...</p>
<p>Is there some c++ template madness to get this kind of explicit parallelism generated?</p>
<p>Of course I can do the interleaving - and even staggering - myself in code, but it makes for much less readable code. And if I really want unreadable, I can go so far as assembler! But surely there is some pattern for this kind of thing?</p>
| [
{
"answer_id": 142277,
"author": "Adrian Mouat",
"author_id": 4332,
"author_profile": "https://Stackoverflow.com/users/4332",
"pm_score": 2,
"selected": false,
"text": "<p>Your best plan may be to look into <a href=\"http://openmp.org\" rel=\"nofollow noreferrer\">OpenMP</a>. It basicall... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15721/"
] | Out of order execution in CPUs means that a CPU can reorder instructions to gain better performance and it means the CPU is having to do some very nifty bookkeeping and such. There are other processor approaches too, such as hyper-threading.
Some fancy compilers understand the (un)interrelatedness of instructions to a limited extent, and will automatically interleave instruction flows (probably over a longer window than the CPU sees) to better utilise the processor. Deliberate compile-time interleaving of floating and integer instructions is another example of this.
Now I have highly-parallel task. And I typically have an ageing single-core x86 processor without hyper-threading.
Is there a straight-forward way to get my the body of my 'for' loop for this highly-parallel task to be interleaved so that two (or more) iterations are being done together? (This is slightly different from 'loop unwinding' as I understand it.)
My task is a 'virtual machine' running through a set of instructions, which I'll really simplify for illustration as:
```
void run(int num) {
for(int n=0; n<num; n++) {
vm_t data(n);
for(int i=0; i<data.len(); i++) {
data.insn(i).parse();
data.insn(i).eval();
}
}
}
```
So the execution trail might look like this:
```
data(1) insn(0) parse
data(1) insn(0) eval
data(1) insn(1) parse
...
data(2) insn(1) eval
data(2) insn(2) parse
data(2) insn(2) eval
```
Now, what I'd like is to be able to do two (or more) iterations explicitly in parallel:
```
data(1) insn(0) parse
data(2) insn(0) parse \ processor can do OOO as these two flow in
data(1) insn(0) eval /
data(2) insn(0) eval \ OOO opportunity here too
data(1) insn(1) parse /
data(2) insn(1) parse
```
I know, from profiling, (e.g. using Callgrind with --simulate-cache=yes), that parsing is about random memory accesses (cache missing) and eval is about doing ops in registers and then writing results back. Each step is several thousand instructions long. So if I can intermingle the two steps for two iterations at once, the processor will hopefully have something to do whilst the cache misses of the parse step are occurring...
Is there some c++ template madness to get this kind of explicit parallelism generated?
Of course I can do the interleaving - and even staggering - myself in code, but it makes for much less readable code. And if I really want unreadable, I can go so far as assembler! But surely there is some pattern for this kind of thing? | It sounds like you ran into the same problem chip designers face: Executing a single instruction takes a lot of effort, but it involves a bunch of different steps that can be strung together in an [execution pipeline](http://en.wikipedia.org/wiki/Pipeline_(computing)). (It is easier to execute things in parallel when you can build them out of separate blocks of hardware.)
The most obvious way is to split each task into different threads. You might want to create a single thread to execute each instruction to completion, or create one thread for each of your two execution steps and pass data between them. In either case, you'll have to be very careful with how you share data between threads and make sure to handle the case where one instruction affects the result of the following instruction. Even though you only have one core and only one thread can be running at any given time, your operating system should be able to schedule compute-intense threads while other threads are waiting for their cache misses.
(A few hours of your time would probably pay for a single very fast computer, but if you're trying to deploy it widely on cheap hardware it might make sense to consider the problem the way you're looking at it. Regardless, it's an interesting problem to consider.) |
142,252 | <p>This code works (C# 3)</p>
<pre><code>double d;
if(d == (double)(int)d) ...;
</code></pre>
<ol>
<li>Is there a better way to do this?</li>
<li>For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)</li>
</ol>
<p><em>Note:</em> Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.</p>
| [
{
"answer_id": 142262,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need the extra (double) in there. This works:</p>\n\n<pre><code>if (d == (int)d) {\n //...\n}\n</code></pre>\n"... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] | This code works (C# 3)
```
double d;
if(d == (double)(int)d) ...;
```
1. Is there a better way to do this?
2. For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)
*Note:* Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me. | ```
d == Math.Floor(d)
```
does the same thing in other words.
NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason. |
142,317 | <p>I have the following code that shows either a bug or a misunderstanding on my part.</p>
<p>I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.</p>
<p>Is this work as it should, or should I file a bug?</p>
<pre>
import java.io.*;
import java.net.*;
import java.util.*;
public class OOS {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
ServerSocket ss = new ServerSocket(12344);
Socket s= ss.accept();
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
List same = new ArrayList();
same.add(0);
oos.writeObject(same);
same.clear();
same.add(1);
oos.writeObject(same);
} catch(Exception e) {
e.printStackTrace();
}
}
});
t1.start();
Socket s = new Socket("localhost", 12344);
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
// outputs [0] as expected
System.out.println(ois.readObject());
// outputs [0], but expected [1]
System.out.println(ois.readObject());
System.exit(0);
}
}
</pre>
| [
{
"answer_id": 142367,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 6,
"selected": true,
"text": "<p>The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you w... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21838/"
] | I have the following code that shows either a bug or a misunderstanding on my part.
I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.
Is this work as it should, or should I file a bug?
```
import java.io.*;
import java.net.*;
import java.util.*;
public class OOS {
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
ServerSocket ss = new ServerSocket(12344);
Socket s= ss.accept();
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
List same = new ArrayList();
same.add(0);
oos.writeObject(same);
same.clear();
same.add(1);
oos.writeObject(same);
} catch(Exception e) {
e.printStackTrace();
}
}
});
t1.start();
Socket s = new Socket("localhost", 12344);
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
// outputs [0] as expected
System.out.println(ois.readObject());
// outputs [0], but expected [1]
System.out.println(ois.readObject());
System.exit(0);
}
}
``` | The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).
See the reset() method if you want to reset the graph. |
142,319 | <p>This is a new gmail labs feature that lets you specify an RSS feed to grab random quotes from to append to your email signature. I'd like to use that to generate signatures programmatically based on parameters I pass in, the current time, etc. (For example, I have a script in pine that appends the current probabilities of McCain and Obama winning, fetched from intrade's API. See below.) But it seems gmail caches the contents of the URL you specify. Any way to control that or anyone know how often gmail looks at the URL?</p>
<p>ADDED: Here's the program I'm using to test this. This file lives at <a href="http://kibotzer.com/sigs.php" rel="nofollow noreferrer">http://kibotzer.com/sigs.php</a>. The no-cache header idea, taken from here -- <a href="http://mapki.com/wiki/Dynamic_XML" rel="nofollow noreferrer">http://mapki.com/wiki/Dynamic_XML</a> -- seems to not help.</p>
<pre><code><?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
//XML Header
header("content-type:text/xml");
?>
<!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd">
<rss version="0.91">
<channel>
<title>Dynamic Signatures</title>
<link>http://kibotzer.com</link>
<description>Blah blah</description>
<language>en-us</language>
<pubDate>26 Sep 2008 02:15:01 -0000</pubDate>
<webMaster>dreeves@kibotzer.com</webMaster>
<managingEditor>dreeves@kibotzer.com (Daniel Reeves)</managingEditor>
<lastBuildDate>26 Sep 2008 02:15:01 -0000</lastBuildDate>
<image>
<title>Kibotzer Logo</title>
<url>http://kibotzer.com/logos/kibo-logo-1.gif</url>
<link>http://kibotzer.com/</link>
<width>120</width>
<height>60</height>
<description>Kibotzer</description>
</image>
<item>
<title>
Dynamic Signature 1 (<?php echo gmdate("H:i:s"); ?>)
</title>
<link>http://kibotzer.com</link>
<description>This is the description for Signature 1 (<?php echo gmdate("H:i:s"); ?>) </description>
</item>
<item>
<title>
Dynamic Signature 2 (<?php echo gmdate("H:i:s"); ?>)
</title>
<link>http://kibotzer.com</link>
<description>This is the description for Signature 2 (<?php echo gmdate("H:i:s"); ?>) </description>
</item>
</channel>
</rss>
</code></pre>
<pre>
--
http://ai.eecs.umich.edu/people/dreeves - - search://"Daniel Reeves"
Latest probabilities from intrade...
42.1% McCain becomes president (last trade 18:07 FRI)
57.0% Obama becomes president (last trade 18:34 FRI)
17.6% US recession in 2008 (last trade 16:24 FRI)
16.1% Overt air strike against Iran in '08 (last trade 17:39 FRI)
</pre>
| [
{
"answer_id": 142367,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 6,
"selected": true,
"text": "<p>The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you w... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
] | This is a new gmail labs feature that lets you specify an RSS feed to grab random quotes from to append to your email signature. I'd like to use that to generate signatures programmatically based on parameters I pass in, the current time, etc. (For example, I have a script in pine that appends the current probabilities of McCain and Obama winning, fetched from intrade's API. See below.) But it seems gmail caches the contents of the URL you specify. Any way to control that or anyone know how often gmail looks at the URL?
ADDED: Here's the program I'm using to test this. This file lives at <http://kibotzer.com/sigs.php>. The no-cache header idea, taken from here -- <http://mapki.com/wiki/Dynamic_XML> -- seems to not help.
```
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
//XML Header
header("content-type:text/xml");
?>
<!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd">
<rss version="0.91">
<channel>
<title>Dynamic Signatures</title>
<link>http://kibotzer.com</link>
<description>Blah blah</description>
<language>en-us</language>
<pubDate>26 Sep 2008 02:15:01 -0000</pubDate>
<webMaster>dreeves@kibotzer.com</webMaster>
<managingEditor>dreeves@kibotzer.com (Daniel Reeves)</managingEditor>
<lastBuildDate>26 Sep 2008 02:15:01 -0000</lastBuildDate>
<image>
<title>Kibotzer Logo</title>
<url>http://kibotzer.com/logos/kibo-logo-1.gif</url>
<link>http://kibotzer.com/</link>
<width>120</width>
<height>60</height>
<description>Kibotzer</description>
</image>
<item>
<title>
Dynamic Signature 1 (<?php echo gmdate("H:i:s"); ?>)
</title>
<link>http://kibotzer.com</link>
<description>This is the description for Signature 1 (<?php echo gmdate("H:i:s"); ?>) </description>
</item>
<item>
<title>
Dynamic Signature 2 (<?php echo gmdate("H:i:s"); ?>)
</title>
<link>http://kibotzer.com</link>
<description>This is the description for Signature 2 (<?php echo gmdate("H:i:s"); ?>) </description>
</item>
</channel>
</rss>
```
```
--
http://ai.eecs.umich.edu/people/dreeves - - search://"Daniel Reeves"
Latest probabilities from intrade...
42.1% McCain becomes president (last trade 18:07 FRI)
57.0% Obama becomes president (last trade 18:34 FRI)
17.6% US recession in 2008 (last trade 16:24 FRI)
16.1% Overt air strike against Iran in '08 (last trade 17:39 FRI)
``` | The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).
See the reset() method if you want to reset the graph. |
142,320 | <p>I'm setting up our new Dev server, what is the easiest way to assign multiple IP addresses to Windows 2008 Server Network Adapter?</p>
<p>I'm setting up our development machine, running IIS 7 and want to have the range between 192.168.1.200 - .254 available when I'm setting up a new website in IIS 7.</p>
| [
{
"answer_id": 142347,
"author": "David",
"author_id": 3351,
"author_profile": "https://Stackoverflow.com/users/3351",
"pm_score": 0,
"selected": false,
"text": "<p>Network Connections -> Local Area Network Connection Properties -> TCP/IP Properties -> Advanced -> IP Settings -> Add Butt... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | I'm setting up our new Dev server, what is the easiest way to assign multiple IP addresses to Windows 2008 Server Network Adapter?
I'm setting up our development machine, running IIS 7 and want to have the range between 192.168.1.200 - .254 available when I'm setting up a new website in IIS 7. | The complete CMD.EXE loop:
```
FOR /L %b IN (200,1,254) DO netsh interface ip add address "your_adapter" 192.168.1.%b 255.255.255.0
```
In the code above, replace "your\_adapter" with the actual interface name (usually "Local Area Connection"). In addition, the netmask at the end is an assumption of /24 or Class C subnet; substitute the correct netmask. |
142,356 | <p>What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?</p>
<p>I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.</p>
<pre><code>Type type = typeof(FooBar)
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
type.GetConstructors(flags)
.Where(constructor => constructor.GetParameters().Length == 0)
.First();
</code></pre>
| [
{
"answer_id": 142362,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 8,
"selected": true,
"text": "<pre><code>type.GetConstructor(Type.EmptyTypes)\n</code></pre>\n"
},
{
"answer_id": 142442,
"author": "Ale... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12784/"
] | What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?
I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.
```
Type type = typeof(FooBar)
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
type.GetConstructors(flags)
.Where(constructor => constructor.GetParameters().Length == 0)
.First();
``` | ```
type.GetConstructor(Type.EmptyTypes)
``` |
142,357 | <p>What are the best JVM settings you have found for running Eclipse?</p>
| [
{
"answer_id": 142384,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 0,
"selected": false,
"text": "<p>Here's what I use (though I have them in the shortcut instead of the settings file):</p>\n\n<p>eclipse.exe -showlocation ... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
] | What are the best JVM settings you have found for running Eclipse? | It is that time of year again: "eclipse.ini take 3" the settings strike back!
Eclipse Helios 3.6 and 3.6.x settings
=====================================
[alt text http://www.eclipse.org/home/promotions/friends-helios/helios.png](http://www.eclipse.org/home/promotions/friends-helios/helios.png)
After settings for [Eclipse Ganymede 3.4.x](https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/144349#144349) and [Eclipse Galileo 3.5.x](https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/1409590#1409590), here is an in-depth look at an "optimized" **[eclipse.ini](http://wiki.eclipse.org/Eclipse.ini)** settings file for Eclipse Helios 3.6.x:
* based on **[runtime options](http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html)**,
* and using the **Sun-Oracle JVM 1.6u21 b7**, [released July, 27th](http://java.about.com/b/2010/07/27/java-6-update-21-build-07-released.htm) (~~some some Sun proprietary options may be involved~~).
(by "optimized", I mean able to run a full-fledge Eclipse on our crappy workstation at work, some old P4 from 2002 with 2Go RAM and XPSp3. But I have also tested those same settings on Windows7)
Eclipse.ini
-----------

**WARNING**: for non-windows platform, use the Sun proprietary option `-XX:MaxPermSize` instead of the Eclipse proprietary option `--launcher.XXMaxPermSize`.
That is: **Unless** you are using the latest **jdk6u21 build 7**.
See the Oracle section below.
```
-data
../../workspace
-showlocation
-showsplash
org.eclipse.platform
--launcher.defaultAction
openFile
-vm
C:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Declipse.p2.unsignedPolicy=allow
-Xms128m
-Xmx384m
-Xss4m
-XX:PermSize=128m
-XX:MaxPermSize=384m
-XX:CompileThreshold=5
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+CMSIncrementalPacing
-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
-Dcom.sun.management.jmxremote
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons
```
Note:
Adapt the `p2.reconciler.dropins.directory` to an external directory of your choice.
See this [SO answer](https://stackoverflow.com/questions/2763843/eclipse-plugins-vs-features-vs-dropins/2763891#2763891).
The idea is to be able to drop new plugins in a directory independently from any Eclipse installation.
The following sections detail what are in this `eclipse.ini` file.
---
The dreaded Oracle JVM 1.6u21 (pre build 7) and Eclipse crashes
---------------------------------------------------------------
[Andrew Niefer](https://stackoverflow.com/users/84728/andrew-niefer) did alert me to this situation, and wrote a [blog post](http://aniefer.blogspot.com/2010/07/permgen-problems-and-running-eclipse-on.html), about a non-standard vm argument (**`-XX:MaxPermSize`**) and can cause vms from other vendors to not start at all.
But the eclipse version of that option (**`--launcher.XXMaxPermSize`**) is not working with the new JDK (6u21, unless you are using the 6u21 build 7, see below).
The ~~final~~ solution is on the [Eclipse Wiki](http://wiki.eclipse.org/FAQ_How_do_I_run_Eclipse%3F#Oracle.2FSun_VM_1.6.0_21_on_Windows), and **for Helios on Windows with 6u21 pre build 7** only:
* **downloading the fixed [eclipse\_1308.dll](https://bugs.eclipse.org/bugs/attachment.cgi?id=174343)** (July 16th, 2010)
* and place it into
```
(eclipse_home)/plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.0.v20100503
```
That's it. No setting to tweak here (again, only for Helios **on Windows** with a **6u21 pre build 7**).
For non-Windows platform, you need to revert to the Sun proprietary option `-XX:MaxPermSize`.
The issue is based one a regression: [JVM identification fails due to Oracle rebranding in java.exe](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6969236), and triggered [bug 319514](https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514) on Eclipse.
Andrew took care of [Bug 320005 - [launcher] `--launcher.XXMaxPermSize: isSunVM` should return true for Oracle](https://bugs.eclipse.org/bugs/show_bug.cgi?id=320005), but that will be only for Helios 3.6.1.
[Francis Upton](http://dev.eclipse.org/blogs/francis/about/), another Eclipse committer, [reflects on the all situation](http://dev.eclipse.org/blogs/francis/2010/07/15/some-thoughts-on-the-java-u21-problem/).
**Update u21b7, July, 27th**:
**Oracle have regressed the change for the next Java 6 release and won't implement it again until JDK 7**.
If you use **[jdk6u21 build 7](http://www.oracle.com/technetwork/java/javase/downloads/index.html)**, you can revert to the **`--launcher.XXMaxPermSize`** (eclipse option) instead of **`-XX:MaxPermSize`** (the non-standard option).
The [auto-detection happening in the C launcher shim `eclipse.exe`](http://www.infoq.com/news/2010/07/eclipse-java-6u21) will still look for the "`Sun Microsystems`" string, but with 6u21b7, it will now work - again.
For now, I still keep the `-XX:MaxPermSize` version (because I have no idea when everybody will launch eclipse the *right* JDK).
---
Implicit `-startup` and `--launcher.library`
--------------------------------------------
Contrary to the previous settings, the exact path for those modules is not set anymore, which is convenient since it can vary between different Eclipse 3.6.x releases:
* startup: If not specified, the executable will look in the plugins directory for the `org.eclipse.equinox.launcher` bundle with the highest version.
* launcher.library: If not specified, the executable looks in the `plugins` directory for the appropriate `org.eclipse.equinox.launcher.[platform]` fragment with the highest version and uses the shared library named `eclipse_*` inside.
---
Use JDK6
--------
The JDK6 is now explicitly required to launch Eclipse:
```
-Dosgi.requiredJavaVersion = 1.6
```
This [SO question](https://stackoverflow.com/questions/2787055/using-the-android-sdk-on-a-mac-eclipse-is-really-slow-how-can-i-speed-it-up) reports a positive incidence for development on Mac OS.
---
+UnlockExperimentalVMOptions
----------------------------
The following options are part of some of the experimental options of the Sun JVM.
```
-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
```
They have been reported in this [blog post](http://ugosan.org/speeding-up-eclipse-a-bit-with-unlockexperimentalvmoptions/) to potentially speed up Eclipse.
See all the [JVM options here](http://blogs.oracle.com/watt/resource/jvm-options-list.html) and also in the official [Java Hotspot options page](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp).
Note: the [detailed list of those options](http://www.md.pp.ru/~eu/jdk6options.html) reports that `UseFastAccessorMethods` might be active by default.
See also ["Update your JVM"](http://translate.googleusercontent.com/translate_c?hl=en&sl=fr&tl=en&u=http://blog.xebia.fr/2010/07/13/revue-de-presse-xebia-167/&rurl=translate.google.com&twu=1&usg=ALkJrhgLW58oZuCouEaFZBTA_u6ZTQwvGA#MettezjourvotreJVM):
>
> As a reminder, G1 is the new garbage collector in preparation for the JDK 7, but already used in the version 6 release from u17.
>
>
>
---
Opening files in Eclipse from the command line
----------------------------------------------
See the [blog post](http://aniefer.blogspot.com/2010/05/opening-files-in-eclipse-from-command.html) from Andrew Niefer reporting this new option:
```
--launcher.defaultAction
openFile
```
>
> This tells the launcher that if it is called with a command line that only contains arguments that don't start with "`-`", then those arguments should be treated as if they followed "`--launcher.openFile`".
>
>
>
```
eclipse myFile.txt
```
>
> This is the kind of command line the launcher will receive on windows when you double click a file that is associated with eclipse, or you select files and choose "`Open With`" or "`Send To`" Eclipse.
>
>
> [Relative paths](https://bugs.eclipse.org/bugs/show_bug.cgi?id=300532) will be resolved first against the current working directory, and second against the eclipse program directory.
>
>
>
See [bug 301033](https://bugs.eclipse.org/bugs/show_bug.cgi?id=301033) for reference. Originally [bug 4922](https://bugs.eclipse.org/bugs/show_bug.cgi?id=4922) (October 2001, fixed 9 years later).
---
p2 and the Unsigned Dialog Prompt
---------------------------------
If you are tired of this dialog box during the installation of your many plugins:

, add in your `eclipse.ini`:
```
-Declipse.p2.unsignedPolicy=allow
```
See this [blog post](http://aniszczyk.org/2010/05/20/p2-and-the-unsigned-dialog-prompt/) from [Chris Aniszczy](http://aniszczyk.org/about/), and the [bug report 235526](https://bugs.eclipse.org/bugs/show_bug.cgi?id=235526).
>
> I do want to say that security research supports the fact that less prompts are better.
>
> People ignore things that pop up in the flow of something they want to get done.
>
>
> For 3.6, we should not pop up warnings in the middle of the flow - no matter how much we simplify, people will just ignore them.
>
> Instead, we should collect all the problems, do *not* install those bundles with problems, and instead bring the user back to a point in the workflow where they can fixup - add trust, configure security policy more loosely, etc. This is called **['safe staging'](http://www.eecs.berkeley.edu/~tygar/papers/Safe_staging_for_computer_security.pdf)**.
>
>
>
[---------- http://www.eclipse.org/home/categories/images/wiki.gif](http://www.eclipse.org/home/categories/images/wiki.gif) [alt text http://www.eclipse.org/home/categories/images/wiki.gif](http://www.eclipse.org/home/categories/images/wiki.gif) [alt text http://www.eclipse.org/home/categories/images/wiki.gif](http://www.eclipse.org/home/categories/images/wiki.gif)
Additional options
-------------------
Those options are not directly in the `eclipse.ini` above, but can come in handy if needed.
---
### The `user.home` issue on Windows7
When eclipse starts, it will read its keystore file (where passwords are kept), a file located in `user.home`.
If for some reason that `user.home` doesn't resolve itself properly to a full-fledge path, Eclipse won't start.
Initially raised in [this SO question](https://stackoverflow.com/questions/2120160/eclipse-is-not-starting-on-windows-7/2120198#2120198), if you experience this, you need to redefine the keystore file to an explicit path (no more user.home to resolve at the start)
Add in your `eclipse.ini`:
```
-eclipse.keyring
C:\eclipse\keyring.txt
```
This has been tracked by [bug 300577](https://bugs.eclipse.org/bugs/show_bug.cgi?id=300577), it has been solve in this [other SO question](https://stackoverflow.com/questions/2134338/java-user-home-is-being-set-to-userprofile-and-not-being-resolved).
---
### Debug mode
Wait, there's more than one setting file in Eclipse.
if you add to your `eclipse.ini` the option:
```
-debug
```
, you enable the [debug mode](http://www.eclipse.org/eclipse/platform-core/documents/3.1/debug.html) and Eclipse will look for *another* setting file: a `.options` file where you can specify some OSGI options.
And that is great when you are adding new plugins through the dropins folder.
Add in your .options file the following settings, as described in this [blog post "**Dropins diagnosis**"](http://eclipser-blog.blogspot.com/2010/01/dropins-diagnosis.html):
```
org.eclipse.equinox.p2.core/debug=true
org.eclipse.equinox.p2.core/reconciler=true
```
>
> P2 will inform you what bundles were found in `dropins/` folder, what request was generated, and what is the plan of installation. Maybe it is not detailed explanation of what actually happened, and what went wrong, but it should give you strong information about where to start:
>
>
> * was your bundle in the plan?
> * Was it installation problem (P2 fault)
> * or maybe it is just not optimal to include your feature?
>
>
>
That comes from [Bug 264924 - [reconciler] No diagnosis of dropins problems](https://bugs.eclipse.org/bugs/show_bug.cgi?id=264924), which finally solves the following issue like:
```
Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipse
Unzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5
```
>
> This is a problematic configuration since OCL depends on EMF which is missing.
>
> 3.5M5 provides no diagnosis of this problem.
>
>
> Start eclipse.
>
> No obvious problems. Nothing in Error Log.
>
>
> * `Help / About / Plugin` details shows `org.eclipse.ocl.doc`, but not `org.eclipse.ocl`.
> * `Help / About / Configuration` details has no (diagnostic) mention of
> `org.eclipse.ocl`.
> * `Help / Installation / Information Installed Software` has no mention of `org.eclipse.ocl`.
>
>
> Where are the nice error markers?
>
>
>
---
### Manifest Classpath
See this [blog post](http://lt-rider.blogspot.com/2010/05/jdt-manifest-classpath-classpath.html):
>
> * In Galileo (aka Eclipse 3.5), JDT started resolving manifest classpath in libraries added to project’s build path. This worked whether the library was added to project’s build path directly or via a classpath container, such as the user library facility provided by JDT or one implemented by a third party.
> * In Helios, this behavior was changed to exclude classpath containers from manifest classpath resolution.
>
>
>
That means some of your projects might no longer compile in Helios.
If you want to revert to Galileo behavior, add:
```
-DresolveReferencedLibrariesForContainers=true
```
See [bug 305037](https://bugs.eclipse.org/bugs/show_bug.cgi?id=305037), [bug 313965](https://bugs.eclipse.org/bugs/show_bug.cgi?id=313965) and [bug 313890](https://bugs.eclipse.org/bugs/show_bug.cgi?id=313890) for references.
---
### IPV4 stack
This [SO question](https://stackoverflow.com/questions/1500646/eclipse-3-5-unable-to-install-plugins) mentions a potential fix when not accessing to plugin update sites:
```
-Djava.net.preferIPv4Stack=true
```
Mentioned here just in case it could help in your configuration.
---
### JVM1.7x64 potential optimizations
[This article](http://nerds-central.blogspot.com/2009/09/tuning-jvm-for-unusual-uses-have-some.html) reports:
>
> For the record, the very fastest options I have found so far for my bench test with the 1.7 x64 JVM n Windows are:
>
>
>
```
-Xincgc
-XX:-DontCompileHugeMethods
-XX:MaxInlineSize=1024
-XX:FreqInlineSize=1024
```
>
> But I am still working on it...
>
>
> |
142,391 | <p>I am making extensive use of <code>boost:shared_ptr</code> in my code. In fact, most of the objects that are allocated on the heap are held by a <code>shared_ptr</code>. Unfortunately this means that I can't pass <code>this</code> into any function that takes a <code>shared_ptr</code>. Consider this code:</p>
<pre><code>void bar(boost::shared_ptr<Foo> pFoo)
{
...
}
void Foo::someFunction()
{
bar(this);
}
</code></pre>
<p>There are two problems here. First, this won't compile because the T* constructor for <code>shared_ptr</code> is explicit. Second, if I force it to build with <code>bar(boost::shared_ptr<Foo>(this))</code> I will have created a second shared pointer to my object that will eventually lead to a double-delete.</p>
<p>This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here?</p>
| [
{
"answer_id": 142397,
"author": "David Pierre",
"author_id": 18296,
"author_profile": "https://Stackoverflow.com/users/18296",
"pm_score": 4,
"selected": false,
"text": "<p>boost has a solution for this use case, check <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031/"
] | I am making extensive use of `boost:shared_ptr` in my code. In fact, most of the objects that are allocated on the heap are held by a `shared_ptr`. Unfortunately this means that I can't pass `this` into any function that takes a `shared_ptr`. Consider this code:
```
void bar(boost::shared_ptr<Foo> pFoo)
{
...
}
void Foo::someFunction()
{
bar(this);
}
```
There are two problems here. First, this won't compile because the T\* constructor for `shared_ptr` is explicit. Second, if I force it to build with `bar(boost::shared_ptr<Foo>(this))` I will have created a second shared pointer to my object that will eventually lead to a double-delete.
This brings me to my question: Is there any standard pattern for getting a copy of the existing shared pointer you know exists from inside a method on one of those objects? Is using intrusive reference counting my only option here? | You can derive from [enable\_shared\_from\_this](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/enable_shared_from_this.html) and then you can use "shared\_from\_this()" instead of "this" to spawn a shared pointer to your own self object.
Example in the link:
```
#include <boost/enable_shared_from_this.hpp>
class Y: public boost::enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}
```
It's a good idea when spawning threads from a member function to boost::bind to a shared\_from\_this() instead of this. It will ensure that the object is not released. |
142,400 | <p>I've had a hard time finding good ways of taking a time format and easily determining if it's valid then producing a resulting element that has some formatting using XSLT 1.0.</p>
<p>Given the following xml:</p>
<pre><code><root>
<srcTime>2300</srcTime>
</root>
</code></pre>
<p>It would be great to produce the resulting xml:</p>
<pre><code><root>
<dstTime>23:00</dstTime>
</root>
</code></pre>
<p>However, if the source xml contains an invalid 24 hour time format, the resulting <em>dstTime</em> element should be blank.</p>
<p>For example, when the invalid source xml is the following:</p>
<pre><code><root>
<srcTime>NOON</srcTime>
</root>
</code></pre>
<p>The resulting xml should be:</p>
<pre><code><root>
<dstTime></dstTime>
</root>
</code></pre>
<p>The question is, what's the <strong>best XSLT 1.0</strong> fragment that could be written to produce the desired results? The hope would be to keep it quite simple and not have to parse the every piece of the time (i.e. pattern matching would be sweet if possible).</p>
| [
{
"answer_id": 142416,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "<p>XSLT 1.0 does not have any standard support for date/time manipulation.</p>\n\n<p>You must write a simple parsing and form... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] | I've had a hard time finding good ways of taking a time format and easily determining if it's valid then producing a resulting element that has some formatting using XSLT 1.0.
Given the following xml:
```
<root>
<srcTime>2300</srcTime>
</root>
```
It would be great to produce the resulting xml:
```
<root>
<dstTime>23:00</dstTime>
</root>
```
However, if the source xml contains an invalid 24 hour time format, the resulting *dstTime* element should be blank.
For example, when the invalid source xml is the following:
```
<root>
<srcTime>NOON</srcTime>
</root>
```
The resulting xml should be:
```
<root>
<dstTime></dstTime>
</root>
```
The question is, what's the **best XSLT 1.0** fragment that could be written to produce the desired results? The hope would be to keep it quite simple and not have to parse the every piece of the time (i.e. pattern matching would be sweet if possible). | There aren't any regular expressions in XSLT 1.0, so I'm afraid that pattern matching isn't going to be possible.
I'm not clear if `<srcTime>23:00</srcTime>` is supposed to be legal or not? If it is, try:
```
<dstTime>
<xsl:if test="string-length(srcTime) = 4 or
string-length(srcTime) = 5">
<xsl:variable name="hour" select="substring(srcTime, 1, 2)" />
<xsl:if test="$hour >= 0 and 24 > $hour">
<xsl:variable name="minute">
<xsl:choose>
<xsl:when test="string-length(srcTime) = 5 and
substring(srcTime, 3, 1) = ':'">
<xsl:value-of select="substring(srcTime, 4, 2)" />
</xsl:when>
<xsl:when test="string-length(srcTime) = 4">
<xsl:value-of select="substring(srcTime, 3, 2)" />
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:if test="$minute >= 0 and 60 > $minute">
<xsl:value-of select="concat($hour, ':', $minute)" />
</xsl:if>
</xsl:if>
</xsl:if>
</dstTime>
```
If it isn't, and four digits is the only thing that's legal then:
```
<dstTime>
<xsl:if test="string-length(srcTime) = 4">
<xsl:variable name="hour" select="substring(srcTime, 1, 2)" />
<xsl:if test="$hour >= 0 and 24 > $hour">
<xsl:variable name="minute" select="substring(srcTime, 3, 2)" />
<xsl:if test="$minute >= 0 and 60 > $minute">
<xsl:value-of select="concat($hour, ':', $minute)" />
</xsl:if>
</xsl:if>
</xsl:if>
</dstTime>
``` |
142,407 | <p>I am testing a Ruby Rails website and wanted to get started with Unit and Functional testing.</p>
| [
{
"answer_id": 142540,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://github.com/aslakhellesoy/cucumber/wikis\" rel=\"nofollow noreferrer\">Cucumber</a> and <a href=\"ht... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22883/"
] | I am testing a Ruby Rails website and wanted to get started with Unit and Functional testing. | [Cucumber](http://github.com/aslakhellesoy/cucumber/wikis) and [RSpec](http://rspec.info/) are worth a look. They encourage testing in a [behaviour-driven](http://behaviour-driven.org/), example-based style.
RSpec is a library for unit-level testing:
```
describe "hello_world"
it "should say hello to the world" do
# RSpec comes with its own mock-object framework built in,
# though it lets you use others if you prefer
world = mock("World", :population => 6e9)
world.should_receive(:hello)
hello_world(world)
end
end
```
It has special support for Rails (e.g. it can test models, views and controllers in isolation) and can replace the testing mechanisms built in to Rails.
Cucumber (formerly known as the RSpec Story Runner) lets you write high-level acceptance tests in (fairly) plain English that you could show to (and agree with) a customer, then run them:
```
Story: Commenting on articles
As a visitor to the blog
I want to post comments on articles
So that I can have my 15 minutes of fame
Scenario: Post a new comment
Given I am viewing an article
When I add a comment "Me too!"
And I fill in the CAPTCHA correctly
Then I should see a comment "Me too!"
``` |
142,417 | <p>Recently, <a href="https://stackoverflow.com/users/5200/lee-baldwin">Lee Baldwin</a> showed how to write a <a href="https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#141689">generic, variable argument memoize function</a>. I thought it would be better to return a simpler function where only one parameter is required. Here is my total bogus attempt:</p>
<pre><code>local function memoize(f)
local cache = {}
if select('#', ...) == 1 then
return function (x)
if cache[x] then
return cache[x]
else
local y = f(x)
cache[x] = y
return y
end
end
else
return function (...)
local al = varg_tostring(...)
if cache[al] then
return cache[al]
else
local y = f(...)
cache[al] = y
return y
end
end
end
end
</code></pre>
<p>Obviously, <code>select('#', ...)</code> fails in this context and wouldn't really do what I want anyway. Is there any way to tell inside <strong>memoize</strong> how many arguments <strong>f</strong> expects? </p>
<hr>
<p>"No" is a fine answer if you know for sure. It's not a big deal to use two separate <strong>memoize</strong> functions.</p>
| [
{
"answer_id": 142424,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>I guess you could go into the debug info and determine this from the source-code, but basically it's a \"no\", sorry.</p>\n"... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] | Recently, [Lee Baldwin](https://stackoverflow.com/users/5200/lee-baldwin) showed how to write a [generic, variable argument memoize function](https://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function#141689). I thought it would be better to return a simpler function where only one parameter is required. Here is my total bogus attempt:
```
local function memoize(f)
local cache = {}
if select('#', ...) == 1 then
return function (x)
if cache[x] then
return cache[x]
else
local y = f(x)
cache[x] = y
return y
end
end
else
return function (...)
local al = varg_tostring(...)
if cache[al] then
return cache[al]
else
local y = f(...)
cache[al] = y
return y
end
end
end
end
```
Obviously, `select('#', ...)` fails in this context and wouldn't really do what I want anyway. Is there any way to tell inside **memoize** how many arguments **f** expects?
---
"No" is a fine answer if you know for sure. It's not a big deal to use two separate **memoize** functions. | I guess you could go into the debug info and determine this from the source-code, but basically it's a "no", sorry. |
142,420 | <p>I have a method lets say:</p>
<pre><code>private static String drawCellValue(
int maxCellLength, String cellValue, String align) { }
</code></pre>
<p>and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?</p>
<p>Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 142428,
"author": "Carra",
"author_id": 21679,
"author_profile": "https://Stackoverflow.com/users/21679",
"pm_score": 7,
"selected": true,
"text": "<p>This should do it:</p>\n\n<pre><code>private enum Alignment { LEFT, RIGHT }; \nString drawCellValue (int maxCellLength,... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6618/"
] | I have a method lets say:
```
private static String drawCellValue(
int maxCellLength, String cellValue, String align) { }
```
and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?
Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.
Any ideas? | This should do it:
```
private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
if (align == Alignment.LEFT)
{
//Process it...
}
}
``` |
142,431 | <p>I'm setting up a server to offer JIRA and SVN. I figure, I'll use LDAP to keep the identity management simple. </p>
<p>So, before I write one.... is there a good app out there to let users change their ldap password? I want something that lets a user authenticate with ldap and update their password. A form with username, old password, new password and verification would be enough. </p>
<p>I can write my own, but it seems silly to do so if there's already a good app out there that handles this....</p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 142428,
"author": "Carra",
"author_id": 21679,
"author_profile": "https://Stackoverflow.com/users/21679",
"pm_score": 7,
"selected": true,
"text": "<p>This should do it:</p>\n\n<pre><code>private enum Alignment { LEFT, RIGHT }; \nString drawCellValue (int maxCellLength,... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9950/"
] | I'm setting up a server to offer JIRA and SVN. I figure, I'll use LDAP to keep the identity management simple.
So, before I write one.... is there a good app out there to let users change their ldap password? I want something that lets a user authenticate with ldap and update their password. A form with username, old password, new password and verification would be enough.
I can write my own, but it seems silly to do so if there's already a good app out there that handles this....
Thanks for the help. | This should do it:
```
private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
if (align == Alignment.LEFT)
{
//Process it...
}
}
``` |
142,452 | <p>There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature:</p>
<pre><code>bool MyFunction( char* buffer, int* bufferSize )
</code></pre>
<p>I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is <strong>best done in PowerShell 1.0</strong>. The fact that the function needing to be called <strong><em>is using pointers</em></strong> could affect the solution (yet I don't really know).</p>
<p>So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above?</p>
<p><strong>Remember for PowerShell 1.0.</strong></p>
| [
{
"answer_id": 142510,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<p>There isn't any mechanism in PowerShell 1.0 to directly call Win32 API's. You could of course write a C# or VB.NET helper class... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] | There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature:
```
bool MyFunction( char* buffer, int* bufferSize )
```
I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is **best done in PowerShell 1.0**. The fact that the function needing to be called ***is using pointers*** could affect the solution (yet I don't really know).
So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above?
**Remember for PowerShell 1.0.** | To call unmanaged code from Powershell, use the Invoke-Win32 function created by Lee Holmes. You can find the source [here](http://www.leeholmes.com/blog/GetTheOwnerOfAProcessInPowerShellPInvokeAndRefOutParameters.aspx). There you can see an example of how to call a function that has pointers, but a more trivial usage would be:
```
PS C:\> Invoke-Win32 "msvcrt.dll" ([Int32]) "puts" ([String]) "Test"
Test
0
``` |
142,508 | <p>I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:</p>
<pre><code>#ifdef OSisWindows
// do Windows-specific stuff
#else
// do Unix-specific stuff
#endif
</code></pre>
<p>Is there a way to do this? Is there a better way to do the same thing?</p>
| [
{
"answer_id": 142522,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 0,
"selected": false,
"text": "<p>Some compilers will generate #defines that can help you with this. Read the compiler documentation to determine what the... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10601/"
] | I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:
```
#ifdef OSisWindows
// do Windows-specific stuff
#else
// do Unix-specific stuff
#endif
```
Is there a way to do this? Is there a better way to do the same thing? | The **[Predefined Macros for OS](https://sourceforge.net/p/predef/wiki/OperatingSystems/)** site has a very complete list of checks. Here are a few of them, with links to where they're found:
[Windows](http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx)
-----------------------------------------------------------------------
`_WIN32` Both 32 bit and 64 bit
`_WIN64` 64 bit only
`__CYGWIN__`
Unix (Linux, \*BSD, but not Mac OS X)
-------------------------------------
See this [related question](https://stackoverflow.com/questions/7063303/) on some of the pitfalls of using this check.
`unix`
`__unix`
`__unix__`
Mac OS X
--------
`__APPLE__` Also used for classic
`__MACH__`
Both are defined; checking for either should work.
[Linux](http://www.faqs.org/docs/Linux-HOWTO/GCC-HOWTO.html)
------------------------------------------------------------
`__linux__`
`linux` Obsolete (not POSIX compliant)
`__linux` Obsolete (not POSIX compliant)
[FreeBSD](http://www.freebsd.org/doc/en/books/porters-handbook/porting-versions.html)
-------------------------------------------------------------------------------------
`__FreeBSD__`
Android
-------
`__ANDROID__` |
142,527 | <p>Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text <em>selected</em>?</p>
| [
{
"answer_id": 7599199,
"author": "Julien L",
"author_id": 690236,
"author_profile": "https://Stackoverflow.com/users/690236",
"pm_score": 4,
"selected": false,
"text": "<p>Try this piece of code I wrote this morning, it will highlight a defined set of words:</p>\n\n<pre><code><html&g... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80/"
] | Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text *selected*? | Try this piece of code I wrote this morning, it will highlight a defined set of words:
```
<html>
<head>
<title></title>
<!-- Load jQuery -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<!-- The javascript xontaining the plugin and the code to init the plugin -->
<script type="text/javascript">
$(function() {
// let's init the plugin, that we called "highlight".
// We will highlight the words "hello" and "world",
// and set the input area to a widht and height of 500 and 250 respectively.
$("#container").highlight({
words: ["hello","world"],
width: 500,
height: 250
});
});
// the plugin that would do the trick
(function($){
$.fn.extend({
highlight: function() {
// the main class
var pluginClass = function() {};
// init the class
// Bootloader
pluginClass.prototype.__init = function (element) {
try {
this.element = element;
} catch (err) {
this.error(err);
}
};
// centralized error handler
pluginClass.prototype.error = function (e) {
// manage error and exceptions here
//console.info("error!",e);
};
// Centralized routing function
pluginClass.prototype.execute = function (fn, options) {
try {
options = $.extend({},options);
if (typeof(this[fn]) == "function") {
var output = this[fn].apply(this, [options]);
} else {
this.error("undefined_function");
}
} catch (err) {
this.error(err);
}
};
// **********************
// Plugin Class starts here
// **********************
// init the component
pluginClass.prototype.init = function (options) {
try {
// the element's reference ( $("#container") ) is stored into "this.element"
var scope = this;
this.options = options;
// just find the different elements we'll need
this.highlighterContainer = this.element.find('#highlighterContainer');
this.inputContainer = this.element.find('#inputContainer');
this.textarea = this.inputContainer.find('textarea');
this.highlighter = this.highlighterContainer.find('#highlighter');
// apply the css
this.element.css('position','relative');
// place both the highlight container and the textarea container
// on the same coordonate to superpose them.
this.highlighterContainer.css({
'position': 'absolute',
'left': '0',
'top': '0',
'border': '1px dashed #ff0000',
'width': this.options.width,
'height': this.options.height,
'cursor': 'text'
});
this.inputContainer.css({
'position': 'absolute',
'left': '0',
'top': '0',
'border': '1px solid #000000'
});
// now let's make sure the highlit div and the textarea will superpose,
// by applying the same font size and stuffs.
// the highlighter must have a white text so it will be invisible
this.highlighter.css({
'padding': '7px',
'color': '#eeeeee',
'background-color': '#ffffff',
'margin': '0px',
'font-size': '11px',
'font-family': '"lucida grande",tahoma,verdana,arial,sans-serif'
});
// the textarea must have a transparent background so we can see the highlight div behind it
this.textarea.css({
'background-color': 'transparent',
'padding': '5px',
'margin': '0px',
'font-size': '11px',
'width': this.options.width,
'height': this.options.height,
'font-family': '"lucida grande",tahoma,verdana,arial,sans-serif'
});
// apply the hooks
this.highlighterContainer.bind('click', function() {
scope.textarea.focus();
});
this.textarea.bind('keyup', function() {
// when we type in the textarea,
// we want the text to be processed and re-injected into the div behind it.
scope.applyText($(this).val());
});
} catch (err) {
this.error(err);
}
return true;
};
pluginClass.prototype.applyText = function (text) {
try {
var scope = this;
// parse the text:
// replace all the line braks by <br/>, and all the double spaces by the html version
text = this.replaceAll(text,'\n','<br/>');
text = this.replaceAll(text,' ',' ');
// replace the words by a highlighted version of the words
for (var i=0;i<this.options.words.length;i++) {
text = this.replaceAll(text,this.options.words[i],'<span style="background-color: #D8DFEA;">'+this.options.words[i]+'</span>');
}
// re-inject the processed text into the div
this.highlighter.html(text);
} catch (err) {
this.error(err);
}
return true;
};
// "replace all" function
pluginClass.prototype.replaceAll = function(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'),with_this);
}
// don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here.
//**********************
// process
var fn;
var options;
if (arguments.length == 0) {
fn = "init";
options = {};
} else if (arguments.length == 1 && typeof(arguments[0]) == 'object') {
fn = "init";
options = $.extend({},arguments[0]);
} else {
fn = arguments[0];
options = $.extend({},arguments[1]);
}
$.each(this, function(idx, item) {
// if the component is not yet existing, create it.
if ($(item).data('highlightPlugin') == null) {
$(item).data('highlightPlugin', new pluginClass());
$(item).data('highlightPlugin').__init($(item));
}
$(item).data('highlightPlugin').execute(fn, options);
});
return this;
}
});
})(jQuery);
</script>
</head>
<body>
<div id="container">
<div id="highlighterContainer">
<div id="highlighter">
</div>
</div>
<div id="inputContainer">
<textarea cols="30" rows="10">
</textarea>
</div>
</div>
</body>
</html>
```
This was written for another post (http://facebook.stackoverflow.com/questions/7497824/how-to-highlight-friends-name-in-facebook-status-update-box-textarea/7597420#7597420), but it seems to be what you're searching for. |
142,545 | <p>The <code>__debug__</code> variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?</p>
<p>The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.</p>
| [
{
"answer_id": 142561,
"author": "awatts",
"author_id": 22847,
"author_profile": "https://Stackoverflow.com/users/22847",
"pm_score": 1,
"selected": false,
"text": "<p>This sounds like modifying the <code>__builtin__</code> name space. To do it:</p>\n\n<pre><code>import __builtin__\n__b... | 2008/09/26 | [
"https://Stackoverflow.com/questions/142545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22897/"
] | The `__debug__` variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?
The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it. | I don't endorse this solution in any way, shape or form. But if you add a variable to the `__builtin__` module, it will be accessible as if a global from any other module that includes `__builtin__` -- which is all of them, by default.
a.py contains
```
print foo
```
b.py contains
```
import __builtin__
__builtin__.foo = 1
import a
```
The result is that "1" is printed.
**Edit:** The `__builtin__` module is available as the local symbol `__builtins__` -- that's the reason for the discrepancy between two of these answers. Also note that `__builtin__` has been renamed to `builtins` in python3. |
142,633 | <p>I have a Button inside an UpdatePanel. The button is being used as the OK button for a ModalPopupExtender. For some reason, the button click event is not firing. Any ideas? Am I missing something?</p>
<pre><code><asp:updatepanel id="UpdatePanel1" runat="server">
<ContentTemplate>
<cc1:ModalPopupExtender ID="ModalDialog" runat="server"
TargetControlID="OpenDialogLinkButton"
PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton"
BackgroundCssClass="ModalBackground">
</cc1:ModalPopupExtender>
<asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server">
...
<asp:Button ID="ModalOKButton" runat="server" Text="OK"
onclick="ModalOKButton_Click" />
</asp:Panel>
</ContentTemplate>
</asp:updatepanel>
</code></pre>
| [
{
"answer_id": 142656,
"author": "Kyle Trauberman",
"author_id": 21461,
"author_profile": "https://Stackoverflow.com/users/21461",
"pm_score": 3,
"selected": false,
"text": "<p>It appears that a button that is used as the OK or CANCEL button for a ModalPopupExtender cannot have a click e... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21461/"
] | I have a Button inside an UpdatePanel. The button is being used as the OK button for a ModalPopupExtender. For some reason, the button click event is not firing. Any ideas? Am I missing something?
```
<asp:updatepanel id="UpdatePanel1" runat="server">
<ContentTemplate>
<cc1:ModalPopupExtender ID="ModalDialog" runat="server"
TargetControlID="OpenDialogLinkButton"
PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton"
BackgroundCssClass="ModalBackground">
</cc1:ModalPopupExtender>
<asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server">
...
<asp:Button ID="ModalOKButton" runat="server" Text="OK"
onclick="ModalOKButton_Click" />
</asp:Panel>
</ContentTemplate>
</asp:updatepanel>
``` | Aspx
```
<ajax:ModalPopupExtender runat="server" ID="modalPop"
PopupControlID="pnlpopup"
TargetControlID="btnGo"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="btnCancel" X="470" Y="300" />
//Codebehind
protected void OkButton_Clicked(object sender, EventArgs e)
{
modalPop.Hide();
//Do something in codebehind
}
```
**And don't set the OK button as OkControlID.** |
142,708 | <p>I can't seem to find any <em>useful</em> documentation from Microsoft about how one would use the <code>Delimiter</code> and <code>InheritsFromParent</code> attributes in the <code>UserMacro</code> element when defining user Macros in <code>.vsprops</code> property sheet files for Visual Studio.</p>
<p>Here's sample usage:</p>
<pre><code><UserMacro Name="INCLUDEPATH" Value="$(VCROOT)\Inc"
InheritsFromParent="TRUE" Delimiter=";"/>
</code></pre>
<p>From the above example, I'm guessing that <em>"inherit"</em> really means <em>"a) if definition is non-empty then append delimiter, and b) append new definition"</em> where as the non-inherit behavior would be to simply replace any current macro definition. Does anyone know for sure? Even better, does anyone have any suggested source of alternative documentation for Visual Studio <code>.vsprops</code> files and macros?</p>
<p>NOTE: this is <em>not</em> the same as the <code>InheritedPropertySheets</code> attribute of the <code>VisualStudioPropertySheet</code> element, for example:</p>
<pre><code><VisualStudioPropertySheet ... InheritedPropertySheets=".\my.vsprops">
</code></pre>
<p>In this case <em>"inherit"</em> basically means <em>"include"</em>.</p>
| [
{
"answer_id": 144032,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 0,
"selected": false,
"text": "<p>There's documentation on the UI version of this <a href=\"http://msdn.microsoft.com/en-us/library/a2zdt10t.aspx\" rel=\"n... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] | I can't seem to find any *useful* documentation from Microsoft about how one would use the `Delimiter` and `InheritsFromParent` attributes in the `UserMacro` element when defining user Macros in `.vsprops` property sheet files for Visual Studio.
Here's sample usage:
```
<UserMacro Name="INCLUDEPATH" Value="$(VCROOT)\Inc"
InheritsFromParent="TRUE" Delimiter=";"/>
```
From the above example, I'm guessing that *"inherit"* really means *"a) if definition is non-empty then append delimiter, and b) append new definition"* where as the non-inherit behavior would be to simply replace any current macro definition. Does anyone know for sure? Even better, does anyone have any suggested source of alternative documentation for Visual Studio `.vsprops` files and macros?
NOTE: this is *not* the same as the `InheritedPropertySheets` attribute of the `VisualStudioPropertySheet` element, for example:
```
<VisualStudioPropertySheet ... InheritedPropertySheets=".\my.vsprops">
```
In this case *"inherit"* basically means *"include"*. | *[Answering my own question]*
`InheritsFromParent` means prepend. To verify this, I did an experiment that reveals how User Macros work in Visual Studio 2008. Here's the setup:
* Project `p.vcproj` includes the property sheet file `d.vsprops` ('d' for *derived*) using the `InheritedPropertySheets` tag.
* `d.vsprops` includes the property sheet file `b.vsprops` ('b' for *base*.)
* `p.vcproj` also defines a Pre-Build Event which dumps the environment.
* Both `.vsprops` files contain User Macro definitions.
**b.vsprops**
```
...
<UserMacro Name="NOENV" Value="B"/>
<UserMacro Name="OVERRIDE" Value="B" PerformEnvironmentSet="true"/>
<UserMacro Name="PREPEND" Value="B" PerformEnvironmentSet="true"/>
...
```
**d.vsprops**
```
...
<VisualStudioPropertySheet ... InheritedPropertySheets=".\b.vsprops">
<UserMacro Name="ENV" Value="$(NOENV)" PerformEnvironmentSet="true"/>
<UserMacro Name="OVERRIDE" Value="D" PerformEnvironmentSet="true"/>
<UserMacro Name="PREPEND" Value="D" InheritsFromParent="true"
Delimiter="+" PerformEnvironmentSet="true"/>
...
```
**p.vcproj**
```
...
<Configuration ... InheritedPropertySheets=".\d.vsprops">
<Tool Name="VCPreBuildEventTool" CommandLine="set | sort"/>
...
```
**build output**
```
...
ENV=B
OVERRIDE=D
PREPEND=D+B
...
```
From these results we can conclude the following:
1. `PerformEnvironmentSet="true"` is necessary for User Macros to be defined in the environment used for build events. Proof: `NOENV` not shown in build output.
2. User Macros are ***always*** inherited from included property sheets regardless of `PerformEnvironmentSet` or `InheritsFromParent`. Proof: in `b.vsprops`, `NOENV` is not set in the environment and in `d.vsprops` it is used without need of `InheritsFromParent`.
3. Simple redefinition of a User Macro ***overrides*** any previous definition. Proof: `OVERRIDE` is set to `D` although it was earlier defined as `B`.
4. Redefinition of a User Macro with `InheritsFromParent="true"` ***prepends*** the new definition to any previous definition, separated by a specified `Delimiter`. Proof: `PREPEND` is set to `D+B` (not `D` or `B+D`.)
Here are some additional resources I found for explanation of Visual Studio `.vsprops` files and related topics, it's from a few years back but it is still helpful:
[understanding the VC project system part I: files and tools](http://blogs.msdn.com/josh_/archive/2004/02/03/66965.aspx)
[understanding the VC project system part II: configurations and the project property pages dialog](http://blogs.msdn.com/josh_/archive/2004/02/04/67705.aspx)
[understanding the VC project system part III: macros, environment variables and sharing](http://blogs.msdn.com/josh_/archive/2004/02/05/68366.aspx)
[understanding the VC project system part IV: properties and property inheritance](http://blogs.msdn.com/josh_/archive/2004/02/09/70335.aspx)
[understanding the VC project system part V: building, tools and dependencies](http://blogs.msdn.com/josh_/archive/2004/02/13/72844.aspx)
[understanding the VC project system part VI: custom build steps and build events](http://blogs.msdn.com/josh_/archive/2004/03/02/83035.aspx)
[understanding the VC project system part VII: "makefile" projects and (re-)using environments](http://blogs.msdn.com/josh_/archive/2004/05/18/134638.aspx) |
142,740 | <p>I want to do something like the following in spring:</p>
<pre><code><beans>
...
<bean id="bean1" ... />
<bean id="bean2">
<property name="propName" value="bean1.foo" />
...
</code></pre>
<p>I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.</p>
| [
{
"answer_id": 142765,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": -1,
"selected": false,
"text": "<p>I think you have to inject bean1, then get <code>foo</code> manually because of a timing issue. When does the framework ... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22063/"
] | I want to do something like the following in spring:
```
<beans>
...
<bean id="bean1" ... />
<bean id="bean2">
<property name="propName" value="bean1.foo" />
...
```
I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work. | What I understood:
1. You have a bean (bean1) with a
property called "foo"
2. You have another bean (bean2) with a
property named "propName", wich also
has to have the same "foo" that in
bean1.
why not doing this:
```
<beans>
...
<bean id="foo" class="foopackage.foo"/>
<bean id="bean1" class="foopackage.bean1">
<property name="foo" ref="foo"/>
</bean>
<bean id="bean2" class="foopackage.bean2">
<property name="propName" ref="foo"/>
</bean>
....
</beans>
```
Doing this, your bean2 is not coupled to bean1 like in your example. You can change bean1 and bean2 without affecting each other.
If you **REALLY** need to do the injection you proposed, you can use:
```
<util:property-path id="propName" path="bean1.foo"/>
``` |
142,750 | <p>I'm trying to get either CreateProcess or CreateProcessW to execute a process with a name < MAX_PATH characters but in a path that's greater than MAX_PATH characters. According to the docs at: <a href="http://msdn.microsoft.com/en-us/library/ms682425.aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/ms682425.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms682425.aspx</a></a>, I need to make sure lpApplicationName isn't NULL and then lpCommandLine can be up to 32,768 characters.</p>
<p>I tried that, but I get ERROR_PATH_NOT_FOUND.</p>
<p>I changed to CreateProcessW, but still get the same error. When I prefix lpApplicationName with \\?\ as described in <a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx</a></a> when calling CreateProcessW I get a different error that makes me think I'm a bit closer: ERROR_SXS_CANT_GEN_ACTCTX.</p>
<p>My call to CreateProcessW is:</p>
<p><code>
CreateProcessW(w_argv0,arg_string,NULL,NULL,0,NULL,NULL,&si,&ipi);
</code></p>
<p>where w_argv0 is <code>\\?\<long absolute path>\foo.exe.</code></p>
<p>arg_string contains "<long absolute path>\foo.exe" foo </p>
<p>si is set as follows:</p>
<pre>
memset(&si,0,sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;>
</pre>
<p>and pi is empty, as in:</p>
<pre>
memset(&pi,0,sizeof(pi));
</pre>
<p>I looked in the system event log and there's a new entry each time I try this with event id 59, source SideBySide: Generate Activation Context failed for .Manifest. Reference error message: The operation completed successfully.</p>
<p>The file I'm trying to execute runs fine in a path < MAX_PATH characters.</p>
<p>To clarify, no one component of <long absolute path> is greater than MAX_PATH characters. The name of the executable itself certainly isn't, even with .manifest on the end. But, the entire path together is greater than MAX_PATH characters long.</p>
<p>I get the same error whether I embed its manifest or not. The manifest is named foo.exe.manifest and lives in the same directory as the executable when it's not embedded. It contains:</p>
<pre>
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.762' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
</pre>
<p>Anyone know how to get this to work? Possibly:</p>
<ul>
<li><p>some other way to call CreateProcess or CreateProcessW to execute a process in a path > MAX_PATH characters</p></li>
<li><p>something I can do in the manifest file</p></li>
</ul>
<p>I'm building with Visual Studio 2005 on XP SP2 and running native.</p>
<p>Thanks for your help.</p>
| [
{
"answer_id": 143399,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 1,
"selected": false,
"text": "<p>I don't see any reference in the CreateProcess documentation saying that the '\\\\?\\' syntax is valid for the module name. T... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9572/"
] | I'm trying to get either CreateProcess or CreateProcessW to execute a process with a name < MAX\_PATH characters but in a path that's greater than MAX\_PATH characters. According to the docs at: [<http://msdn.microsoft.com/en-us/library/ms682425.aspx>](http://msdn.microsoft.com/en-us/library/ms682425.aspx), I need to make sure lpApplicationName isn't NULL and then lpCommandLine can be up to 32,768 characters.
I tried that, but I get ERROR\_PATH\_NOT\_FOUND.
I changed to CreateProcessW, but still get the same error. When I prefix lpApplicationName with \\?\ as described in [<http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx>](http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx) when calling CreateProcessW I get a different error that makes me think I'm a bit closer: ERROR\_SXS\_CANT\_GEN\_ACTCTX.
My call to CreateProcessW is:
`CreateProcessW(w_argv0,arg_string,NULL,NULL,0,NULL,NULL,&si,&ipi);`
where w\_argv0 is `\\?\<long absolute path>\foo.exe.`
arg\_string contains "<long absolute path>\foo.exe" foo
si is set as follows:
```
memset(&si,0,sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;>
```
and pi is empty, as in:
```
memset(π,0,sizeof(pi));
```
I looked in the system event log and there's a new entry each time I try this with event id 59, source SideBySide: Generate Activation Context failed for .Manifest. Reference error message: The operation completed successfully.
The file I'm trying to execute runs fine in a path < MAX\_PATH characters.
To clarify, no one component of <long absolute path> is greater than MAX\_PATH characters. The name of the executable itself certainly isn't, even with .manifest on the end. But, the entire path together is greater than MAX\_PATH characters long.
I get the same error whether I embed its manifest or not. The manifest is named foo.exe.manifest and lives in the same directory as the executable when it's not embedded. It contains:
```
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.762' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
```
Anyone know how to get this to work? Possibly:
* some other way to call CreateProcess or CreateProcessW to execute a process in a path > MAX\_PATH characters
* something I can do in the manifest file
I'm building with Visual Studio 2005 on XP SP2 and running native.
Thanks for your help. | Embedding the manifest and using GetShortPathNameW did it for me. One or the other on their own wasn't enough.
Before calling CreateProcessW using the \\?-prefixed absolute path name of the process to execute as the first argument, I check:
```
wchar_t *w_argv0;
wchar_t *w_short_argv0;
...
if (wcslen(w_argv0) >= MAX_PATH)
{
num_chars = GetShortPathNameW(w_argv0,NULL,0);
if (num_chars == 0) {
syslog(LOG_ERR,"GetShortPathName(%S) to get size failed (%d)",
w_argv0,GetLastError());
/*
** Might as well keep going and try with the long name
*/
} else {
w_short_argv0 = malloc(num_chars * sizeof(wchar_t));
memset(w_short_argv0,0,num_chars * sizeof(wchar_t));
if (GetShortPathNameW(w_argv0,w_short_argv0,num_chars) == 0) {
syslog(LOG_ERR,"GetShortPathName(%S) failed (%d)",w_argv0,
GetLastError());
free(w_short_argv0);
w_short_argv0 = NULL;
} else {
syslog(LOG_DEBUG,"using short name %S for %S",w_short_argv0,
w_argv0);
}
}
}
```
and then call CreateProcessW(w\_short\_argv0 ? w\_short\_argv0 : w\_argv0...);
remembering to free(w\_short\_argv0); afterwards.
This may not solve every case, but it lets me spawn more child processes than I could before. |
142,772 | <p>What is the difference between the Project and SVN workingDirectory Config Blocks in CruiseControl.NET?</p>
<p>I setup Subversion and now I'm working on CruiseControl.NET and noticed there are two workingDirectory blocks in the config files. I've looked through their google groups and documentation and maybe I missed something but I did not see a clear example of how they are used during the build process.</p>
<p>The partial config below is taken from their Project file example page
<a href="http://confluence.public.thoughtworks.org/display/CCNET/Configuring+the+Server" rel="nofollow noreferrer">http://confluence.public.thoughtworks.org/display/CCNET/Configuring+the+Server</a></p>
<pre><code><cruisecontrol>
<queue name="Q1" duplicates="ApplyForceBuildsReplace"/>
<project name="MyProject" queue="Q1" queuePriority="1">
<webURL>http://mybuildserver/ccnet/</webURL>
<workingDirectory>C:\Integration\MyProject\WorkingDirectory</workingDirectory>
<artifactDirectory>C:\Integration\MyProject\Artifacts</artifactDirectory>
<modificationDelaySeconds>10</modificationDelaySeconds>
<triggers>
<intervalTrigger seconds="60" name="continuous" />
</triggers>
<sourcecontrol type="cvs">
<executable>c:\putty\cvswithplinkrsh.bat</executable>
<workingDirectory>c:\fromcvs\myrepo</workingDirectory>
<cvsroot>:ext:mycvsserver:/cvsroot/myrepo</cvsroot>
</sourcecontrol>
</project>
</cruisecontrol>
</code></pre>
| [
{
"answer_id": 142795,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block\" rel=\"nofollow norefe... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | What is the difference between the Project and SVN workingDirectory Config Blocks in CruiseControl.NET?
I setup Subversion and now I'm working on CruiseControl.NET and noticed there are two workingDirectory blocks in the config files. I've looked through their google groups and documentation and maybe I missed something but I did not see a clear example of how they are used during the build process.
The partial config below is taken from their Project file example page
<http://confluence.public.thoughtworks.org/display/CCNET/Configuring+the+Server>
```
<cruisecontrol>
<queue name="Q1" duplicates="ApplyForceBuildsReplace"/>
<project name="MyProject" queue="Q1" queuePriority="1">
<webURL>http://mybuildserver/ccnet/</webURL>
<workingDirectory>C:\Integration\MyProject\WorkingDirectory</workingDirectory>
<artifactDirectory>C:\Integration\MyProject\Artifacts</artifactDirectory>
<modificationDelaySeconds>10</modificationDelaySeconds>
<triggers>
<intervalTrigger seconds="60" name="continuous" />
</triggers>
<sourcecontrol type="cvs">
<executable>c:\putty\cvswithplinkrsh.bat</executable>
<workingDirectory>c:\fromcvs\myrepo</workingDirectory>
<cvsroot>:ext:mycvsserver:/cvsroot/myrepo</cvsroot>
</sourcecontrol>
</project>
</cruisecontrol>
``` | I think the project working directory is used as the root folder for all commands in the CruiseControl block. So if I have a Nant task/script with relative folders, it will be appended to this root folder for actual execution.
>
> The Working Directory for the project
> (this is used by other blocks).
> Relative paths are relative to a
> directory called the project Name in
> the directory where the
> CruiseControl.NET server was launched
> from. The Working Directory is meant
> to contain the checked out version of
> the project under integration.
>
>
>
The SourceControl working directory is where your SVN or CVS will check out files, when invoked. So this would be the 'Src' subdirectory under your project folder for instance.
>
> The folder that the source has been
> checked out into.
>
>
>
Quoted Sources:
* <http://confluence.public.thoughtworks.org/display/CCNET/Project+Configuration+Block>
* <http://confluence.public.thoughtworks.org/display/CCNET/CVS+Source+Control+Block> |
142,789 | <p>From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story). </p>
<p>I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated.</p>
| [
{
"answer_id": 142792,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your functi... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22913/"
] | From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story).
I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated. | There is no "callback" in C - not more than any other generic programming concept.
They're implemented using function pointers. Here's an example:
```
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++)
array[i] = getNextValue();
}
int getNextRandomValue(void)
{
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
...
}
```
Here, the `populate_array` function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback `getNextRandomValue`, which returns a random-ish value, and passed a pointer to it to `populate_array`. `populate_array` will call our callback function 10 times and assign the returned values to the elements in the given array. |
142,813 | <p>I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#. </p>
<p>Example:</p>
<pre>
2748 to "ABC"
</pre>
| [
{
"answer_id": 142819,
"author": "Muxa",
"author_id": 10793,
"author_profile": "https://Stackoverflow.com/users/10793",
"pm_score": 3,
"selected": true,
"text": "<p>try</p>\n\n<pre><code>2748.ToString(\"X\")\n</code></pre>\n"
},
{
"answer_id": 142822,
"author": "TraumaPony",
... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609/"
] | I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#.
Example:
```
2748 to "ABC"
``` | try
```
2748.ToString("X")
``` |
142,820 | <p>I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write </p>
<pre><code>myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction);
</code></pre>
<p>this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too.</p>
| [
{
"answer_id": 142823,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 6,
"selected": true,
"text": "<p>Make sure your events are exposed as public. For example...</p>\n\n<pre><code>[Browsable(true)]\npublic event EventHan... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403/"
] | I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write
```
myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction);
```
this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too. | Make sure your events are exposed as public. For example...
```
[Browsable(true)]
public event EventHandler MyCustomEvent;
``` |
142,826 | <p>I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.</p>
<p>I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework.</p>
<p>Is there any good general purpose way to indefinitely pause a worker thread in C# .NET.</p>
<p>I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case.</p>
| [
{
"answer_id": 142833,
"author": "Shabbyrobe",
"author_id": 15004,
"author_profile": "https://Stackoverflow.com/users/15004",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming\" rel=\"noreferrer\">Threading i... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.
I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework.
Is there any good general purpose way to indefinitely pause a worker thread in C# .NET.
I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case. | Never, ever use `Thread.Suspend`. The major problem with it is that 99% of the time you can't know what that thread is doing when you suspend it. If that thread holds a lock, you make it easier to get into a deadlock situation, etc. Keep in mind that code you are calling may be acquiring/releasing locks behind the scenes. Win32 has a similar API: `SuspendThread` and `ResumeThread`. The following docs for `SuspendThread` give a nice summary of the dangers of the API:
<http://msdn.microsoft.com/en-us/library/ms686345(VS.85).aspx>
>
> This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately.
>
>
>
The proper way to suspend a thread indefinitely is to use a `ManualResetEvent`. The thread is most likely looping, performing some work. The easiest way to suspend the thread is to have the thread "check" the event each iteration, like so:
```
while (true)
{
_suspendEvent.WaitOne(Timeout.Infinite);
// Do some work...
}
```
You specify an infinite timeout so when the event is not signaled, the thread will block indefinitely, until the event is signaled at which point the thread will resume where it left off.
You would create the event like so:
```
ManualResetEvent _suspendEvent = new ManualResetEvent(true);
```
The `true` parameter tells the event to start out in the signaled state.
When you want to pause the thread, you do the following:
```
_suspendEvent.Reset();
```
And to resume the thread:
```
_suspendEvent.Set();
```
You can use a similar mechanism to signal the thread to exit and wait on both events, detecting which event was signaled.
Just for fun I'll provide a complete example:
```
public class Worker
{
ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
ManualResetEvent _pauseEvent = new ManualResetEvent(true);
Thread _thread;
public Worker() { }
public void Start()
{
_thread = new Thread(DoWork);
_thread.Start();
}
public void Pause()
{
_pauseEvent.Reset();
}
public void Resume()
{
_pauseEvent.Set();
}
public void Stop()
{
// Signal the shutdown event
_shutdownEvent.Set();
// Make sure to resume any paused threads
_pauseEvent.Set();
// Wait for the thread to exit
_thread.Join();
}
public void DoWork()
{
while (true)
{
_pauseEvent.WaitOne(Timeout.Infinite);
if (_shutdownEvent.WaitOne(0))
break;
// Do the work here..
}
}
}
``` |
142,844 | <p>I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.</p>
<p>Is there some kind of configuration that needs to be done somewhere for this work?</p>
| [
{
"answer_id": 142854,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": true,
"text": "<p>Sure. From a <a href=\"http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/\"... | 2008/09/27 | [
"https://Stackoverflow.com/questions/142844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4859/"
] | I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.
Is there some kind of configuration that needs to be done somewhere for this work? | Sure. From a [mindless technology article called "Make Python Scripts Droppable in Windows"](http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/), you can add a drop handler by adding a registry key:
>
> Here’s a registry import file that you can use to do this. Copy the
> following into a .reg file and run it
> (Make sure that your .py extensions
> are mapped to Python.File).
>
>
>
> ```
> Windows Registry Editor Version 5.00
>
> [HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]
> @="{60254CA5-953B-11CF-8C96-00AA00B8708C}"
>
> ```
>
>
This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with `86C86720-42A0-1069-A2E8-08002B30309D`.
A comment in that post indicates that one can enable dropping on "no console Python files (`.pyw`)" or "compiled Python files (`.pyc`)" by using the `Python.NoConFile` and `Python.CompiledFile` classes. |