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 |
|---|---|---|---|---|---|---|
120,033 | <p>In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays?</p>
<p>[Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts, even before <code>main</code>. However, it is not always possible to have a default constructor for every class, and besides, reinitializing the data again in the constructor rather defeats the purpose anyway.]</p>
<p>E.g. I'd like to have something like this (but this one doesn't work):</p>
<pre><code>class OtherClass {
private:
int data;
public:
OtherClass(int i) : data(i) {}; // No default constructor!
};
class Foo {
private:
OtherClass inst[3]; // Array size fixed and known ahead of time.
public:
Foo(...)
: inst[0](0), inst[1](1), inst[2](2)
{};
};
</code></pre>
<p>The only workaround I'm aware of is the non-array one:</p>
<pre><code>class Foo {
private:
OtherClass inst0;
OtherClass inst1;
OtherClass inst2;
OtherClass *inst[3];
public:
Foo(...)
: inst0(0), inst1(1), inst2(2) {
inst[0]=&inst0;
inst[1]=&inst1;
inst[2]=&inst2;
};
};
</code></pre>
<p><b>Edit</b>: It should be stressed that <code>OtherClass</code> has no default constructor, and that it is very desirable to have the linker be able to allocate any memory needed (one or more static instances of <code>Foo</code> will be created), using the heap is essentially <i>verboten</i>. I've updated the examples above to highlight the first point.</p>
| [
{
"answer_id": 120084,
"author": "Suma",
"author_id": 16673,
"author_profile": "https://Stackoverflow.com/users/16673",
"pm_score": 3,
"selected": true,
"text": "<p>One possible workaround is to avoid the compiler calling the OtherClass constructor at all, and to call it on your own usin... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20957/"
] | In C++, it's not possible to initialize array members in the initialization list, thus member objects should have default constructors and they should be properly initialized in the constructor. Is there any (reasonable) workaround for this apart from not using arrays?
[Anything that can be initialized using only the initialization list is in our application far preferable to using the constructor, as that data can be allocated and initialized by the compiler and linker, and every CPU clock cycle counts, even before `main`. However, it is not always possible to have a default constructor for every class, and besides, reinitializing the data again in the constructor rather defeats the purpose anyway.]
E.g. I'd like to have something like this (but this one doesn't work):
```
class OtherClass {
private:
int data;
public:
OtherClass(int i) : data(i) {}; // No default constructor!
};
class Foo {
private:
OtherClass inst[3]; // Array size fixed and known ahead of time.
public:
Foo(...)
: inst[0](0), inst[1](1), inst[2](2)
{};
};
```
The only workaround I'm aware of is the non-array one:
```
class Foo {
private:
OtherClass inst0;
OtherClass inst1;
OtherClass inst2;
OtherClass *inst[3];
public:
Foo(...)
: inst0(0), inst1(1), inst2(2) {
inst[0]=&inst0;
inst[1]=&inst1;
inst[2]=&inst2;
};
};
```
**Edit**: It should be stressed that `OtherClass` has no default constructor, and that it is very desirable to have the linker be able to allocate any memory needed (one or more static instances of `Foo` will be created), using the heap is essentially *verboten*. I've updated the examples above to highlight the first point. | One possible workaround is to avoid the compiler calling the OtherClass constructor at all, and to call it on your own using placement new to initialize it whichever way you need. Example:
```
class Foo
{
private:
char inst[3*sizeof(OtherClass)]; // Array size fixed. OtherClass has no default ctor.
// use Inst to access, not inst
OtherClass &Inst(int i) {return (OtherClass *)inst+i;}
const OtherClass &Inst(int i) const {return (const OtherClass *)inst+i;}
public:
Foo(...)
{
new (Inst(0)) OtherClass(...);
new (Inst(1)) OtherClass(...);
new (Inst(2)) OtherClass(...);
}
~Foo()
{
Inst(0)->~OtherClass();
Inst(1)->~OtherClass();
Inst(2)->~OtherClass();
}
};
```
To cater for possible alignment requirements of the OtherClass, you may need to use \_\_declspec(align(x)) if working in VisualC++, or to use a type other than char like:
```
Type inst[3*(sizeof(OtherClass)+sizeof(Type)-1)/sizeof(Type)];
```
... where Type is int, double, long long, or whatever describes the alignment requirements. |
120,061 | <p>I try to fetch a Wikipedia article with Python's urllib:</p>
<pre><code>f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes")
s = f.read()
f.close()
</code></pre>
<p>However instead of the html page I get the following response: Error - Wikimedia Foundation:</p>
<pre><code>Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to ()
Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT
</code></pre>
<p>Wikipedia seems to block request which are not from a standard browser.</p>
<p>Anybody know how to work around this?</p>
| [
{
"answer_id": 120073,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 1,
"selected": false,
"text": "<p>Try changing the user agent header you are sending in your request to something like:\nUser-Agent: Mozilla/5.0 (X11; U; Lin... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20999/"
] | I try to fetch a Wikipedia article with Python's urllib:
```
f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes")
s = f.read()
f.close()
```
However instead of the html page I get the following response: Error - Wikimedia Foundation:
```
Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to ()
Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT
```
Wikipedia seems to block request which are not from a standard browser.
Anybody know how to work around this? | You need to use the [urllib2](http://docs.python.org/lib/module-urllib2.html) that superseedes [urllib](http://docs.python.org/lib/module-urllib.html) in the [python std library](http://docs.python.org/lib/) in order to change the user agent.
Straight from the [examples](http://web.archive.org/web/20070202031348/http://docs.python.org/lib/urllib2-examples.html)
```
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes')
page = infile.read()
``` |
120,071 | <p>I have a string of arbitrary length, and starting at position p0, I need to find the first occurrence of one of three 3-letter patterns.</p>
<p>Assume the string contain only letters. I need to find the count of triplets starting at position p0 and jumping forward in triplets until the first occurrence of either 'aaa' or 'bbb' or 'ccc'.</p>
<p>Is this even possible using just a regex?</p>
| [
{
"answer_id": 120094,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$string=~/^ # from the start of the string\n (?:.{$p0}) # skip (don't capture) \"$p0\" occurrences... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
] | I have a string of arbitrary length, and starting at position p0, I need to find the first occurrence of one of three 3-letter patterns.
Assume the string contain only letters. I need to find the count of triplets starting at position p0 and jumping forward in triplets until the first occurrence of either 'aaa' or 'bbb' or 'ccc'.
Is this even possible using just a regex? | Moritz says this might be faster than a regex. Even if it's a little slower, it's easier to understand at 5 am. :)
```
#0123456789.123456789.123456789.
my $string = "alsdhfaaasccclaaaagalkfgblkgbklfs";
my $pos = 9;
my $length = 3;
my $regex = qr/^(aaa|bbb|ccc)/;
while( $pos < length $string )
{
print "Checking $pos\n";
if( substr( $string, $pos, $length ) =~ /$regex/ )
{
print "Found $1 at $pos\n";
last;
}
$pos += $length;
}
``` |
120,082 | <p>I have a problem with the design of a <code>VetoableChangeListener</code>. I implement the <code>VetoableChangeListener</code> interface to listen changes of a property in a model class, so when the model fires </p>
<pre><code>vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException
</code></pre>
<p>…I try to save the change in a DB, which could fail (by an <code>SQLException</code>, for example). If it fails I throw a <code>PropertyVetoException</code> to revert changes in the model.</p>
<p>The model is delegating in a <code>VetoableChangeSupport</code> (JDK class), which when it receives a <code>PropertyVetoException</code> catches it and notifies the revert to ALL the <code>VetoableChangeListener</code>, with the <code>oldValue</code>/<code>newValue</code> interchanged (later it rethrows the exception), so that the event comes to my class again and I try to save in DB again, etc...</p>
<p>I have a workaround which is that the model does NOT change until nobody throws a <code>PropertyVetoException</code>, so that in the <code>VetoableChangeListener</code> I FIRST check if the data I'm going to save in the database is NOT equal to the data in the model, if it's equal I simply ignore the change.</p>
<p>Is there another, better workaround?</p>
| [
{
"answer_id": 120712,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 0,
"selected": false,
"text": "<p>You should check the Vetoable change before you change the model, not after...</p>\n\n<p>ie: if there is a problem, th... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518/"
] | I have a problem with the design of a `VetoableChangeListener`. I implement the `VetoableChangeListener` interface to listen changes of a property in a model class, so when the model fires
```
vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException
```
…I try to save the change in a DB, which could fail (by an `SQLException`, for example). If it fails I throw a `PropertyVetoException` to revert changes in the model.
The model is delegating in a `VetoableChangeSupport` (JDK class), which when it receives a `PropertyVetoException` catches it and notifies the revert to ALL the `VetoableChangeListener`, with the `oldValue`/`newValue` interchanged (later it rethrows the exception), so that the event comes to my class again and I try to save in DB again, etc...
I have a workaround which is that the model does NOT change until nobody throws a `PropertyVetoException`, so that in the `VetoableChangeListener` I FIRST check if the data I'm going to save in the database is NOT equal to the data in the model, if it's equal I simply ignore the change.
Is there another, better workaround? | Your "workaround" is not really a workaround but in fact sounds like the proper solution to me: confirming that there is in fact a change for the current state of the object prior to attempting to "change" the persisted version. This will also be much more efficient (database access is expensive). |
120,083 | <p>Is there a way to alter the precision of an existing decimal column in Microsoft SQL Server?</p>
| [
{
"answer_id": 120821,
"author": "VanSkalen",
"author_id": 7367,
"author_profile": "https://Stackoverflow.com/users/7367",
"pm_score": 9,
"selected": true,
"text": "<pre><code>ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)\n</code></pre>\n\n<p>Just put <code>decimal(precision, sc... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12767/"
] | Is there a way to alter the precision of an existing decimal column in Microsoft SQL Server? | ```
ALTER TABLE Testing ALTER COLUMN TestDec decimal(16,1)
```
Just put `decimal(precision, scale)`, replacing the precision and scale with your desired values.
I haven't done any testing with this with data in the table, but if you alter the precision, you would be subject to losing data if the new precision is lower. |
120,102 | <p>My stored procedure is called as below from an SQL instegartion package within SQL Server 2005</p>
<p>EXEC ? = Validation.PopulateFaultsFileDetails ? , 0</p>
<p>Though i'm not sure what the ? means</p>
| [
{
"answer_id": 120115,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 1,
"selected": false,
"text": "<p>The ? stands fora variable, to be precise, a parameter. The first ? is the return value of the stored prcoedure and the secon... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21004/"
] | My stored procedure is called as below from an SQL instegartion package within SQL Server 2005
EXEC ? = Validation.PopulateFaultsFileDetails ? , 0
Though i'm not sure what the ? means | When this SQL statment is called, both question marks (?) will be replaced. The first will be replaced by a variable which will receive the return value of the stored procedure. The second will be replaced by a value which will be passed into the stored procedure. The code to use this statement will look something like this (pseudocode):
```
dim result
SQL = "EXEC ? = Validation.PopulateFaultsFileDetails ? , 0"
SQL.execute(result, 99) // pass in 99 to the stored proc
debug.print result
```
This gives you 3 advantages:
1. you can re-use the same bit of SQL with different values
2. you can pick up the return value and test for success/error
3. if the value you are passing in is a string, it should be correctly escaped for you, reducing the risk of SQL injection vulnerabilities in your app. |
120,114 | <p>I am using following PHP code to connect to MS Access database:</p>
<pre><code>$odb_conn = new COM("ADODB.Connection");
$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". $db_path.";";
$odb_conn->open($connstr);
</code></pre>
<p>How can I retrieve database catalog/metadata from the mdb file?</p>
<p><strong>FOUND THE SOLUTION</strong></p>
<pre><code>$rs_meta = $odb_conn->OpenSchema(20, array(Null, Null, Null, "TABLE"));
</code></pre>
| [
{
"answer_id": 120195,
"author": "Abbas",
"author_id": 4714,
"author_profile": "https://Stackoverflow.com/users/4714",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>MSysObjects</code> table can be used to query metadata in Access:</p>\n\n<pre><code>SELECT NAME\nFROM MSysObjects... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
] | I am using following PHP code to connect to MS Access database:
```
$odb_conn = new COM("ADODB.Connection");
$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". $db_path.";";
$odb_conn->open($connstr);
```
How can I retrieve database catalog/metadata from the mdb file?
**FOUND THE SOLUTION**
```
$rs_meta = $odb_conn->OpenSchema(20, array(Null, Null, Null, "TABLE"));
``` | You will find information on ADO here :
* <http://msdn.microsoft.com/en-us/library/ms675532(VS.85).aspx>
* <http://www.w3schools.com/ado/default.asp>
The connection object has an OpenSchema method to get database schema information.
I don't know how to use MS Acces DB with PHP and how your new COM() object works, but I think it's better to use an OleDB connection instead an ADO object : <http://msdn.microsoft.com/en-us/library/ms722784(VS.85).aspx> |
120,170 | <p>I'm doing some testing on Firefox toolbars for the sake of learning and I can't find out any information on how to store the contents of a "search" drop-down inside the user's profile.</p>
<p>Is there any tutorial on how to sort this out?</p>
| [
{
"answer_id": 121358,
"author": "Gustavo Carreno",
"author_id": 8167,
"author_profile": "https://Stackoverflow.com/users/8167",
"pm_score": 2,
"selected": true,
"text": "<p>Since it's taking quite a bit to get an answer I went and investigate it myself.\nHere is what I've got now. Not a... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
] | I'm doing some testing on Firefox toolbars for the sake of learning and I can't find out any information on how to store the contents of a "search" drop-down inside the user's profile.
Is there any tutorial on how to sort this out? | Since it's taking quite a bit to get an answer I went and investigate it myself.
Here is what I've got now. Not all is clear to me but it works.
Let's assume you have a <textbox> like this, on your .xul:
```
<textbox id="search_with_history" />
```
You now have to add some other attributes to enable history.
```
<textbox id="search_with_history" type="autocomplete"
autocompletesearch="form-history"
autocompletesearchparam="Search-History-Name"
ontextentered="Search_Change(param);"
enablehistory="true"
/>
```
This gives you the minimum to enable a history on that textbox.
For some reason, and here is where my ignorance shows, the onTextEntered event function has to have the param to it called "param". I tried "event" and it didn't work.
But that alone will not do work by itself. One has to add some Javascript to help with the job.
```
// This is the interface to store the history
const HistoryObject = Components.classes["@mozilla.org/satchel/form-history;1"]
.getService(
Components.interfaces.nsIFormHistory2 || Components.interfaces.nsIFormHistory
);
// The above line was broken into 4 for clearness.
// If you encounter problems please use only one line.
// This function is the one called upon the event of pressing <enter>
// on the text box
function Search_Change(event) {
var terms = document.getElementById('search_with_history').value;
HistoryObject.addEntry('Search-History-Name', terms);
}
```
This is the absolute minimum to get a history going on. |
120,180 | <p>I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it!</p>
<p>I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated!</p>
<p>To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.</p>
| [
{
"answer_id": 120430,
"author": "Alexandre Victoor",
"author_id": 11897,
"author_profile": "https://Stackoverflow.com/users/11897",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the class <strong>PrefixQuery</strong> on a \"dictionary\" index. The class <strong>LuceneDiction... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6282/"
] | I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it!
I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated!
To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc. | Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want.
This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sorted by the number of matching documents with that term in the original index, so more popular terms appear first. Seems to work pretty well :)
```
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.ISOLatin1AccentFilter;
import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter;
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* Search term auto-completer, works for single terms (so use on the last term
* of the query).
* <p>
* Returns more popular terms first.
*
* @author Mat Mannion, M.Mannion@warwick.ac.uk
*/
public final class Autocompleter {
private static final String GRAMMED_WORDS_FIELD = "words";
private static final String SOURCE_WORD_FIELD = "sourceWord";
private static final String COUNT_FIELD = "count";
private static final String[] ENGLISH_STOP_WORDS = {
"a", "an", "and", "are", "as", "at", "be", "but", "by",
"for", "i", "if", "in", "into", "is",
"no", "not", "of", "on", "or", "s", "such",
"t", "that", "the", "their", "then", "there", "these",
"they", "this", "to", "was", "will", "with"
};
private final Directory autoCompleteDirectory;
private IndexReader autoCompleteReader;
private IndexSearcher autoCompleteSearcher;
public Autocompleter(String autoCompleteDir) throws IOException {
this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir,
null);
reOpenReader();
}
public List<String> suggestTermsFor(String term) throws IOException {
// get the top 5 terms for query
Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term));
Sort sort = new Sort(COUNT_FIELD, true);
TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort);
List<String> suggestions = new ArrayList<String>();
for (ScoreDoc doc : docs.scoreDocs) {
suggestions.add(autoCompleteReader.document(doc.doc).get(
SOURCE_WORD_FIELD));
}
return suggestions;
}
@SuppressWarnings("unchecked")
public void reIndex(Directory sourceDirectory, String fieldToAutocomplete)
throws CorruptIndexException, IOException {
// build a dictionary (from the spell package)
IndexReader sourceReader = IndexReader.open(sourceDirectory);
LuceneDictionary dict = new LuceneDictionary(sourceReader,
fieldToAutocomplete);
// code from
// org.apache.lucene.search.spell.SpellChecker.indexDictionary(
// Dictionary)
IndexReader.unlock(autoCompleteDirectory);
// use a custom analyzer so we can do EdgeNGramFiltering
IndexWriter writer = new IndexWriter(autoCompleteDirectory,
new Analyzer() {
public TokenStream tokenStream(String fieldName,
Reader reader) {
TokenStream result = new StandardTokenizer(reader);
result = new StandardFilter(result);
result = new LowerCaseFilter(result);
result = new ISOLatin1AccentFilter(result);
result = new StopFilter(result,
ENGLISH_STOP_WORDS);
result = new EdgeNGramTokenFilter(
result, Side.FRONT,1, 20);
return result;
}
}, true);
writer.setMergeFactor(300);
writer.setMaxBufferedDocs(150);
// go through every word, storing the original word (incl. n-grams)
// and the number of times it occurs
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
Iterator<String> iter = (Iterator<String>) dict.getWordsIterator();
while (iter.hasNext()) {
String word = iter.next();
int len = word.length();
if (len < 3) {
continue; // too short we bail but "too long" is fine...
}
if (wordsMap.containsKey(word)) {
throw new IllegalStateException(
"This should never happen in Lucene 2.3.2");
// wordsMap.put(word, wordsMap.get(word) + 1);
} else {
// use the number of documents this word appears in
wordsMap.put(word, sourceReader.docFreq(new Term(
fieldToAutocomplete, word)));
}
}
for (String word : wordsMap.keySet()) {
// ok index the word
Document doc = new Document();
doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES,
Field.Index.UN_TOKENIZED)); // orig term
doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES,
Field.Index.TOKENIZED)); // grammed
doc.add(new Field(COUNT_FIELD,
Integer.toString(wordsMap.get(word)), Field.Store.NO,
Field.Index.UN_TOKENIZED)); // count
writer.addDocument(doc);
}
sourceReader.close();
// close writer
writer.optimize();
writer.close();
// re-open our reader
reOpenReader();
}
private void reOpenReader() throws CorruptIndexException, IOException {
if (autoCompleteReader == null) {
autoCompleteReader = IndexReader.open(autoCompleteDirectory);
} else {
autoCompleteReader.reopen();
}
autoCompleteSearcher = new IndexSearcher(autoCompleteReader);
}
public static void main(String[] args) throws Exception {
Autocompleter autocomplete = new Autocompleter("/index/autocomplete");
// run this to re-index from the current index, shouldn't need to do
// this very often
// autocomplete.reIndex(FSDirectory.getDirectory("/index/live", null),
// "content");
String term = "steve";
System.out.println(autocomplete.suggestTermsFor(term));
// prints [steve, steven, stevens, stevenson, stevenage]
}
}
``` |
120,191 | <p>So you've created a ruby library.</p>
<p>How do you create and publish your rubygem? And what common pitfalls and gotchas are there pertaining to creating and publishing rubygems?</p>
| [
{
"answer_id": 120390,
"author": "user6325",
"author_id": 6325,
"author_profile": "https://Stackoverflow.com/users/6325",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend <a href=\"http://gems.github.com\" rel=\"nofollow noreferrer\">github</a> as a place to start, especially fo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683/"
] | So you've created a ruby library.
How do you create and publish your rubygem? And what common pitfalls and gotchas are there pertaining to creating and publishing rubygems? | There are several tools to help you build your own gems. [hoe](http://seattlerb.rubyforge.org/hoe/) and [newgem](http://newgem.rubyforge.org/) are the best-known, and have a lot of good qualities. However, hoe adds itself as a dependency to your gem, and newgem has become a very large tool, one that I find unwieldy when I want to create and deploy a gem quickly.
My favorite tool is [Mr Bones](http://codeforpeople.rubyforge.org/bones/) by Tim Pease. It’s lightweight, featureful, and does not add dependencies to your project. To create a project with it, you just run `bones <my_project_name>` on the command line, and a skeleton is built for you, complete with a `lib` directory for your code, a `bin` directory for your tools, and a test directory. The configuration is in a `Rakefile`, and it’s clear and concise. Here's the configuration for a project I did a few months ago:
```
load 'tasks/setup.rb'
ensure_in_path 'lib'
require 'friend-feed'
task :default => 'test'
PROJ.name = 'friend-feed'
PROJ.authors = 'Clinton R. Nixon'
PROJ.email = 'crnixon@gmail.com'
PROJ.url = 'friend-feed.rubyforge.org'
PROJ.rubyforge_name = 'friend-feed'
PROJ.dependencies = ['json']
PROJ.version = FriendFeed::VERSION
PROJ.exclude = %w(.git pkg)
```
Mr Bones has the standard set of features you’d expect: you can use it to package up gems and tarfiles of your library, as well as release it on RubyForge and deploy your documentation there. Its killer feature, though, is its ability to freeze its skeleton in your home directory. When you run `bones --freeze`, a directory named `.mrbones` is copied into your home directory. You can edit the files in there to make a skeleton for your gems that works the way you work, and from then on, when you run bones to create a new gem, it will use your personal gem skeleton. You can unfreeze Mr Bones by running `bones --unfreeze` and your skeleton will be backed up, and the default skeleton will be used again.
(Editorial note: I wrote a blog post about this several months ago, and most of this is copied from it.) |
120,201 | <p>I want to upload and then process a file in a Ruby on Rails app. The file upload is usually quite short, but the server-side processing can take some time (more than 20 seconds) so I want to give the user some indicator - something better than a meaningless 'processing...' screen.</p>
<p>I'm trying to use the following code in the view</p>
<pre><code><%= periodically_call_remote(:url => {:action => 'progress_monitor', :controller => 'files'},
:frequency => '5',
:update => "setProgress('progressBar','5')"
) %>
</code></pre>
<p>The content of the :update parameter is the javascript I want to run every 5 seconds</p>
<p>and the following code is in the files controller</p>
<pre><code>def progress_monitor
render :text => 'whatever'
end
</code></pre>
<p>Eventually the progress_monitor method will return the current progress as an integer (% complete) and that will be passed into the 'setProgress' JavaScript code (that will update an on screen element)</p>
<p>However, I'm struggling to get a correct response from from the server that can then be passed into JavaScript.</p>
<p>Can anyone help, or am I approaching this the wrong way?</p>
<p>There is a follow up question to this, I originally updated this question but the update was sufficiently different to warrant a new question, <a href="https://stackoverflow.com/questions/126011/monitoring-a-server-side-process-on-rails-application-using-ajax-xmlhttprequest">here</a>.</p>
| [
{
"answer_id": 120317,
"author": "liangzan",
"author_id": 11927,
"author_profile": "https://Stackoverflow.com/users/11927",
"pm_score": 3,
"selected": true,
"text": "<p><code>periodically_call_remote()</code> updates a <code>div</code>. It won't call your JavaScript function. I'm no Java... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6106/"
] | I want to upload and then process a file in a Ruby on Rails app. The file upload is usually quite short, but the server-side processing can take some time (more than 20 seconds) so I want to give the user some indicator - something better than a meaningless 'processing...' screen.
I'm trying to use the following code in the view
```
<%= periodically_call_remote(:url => {:action => 'progress_monitor', :controller => 'files'},
:frequency => '5',
:update => "setProgress('progressBar','5')"
) %>
```
The content of the :update parameter is the javascript I want to run every 5 seconds
and the following code is in the files controller
```
def progress_monitor
render :text => 'whatever'
end
```
Eventually the progress\_monitor method will return the current progress as an integer (% complete) and that will be passed into the 'setProgress' JavaScript code (that will update an on screen element)
However, I'm struggling to get a correct response from from the server that can then be passed into JavaScript.
Can anyone help, or am I approaching this the wrong way?
There is a follow up question to this, I originally updated this question but the update was sufficiently different to warrant a new question, [here](https://stackoverflow.com/questions/126011/monitoring-a-server-side-process-on-rails-application-using-ajax-xmlhttprequest). | `periodically_call_remote()` updates a `div`. It won't call your JavaScript function. I'm no JavaScript guru, but to solve your problem, you should do your own `xmlhttp` call. If I were you, I'd use prototype's AJAX request
<http://www.prototypejs.org/api/ajax/request>
and use JavaScript's settimeout or setinterval to do the periodic polling
<http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/>
hope this helps cos actually I've encountered the same prb too =) |
120,206 | <p>The problem is not about randomness itself (we have rand), but in cryptographically secure PRNG. What can be used on Linux, or ideally POSIX? Does NSS have something useful?</p>
<p><strong>Clarification</strong>: I know about /dev/random, but it may run out of entropy pool. And I'm not sure whether /dev/urandom is guaranteed to be cryptographically secure.</p>
| [
{
"answer_id": 120209,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>/dev/random</code> device is intended to be a source of cryptographically secure bits.</p>\n"
},
{
"... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] | The problem is not about randomness itself (we have rand), but in cryptographically secure PRNG. What can be used on Linux, or ideally POSIX? Does NSS have something useful?
**Clarification**: I know about /dev/random, but it may run out of entropy pool. And I'm not sure whether /dev/urandom is guaranteed to be cryptographically secure. | Use `/dev/random` (requires user input, eg mouse movements) or `/dev/urandom`. The latter has an entropy pool and doesn't require any user input unless the pool is empty.
You can read from the pool like this:
```
char buf[100];
FILE *fp;
if (fp = fopen("/dev/urandom", "r")) {
fread(&buf, sizeof(char), 100, fp);
fclose(fp);
}
```
Or something like that. |
120,212 | <p>I am using VMware Server 1.0.7 on Windows XP SP3 at the moment to test software in virtual machines.</p>
<p>I have also tried Microsoft Virtual PC (do not remeber the version, could be 2004 or 2007) and VMware was way faster at the time.</p>
<p>I have heard of Parallels and VirtualBox but I did not have the time to try them out. Anybody has some benchmarks how fast is each of them (or some other)?</p>
<p>I searched for benchmarks on the web, but found nothing useful.</p>
<p>I am looking primarily for free software, but if it is really better than free ones I would pay for it.</p>
<p>Also, if you are using (or know of) a good virtualization software but have no benchmarks for it, please let me know.</p>
| [
{
"answer_id": 120209,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>/dev/random</code> device is intended to be a source of cryptographically secure bits.</p>\n"
},
{
"... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17469/"
] | I am using VMware Server 1.0.7 on Windows XP SP3 at the moment to test software in virtual machines.
I have also tried Microsoft Virtual PC (do not remeber the version, could be 2004 or 2007) and VMware was way faster at the time.
I have heard of Parallels and VirtualBox but I did not have the time to try them out. Anybody has some benchmarks how fast is each of them (or some other)?
I searched for benchmarks on the web, but found nothing useful.
I am looking primarily for free software, but if it is really better than free ones I would pay for it.
Also, if you are using (or know of) a good virtualization software but have no benchmarks for it, please let me know. | Use `/dev/random` (requires user input, eg mouse movements) or `/dev/urandom`. The latter has an entropy pool and doesn't require any user input unless the pool is empty.
You can read from the pool like this:
```
char buf[100];
FILE *fp;
if (fp = fopen("/dev/urandom", "r")) {
fread(&buf, sizeof(char), 100, fp);
fclose(fp);
}
```
Or something like that. |
120,228 | <p>I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?</p>
<p>What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not.</p>
<p>This is just a quick example of what I was thinking about:</p>
<pre><code>if ($alreadyDone == 0 && time() > $timeToRunMaintainance) {
runTask();
$timeToRunMaintainance = time() + $interval;
}
</code></pre>
<p>Anything else I should take into consideration or is there a better method than this?</p>
| [
{
"answer_id": 120236,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 5,
"selected": false,
"text": "<p>That's what cronjobs are made for. <code>man crontab</code> assuming you are running a linux server. If you do... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15214/"
] | I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?
What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not.
This is just a quick example of what I was thinking about:
```
if ($alreadyDone == 0 && time() > $timeToRunMaintainance) {
runTask();
$timeToRunMaintainance = time() + $interval;
}
```
Anything else I should take into consideration or is there a better method than this? | That's what cronjobs are made for. `man crontab` assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs. |
120,244 | <p>I'm trying to put together a selector in SASS that will operate on the visted, hovered state of a link, but I can't quite seem to get the markup right, can someone enlighten me?
I was writing it like this:</p>
<pre><code> &:visited:hover
attribute: foo
</code></pre>
| [
{
"answer_id": 120515,
"author": "user6325",
"author_id": 6325,
"author_profile": "https://Stackoverflow.com/users/6325",
"pm_score": 1,
"selected": false,
"text": "<pre><code>a\n &:visited:hover\n :attribute foo\n</code></pre>\n\n<p>Try that - note that identation is two spaces, ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977/"
] | I'm trying to put together a selector in SASS that will operate on the visted, hovered state of a link, but I can't quite seem to get the markup right, can someone enlighten me?
I was writing it like this:
```
&:visited:hover
attribute: foo
``` | ```
a
&:visited:hover
attribute: foo
```
Nowadays, this is the only valid form. Indention has to be consistent (2 spaces are recommended) and the colon follows the attribute. |
120,250 | <p>Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory. </p>
<p>So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?</p>
| [
{
"answer_id": 120256,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 5,
"selected": false,
"text": "<p>Nope. But you can use short integers in arrays:</p>\n\n<pre><code>from array import array\na = array(\"h\") # h... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21029/"
] | Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory.
So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')? | Nope. But you can use short integers in arrays:
```
from array import array
a = array("h") # h = signed short, H = unsigned short
```
As long as the value stays in that array it will be a short integer.
* documentation for the [array module](http://docs.python.org/dev/library/array) |
120,262 | <p>Say for instance I was writing a function that was designed to accept multiple argument types:</p>
<pre><code>var overloaded = function (arg) {
if (is_dom_element(arg)) {
// Code for DOM Element argument...
}
};
</code></pre>
<p>What's the best way to implement <strong><code>is_dom_element</code></strong> so that it works in a cross-browser, fairly accurate way?</p>
| [
{
"answer_id": 120275,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "<p>Probably this one here:</p>\n\n<pre><code>node instanceof HTMLElement\n</code></pre>\n\n<p>That should work in m... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10942/"
] | Say for instance I was writing a function that was designed to accept multiple argument types:
```
var overloaded = function (arg) {
if (is_dom_element(arg)) {
// Code for DOM Element argument...
}
};
```
What's the best way to implement **`is_dom_element`** so that it works in a cross-browser, fairly accurate way? | jQuery checks the nodeType property. So you would have:
```
var overloaded = function (arg) {
if (arg.nodeType) {
// Code for DOM Element argument...
}
};
```
Although this would detect all DOM objects, not just elements. If you want elements alone, that would be:
```
var overloaded = function (arg) {
if (arg.nodeType && arg.nodeType == 1) {
// Code for DOM Element argument...
}
};
``` |
120,266 | <p>In my database, I have a model which has a field which should be selected from one of a list of options. As an example, consider a model which needs to store a measurement, such as 5ft or 13cm or 12.24m3. The obvious way to achieve this is to have a decimal field and then some other field to store the unit of measurement. </p>
<p>So what is the best way to store the unit of measurement? I've used a couple of approaches in the past:</p>
<p>1) Storing the various options in another DB table (and associated model), and linking the two with a standard foreign key (and usually eager loading the associated model). This seems like overkill, as you are forcing the DB to perform a join on every query.</p>
<p>2) Storing the options as a constant Hash, loaded in one of the initializers, where the key into the Hash is stored in the unit of measurement field. This way, you effectively do the join in Ruby (which may or may not be a performance increase), but you lose the ability to query from the "unit of measurement" side. This wouldn't be a problem provided it's unlikely you'd need to do queries like "find me all measurements with units of cm".</p>
<p>Neither of these feel particularly elegant to me.. can anyone suggest something better?</p>
| [
{
"answer_id": 120281,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>I would go with option one. How large will it be the UnitOfMeasurement table? And, if using an integer primary key, why do y... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In my database, I have a model which has a field which should be selected from one of a list of options. As an example, consider a model which needs to store a measurement, such as 5ft or 13cm or 12.24m3. The obvious way to achieve this is to have a decimal field and then some other field to store the unit of measurement.
So what is the best way to store the unit of measurement? I've used a couple of approaches in the past:
1) Storing the various options in another DB table (and associated model), and linking the two with a standard foreign key (and usually eager loading the associated model). This seems like overkill, as you are forcing the DB to perform a join on every query.
2) Storing the options as a constant Hash, loaded in one of the initializers, where the key into the Hash is stored in the unit of measurement field. This way, you effectively do the join in Ruby (which may or may not be a performance increase), but you lose the ability to query from the "unit of measurement" side. This wouldn't be a problem provided it's unlikely you'd need to do queries like "find me all measurements with units of cm".
Neither of these feel particularly elegant to me.. can anyone suggest something better? | Have you seen [constant\_cache](http://github.com/vigetlabs/constant_cache/tree/master)? It's sort of the combination of the best of 1 and 2 - lookup data is stored in the DB, but it's exposed as class constants on the lookup model and only loaded at application start, so you don't suffer the join penalties constantly. The following example comes from the README:
migration:
```
create_table :account_statuses do |t|
t.string :name, :description
end
AccountStatus.create!(:name => 'Active', :description => 'Active user account')
AccountStatus.create!(:name => 'Pending', :description => 'Pending user account')
AccountStatus.create!(:name => 'Disabled', :description => 'Disabled user account')
```
model:
```
class AccountStatus < ActiveRecord::Base
caches_constants
end
```
using it:
```
Account.new(:username => 'preagan', :status => AccountStatus::PENDING)
``` |
120,334 | <p>I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution.
The following does not work on my windows development machine (although I'd think that this should be at least a possible solution):</p>
<pre><code>$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');
$oldLocal=setlocale(LC_COLLATE, "0");
var_dump(setlocale(LC_COLLATE, 'German_Germany.65001'));
usort($array, 'strcoll');
var_dump(setlocale(LC_COLLATE, $oldLocal));
var_dump($array);
</code></pre>
<p>The output is:</p>
<pre><code>string(20) "German_Germany.65001"
string(1) "C"
array(6) {
[0]=>
string(6) "Birnen"
[1]=>
string(9) "Ungetiere"
[2]=>
string(6) "Äpfel"
[3]=>
string(5) "Apfel"
[4]=>
string(9) "Ungetüme"
[5]=>
string(11) "Österreich"
}
</code></pre>
<p>This is complete nonsense. Using 1252 as the codepage for <code>setlocale()</code> gives another output but still a plainly wrong one:</p>
<pre><code>string(19) "German_Germany.1252"
string(1) "C"
array(6) {
[0]=>
string(11) "Österreich"
[1]=>
string(6) "Äpfel"
[2]=>
string(5) "Apfel"
[3]=>
string(6) "Birnen"
[4]=>
string(9) "Ungetüme"
[5]=>
string(9) "Ungetiere"
}
</code></pre>
<p>Is there a way to sort an array with UTF-8 strings locale aware?</p>
<p><em>Just noted that this seems to be PHP on Windows problem, as the same snippet with <code>de_DE.utf8</code> used as locale works on a Linux machine. Nevertheless a solution for this Windows-specific problem would be nice...</em></p>
| [
{
"answer_id": 120361,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>This is a very complex <a href=\"http://unicode.org/reports/tr10/\" rel=\"nofollow noreferrer\">issue</a>, since UTF-8 encod... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11354/"
] | I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution.
The following does not work on my windows development machine (although I'd think that this should be at least a possible solution):
```
$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich');
$oldLocal=setlocale(LC_COLLATE, "0");
var_dump(setlocale(LC_COLLATE, 'German_Germany.65001'));
usort($array, 'strcoll');
var_dump(setlocale(LC_COLLATE, $oldLocal));
var_dump($array);
```
The output is:
```
string(20) "German_Germany.65001"
string(1) "C"
array(6) {
[0]=>
string(6) "Birnen"
[1]=>
string(9) "Ungetiere"
[2]=>
string(6) "Äpfel"
[3]=>
string(5) "Apfel"
[4]=>
string(9) "Ungetüme"
[5]=>
string(11) "Österreich"
}
```
This is complete nonsense. Using 1252 as the codepage for `setlocale()` gives another output but still a plainly wrong one:
```
string(19) "German_Germany.1252"
string(1) "C"
array(6) {
[0]=>
string(11) "Österreich"
[1]=>
string(6) "Äpfel"
[2]=>
string(5) "Apfel"
[3]=>
string(6) "Birnen"
[4]=>
string(9) "Ungetüme"
[5]=>
string(9) "Ungetiere"
}
```
Is there a way to sort an array with UTF-8 strings locale aware?
*Just noted that this seems to be PHP on Windows problem, as the same snippet with `de_DE.utf8` used as locale works on a Linux machine. Nevertheless a solution for this Windows-specific problem would be nice...* | Eventually this problem cannot be solved in a simple way without using recoded strings (UTF-8 → Windows-1252 or ISO-8859-1) as suggested by ΤΖΩΤΖΙΟΥ due to an obvious PHP bug as discovered by Huppie.
To summarize the problem, I created the following code snippet which clearly demonstrates that the problem is the strcoll() function when using the 65001 Windows-UTF-8-codepage.
```
function traceStrColl($a, $b) {
$outValue=strcoll($a, $b);
echo "$a $b $outValue\r\n";
return $outValue;
}
$locale=(defined('PHP_OS') && stristr(PHP_OS, 'win')) ? 'German_Germany.65001' : 'de_DE.utf8';
$string="ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöüß";
$array=array();
for ($i=0; $i<mb_strlen($string, 'UTF-8'); $i++) {
$array[]=mb_substr($string, $i, 1, 'UTF-8');
}
$oldLocale=setlocale(LC_COLLATE, "0");
var_dump(setlocale(LC_COLLATE, $locale));
usort($array, 'traceStrColl');
setlocale(LC_COLLATE, $oldLocale);
var_dump($array);
```
The result is:
```
string(20) "German_Germany.65001"
a B 2147483647
[...]
array(59) {
[0]=>
string(1) "c"
[1]=>
string(1) "B"
[2]=>
string(1) "s"
[3]=>
string(1) "C"
[4]=>
string(1) "k"
[5]=>
string(1) "D"
[6]=>
string(2) "ä"
[7]=>
string(1) "E"
[8]=>
string(1) "g"
[...]
```
The same snippet works on a Linux machine without any problems producing the following output:
```
string(10) "de_DE.utf8"
a B -1
[...]
array(59) {
[0]=>
string(1) "a"
[1]=>
string(1) "A"
[2]=>
string(2) "ä"
[3]=>
string(2) "Ä"
[4]=>
string(1) "b"
[5]=>
string(1) "B"
[6]=>
string(1) "c"
[7]=>
string(1) "C"
[...]
```
The snippet also works when using Windows-1252 (ISO-8859-1) encoded strings (of course the mb\_\* encodings and the locale must be changed then).
I filed a bug report on [bugs.php.net](http://bugs.php.net): [Bug #46165 strcoll() does not work with UTF-8 strings on Windows](http://bugs.php.net/bug.php?id=46165). If you experience the same problem, you can give your feedback to the PHP team on the bug-report page (two other, probably related, bugs have been classified as *bogus* - I don't think that this bug is *bogus* ;-).
Thanks to all of you. |
120,420 | <p>I would like to have information about the icons which are displayed alongside the site URLs on a web browser. Is this some browser specific feature? Where do we specify the icon source, ie, is it in some tag on the web page itself ?</p>
| [
{
"answer_id": 120427,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": -1,
"selected": false,
"text": "<p>It was originally a windows icon format file, stored under the URL <a href=\"http://site/favicon.ico\" rel=\"nofollow no... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11614/"
] | I would like to have information about the icons which are displayed alongside the site URLs on a web browser. Is this some browser specific feature? Where do we specify the icon source, ie, is it in some tag on the web page itself ? | These icons are called [favicons](http://en.wikipedia.org/wiki/Favicon)
Most web browsers support <http://mysite.com/favicon.ico> but the proper way to do it is to include an icon meta tag in the head profile.
```
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
type="image/png"
href="/somewhere/myicon.png" />
[…]
</head>
```
[Source from the W3C itself.](http://www.w3.org/2005/10/howto-favicon)
Your best bet is to probably do both with the same icon image. |
120,422 | <p>How do I iterate over a set of records in RPG(LE) with embedded SQL?</p>
| [
{
"answer_id": 120993,
"author": "Mike Wills",
"author_id": 2535,
"author_profile": "https://Stackoverflow.com/users/2535",
"pm_score": 5,
"selected": true,
"text": "<p>Usually I'll create a cursor and fetch each record.</p>\n\n<pre><code> //********************************************... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How do I iterate over a set of records in RPG(LE) with embedded SQL? | Usually I'll create a cursor and fetch each record.
```
//***********************************************************************
// Main - Main Processing Routine
begsr Main;
exsr BldSqlStmt;
if OpenSqlCursor() = SQL_SUCCESS;
dow FetchNextRow() = SQL_SUCCESS;
exsr ProcessRow;
enddo;
if sqlStt = SQL_NO_MORE_ROWS;
CloseSqlCursor();
endif;
endif;
CloseSqlCursor();
endsr; // Main
```
I have added more detail to this answer [in a post on my website](http://mikewills.me/blog/how-do-i-iterate-over-a-set-of-records-in-rpg-with-embedded-sql/). |
120,467 | <p>I would like to confirm that the following analysis is correct:</p>
<p>I am building a web app in RoR. I have a data structure for my postgres db designed (around 70 tables; this design may need changes and additions during development to reflect Rails ways of doing things. EG, I designed some user and role tables - but if it makes sense to use Restful Authentication, I will scrub them and replace with whatever RA requires. ).</p>
<p>I have a shellscript which calls a series of .sql files to populate the empty database with tables and initial data (eg, Towns gets pre-filled with post towns) as well as test data (eg, Companies gets a few dummy companies so I have data to play with). </p>
<p>for example:</p>
<pre><code>CREATE TABLE towns (
id integer PRIMARY KEY DEFAULT nextval ('towns_seq'),
county_id integer REFERENCES counties ON DELETE RESTRICT ON UPDATE CASCADE,
country_id integer REFERENCES countries ON DELETE RESTRICT ON UPDATE CASCADE NOT NULL,
name text NOT NULL UNIQUE
);
</code></pre>
<p>Proposition 0: Data lasts longer than apps, so I am convinced that I want referential integrity enforced at the DB level as well as validations in my RoR models, despite the lack of DRYNESS.</p>
<p>Proposition 1: If I replace the script and sql files with Migrations, it is currently impossible to tell my Postgres database about the Foreign Key and other constraints I currently set in SQL DDL files within the migration code. </p>
<p>Proposition 2: The touted benefit of migrations is that changes to the schema are versioned along with the RoR model code. But if I keep my scripts and .sql files in railsapp/db, I can version them just as easily.</p>
<p>Proposition 3: Given that migrations lack functionality I want, and provide benefits I can replicate, there is little reason for me to consider using them. So I should --skipmigrations at script/generate model time. </p>
<p>My question: If Proposition 0 is accepted, are Propositions 1,2,3 true or false, and why?</p>
<p>Thanks!</p>
| [
{
"answer_id": 120491,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 2,
"selected": false,
"text": "<p>Proposition 1 is mistaken : you can definitely define referential integrity using migrations if only by using direct SQL ins... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6941/"
] | I would like to confirm that the following analysis is correct:
I am building a web app in RoR. I have a data structure for my postgres db designed (around 70 tables; this design may need changes and additions during development to reflect Rails ways of doing things. EG, I designed some user and role tables - but if it makes sense to use Restful Authentication, I will scrub them and replace with whatever RA requires. ).
I have a shellscript which calls a series of .sql files to populate the empty database with tables and initial data (eg, Towns gets pre-filled with post towns) as well as test data (eg, Companies gets a few dummy companies so I have data to play with).
for example:
```
CREATE TABLE towns (
id integer PRIMARY KEY DEFAULT nextval ('towns_seq'),
county_id integer REFERENCES counties ON DELETE RESTRICT ON UPDATE CASCADE,
country_id integer REFERENCES countries ON DELETE RESTRICT ON UPDATE CASCADE NOT NULL,
name text NOT NULL UNIQUE
);
```
Proposition 0: Data lasts longer than apps, so I am convinced that I want referential integrity enforced at the DB level as well as validations in my RoR models, despite the lack of DRYNESS.
Proposition 1: If I replace the script and sql files with Migrations, it is currently impossible to tell my Postgres database about the Foreign Key and other constraints I currently set in SQL DDL files within the migration code.
Proposition 2: The touted benefit of migrations is that changes to the schema are versioned along with the RoR model code. But if I keep my scripts and .sql files in railsapp/db, I can version them just as easily.
Proposition 3: Given that migrations lack functionality I want, and provide benefits I can replicate, there is little reason for me to consider using them. So I should --skipmigrations at script/generate model time.
My question: If Proposition 0 is accepted, are Propositions 1,2,3 true or false, and why?
Thanks! | Proposition 1 is false in at least two situations - you can use plugins like [foreign\_key\_migrations](http://github.com/vigetlabs/foreign_key_migrations/tree) to do the following:
```
def self.up
create_table :users do |t|
t.column :department_id, :integer, :references => :departments
end
end
```
which creates the appropriate foreign key constraint in your DB.
Of course, you might have other things that you want to do in your DDL, in which case the second situation becomes more compelling: you're not forced to use the Ruby DSL in migrations. Try the `execute` method, instead:
```
def self.up
execute 'YOUR SQL HERE'
end
```
With that, you can keep the contents of your SQL scripts in migrations, gaining the benefits of the latter (most prominently the `down` methods, which you didn't address in your original question) and retaining the lower-level control you prefer. |
120,470 | <p>I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table.</p>
<p>This is an excerpt the mapping file:</p>
<pre><code><property name="Name" type="string" />
<property name="Value" type="string" />
</code></pre>
<p>Name is a regular string/nvarchar(50), and Value is set as ntext in the DB</p>
<p>I'm trying to write a large amount of xml to the "Value" property. I get an exception every time:</p>
<pre><code>@p1 : String truncation: max=4000, len=35287, value='<lots of xml..../>'
</code></pre>
<p>I've googled it quite a bit, and tried a number of different mapping configurations:</p>
<pre><code><property name="Name" type="string" />
<property name="Value" type="string" >
<column name="Value" sql-type="StringClob" />
</property>
</code></pre>
<p>That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception.</p>
<p>Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how?</p>
<p>Many thanks!</p>
| [
{
"answer_id": 120560,
"author": "Jimmeh",
"author_id": 20749,
"author_profile": "https://Stackoverflow.com/users/20749",
"pm_score": 0,
"selected": false,
"text": "<pre><code><property name=\"Value\" type=\"string\" />\n <column name=\"Value\" sql-type=\"StringClob\" />\n&l... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21033/"
] | I'm using nhibernate to store some user settings for an app in a SQL Server Compact Edition table.
This is an excerpt the mapping file:
```
<property name="Name" type="string" />
<property name="Value" type="string" />
```
Name is a regular string/nvarchar(50), and Value is set as ntext in the DB
I'm trying to write a large amount of xml to the "Value" property. I get an exception every time:
```
@p1 : String truncation: max=4000, len=35287, value='<lots of xml..../>'
```
I've googled it quite a bit, and tried a number of different mapping configurations:
```
<property name="Name" type="string" />
<property name="Value" type="string" >
<column name="Value" sql-type="StringClob" />
</property>
```
That's one example. Other configurations include "ntext" instead of "StringClob". Those configurations that don't throw mapping exceptions still throw the string truncation exception.
Is this a problem ("feature") with SQL CE? Is it possible to put more than 4000 characters into a SQL CE database with nhibernate? If so, can anyone tell me how?
Many thanks! | Okay, with many thanks to Artur in [this thread](http://groups.google.com/group/nhusers/browse_thread/thread/4f865f0f516234ca), here's the solution:
Inherit from the SqlServerCeDriver with a new one, and override the InitializeParamter method:
```
using System.Data;
using System.Data.SqlServerCe;
using NHibernate.Driver;
using NHibernate.SqlTypes;
namespace MySqlServerCeDriverNamespace
{
/// <summary>
/// Overridden Nhibernate SQL CE Driver,
/// so that ntext fields are not truncated at 4000 characters
/// </summary>
public class MySqlServerCeDriver : SqlServerCeDriver
{
protected override void InitializeParameter(
IDbDataParameter dbParam,
string name,
SqlType sqlType)
{
base.InitializeParameter(dbParam, name, sqlType);
if (sqlType is StringClobSqlType)
{
var parameter = (SqlCeParameter)dbParam;
parameter.SqlDbType = SqlDbType.NText;
}
}
}
}
```
Then, use this driver instead of NHibernate's in your app.config
```
<nhibernateDriver>MySqlServerCeDriverNamespace.MySqlServerCeDriver , MySqlServerCeDriverNamespace</nhibernateDriver>
```
I saw a lot of other posts where people had this problem, and solved it by just changing the sql-type attribute to "StringClob" - as attempted in this thread.
I'm not sure why it wouldn't work for me, but I suspect it is the fact that I'm using SQL CE and not some other DB. But, there you have it! |
120,503 | <p>I'm trying to populate a TDBGrid with the results of the following TQuery against the file Journal.db:</p>
<pre><code>select * from Journal
where Journal.where = "RainPump"
</code></pre>
<p>I've tried both <code>Journal."Where"</code> and <code>Journal.[Where]</code> to no avail.</p>
<p>I've also tried: <code>select Journal.[Where] as "Location"</code> with the same result.</p>
<p>Journal.db is a file created by a third party and I am unable to change the field names.</p>
<p>The problem is that the field I'm interested in is called 'where' and understandably causes the above error. How do I reference this field without causing the BDE (presumably) to explode?</p>
| [
{
"answer_id": 120518,
"author": "Johan Bresler",
"author_id": 3535708,
"author_profile": "https://Stackoverflow.com/users/3535708",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select * from Journal where Journal.\"where\" = \"RainPump\"\n</code></pre>\n"
},
{
"answer_i... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11781/"
] | I'm trying to populate a TDBGrid with the results of the following TQuery against the file Journal.db:
```
select * from Journal
where Journal.where = "RainPump"
```
I've tried both `Journal."Where"` and `Journal.[Where]` to no avail.
I've also tried: `select Journal.[Where] as "Location"` with the same result.
Journal.db is a file created by a third party and I am unable to change the field names.
The problem is that the field I'm interested in is called 'where' and understandably causes the above error. How do I reference this field without causing the BDE (presumably) to explode? | You can insert the resultset into a new table with "values" (specifying no column names) where you have given your own column names in the new table and then do a select from that table, Using a TQuery, something like:
```
Query1.sql.clear;
query1,sql.add('Insert into newtable values (select * from Journal);');
query1.sql.add('Select * from newtable where newcolumn = "Rainpump";');
query1.open;
``` |
120,504 | <p>I'm trying to run the following SQL statement in Oracle, and it takes ages to run:</p>
<pre><code>SELECT orderID FROM tasks WHERE orderID NOT IN
(SELECT DISTINCT orderID FROM tasks WHERE
engineer1 IS NOT NULL AND engineer2 IS NOT NULL)
</code></pre>
<p>If I run just the sub-part that is in the IN clause, that runs very quickly in Oracle, i.e.</p>
<pre><code>SELECT DISTINCT orderID FROM tasks WHERE
engineer1 IS NOT NULL AND engineer2 IS NOT NULL
</code></pre>
<p>Why does the whole statement take such a long time in Oracle? In SQL Server the whole statement runs quickly.</p>
<p>Alternatively is there a simpler/different/better SQL statement I should use?</p>
<p>Some more details about the problem:</p>
<ul>
<li>Each order is made of many tasks</li>
<li>Each order will be allocated (one or more of its task will have engineer1 and engineer2 set) or the order can be unallocated (all its task have null values for the engineer fields)</li>
<li>I am trying to find all the orderIDs that are unallocated.</li>
</ul>
<p>Just in case it makes any difference, there are ~120k rows in the table, and 3 tasks per order, so ~40k different orders.</p>
<p>Responses to answers:</p>
<ul>
<li>I would prefer a SQL statement that works in both SQL Server and Oracle.</li>
<li>The tasks only has an index on the orderID and taskID.</li>
<li>I tried the NOT EXISTS version of the statement but it ran for over 3 minutes before I cancelled it. Perhaps need a JOIN version of the statement?</li>
<li>There is an "orders" table as well with the orderID column. But I was trying to simplify the question by not including it in the original SQL statement.</li>
</ul>
<p>I guess that in the original SQL statement the sub-query is run every time for each row in the first part of the SQL statement - even though it is static and should only need to be run once?</p>
<p>Executing</p>
<pre><code>ANALYZE TABLE tasks COMPUTE STATISTICS;
</code></pre>
<p>made my original SQL statement execute much faster. </p>
<p>Although I'm still curious why I have to do this, and if/when I would need to run it again?</p>
<blockquote>
<p>The statistics give Oracle's
cost-based optimzer information that
it needs to determine the efficiency
of different execution plans: for
example, the number of rowsin a table,
the average width of rows, highest and
lowest values per column, number of
distinct values per column, clustering
factor of indexes etc.</p>
<p>In a small database you can just setup
a job to gather statistics every night
and leave it alone. In fact, this is
the default under 10g. For larger
implementations you usually have to
weigh the stability of the execution
plans against the way that the data
changes, which is a tricky balance.</p>
<p>Oracle also has a feature called
"dynamic sampling" that is used to
sample tables to determine relevant
statistics at execution time. It's
much more often used with data
warehouses where the overhead of the
sampling it outweighed by the
potential performance increase for a
long-running query.</p>
</blockquote>
| [
{
"answer_id": 120516,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 2,
"selected": false,
"text": "<p>The \"IN\" - clause is known in Oracle to be pretty slow. In fact, the internal query optimizer in Oracle cannot handle ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7261/"
] | I'm trying to run the following SQL statement in Oracle, and it takes ages to run:
```
SELECT orderID FROM tasks WHERE orderID NOT IN
(SELECT DISTINCT orderID FROM tasks WHERE
engineer1 IS NOT NULL AND engineer2 IS NOT NULL)
```
If I run just the sub-part that is in the IN clause, that runs very quickly in Oracle, i.e.
```
SELECT DISTINCT orderID FROM tasks WHERE
engineer1 IS NOT NULL AND engineer2 IS NOT NULL
```
Why does the whole statement take such a long time in Oracle? In SQL Server the whole statement runs quickly.
Alternatively is there a simpler/different/better SQL statement I should use?
Some more details about the problem:
* Each order is made of many tasks
* Each order will be allocated (one or more of its task will have engineer1 and engineer2 set) or the order can be unallocated (all its task have null values for the engineer fields)
* I am trying to find all the orderIDs that are unallocated.
Just in case it makes any difference, there are ~120k rows in the table, and 3 tasks per order, so ~40k different orders.
Responses to answers:
* I would prefer a SQL statement that works in both SQL Server and Oracle.
* The tasks only has an index on the orderID and taskID.
* I tried the NOT EXISTS version of the statement but it ran for over 3 minutes before I cancelled it. Perhaps need a JOIN version of the statement?
* There is an "orders" table as well with the orderID column. But I was trying to simplify the question by not including it in the original SQL statement.
I guess that in the original SQL statement the sub-query is run every time for each row in the first part of the SQL statement - even though it is static and should only need to be run once?
Executing
```
ANALYZE TABLE tasks COMPUTE STATISTICS;
```
made my original SQL statement execute much faster.
Although I'm still curious why I have to do this, and if/when I would need to run it again?
>
> The statistics give Oracle's
> cost-based optimzer information that
> it needs to determine the efficiency
> of different execution plans: for
> example, the number of rowsin a table,
> the average width of rows, highest and
> lowest values per column, number of
> distinct values per column, clustering
> factor of indexes etc.
>
>
> In a small database you can just setup
> a job to gather statistics every night
> and leave it alone. In fact, this is
> the default under 10g. For larger
> implementations you usually have to
> weigh the stability of the execution
> plans against the way that the data
> changes, which is a tricky balance.
>
>
> Oracle also has a feature called
> "dynamic sampling" that is used to
> sample tables to determine relevant
> statistics at execution time. It's
> much more often used with data
> warehouses where the overhead of the
> sampling it outweighed by the
> potential performance increase for a
> long-running query.
>
>
> | Often this type of problem goes away if you analyze the tables involved (so Oracle has a better idea of the distribution of the data)
```
ANALYZE TABLE tasks COMPUTE STATISTICS;
``` |
120,540 | <p>I´m programming a .NET Compact Framework application which shows maps on a PDA.</p>
<p>I´ve created an ad hoc component that paints it´s own piece of the whole map, using several of this components the big picture is composed. I did it this way to avoid the latency of painting the whole map in a single step.</p>
<p>What I would like to do now is to paint this pieces in their own thread, so the map appears to grow as a single entity and (also, and more important) to avoid freezing the rest of the user interface.</p>
<p>Right know each piece of the map is painted in its onPaint method. My idea is to, somehow, tell the system "execute this code in a thread please".</p>
<p>Something like:</p>
<pre><code>protected override void OnPaint(PaintEventArgs e)
{
// <code to be executed in a thread>
e.Graphics.paintTHis();
e.Graphics.paintThat();
whateverItTakesToPaintThisPieceOfTheMap();
// </code to be executed in a thread>
}
</code></pre>
<p>Do you know how to do this? Or is my approach simply wrong?</p>
<p>Thanks for your time!</p>
| [
{
"answer_id": 120553,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>The approach is wrong. Code that updates the ui has to run on the ui thread. You'll get an exception if you update the ui... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623/"
] | I´m programming a .NET Compact Framework application which shows maps on a PDA.
I´ve created an ad hoc component that paints it´s own piece of the whole map, using several of this components the big picture is composed. I did it this way to avoid the latency of painting the whole map in a single step.
What I would like to do now is to paint this pieces in their own thread, so the map appears to grow as a single entity and (also, and more important) to avoid freezing the rest of the user interface.
Right know each piece of the map is painted in its onPaint method. My idea is to, somehow, tell the system "execute this code in a thread please".
Something like:
```
protected override void OnPaint(PaintEventArgs e)
{
// <code to be executed in a thread>
e.Graphics.paintTHis();
e.Graphics.paintThat();
whateverItTakesToPaintThisPieceOfTheMap();
// </code to be executed in a thread>
}
```
Do you know how to do this? Or is my approach simply wrong?
Thanks for your time! | The approach is wrong. Code that updates the ui has to run on the ui thread. You'll get an exception if you update the ui from another thread. |
120,561 | <p>We have a vxWorks design which requires one task to process both high and low priority messages sent over two message queues.<br>
The messages for a given priority have to be processed in FIFO order. </p>
<p>For example, process all the high priority messages in the order they were received, then process the low priority messages. If there is no high priority message, then process the low priority message immediately.</p>
<p>Is there a way to do this?</p>
| [
{
"answer_id": 120788,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 1,
"selected": false,
"text": "<p>In vxWorks, you can't wait directly on multiple queues. You can however use the OS events (from eventLib) to achieve th... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] | We have a vxWorks design which requires one task to process both high and low priority messages sent over two message queues.
The messages for a given priority have to be processed in FIFO order.
For example, process all the high priority messages in the order they were received, then process the low priority messages. If there is no high priority message, then process the low priority message immediately.
Is there a way to do this? | If you use named pipes (pipeDevCreate(), write(), read()) instead of message queues, you can use select() to block until there are messages in either pipe.
Whenever select() triggers, you process all messages in the high priority pipe. Then you process a single message from the low priority pipe. Then call select again (loop).
Example Code snippets:
```
// Initialization: Create high and low priority named pipes
pipeDrv(); //initialize pipe driver
int fdHi = pipeDevCreate("/pipe/high",numMsgs,msgSize);
int fdLo = pipeDevCreate("/pipe/low",numMsgs,msgSize);
...
// Message sending thread: Add messages to pipe
write(fdHi, buf, sizeof(buf));
...
// Message processing Thread: select loop
fd_set rdFdSet;
while(1)
{
FD_ZERO(&rdFdSet);
FD_SET(fdHi, &rdFdSet);
FD_SET(fdLo, &rdFdSet;
if (select(FD_SETSIZE, &rdFdSet, NULL, NULL, NULL) != ERROR)
{
if (FD_ISSET(fdHi, &rdFdSet))
{
// process all high-priority messages
while(read(fdHi,buf,size) > 0)
{
//process high-priority
}
}
if (FD_ISSET(fdLo, &rdFdSet))
{
// process a single low priority message
if (read(fdLo,buf,size) > 0)
{
// process low priority
}
}
}
}
``` |
120,584 | <p>In a <a href="http://www.pygame.org/" rel="nofollow noreferrer">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>How can I achieve this?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html" rel="nofollow noreferrer">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
| [
{
"answer_id": 120794,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"http://www.cairographics.org/\" rel=\"noreferrer\">Cairo</a> (with PyCairo), which has suppor... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8450/"
] | In a [pyGame](http://www.pygame.org/) application, I would like to render resolution-free GUI widgets described in SVG.
How can I achieve this?
(I like the [OCEMP GUI](http://ocemp.sourceforge.net/gui.html) toolkit but it seems to be bitmap dependent for its rendering) | This is a complete example which combines hints by other people here.
It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.
```
#!/usr/bin/python
import array
import math
import cairo
import pygame
import rsvg
WIDTH = 512
HEIGHT = 512
data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)
surface = cairo.ImageSurface.create_for_data(
data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
svg = rsvg.Handle(file="test.svg")
ctx = cairo.Context(surface)
svg.render_cairo(ctx)
screen = pygame.display.get_surface()
image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")
screen.blit(image, (0, 0))
pygame.display.flip()
clock = pygame.time.Clock()
while True:
clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
``` |
120,587 | <p>I would like to trash the mail received by a single qmail alias. I don't want any mail delivery errors, and I want qmail to be happy about having delivered the mail.</p>
<p>How can I do this, preferably without adding another local email account?</p>
| [
{
"answer_id": 120771,
"author": "Roman Odaisky",
"author_id": 21055,
"author_profile": "https://Stackoverflow.com/users/21055",
"pm_score": 2,
"selected": false,
"text": "<p>Create an alias by creating a file /var/qmail/aliases/.qmail-<em>blackhole</em> with this content:</p>\n\n<pre><c... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15992/"
] | I would like to trash the mail received by a single qmail alias. I don't want any mail delivery errors, and I want qmail to be happy about having delivered the mail.
How can I do this, preferably without adding another local email account? | Create an alias with only a comment and no delivery instructions, like:
```
echo "# drop all messages on the floor" > ~alias/.qmail-devnull
```
Replace "devnull" with whatever alias name you need of course. |
120,588 | <p>I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in 'fran', I want to be able to give her people in San Francisco.</p>
<p>SQL is not my strong suit, and I prefer Hibernate's <code>Criteria</code> building code to hard-coded strings as it is. Can anyone point me in the right direction about how to do this in code, and if impossible, how the hard-coded SQL should look like?</p>
<p>Thanks,</p>
<p>Yuval =8-)</p>
| [
{
"answer_id": 120600,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>Most default database collations are not case-sensitive, but in the SQL Server world it can be set at the instance, t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2819/"
] | I'm using Hibernate for ORM of my Java app to an Oracle database (not that the database vendor matters, we may switch to another database one day), and I want to retrieve objects from the database according to user-provided strings. For example, when searching for people, if the user is looking for people who live in 'fran', I want to be able to give her people in San Francisco.
SQL is not my strong suit, and I prefer Hibernate's `Criteria` building code to hard-coded strings as it is. Can anyone point me in the right direction about how to do this in code, and if impossible, how the hard-coded SQL should look like?
Thanks,
Yuval =8-) | For the simple case you describe, look at Restrictions.ilike(), which does a case-insensitive search.
```
Criteria crit = session.createCriteria(Person.class);
crit.add(Restrictions.ilike('town', '%fran%');
List results = crit.list();
``` |
120,607 | <p>I am trying to separate some asp logic out into a separate page.
For now, I am trying to call a simple function. </p>
<p>Here is the simple index page that I am using</p>
<pre><code><html>
<head>
<title>Calling a webservice from classic ASP</title>
</head>
<body>
<%
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
%>
<!--#include file="aspFunctions.asp"-->
<%
doStuff()
End If
%>
<FORM method=POST name="form1" ID="Form1">
ID:
<INPUT type="text" name="corpId" ID="id" value="050893">
<BR><BR>
<INPUT type="submit" value="GO" name="submit1" ID="Submit1" >
</form>
</body>
</html>
</code></pre>
<p>Here is aspfunctions.asp</p>
<pre><code>sub doStuff()
Response.Write("In Do Stuff")
end sub
</code></pre>
<p>When i hit the submit button on my form i get the below
sub doStuff() Response.Write("In Do Stuff") end sub</p>
<p>Microsoft VBScript runtime error '800a000d'</p>
<p>Does anyone have any idea what i could be doing wrong?</p>
<p>Any help is greatly appreciated</p>
<p>Thanks
Damien
Type mismatch: 'doStuff'</p>
<p>/uat/damien/index.asp, line 15 </p>
| [
{
"answer_id": 120619,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 1,
"selected": false,
"text": "<p>If I remember correctly, you need no brackets for calls without a return value (untested solution):</p>\n\n<pre><... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
] | I am trying to separate some asp logic out into a separate page.
For now, I am trying to call a simple function.
Here is the simple index page that I am using
```
<html>
<head>
<title>Calling a webservice from classic ASP</title>
</head>
<body>
<%
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
%>
<!--#include file="aspFunctions.asp"-->
<%
doStuff()
End If
%>
<FORM method=POST name="form1" ID="Form1">
ID:
<INPUT type="text" name="corpId" ID="id" value="050893">
<BR><BR>
<INPUT type="submit" value="GO" name="submit1" ID="Submit1" >
</form>
</body>
</html>
```
Here is aspfunctions.asp
```
sub doStuff()
Response.Write("In Do Stuff")
end sub
```
When i hit the submit button on my form i get the below
sub doStuff() Response.Write("In Do Stuff") end sub
Microsoft VBScript runtime error '800a000d'
Does anyone have any idea what i could be doing wrong?
Any help is greatly appreciated
Thanks
Damien
Type mismatch: 'doStuff'
/uat/damien/index.asp, line 15 | `aspfunctions.asp` should be inside tags so the asp is "executed", e.g.
aspfunctions.asp file:
```
<%
sub doStuff()
Response.Write("In Do Stuff")
end sub
%>
```
Otherwise the asp in `aspfunctions.asp` is just seen as plain-text, so as far as the server is concerned, `doStuff` has never been defined. |
120,618 | <p>What logging solutions exist for j2me? </p>
<p>I'm specifically interested in easily excluding logging for "release" version, to have a smaller package & memory footprint. </p>
| [
{
"answer_id": 120772,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 1,
"selected": false,
"text": "<p>I've used <a href=\"http://www.mobilelandscape.uklinux.net/j2medownload/MIDPLogger.php\" rel=\"nofollow nor... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6827/"
] | What logging solutions exist for j2me?
I'm specifically interested in easily excluding logging for "release" version, to have a smaller package & memory footprint. | If you are using preprocessing and obfuscation with Proguard, then you can have a simple logging class.
```
public class Log {
public static void debug(final String message) {
//#if !release.build
System.out.println(message);
//#endif
}
}
```
Or do logging where ever you need to. Now, if release.build property is set to true, this code will be commented out, that will result in an empty method. Proguard will remove all usages of empty method - In effect release build will have all debug messages removed.
Edit:
Thinking about it on library level (I'm working on mapping J2ME library) I have, probably, found a better solution.
```
public class Log {
private static boolean showDebug;
public static void debug(final String message) {
if (showDebug) {
System.out.println(message);
}
}
public static void setShowDebug(final boolean show) {
showDebug = show;
}
}
```
This way end developer can enable log levels inside library that he/she is interested in. If nothing will be enabled, all logging code will be removed in end product obfuscation. Sweet :)
/JaanusSiim |
120,627 | <p>I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error:</p>
<pre><code>MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj)
</code></pre>
<p>This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it?</p>
<p>I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library.</p>
| [
{
"answer_id": 120650,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 2,
"selected": false,
"text": "<p>I think it depends in which order you link the files. I think you need to link your custom function first, then the im... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14443/"
] | I would like to replace the default malloc at link time to use a custom malloc. But when I try to redefine malloc in my program, I get this error:
```
MSVCRT.lib(MSVCR80.dll) : error LNK2005: _malloc already defined in test.lib(test.obj)
```
This works perfectly on any Unix, and it works on Windows with most functions, but not with malloc. How can I do this? And what is different with malloc that disallow overriding it?
I know I could replace every call to malloc with my custom malloc, or use a macro to do this, but I would rather not modify every third party library. | There is really good discussion of how hard this is here:
<http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/>
~~Apparently, you need to patch the CRT~~
Edit: actually, a MS employee gave the technique in the discussion. You need to move your malloc to a lib, and then link it before the CRT
"he also mentions that if you link your malloc as a lib *before* the CRT (i.e. make sure to turn on ‘ignore default libs’ and explictly include the CRT), you’ll get what you want, and can redistribute this lib without problems." |
120,648 | <p>I use Assert.Fail a lot when doing TDD. I'm usually working on one test at a time but when I get ideas for things I want to implement later I quickly write an empty test where the name of the test method indicates what I want to implement as sort of a todo-list. To make sure I don't forget I put an Assert.Fail() in the body.</p>
<p>When trying out xUnit.Net I found they hadn't implemented Assert.Fail. Of course you can always Assert.IsTrue(false) but this doesn't communicate my intention as well. I got the impression Assert.Fail wasn't implemented on purpose. Is this considered bad practice? If so why?</p>
<hr>
<p>@Martin Meredith
That's not exactly what I do. I do write a test first and then implement code to make it work. Usually I think of several tests at once. Or I think about a test to write when I'm working on something else. That's when I write an empty failing test to remember. By the time I get to writing the test I neatly work test-first.</p>
<p>@Jimmeh
That looks like a good idea. Ignored tests don't fail but they still show up in a separate list. Have to try that out.</p>
<p>@Matt Howells
Great Idea. NotImplementedException communicates intention better than assert.Fail() in this case</p>
<p>@Mitch Wheat
That's what I was looking for. It seems it was left out to prevent it being abused in another way I abuse it.</p>
| [
{
"answer_id": 120670,
"author": "Jimmeh",
"author_id": 20749,
"author_profile": "https://Stackoverflow.com/users/20749",
"pm_score": 3,
"selected": false,
"text": "<p>I use MbUnit for my Unit Testing. They have an option to Ignore tests, which show up as Orange (rather than Green or Red... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3320/"
] | I use Assert.Fail a lot when doing TDD. I'm usually working on one test at a time but when I get ideas for things I want to implement later I quickly write an empty test where the name of the test method indicates what I want to implement as sort of a todo-list. To make sure I don't forget I put an Assert.Fail() in the body.
When trying out xUnit.Net I found they hadn't implemented Assert.Fail. Of course you can always Assert.IsTrue(false) but this doesn't communicate my intention as well. I got the impression Assert.Fail wasn't implemented on purpose. Is this considered bad practice? If so why?
---
@Martin Meredith
That's not exactly what I do. I do write a test first and then implement code to make it work. Usually I think of several tests at once. Or I think about a test to write when I'm working on something else. That's when I write an empty failing test to remember. By the time I get to writing the test I neatly work test-first.
@Jimmeh
That looks like a good idea. Ignored tests don't fail but they still show up in a separate list. Have to try that out.
@Matt Howells
Great Idea. NotImplementedException communicates intention better than assert.Fail() in this case
@Mitch Wheat
That's what I was looking for. It seems it was left out to prevent it being abused in another way I abuse it. | For this scenario, rather than calling Assert.Fail, I do the following (in C# / NUnit)
```
[Test]
public void MyClassDoesSomething()
{
throw new NotImplementedException();
}
```
It is more explicit than an Assert.Fail.
There seems to be general agreement that it is preferable to use more explicit assertions than Assert.Fail(). Most frameworks have to include it though because they don't offer a better alternative. For example, NUnit (and others) provide an ExpectedExceptionAttribute to test that some code throws a particular class of exception. However in order to test that a property on the exception is set to a particular value, one cannot use it. Instead you have to resort to Assert.Fail:
```
[Test]
public void ThrowsExceptionCorrectly()
{
const string BAD_INPUT = "bad input";
try
{
new MyClass().DoSomething(BAD_INPUT);
Assert.Fail("No exception was thrown");
}
catch (MyCustomException ex)
{
Assert.AreEqual(BAD_INPUT, ex.InputString);
}
}
```
The xUnit.Net method Assert.Throws makes this a lot neater without requiring an Assert.Fail method. By not including an Assert.Fail() method xUnit.Net encourages developers to find and use more explicit alternatives, and to support the creation of new assertions where necessary. |
120,656 | <p>How do I get a list of all files (and directories) in a given directory in Python?</p>
| [
{
"answer_id": 120676,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 9,
"selected": false,
"text": "<p>You can use</p>\n\n<pre><code>os.listdir(path)\n</code></pre>\n\n<p>For reference and more os functions look here:</p>\n... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
] | How do I get a list of all files (and directories) in a given directory in Python? | This is a way to traverse every file and directory in a directory tree:
```
import os
for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
``` |
120,657 | <p>I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.</p>
<p>The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?</p>
<p>To clarify from current responses:</p>
<ol>
<li>I am using the subprocess module</li>
<li>I am passing the command line + arguments in as a list</li>
<li>The issue is with the path to the command itself, not any of the arguments</li>
<li>I've tried quoting the command. It causes a <code>[Error 123] The filename, directory name, or volume label syntax is incorrect</code> error</li>
<li>I'm using no shell argument (so <code>shell=false</code>) </li>
<li>In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin</li>
<li>It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.</li>
<li>The command that is failing is: </li>
</ol>
<blockquote>
<p>p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)</p>
</blockquote>
<p>when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.</p>
| [
{
"answer_id": 120705,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 1,
"selected": false,
"text": "<p>A proper answer will need more information than that. What are you actually doing? How does it fail? Are you usi... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16035/"
] | I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.
The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?
To clarify from current responses:
1. I am using the subprocess module
2. I am passing the command line + arguments in as a list
3. The issue is with the path to the command itself, not any of the arguments
4. I've tried quoting the command. It causes a `[Error 123] The filename, directory name, or volume label syntax is incorrect` error
5. I'm using no shell argument (so `shell=false`)
6. In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin
7. It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.
8. The command that is failing is:
>
> p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)
>
>
>
when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work. | Make sure you are using lists and no shell expansion:
```
subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
``` |
120,662 | <p>I'm trying to run SQuirreL SQL.<br>
I've downloaded it and installed it, but when I try to run it I get this error message: </p>
<blockquote>
<p>Java Virtual Machine Launcher.<br>
Could not find the main class.<br>
Program will exit. </p>
</blockquote>
<p>I get the gist of this, but I have not idea how to fix it. Any help? </p>
<h3>more info:</h3>
<ul>
<li>I'm on Windows XP pro. </li>
<li>I have java 1.6 installed, and other apps are running OK. </li>
<li>The install ran OK. </li>
<li>I believe I've followed the installation instructions correctly. </li>
<li>To run it, I'm invoking the <strong>squirrel-sql.bat</strong> file. </li>
</ul>
<h3>Update</h3>
<p>This question: <a href="https://stackoverflow.com/questions/1417328/could-not-find-the-main-class">"Could not find the main class: XX. Program will exit."</a> gives some background on this error from the point of view of a java developer. </p>
| [
{
"answer_id": 120698,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 2,
"selected": false,
"text": "<p>Have you followed these instructions:</p>\n\n<p><a href=\"http://www.squirrelsql.org/#installation\" rel=\"nofollow nor... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] | I'm trying to run SQuirreL SQL.
I've downloaded it and installed it, but when I try to run it I get this error message:
>
> Java Virtual Machine Launcher.
>
> Could not find the main class.
>
> Program will exit.
>
>
>
I get the gist of this, but I have not idea how to fix it. Any help?
### more info:
* I'm on Windows XP pro.
* I have java 1.6 installed, and other apps are running OK.
* The install ran OK.
* I believe I've followed the installation instructions correctly.
* To run it, I'm invoking the **squirrel-sql.bat** file.
### Update
This question: ["Could not find the main class: XX. Program will exit."](https://stackoverflow.com/questions/1417328/could-not-find-the-main-class) gives some background on this error from the point of view of a java developer. | Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type 'java' from the command line do you get back a list of instructions or do you get something like "java is not recognized as a .....")?
You could try try running `squirrel-sql.jar` from the command line (from the squirrel sql directory), using:
```
java -jar squirrel-sql.jar
``` |
120,693 | <p>I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens.</p>
<p>If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.</p>
<p>Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Regex</title>
<script type="text/javascript" charset="utf-8">
var grep = new RegExp('gr[');
try
{
var results = grep.exec('bob went to town');
}
catch (e)
{
//Do nothing?
}
alert('If you can see this then the script kept going');
</script>
</head>
<body>
</body>
</html>
</code></pre>
| [
{
"answer_id": 120716,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 3,
"selected": false,
"text": "<p>The problem is with this line:</p>\n\n<pre><code>var grep = new RegExp('gr[');\n</code></pre>\n\n<p>'[' is a special cha... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | I've got a function that runs a user generated Regex. However, if the user enters a regex that won't run then it stops and falls over. I've tried wrapping the line in a Try/Catch block but alas nothing happens.
If it helps, I'm running jQuery but the code below does not have it as I'm guessing that it's a little more fundamental than that.
Edit: Yes, I know that I am not escaping the "[", that's intentional and the point of the question. I'm accepting user input and I want to find a way to catch this sort of problem without the application falling flat on it's face.
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Regex</title>
<script type="text/javascript" charset="utf-8">
var grep = new RegExp('gr[');
try
{
var results = grep.exec('bob went to town');
}
catch (e)
{
//Do nothing?
}
alert('If you can see this then the script kept going');
</script>
</head>
<body>
</body>
</html>
``` | Try this the new RegExp is throwing the exception
Regex
```
<script type="text/javascript" charset="utf-8">
var grep;
try {
grep = new RegExp("gr[");
}
catch(e) {
alert(e);
}
try
{
var results = grep.exec('bob went to town');
}
catch (e)
{
//Do nothing?
}
alert('If you can see this then the script kept going');
</script>
``` |
120,702 | <p>Using Scala's command line REPL:</p>
<pre><code>def foo(x: Int): Unit = {}
def foo(x: String): Unit = {println(foo(2))}
</code></pre>
<p>gives</p>
<pre><code>error: type mismatch;
found: Int(2)
required: String
</code></pre>
<p>It seems that you can't define overloaded recursive methods in the REPL. I thought this was a bug in the Scala REPL and filed it, but it was almost instantly closed with "wontfix: I don't see any way this could be supported given the semantics of the interpreter, because these two methods must to be compiled together." He recommended putting the methods in an enclosing object.</p>
<p>Is there a JVM language implementation or Scala expert who could explain why? I can see it would be a problem if the methods called each other for instance, but in this case?</p>
<p>Or if this is too large a question and you think I need more prerequisite knowledge, does someone have any good links to books or sites about language implementations, especially on the JVM? (I know about John Rose's blog, and the book Programming Language Pragmatics... but that's about it. :)</p>
| [
{
"answer_id": 121647,
"author": "user21167",
"author_id": 21167,
"author_profile": "https://Stackoverflow.com/users/21167",
"pm_score": 2,
"selected": false,
"text": "<p>REPL will accept if you copy both lines and paste both at same time.</p>\n"
},
{
"answer_id": 122338,
"au... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15627/"
] | Using Scala's command line REPL:
```
def foo(x: Int): Unit = {}
def foo(x: String): Unit = {println(foo(2))}
```
gives
```
error: type mismatch;
found: Int(2)
required: String
```
It seems that you can't define overloaded recursive methods in the REPL. I thought this was a bug in the Scala REPL and filed it, but it was almost instantly closed with "wontfix: I don't see any way this could be supported given the semantics of the interpreter, because these two methods must to be compiled together." He recommended putting the methods in an enclosing object.
Is there a JVM language implementation or Scala expert who could explain why? I can see it would be a problem if the methods called each other for instance, but in this case?
Or if this is too large a question and you think I need more prerequisite knowledge, does someone have any good links to books or sites about language implementations, especially on the JVM? (I know about John Rose's blog, and the book Programming Language Pragmatics... but that's about it. :) | The issue is due to the fact that the interpreter most often has to *replace* existing elements with a given name, rather than overload them. For example, I will often be running through experimenting with something, often creating a method called `test`:
```
def test(x: Int) = x + x
```
A little later on, let's say that I'm running a *different* experiment and I create another method named `test`, unrelated to the first:
```
def test(ls: List[Int]) = (0 /: ls) { _ + _ }
```
This isn't an entirely unrealistic scenario. In fact, it's precisely how most people use the interpreter, often without even realizing it. If the interpreter arbitrarily decided to keep both versions of `test` in scope, that could lead to confusing semantic differences in using test. For example, we might make a call to `test`, accidentally passing an `Int` rather than `List[Int]` (not the most unlikely accident in the world):
```
test(1 :: Nil) // => 1
test(2) // => 4 (expecting 2)
```
Over time, the root scope of the interpreter would get incredibly cluttered with various versions of methods, fields, etc. I tend to leave my interpreter open for days at a time, but if overloading like this were allowed, we would be forced to "flush" the interpreter every so often as things got to be too confusing.
It's not a limitation of the JVM or the Scala compiler, it's a deliberate design decision. As mentioned in the bug, you can still overload if you're within something other than the root scope. Enclosing your test methods within a class seems like the best solution to me. |
120,731 | <p>Let's assume you have one massive table with three columns as shown below:</p>
<pre><code>[id] INT NOT NULL,
[date] SMALLDATETIME NOT NULL,
[sales] FLOAT NULL
</code></pre>
<p>Also assume you are limited to one physical disk and one filegroup (PRIMARY). You expect this table to hold sales for 10,000,000+ ids, across 100's of dates (easily 1B+ records).</p>
<p>As with many data warehousing scenarios, the data will typically grow sequentially by date (i.e., each time you perform a data load, you will be inserting new dates, and maybe updating some of the more recent dates of data). For analytic purposes, the data will often be queried and aggregated for a random set of ~10,000 ids which will be specified via a join with another table. Often, these queries don't specify date ranges, or specify very wide date ranges, which leads me to my question: What is the best way to index / partition this table?</p>
<p>I have thought about this for a while, but am stuck with conflicting solutions:</p>
<p><strong>Option #1:</strong> As data will be loaded sequentially by date, define the clustered index (and primary key) as [date], [id]. Also create a "sliding window" partitioning function / scheme on date allowing rapid movement of new data in / out of the table. Potentially create a non-clustered index on id to help with querying.</p>
<p><strong>Expected Outcome #1:</strong> This setup will be very fast for data loading purposes, but sub-optimal when it comes to analytic reads as, in a worst case scenario (no limiting by dates, unlucky with set of id's queried), 100% of the data pages may be read.</p>
<p><strong>Option #2:</strong> As the data will be queried for only a small subset of ids at a time, define the clustered index (and primary key) as [id], [date]. Do not bother to create a partitioned table.</p>
<p><strong>Expected Outcome #2:</strong> Expected huge performance hit when it comes to loading data as we can no longer quickly limit by date. Expected huge performance benefit when it comes to my analytic queries as it will minimize the number of data pages read.</p>
<p><strong>Option #3:</strong> Clustered (and primary key) as follows: [id], [date]; "sliding window" partition function / scheme on date.</p>
<p><strong>Expected Outcome #3:</strong> Not sure what to expect. Given that the first column in the clustered index is [id] and thus (it is my understanding) the data is arranged by ID, I would expect good performance from my analytic queries. However, the data is partitioned by date, which is contrary to the definition of the clustered index (but still aligned as date is part of the index). I haven't found much documentation that speaks to this scenario and what, if any, performance benefits I may get from this, which brings me to my final, bonus question:</p>
<p>If I am creating a table on one filegroup on one disk, with a clustered index on one column, is there any benefit (besides partition switching when loading the data) that comes from defining a partition on the same column?</p>
| [
{
"answer_id": 120815,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using the partitions in the select statements, then you cn gain some speed.</p>\n\n<p>If you are not using it, only... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4391/"
] | Let's assume you have one massive table with three columns as shown below:
```
[id] INT NOT NULL,
[date] SMALLDATETIME NOT NULL,
[sales] FLOAT NULL
```
Also assume you are limited to one physical disk and one filegroup (PRIMARY). You expect this table to hold sales for 10,000,000+ ids, across 100's of dates (easily 1B+ records).
As with many data warehousing scenarios, the data will typically grow sequentially by date (i.e., each time you perform a data load, you will be inserting new dates, and maybe updating some of the more recent dates of data). For analytic purposes, the data will often be queried and aggregated for a random set of ~10,000 ids which will be specified via a join with another table. Often, these queries don't specify date ranges, or specify very wide date ranges, which leads me to my question: What is the best way to index / partition this table?
I have thought about this for a while, but am stuck with conflicting solutions:
**Option #1:** As data will be loaded sequentially by date, define the clustered index (and primary key) as [date], [id]. Also create a "sliding window" partitioning function / scheme on date allowing rapid movement of new data in / out of the table. Potentially create a non-clustered index on id to help with querying.
**Expected Outcome #1:** This setup will be very fast for data loading purposes, but sub-optimal when it comes to analytic reads as, in a worst case scenario (no limiting by dates, unlucky with set of id's queried), 100% of the data pages may be read.
**Option #2:** As the data will be queried for only a small subset of ids at a time, define the clustered index (and primary key) as [id], [date]. Do not bother to create a partitioned table.
**Expected Outcome #2:** Expected huge performance hit when it comes to loading data as we can no longer quickly limit by date. Expected huge performance benefit when it comes to my analytic queries as it will minimize the number of data pages read.
**Option #3:** Clustered (and primary key) as follows: [id], [date]; "sliding window" partition function / scheme on date.
**Expected Outcome #3:** Not sure what to expect. Given that the first column in the clustered index is [id] and thus (it is my understanding) the data is arranged by ID, I would expect good performance from my analytic queries. However, the data is partitioned by date, which is contrary to the definition of the clustered index (but still aligned as date is part of the index). I haven't found much documentation that speaks to this scenario and what, if any, performance benefits I may get from this, which brings me to my final, bonus question:
If I am creating a table on one filegroup on one disk, with a clustered index on one column, is there any benefit (besides partition switching when loading the data) that comes from defining a partition on the same column? | This table is awesomely narrow. If the real table will be this narrow, you should be happy to have table scans instead of index->lookups.
I would do this:
```
CREATE TABLE Narrow
(
[id] INT NOT NULL,
[date] SMALLDATETIME NOT NULL,
[sales] FLOAT NULL,
PRIMARY KEY(id, date) --EDIT, just noticed your id is not unique.
)
CREATE INDEX CoveringNarrow ON Narrow(date, id, sales)
```
This handles point queries with seeks and wide-range queries with limited scans against date criteria and id criteria. There is no per-record lookup from index. Yes, I've doubled the write time (and space used) but that's fine, imo.
---
If there's some need for a specific piece of data (and that need is **demonstrated by profiling**!!), I'd create a clustered view targetting that section of the table.
```
CREATE VIEW Narrow200801
AS
SELECT * FROM Narrow WHERE '2008-01-01' <= [date] AND [date] < '2008-02-01'
--There is some command that I don't have at my finger tips to make this a clustered view.
```
Clustered views can be used in queries by name, or the optimizer will choose to use the clustered views when the FROM and WHERE clause are appropriate. For example, this query will use the clustered view. Note that the base table is referred to in the query.
```
SELECT SUM(sales) FROM Narrow WHERE '2008-01-01' <= [date] AND [date] < '2008-02-01'
```
As *index* lets you make specific columns conveniently accessible... *Clustered view* lets you make specific rows conveniently accessible. |
120,751 | <p>I have been trying to use routes.rb for creating a URL /similar-to-:product (where product is dynamic) for my website. The issue is that routes.rb readily supports URLs like /:product-similar but doesn't support the former because it requires :product to be preceded with a separator ('/' is a separator but '-' isn't). The list of separators is in ActionController::Routing::SEPARATORS.</p>
<p>I can't add '-' as a separator because :product can also contain a hyphen. What is the best way of supporting a URL like this?</p>
<p>One way that I have successfully tried is to not use routes.rb and put the URL parsing logic in the controller itself, but that isn't the cleanest way.</p>
| [
{
"answer_id": 120819,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 0,
"selected": false,
"text": "<p>I'm a little confused, but could you maybe add \"to-\" as a seperator? </p>\n"
},
{
"answer_id": 1224... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17494/"
] | I have been trying to use routes.rb for creating a URL /similar-to-:product (where product is dynamic) for my website. The issue is that routes.rb readily supports URLs like /:product-similar but doesn't support the former because it requires :product to be preceded with a separator ('/' is a separator but '-' isn't). The list of separators is in ActionController::Routing::SEPARATORS.
I can't add '-' as a separator because :product can also contain a hyphen. What is the best way of supporting a URL like this?
One way that I have successfully tried is to not use routes.rb and put the URL parsing logic in the controller itself, but that isn't the cleanest way. | In fact you can add `-` as a separator, then use route globbing.
```
map.similar_product '/similar-to-*product', :controller => 'products', :action => 'similar'
```
then, in ProductsController#similar
```
@product = Product.find_by_slug params[:product].join('-')
```
Though refactoring does seem nicer, since with this approach you'll need to specially handle all slugs that can contain hyphens. |
120,763 | <p>I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?</p>
<p>Instead of this:</p>
<pre><code>string filePath = @"C:\somepath\file.txt";
</code></pre>
<p>I want to do this:</p>
<pre><code>string filePath = @helper.getFilePath(); //getFilePath returns a string
</code></pre>
<p>This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?</p>
| [
{
"answer_id": 120776,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 5,
"selected": true,
"text": "<p>I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14777/"
] | I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?
Instead of this:
```
string filePath = @"C:\somepath\file.txt";
```
I want to do this:
```
string filePath = @helper.getFilePath(); //getFilePath returns a string
```
This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something? | I don't think you have to worry about it if you already have the value. The @ operator is for when you're specifying the string (like in your first code snippet).
What are you attempting to do with the path string that isn't working? |
120,766 | <p>I have several <li> elements with different id's on ASP.NET page:</p>
<pre><code><li id="li1" class="class1">
<li id="li2" class="class1">
<li id="li3" class="class1">
</code></pre>
<p>and can change their class using JavaScript like this:</p>
<pre><code>li1.className="class2"
</code></pre>
<p>But is there a way to change <li> element class using ASP.NET? It could be something like:</p>
<pre><code>WebControl control = (WebControl)FindControl("li1");
control.CssClass="class2";
</code></pre>
<p>But FindControl() doesn't work as I expected. Any suggestions?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 120774,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 2,
"selected": false,
"text": "<p>you must set runat=\"server\" like:</p>\n\n<pre><code><li id=\"li1\" runat=\"server\">stuff</li>\n</code>... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] | I have several <li> elements with different id's on ASP.NET page:
```
<li id="li1" class="class1">
<li id="li2" class="class1">
<li id="li3" class="class1">
```
and can change their class using JavaScript like this:
```
li1.className="class2"
```
But is there a way to change <li> element class using ASP.NET? It could be something like:
```
WebControl control = (WebControl)FindControl("li1");
control.CssClass="class2";
```
But FindControl() doesn't work as I expected. Any suggestions?
Thanks in advance! | The FindControl method searches for server controls. That is, it looks for controls with the attribute "runat" set to "server", as in:
```
<li runat="server ... ></li>
```
Because your <li> tags are not server controls, FindControl cannot find them. You can add the "runat" attribute to these controls or use ClientScript.RegisterStartupScript to include some client side script to manipulate the class, e.g.
```
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("document.getElementById(\"li1\").className=\"newClass\";")
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "MyScript", sb.ToString());
``` |
120,783 | <p>Currently I have this (edited after reading advice):</p>
<pre><code>struct Pair<T, K> : IEqualityComparer<Pair<T, K>>
{
readonly private T _first;
readonly private K _second;
public Pair(T first, K second)
{
_first = first;
_second = second;
}
public T First { get { return _first; } }
public K Second { get { return _second; } }
#region IEqualityComparer<Pair<T,K>> Members
public bool Equals(Pair<T, K> x, Pair<T, K> y)
{
return x.GetHashCode(x) == y.GetHashCode(y);
}
public int GetHashCode(Pair<T, K> obj)
{
int hashCode = obj.First == null ? 0 : obj._first.GetHashCode();
hashCode ^= obj.Second == null ? 0 : obj._second.GetHashCode();
return hashCode;
}
#endregion
public override int GetHashCode()
{
return this.GetHashCode(this);
}
public override bool Equals(object obj)
{
return (obj != null) &&
(obj is Pair<T, K>) &&
this.Equals(this, (Pair<T, K>) obj);
}
}
</code></pre>
<p>The problem is that First and Second may not be reference types (VS actually warns me about this), but the code still compiles. Should I cast them (First and Second) to objects before I compare them, or is there a better way to do this?</p>
<p>Edit:
Note that I <em>want</em> this struct to support value and reference types (in other words, constraining by class is not a valid solution)</p>
<p>Edit 2:
As to what I'm trying to achieve, I want this to work in a Dictionary. Secondly, SRP isn't important to me right now because that isn't really the essence of this problem - it can always be refactored later. Thirdly, comparing to default(T) will not work in lieu of comparing to null - try it.</p>
| [
{
"answer_id": 120812,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "<p>Your IEqualityComparer implementation should be a different class (and definately not a struct as you want to reuse the ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] | Currently I have this (edited after reading advice):
```
struct Pair<T, K> : IEqualityComparer<Pair<T, K>>
{
readonly private T _first;
readonly private K _second;
public Pair(T first, K second)
{
_first = first;
_second = second;
}
public T First { get { return _first; } }
public K Second { get { return _second; } }
#region IEqualityComparer<Pair<T,K>> Members
public bool Equals(Pair<T, K> x, Pair<T, K> y)
{
return x.GetHashCode(x) == y.GetHashCode(y);
}
public int GetHashCode(Pair<T, K> obj)
{
int hashCode = obj.First == null ? 0 : obj._first.GetHashCode();
hashCode ^= obj.Second == null ? 0 : obj._second.GetHashCode();
return hashCode;
}
#endregion
public override int GetHashCode()
{
return this.GetHashCode(this);
}
public override bool Equals(object obj)
{
return (obj != null) &&
(obj is Pair<T, K>) &&
this.Equals(this, (Pair<T, K>) obj);
}
}
```
The problem is that First and Second may not be reference types (VS actually warns me about this), but the code still compiles. Should I cast them (First and Second) to objects before I compare them, or is there a better way to do this?
Edit:
Note that I *want* this struct to support value and reference types (in other words, constraining by class is not a valid solution)
Edit 2:
As to what I'm trying to achieve, I want this to work in a Dictionary. Secondly, SRP isn't important to me right now because that isn't really the essence of this problem - it can always be refactored later. Thirdly, comparing to default(T) will not work in lieu of comparing to null - try it. | It looks like you need IEquatable instead:
```
internal struct Pair<T, K> : IEquatable<Pair<T, K>>
{
private readonly T _first;
private readonly K _second;
public Pair(T first, K second)
{
_first = first;
_second = second;
}
public T First
{
get { return _first; }
}
public K Second
{
get { return _second; }
}
public bool Equals(Pair<T, K> obj)
{
return Equals(obj._first, _first) && Equals(obj._second, _second);
}
public override bool Equals(object obj)
{
return obj is Pair<T, K> && Equals((Pair<T, K>) obj);
}
public override int GetHashCode()
{
unchecked
{
return (_first != null ? _first.GetHashCode() * 397 : 0) ^ (_second != null ? _second.GetHashCode() : 0);
}
}
}
``` |
120,797 | <p>Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.</p>
<p>I am behind a proxy server. How can I set my JVM to use the proxy ?</p>
| [
{
"answer_id": 120802,
"author": "Leonel",
"author_id": 15649,
"author_profile": "https://Stackoverflow.com/users/15649",
"pm_score": 10,
"selected": true,
"text": "<p>From the Java documentation (<em>not</em> the javadoc API):</p>\n<p><a href=\"http://download.oracle.com/javase/6/docs/t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] | Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema.
I am behind a proxy server. How can I set my JVM to use the proxy ? | From the Java documentation (*not* the javadoc API):
<http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html>
Set the JVM flags `http.proxyHost` and `http.proxyPort` when starting your JVM on the command line.
This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:
```
JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...
```
When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.
Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information: <http://download.oracle.com/javase/6/docs/technotes/guides/>
---
**Update :** If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:
>
> Also don't forget the http.nonProxyHosts property!
>
>
>
```
-Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.example.com|etc"
``` |
120,804 | <p>I am going through John Resig's excellent <a href="http://ejohn.org/apps/learn/#47" rel="noreferrer">Advanced javascript tutorial</a> and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)</p>
<pre><code>>>> arguments
[3, 1, 2, 3]
>>> Array.slice.call( arguments )
3,1,2,3 0=3 1=1 2=2 3=3
>>> Array.slice.call( arguments, 1 )
[]
>>> Array().slice.call( arguments )
3,1,2,3 0=3 1=1 2=2 3=3
>>> Array().slice.call( arguments, 1 )
1,2,3 0=1 1=2 2=3
</code></pre>
<p>Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).</p>
| [
{
"answer_id": 121054,
"author": "ujh",
"author_id": 4936,
"author_profile": "https://Stackoverflow.com/users/4936",
"pm_score": 3,
"selected": false,
"text": "<p>Array is just a function, albeit a special one (used to initialize arrays). Array.slice is a reference to the slice() functio... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21075/"
] | I am going through John Resig's excellent [Advanced javascript tutorial](http://ejohn.org/apps/learn/#47) and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)
```
>>> arguments
[3, 1, 2, 3]
>>> Array.slice.call( arguments )
3,1,2,3 0=3 1=1 2=2 3=3
>>> Array.slice.call( arguments, 1 )
[]
>>> Array().slice.call( arguments )
3,1,2,3 0=3 1=1 2=2 3=3
>>> Array().slice.call( arguments, 1 )
1,2,3 0=1 1=2 2=3
```
Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list). | Not quite.
Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2):
```
>>> String.substring.call("foo", 1)
"1"
>>> String().substring.call("foo", 1)
"oo"
```
Array.slice is *neither* properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []).
The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. **Try running the equivalent code in IE and you'll get an error that Array.slice is null**.
This is why Array.slice does not behave correctly (nor does String.substring).
Proof (the following is something one should never expect based on the definition of slice()...just like substring() above):
```
>>> Array.slice.call([1,2], [3,4])
3,4
```
Now, if you properly call slice() on either an instantiated object *or* the Array prototype, you'll get what you expect:
```
>>> Array.prototype.slice.call([4,5], 1)
[5]
>>> Array().slice.call([4,5], 1)
[5]
```
More proof...
```
>>> Array.prototype.slice == Array().slice
true
>>> Array.slice == Array().slice
false
``` |
120,851 | <p>We are creating an XBAP application that we need to have rounded corners in various locations in a single page and we would like to have a WPF Rounded Corner container to place a bunch of other elements within. Does anyone have some suggestions or sample code on how we can best accomplish this? Either with styles on a or with creating a custom control?</p>
| [
{
"answer_id": 120895,
"author": "kobusb",
"author_id": 1620,
"author_profile": "https://Stackoverflow.com/users/1620",
"pm_score": 9,
"selected": true,
"text": "<p>You don't need a custom control, just put your container in a border element:</p>\n\n<pre><code><Border BorderBrush=\"#F... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21096/"
] | We are creating an XBAP application that we need to have rounded corners in various locations in a single page and we would like to have a WPF Rounded Corner container to place a bunch of other elements within. Does anyone have some suggestions or sample code on how we can best accomplish this? Either with styles on a or with creating a custom control? | You don't need a custom control, just put your container in a border element:
```
<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
<Grid/>
</Border>
```
You can replace the `<Grid/>` with any of the layout containers... |
120,858 | <p>Is it possible to, for instance, replace and free a TEdit with a subclassed component instantiated (conditionally) at runtime? If so, how and when it should be done? I've tried to set the parent to nil and to call free() in the form constructor and AfterConstruction methods but in both cases I got a runtime error.</p>
<hr>
<p>Being more specific, I got an Access violation error (EAccessViolation). It seems François is right when he says that freeing components at frame costruction messes with Form controls housekeeping.</p>
| [
{
"answer_id": 121091,
"author": "Loesje",
"author_id": 17559,
"author_profile": "https://Stackoverflow.com/users/17559",
"pm_score": 3,
"selected": false,
"text": "<p>You have to call RemoveControl of the TEdit's parent to remove the control. Use InsertControl to add the new control. </... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16120/"
] | Is it possible to, for instance, replace and free a TEdit with a subclassed component instantiated (conditionally) at runtime? If so, how and when it should be done? I've tried to set the parent to nil and to call free() in the form constructor and AfterConstruction methods but in both cases I got a runtime error.
---
Being more specific, I got an Access violation error (EAccessViolation). It seems François is right when he says that freeing components at frame costruction messes with Form controls housekeeping. | This more generic routine works either with a Form or Frame (updated to use a subclass for the new control):
```
function ReplaceControlEx(AControl: TControl; const AControlClass: TControlClass; const ANewName: string; const IsFreed : Boolean = True): TControl;
begin
if AControl = nil then
begin
Result := nil;
Exit;
end;
Result := AControlClass.Create(AControl.Owner);
CloneProperties(AControl, Result);// copy all properties to new control
// Result.Left := AControl.Left; // or copy some properties manually...
// Result.Top := AControl.Top;
Result.Name := ANewName;
Result.Parent := AControl.Parent; // needed for the InsertControl & RemoveControl magic
if IsFreed then
FreeAndNil(AControl);
end;
function ReplaceControl(AControl: TControl; const ANewName: string; const IsFreed : Boolean = True): TControl;
begin
if AControl = nil then
Result := nil
else
Result := ReplaceControlEx(AControl, TControlClass(AControl.ClassType), ANewName, IsFreed);
end;
```
using this routine to pass the properties to the new control
```
procedure CloneProperties(const Source: TControl; const Dest: TControl);
var
ms: TMemoryStream;
OldName: string;
begin
OldName := Source.Name;
Source.Name := ''; // needed to avoid Name collision
try
ms := TMemoryStream.Create;
try
ms.WriteComponent(Source);
ms.Position := 0;
ms.ReadComponent(Dest);
finally
ms.Free;
end;
finally
Source.Name := OldName;
end;
end;
```
use it like:
```
procedure TFrame1.AfterConstruction;
var
I: Integer;
NewEdit: TMyEdit;
begin
inherited;
NewEdit := ReplaceControlEx(Edit1, TMyEdit, 'Edit2') as TMyEdit;
if Assigned(NewEdit) then
begin
NewEdit.Text := 'My Brand New Edit';
NewEdit.Author := 'Myself';
end;
for I:=0 to ControlCount-1 do
begin
ShowMessage(Controls[I].Name);
end;
end;
```
**CAUTION**: If you are doing this inside the AfterConstruction of the Frame, beware that the hosting Form construction is not finished yet.
Freeing Controls there, might cause a lot of problems as you're messing up with Form controls housekeeping.
See what you get if you try to read the new Edit Caption to display in the ShowMessage...
In that case you would want to use
...ReplaceControl(Edit1, 'Edit2', **False**)
and then do a
...FreeAndNil(Edit1)
later. |
120,876 | <p>What are the C++ rules for calling the base class constructor from a derived class?</p>
<p>For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).</p>
| [
{
"answer_id": 120916,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 11,
"selected": true,
"text": "<p>Base class constructors are automatically called for you if they have no argument. If you want to call a superclass const... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4465/"
] | What are the C++ rules for calling the base class constructor from a derived class?
For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing). | Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".
```
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
```
More info on the constructor's initialization list [here](http://www.cprogramming.com/tutorial/initialization-lists-c++.html) and [here](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6). |
120,886 | <p>Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by</p>
<pre><code>infinite = itertools.cycle([[1,2,3]])
</code></pre>
<p>What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return <code>1,2,3,1,2,3,...</code>. The iterator is infinite, so <code>itertools.chain(*infinite)</code> will not work.</p>
<h3>Related</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| [
{
"answer_id": 120905,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 4,
"selected": false,
"text": "<p>Use a generator:</p>\n\n<pre><code>(item for it in infinite for item in it)\n</code></pre>\n\n<p>The * construct... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12166/"
] | Suppose we have an iterator (an infinite one) that returns lists (or finite iterators), for example one returned by
```
infinite = itertools.cycle([[1,2,3]])
```
What is a good Python idiom to get an iterator (obviously infinite) that will return each of the elements from the first iterator, then each from the second one, etc. In the example above it would return `1,2,3,1,2,3,...`. The iterator is infinite, so `itertools.chain(*infinite)` will not work.
### Related
* [Flattening a shallow list in python](https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python) | Starting with Python 2.6, you can use [`itertools.chain.from_iterable`](https://docs.python.org/library/itertools.html#itertools.chain.from_iterable):
```
itertools.chain.from_iterable(iterables)
```
You can also do this with a nested generator comprehension:
```
def flatten(iterables):
return (elem for iterable in iterables for elem in iterable)
``` |
120,900 | <p>I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example.</p>
<p>So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team? </p>
<p>The user_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid.</p>
| [
{
"answer_id": 120911,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 5,
"selected": true,
"text": "<pre><code>SELECT *\nFROM ALL_OBJECTS\nWHERE OBJECT_NAME = trigger_name\nAND OBJECT_TYPE = 'TRIGGER'\nAND STATUS... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9396/"
] | I'm working on databases that have moving tables auto-generated by some obscure tools. By the way, we have to track information changes in the table via some triggers. And, of course, it occurs that some changes in the table structure broke some triggers, by removing a column or changing its type, for example.
So, the question is: Is there a way to query the Oracle metadata to check is some triggers are broken, in order to send a report to the support team?
The user\_triggers give all the triggers and tells if they are enable or not, but does not indicate if they are still valid. | ```
SELECT *
FROM ALL_OBJECTS
WHERE OBJECT_NAME = trigger_name
AND OBJECT_TYPE = 'TRIGGER'
AND STATUS <> 'VALID'
``` |
120,917 | <p>How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on <code>D:\temp\dbFolder</code>. How to do this?</p>
| [
{
"answer_id": 120940,
"author": "Leah",
"author_id": 5506,
"author_profile": "https://Stackoverflow.com/users/5506",
"pm_score": 6,
"selected": true,
"text": "<p>When you create the new database you specify the location. For example:</p>\n\n<pre><code>USE [master]\nGO\n\n CREATE DATA... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on `D:\temp\dbFolder`. How to do this? | When you create the new database you specify the location. For example:
```
USE [master]
GO
CREATE DATABASE [AdventureWorks] ON PRIMARY
( NAME = N'AdventureWorks_Data', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )
LOG ON
( NAME = N'AdventureWorks_Log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB )
GO
``` |
120,928 | <p>I have a web part that I've developed, and if I manually install the web part it is fine.</p>
<p>However when I have packaged the web part following the instructions on this web site as a guide:
<a href="http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html" rel="noreferrer">http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html</a></p>
<p>I get this error in the log files:</p>
<pre><code>09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 8l4d Monitorable Error importing WebPart. Cannot import Project Filter.
09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(...
09/23/2008 14:13:03.67* w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High ...String eventArgument)
</code></pre>
<p>The pertinent bit is:</p>
<pre><code>http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter.
Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter.
at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
</code></pre>
<p>And that's accompanied by a rather terse error message: "Cannot import web part".</p>
<p>I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully.</p>
<p>Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it.</p>
<p>Any help finding a solution is appreciated.</p>
| [
{
"answer_id": 121305,
"author": "Keith Sirmons",
"author_id": 1048,
"author_profile": "https://Stackoverflow.com/users/1048",
"pm_score": 0,
"selected": false,
"text": "<p>Have you recycled your worker process or reset IIS?</p>\n"
},
{
"answer_id": 121883,
"author": "Communi... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a web part that I've developed, and if I manually install the web part it is fine.
However when I have packaged the web part following the instructions on this web site as a guide:
<http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html>
I get this error in the log files:
```
09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 8l4d Monitorable Error importing WebPart. Cannot import Project Filter.
09/23/2008 14:13:03.67 w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter. Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter. at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb) at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(...
09/23/2008 14:13:03.67* w3wp.exe (0x1B5C) 0x1534 Windows SharePoint Services Web Parts 89ku High ...String eventArgument)
```
The pertinent bit is:
```
http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter.
Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter.
at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
```
And that's accompanied by a rather terse error message: "Cannot import web part".
I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully.
Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it.
Any help finding a solution is appreciated. | Figured it out.
The error message is the one from the .webpart file:
```
<?xml version="1.0" encoding="utf-8"?>
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<!--
The following Guid is used as a reference to the web part class,
and it will be automatically replaced with actual type name at deployment time.
-->
<type name="7F8C4D34-6311-4f22-87B4-A221FA8735BA" />
<importErrorMessage>Cannot import Project Filter.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">Project Filter</property>
<property name="Description" type="string">Provides a list of Projects that can be used to Filter other Web Parts.</property>
</properties>
</data>
</webPart>
</webParts>
```
The problem is that the original .webpart file was created on a 32-bit system with Visual Studio Extensions for WSS installed.
However as I'm now on a 64-bit machine VSEWSS is unavailable, and I believe that results in the above GUID not being substituted as I am not using those deployment tools.
Replacing the GUID with the full type name works.
So if you encounter the error message from your importErrorMessage node, then check that your type node in the .webpart file looks more like this (unrelated example):
```
<type name="TitleWP.TitleWP, TitleWP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" />
```
This is in the format:
Class, Namespace, Version, Culture, PublicKey
You can grab that easily from the web.config file associated with your SharePoint instance, as it will be in the safe controls list. |
120,936 | <p>I can add custom version strings to a C++ DLL in Visual Studio by editing the .rc file by hand. For example, if I add to the VersionInfo section of the .rc file</p>
<pre><code>VALUE "BuildDate", "2008/09/19 15:42:52"
</code></pre>
<p>Then that date is visible in the file explorer, in the DLL's properties, under the Version tab.</p>
<p>Can I do the same for a C# DLL? Not just for build date, but for other version information (such as source control information)</p>
<p>UPDATE: I think there may be a way to do this by embedding a windows resource, so I've <a href="https://stackoverflow.com/questions/200485">asked how to do that</a>.</p>
| [
{
"answer_id": 120958,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 2,
"selected": false,
"text": "<p>In AssemblyInfo.cs, you can put:</p>\n\n<pre><code>[assembly: System.Reflection.AssemblyInformationalVersion(\"whatever y... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] | I can add custom version strings to a C++ DLL in Visual Studio by editing the .rc file by hand. For example, if I add to the VersionInfo section of the .rc file
```
VALUE "BuildDate", "2008/09/19 15:42:52"
```
Then that date is visible in the file explorer, in the DLL's properties, under the Version tab.
Can I do the same for a C# DLL? Not just for build date, but for other version information (such as source control information)
UPDATE: I think there may be a way to do this by embedding a windows resource, so I've [asked how to do that](https://stackoverflow.com/questions/200485). | Expanding on the Khoth's answer, In AssemblyInfo.cs:
You can do:
```
[assembly: CustomResource("Build Date", "12/12/2012")]
```
Where CustomResource is defined as:
```
[AttributeUsage(AttributeTargets.Assembly)]
public class CustomResourceAttribute : Attribute
{
private string the_variable;
public string Variable {get { return the_variable; }}
private string the_value;
public string Value {get { return the_value; }}
public CustomResourceAttribute(string variable, string value)
{
this.the_variable = variable;
this.the_value = value;
}
}
```
This solution is nice because it gives you the flexibility you need and it does not cause any compiler warnings.
Unfortunately it is not possible to use a DateTime because the values entered in Attributes must be constants, and a DateTime is not a constant. |
120,951 | <p>I'd like to know do I normalize a URL in python. </p>
<p>For example, If I have a url string like : "<a href="http://www.example.com/foo" rel="noreferrer">http://www.example.com/foo</a> goo/bar.html"</p>
<p>I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.</p>
| [
{
"answer_id": 120959,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "<h3>Py3</h3>\n\n<pre><code>from urllib.parse import urlparse, urlunparse, quote\ndef myquote(url):\n parts = urlparse(url)\n... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13523/"
] | I'd like to know do I normalize a URL in python.
For example, If I have a url string like : "<http://www.example.com/foo> goo/bar.html"
I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL. | Have a look at this module: [werkzeug.utils](https://github.com/pallets/werkzeug/blob/master/src/werkzeug/urls.py). (now in `werkzeug.urls`)
The function you are looking for is called "url\_fix" and works like this:
```
>>> from werkzeug.urls import url_fix
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
```
It's implemented in Werkzeug as follows:
```
import urllib
import urlparse
def url_fix(s, charset='utf-8'):
"""Sometimes you get an URL by a user that just isn't a real
URL because it contains unsafe characters like ' ' and so on. This
function can fix some of the problems in a similar way browsers
handle data entered by the user:
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
:param charset: The target charset for the URL if the url was
given as unicode string.
"""
if isinstance(s, unicode):
s = s.encode(charset, 'ignore')
scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
path = urllib.quote(path, '/%')
qs = urllib.quote_plus(qs, ':&=')
return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
``` |
120,952 | <p>I have an SP that takes 10 seconds to run about 10 times (about a second every time it is ran). The platform is asp .net, and the server is SQL Server 2005. I have indexed the table (not on the PK also), and that is not the issue. Some caveats:</p>
<ul>
<li>usp_SaveKeyword is not the issue. I commented out that entire SP and it made not difference. </li>
<li>I set @SearchID to 1 and the time was significantly reduced, only taking about 15ms on average for the transaction. </li>
<li>I commented out the entire stored procedure except the insert into tblSearches and strangely it took more time to execute. </li>
</ul>
<p>Any ideas of what could be going on? </p>
<pre><code>set ANSI_NULLS ON
go
ALTER PROCEDURE [dbo].[usp_NewSearch]
@Keyword VARCHAR(50),
@SessionID UNIQUEIDENTIFIER,
@time SMALLDATETIME = NULL,
@CityID INT = NULL
AS
BEGIN
SET NOCOUNT ON;
IF @time IS NULL SET @time = GETDATE();
DECLARE @KeywordID INT;
EXEC @KeywordID = usp_SaveKeyword @Keyword;
PRINT 'KeywordID : '
PRINT @KeywordID
DECLARE @SearchID BIGINT;
SELECT TOP 1 @SearchID = SearchID
FROM tblSearches
WHERE SessionID = @SessionID
AND KeywordID = @KeywordID;
IF @SearchID IS NULL BEGIN
INSERT INTO tblSearches
(KeywordID, [time], SessionID, CityID)
VALUES
(@KeywordID, @time, @SessionID, @CityID)
SELECT Scope_Identity();
END
ELSE BEGIN
SELECT @SearchID
END
END
</code></pre>
| [
{
"answer_id": 120973,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>Triggers!</p>\n\n<p>They are insidious indeed.</p>\n"
},
{
"answer_id": 121009,
"author": "stephbu",
"autho... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
] | I have an SP that takes 10 seconds to run about 10 times (about a second every time it is ran). The platform is asp .net, and the server is SQL Server 2005. I have indexed the table (not on the PK also), and that is not the issue. Some caveats:
* usp\_SaveKeyword is not the issue. I commented out that entire SP and it made not difference.
* I set @SearchID to 1 and the time was significantly reduced, only taking about 15ms on average for the transaction.
* I commented out the entire stored procedure except the insert into tblSearches and strangely it took more time to execute.
Any ideas of what could be going on?
```
set ANSI_NULLS ON
go
ALTER PROCEDURE [dbo].[usp_NewSearch]
@Keyword VARCHAR(50),
@SessionID UNIQUEIDENTIFIER,
@time SMALLDATETIME = NULL,
@CityID INT = NULL
AS
BEGIN
SET NOCOUNT ON;
IF @time IS NULL SET @time = GETDATE();
DECLARE @KeywordID INT;
EXEC @KeywordID = usp_SaveKeyword @Keyword;
PRINT 'KeywordID : '
PRINT @KeywordID
DECLARE @SearchID BIGINT;
SELECT TOP 1 @SearchID = SearchID
FROM tblSearches
WHERE SessionID = @SessionID
AND KeywordID = @KeywordID;
IF @SearchID IS NULL BEGIN
INSERT INTO tblSearches
(KeywordID, [time], SessionID, CityID)
VALUES
(@KeywordID, @time, @SessionID, @CityID)
SELECT Scope_Identity();
END
ELSE BEGIN
SELECT @SearchID
END
END
``` | Why are you using `top 1 @SearchID` instead of `max (SearchID)` or `where exists` in this query? `top` requires you to run the query and retrieve the first row from the result set. If the result set is large this could consume quite a lot of resources before you get out the final result set.
```
SELECT TOP 1 @SearchID = SearchID
FROM tblSearches
WHERE SessionID = @SessionID
AND KeywordID = @KeywordID;
```
I don't see any obvious reason for this - either of aforementioned constructs should get you something semantically equivalent to this with a very cheap index lookup. Unless I'm missing something you should be able to do something like
```
select @SearchID = isnull (max (SearchID), -1)
from tblSearches
where SessionID = @SessionID
and KeywordID = @KeywordID
```
This ought to be fairly efficient and (unless I'm missing something) semantically equivalent. |
120,966 | <p>I was writing a (seemingly) straight-forward SQL snippet that drops a column after it makes sure the column exists.<br>
The problem: if the column does NOT exist, the code <em>inside</em> the IF clause complains that it can't find the column! Well, <em>doh</em>, that's why it's inside the IF clause!<br>
So my question is, why does a piece of code that shouldn't be executed give errors?</p>
<p>Here's the snippet:</p>
<pre><code>IF exists (select * from syscolumns
WHERE id=object_id('Table_MD') and name='timeout')
BEGIN
ALTER TABLE [dbo].[Table_MD]
DROP COLUMN timeout
END
GO
</code></pre>
<p>...and here's the error:</p>
<p><code>Error executing SQL script [...]. Invalid column name 'timeout'</code></p>
<p>I'm using Microsoft SQL Server 2005 Express Edition.</p>
| [
{
"answer_id": 120974,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 0,
"selected": false,
"text": "<p>It may never be executed, but it's parsed for validity by Sql Server. The only way to \"get around\" this is to construct a b... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
] | I was writing a (seemingly) straight-forward SQL snippet that drops a column after it makes sure the column exists.
The problem: if the column does NOT exist, the code *inside* the IF clause complains that it can't find the column! Well, *doh*, that's why it's inside the IF clause!
So my question is, why does a piece of code that shouldn't be executed give errors?
Here's the snippet:
```
IF exists (select * from syscolumns
WHERE id=object_id('Table_MD') and name='timeout')
BEGIN
ALTER TABLE [dbo].[Table_MD]
DROP COLUMN timeout
END
GO
```
...and here's the error:
`Error executing SQL script [...]. Invalid column name 'timeout'`
I'm using Microsoft SQL Server 2005 Express Edition. | ```
IF exists (select * from syscolumns
WHERE id=object_id('Table_MD') and name='timeout')
BEGIN
DECLARE @SQL nvarchar(1000)
SET @SQL = N'ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout'
EXEC sp_executesql @SQL
END
GO
```
Reason:
When Sql server compiles the code, they check it for used objects ( if they exists ). This check procedure ignores any "IF", "WHILE", etc... constructs and simply check all used objects in code. |
120,997 | <p>I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags?</p>
<p>For example, when you create an <code>asp:repeater</code> you can add a nested tag for <code>itemtemplate</code>.</p>
| [
{
"answer_id": 121007,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 5,
"selected": true,
"text": "<p>I wrote a <a href=\"https://robertwray.co.uk/blog/describing-asp-net-control-properties-declaratively\" rel=\"nofollow norefer... | 2008/09/23 | [
"https://Stackoverflow.com/questions/120997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11508/"
] | I'm just getting started with Custom User Controls in C# and I'm wondering if there are any examples out there of how to write one which accepts nested tags?
For example, when you create an `asp:repeater` you can add a nested tag for `itemtemplate`. | I wrote a [blog post](https://robertwray.co.uk/blog/describing-asp-net-control-properties-declaratively) about this some time ago. In brief, if you had a control with the following markup:
```
<Abc:CustomControlUno runat="server" ID="Control1">
<Children>
<Abc:Control1Child IntegerProperty="1" />
</Children>
</Abc:CustomControlUno>
```
You'd need the code in the control to be along the lines of:
```
[ParseChildren(true)]
[PersistChildren(true)]
[ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")]
public class CustomControlUno : WebControl, INamingContainer
{
private Control1ChildrenCollection _children;
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Control1ChildrenCollection Children
{
get
{
if (_children == null)
{
_children = new Control1ChildrenCollection();
}
return _children;
}
}
}
public class Control1ChildrenCollection : List<Control1Child>
{
}
public class Control1Child
{
public int IntegerProperty { get; set; }
}
``` |
121,000 | <p>I'm trying to create an Extension Method for MVC's htmlHelper.
The purpose is to enable or disable an ActionLink based on the AuthorizeAttribute set on the controller/action.
Borrowing from the <a href="http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx" rel="nofollow noreferrer">MVCSitemap</a><br>
code that Maarten Balliauw created, I wanted to validate the user's permissions against the controller/action before deciding how to render the actionlink.
When I try to get the MvcHandler, I get a null value.
Is there a better way to the the attributes for the controller/action?</p>
<p>Here is the code for the extension method:</p>
<pre><code>public static class HtmlHelperExtensions
{
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller)
{
//simplified for brevity
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action,controller);
}
else
{
return String.Format("<span>{0}</span>",linkText);
}
}
public static bool IsAccessibleToUser(string action, string controller)
{
HttpContext context = HttpContext.Current;
MvcHandler handler = context.Handler as MvcHandler;
IController verifyController =
ControllerBuilder
.Current
.GetControllerFactory()
.CreateController(handler.RequestContext, controller);
object[] controllerAttributes = verifyController.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true);
object[] actionAttributes = verifyController.GetType().GetMethod(action).GetCustomAttributes(typeof(AuthorizeAttribute), true);
if (controllerAttributes.Length == 0 && actionAttributes.Length == 0)
return true;
IPrincipal principal = handler.RequestContext.HttpContext.User;
string roles = "";
string users = "";
if (controllerAttributes.Length > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Length > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role != "*" && !principal.IsInRole(role)) return false;
}
foreach (string user in usersArray)
{
if (user != "*" && (principal.Identity.Name == "" || principal.Identity.Name != user)) return false;
}
return true;
}
}
</code></pre>
| [
{
"answer_id": 121353,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>Your ViewPage has a reference to the view context, so you could make it an extension method on that instead.</p>\n\... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
] | I'm trying to create an Extension Method for MVC's htmlHelper.
The purpose is to enable or disable an ActionLink based on the AuthorizeAttribute set on the controller/action.
Borrowing from the [MVCSitemap](http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx)
code that Maarten Balliauw created, I wanted to validate the user's permissions against the controller/action before deciding how to render the actionlink.
When I try to get the MvcHandler, I get a null value.
Is there a better way to the the attributes for the controller/action?
Here is the code for the extension method:
```
public static class HtmlHelperExtensions
{
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller)
{
//simplified for brevity
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action,controller);
}
else
{
return String.Format("<span>{0}</span>",linkText);
}
}
public static bool IsAccessibleToUser(string action, string controller)
{
HttpContext context = HttpContext.Current;
MvcHandler handler = context.Handler as MvcHandler;
IController verifyController =
ControllerBuilder
.Current
.GetControllerFactory()
.CreateController(handler.RequestContext, controller);
object[] controllerAttributes = verifyController.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true);
object[] actionAttributes = verifyController.GetType().GetMethod(action).GetCustomAttributes(typeof(AuthorizeAttribute), true);
if (controllerAttributes.Length == 0 && actionAttributes.Length == 0)
return true;
IPrincipal principal = handler.RequestContext.HttpContext.User;
string roles = "";
string users = "";
if (controllerAttributes.Length > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Length > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role != "*" && !principal.IsInRole(role)) return false;
}
foreach (string user in usersArray)
{
if (user != "*" && (principal.Identity.Name == "" || principal.Identity.Name != user)) return false;
}
return true;
}
}
``` | Here is the working code:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using System.Web.Routing;
using System.Web.Mvc;
using System.Collections;
using System.Reflection;
namespace System.Web.Mvc.Html
{
public static class HtmlHelperExtensions
{
public static string SecurityTrimmedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller)
{
return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false);
}
public static string SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, bool showDisabled)
{
if (IsAccessibleToUser(action, controller))
{
return htmlHelper.ActionLink(linkText, action, controller);
}
else
{
return showDisabled ? String.Format("<span>{0}</span>", linkText) : "";
}
}
public static bool IsAccessibleToUser(string actionAuthorize, string controllerAuthorize)
{
Assembly assembly = Assembly.GetExecutingAssembly();
GetControllerType(controllerAuthorize);
Type controllerType = GetControllerType(controllerAuthorize);
var controller = (IController)Activator.CreateInstance(controllerType);
ArrayList controllerAttributes = new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true));
ArrayList actionAttributes = new ArrayList();
MethodInfo[] methods = controller.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);
if ((attributes.Length == 0 && method.Name == actionAuthorize) || (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionAuthorize))
{
actionAttributes.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));
}
}
if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)
return true;
IPrincipal principal = HttpContext.Current.User;
string roles = "";
string users = "";
if (controllerAttributes.Count > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Count > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role == "*" || principal.IsInRole(role))
return true;
}
foreach (string user in usersArray)
{
if (user == "*" && (principal.Identity.Name == user))
return true;
}
return false;
}
public static Type GetControllerType(string controllerName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.GetTypes())
{
if (type.BaseType.Name == "Controller" && (type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper())))
{
return type;
}
}
return null;
}
}
}
```
I don't like using reflection, but I can't get to the ControllerTypeCache. |
121,025 | <p>How do I get the modified date/time of a file in Python?</p>
| [
{
"answer_id": 121030,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 6,
"selected": true,
"text": "<pre><code>os.path.getmtime(filepath)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>os.stat(filepath).st_mtime\n</code><... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
] | How do I get the modified date/time of a file in Python? | ```
os.path.getmtime(filepath)
```
or
```
os.stat(filepath).st_mtime
``` |
121,059 | <p>What is the best way to divide a 32 bit integer into four (unsigned) chars in C#.</p>
| [
{
"answer_id": 121089,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "<p>It's not clear if this is really what you want, but:</p>\n\n<pre><code>int x = yourNumber();\nchar a = (char)(x &... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14759/"
] | What is the best way to divide a 32 bit integer into four (unsigned) chars in C#. | Quick'n'dirty:
```csharp
int value = 0x48454C4F;
Console.WriteLine(Encoding.ASCII.GetString(
BitConverter.GetBytes(value).Reverse().ToArray()
));
```
Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it.
EDIT: The `Reverse` method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario. |
121,063 | <p>I've recently acquired a second monitor and now run VS2008 SP1 maximized on my secondary (and bigger) monitor. This theoretically has the benefit of opening the application under development on the primary monitor, where -- as it seems to me -- all newly started applications go. So far, so good. The problem though is now, that the exception helper popup is <strong>not</strong> opened on the secondary monitor. Even worse, it is <strong>only</strong> shown when the Studio window is far enough on the primary monitor! If I drag the studio with an opened exception helper from the primary to the secondary monitor, the helper is dragged with the window until it hits the border between the two monitors, where it suddenly <strong>disappears</strong>.</p>
<p>Has somebody experienced this too? Is there any workaround? Anything else I should try?</p>
| [
{
"answer_id": 121089,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "<p>It's not clear if this is really what you want, but:</p>\n\n<pre><code>int x = yourNumber();\nchar a = (char)(x &... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] | I've recently acquired a second monitor and now run VS2008 SP1 maximized on my secondary (and bigger) monitor. This theoretically has the benefit of opening the application under development on the primary monitor, where -- as it seems to me -- all newly started applications go. So far, so good. The problem though is now, that the exception helper popup is **not** opened on the secondary monitor. Even worse, it is **only** shown when the Studio window is far enough on the primary monitor! If I drag the studio with an opened exception helper from the primary to the secondary monitor, the helper is dragged with the window until it hits the border between the two monitors, where it suddenly **disappears**.
Has somebody experienced this too? Is there any workaround? Anything else I should try? | Quick'n'dirty:
```csharp
int value = 0x48454C4F;
Console.WriteLine(Encoding.ASCII.GetString(
BitConverter.GetBytes(value).Reverse().ToArray()
));
```
Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it.
EDIT: The `Reverse` method is an extension method from .NET 3.5, just for info. Reversing the byte order may also not be needed in your scenario. |
121,066 | <p>I want to attach a click event to a button element and then later remove it, but I can't get <code>unclick()</code> or <code>unbind()</code> event(s) to work as expected. In the code below, the button is <code>tan</code> colour and the click event works.</p>
<pre><code>window.onload = init;
function init() {
$("#startButton").css('background-color', 'beige').click(process_click);
$("#startButton").css('background-color', 'tan').unclick();
}
</code></pre>
<p>How can I remove events from my elements?</p>
| [
{
"answer_id": 121084,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 2,
"selected": false,
"text": "<p>unbind is your friend.</p>\n\n<pre><code>$(\"#startButton\").unbind('click')\n</code></pre>\n"
},
{
"answer_id"... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | I want to attach a click event to a button element and then later remove it, but I can't get `unclick()` or `unbind()` event(s) to work as expected. In the code below, the button is `tan` colour and the click event works.
```
window.onload = init;
function init() {
$("#startButton").css('background-color', 'beige').click(process_click);
$("#startButton").css('background-color', 'tan').unclick();
}
```
How can I remove events from my elements? | There's no such thing as `unclick()`. Where did you get that from?
You can remove individual event handlers from an element by calling unbind:
```
$("#startButton").unbind("click", process_click);
```
If you want to remove all handlers, or you used an anonymous function as a handler, you can omit the second argument to `unbind()`:
```
$("#startButton").unbind("click");
``` |
121,116 | <p>I have a managed DLL (written in C++/CLI) that contains a class used by a C# executable. In the constructor of the class, I need to get access to the full path of the executable referencing the DLL. In the actual app I know I can use the Application object to do this, but how can I do it from a managed DLL?</p>
| [
{
"answer_id": 121137,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 5,
"selected": true,
"text": "<pre><code>Assembly.GetCallingAssembly()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Assembly.GetExecutingAssembly()\n</code><... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] | I have a managed DLL (written in C++/CLI) that contains a class used by a C# executable. In the constructor of the class, I need to get access to the full path of the executable referencing the DLL. In the actual app I know I can use the Application object to do this, but how can I do it from a managed DLL? | ```
Assembly.GetCallingAssembly()
```
or
```
Assembly.GetExecutingAssembly()
```
or
```
Assembly.GetEntryAssembly()
```
Depending on your need.
Then use Location or CodeBase property (I never remember which one). |
121,117 | <p>Are there any good webservices out there that provide good lookup information for Countries and States/Provinces?</p>
<p>If so what ones do you use?</p>
| [
{
"answer_id": 121160,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 4,
"selected": true,
"text": "<p>If you only need US information, the US Postal Service provides a set of web services it calls WebTools for this exact thing.... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8897/"
] | Are there any good webservices out there that provide good lookup information for Countries and States/Provinces?
If so what ones do you use? | If you only need US information, the US Postal Service provides a set of web services it calls WebTools for this exact thing. <https://www.usps.com/business/web-tools-apis/welcome.htm>. You will need to register to be able to use them but once you're registered they are really simple to use. You just send an XML request over HTTP and the server sends an XML response back and you just have to unpack it.
Sample request:
```
http://SERVERNAME/ShippingAPITest.dll?API=Verify&XML=<AddressValidateRequest%20USERID="xxxxxxx"><Address ID="0"><Address1></Address1><Address2>6406 Ivy Lane</Address2><City>Greenbelt</City><State>MD</State><Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>
```
Sample response:
```
<?xml version="1.0"?>
<AddressValidateResponse>
<Address ID="0">
<Address2>6406 IVY LN</Address2>
<City>GREENBELT</City>
<State>MD</State>
<Zip5>20770</Zip5>
<Zip4>1441</Zip4>
</Address>
</AddressValidateResponse>
```
Here's a link to the technical documentation:
<https://www.usps.com/business/web-tools-apis/documentation-updates.htm> |
121,147 | <p>I'd like to be able to determine if a directory such as a '.app' is considered to be a package or bundle from Finder's point of view on the command line. I don't think this would be difficult to do with a small shell program, but I'd rather not re-invent the wheel if I don't have to.</p>
| [
{
"answer_id": 121181,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": -1,
"selected": false,
"text": "<p>A bundle should always have a file `./contents/Info.plist'. You can check for the existance of this in a directory, ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4468/"
] | I'd like to be able to determine if a directory such as a '.app' is considered to be a package or bundle from Finder's point of view on the command line. I don't think this would be difficult to do with a small shell program, but I'd rather not re-invent the wheel if I don't have to. | Update:
-------
On all systems with Spotlight, using `mdls` you can detect bundles looking at the kMDItemContentTypeTree property. E.g.:
```
mdls -name kMDItemContentTypeTree "/Applications/Safari.app"
```
produces the following output for me
```
kMDItemContentTypeTree = (
"com.apple.application-bundle",
"com.apple.application",
"public.executable",
"com.apple.localizable-name-bundle",
"com.apple.bundle",
"public.directory",
"public.item",
"com.apple.package"
)
```
Whenever you see `com.apple.package` there, it is supposed to be displayed as a package by Finder. Of course, everything with "bundle" in the name implies that already but not all packages are bundles (bundles are a specific subset of packages that have a well defined directory structure).
---
Old Answer:
-----------
You can get a list of all registered file type extensions, using this command (OS X prior to Leopard):
```
/System/Library/Frameworks/ApplicationServices.framework/Frameworks\
/LaunchServices.framework/Support/lsregister -dump
```
or for Leopard and later:
```
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks\
/LaunchServices.framework/Versions/A/Support/lsregister -dump
```
Every file extension there has flags. If the package flag is set, this is a package.
E.g.
```
claim id: 806354944
name: Bundle
role: none
flags: apple-internal relative-icon-path package
icon: Contents/Resources/KEXT.icns
bindings: .bundle
--------------------------------------------------------
claim id: 1276116992
name: Plug-in
role: none
flags: apple-internal relative-icon-path package
icon: Contents/Resources/KEXT.icns
bindings: .plugin
```
Compare this to a file that is no bundle
```
claim id: 2484731904
name: TEXT
role: viewer
flags: apple-internal
icon:
bindings: .txt, .text, 'TEXT'
```
The only way to really get all bundles is by looking up in the LaunchService database (the one we dumped above). If you just go by whether it has a plist or not or whether the bundle bit is set or not, you might catch some or even many bundles, but you can't catch all of them. This is the database Finder uses to determine
* Is this directory a bundle or not?
* Is this a known file extension or not?
* Which applications should be listed under "Open With" for this file type?
* Which icon should I use for displaying this file type?
and some more stuff.
[EDIT: Added path for Leopard, thanks to Hagelin for the update] |
121,162 | <p>What does the <code>explicit</code> keyword mean in C++?</p>
| [
{
"answer_id": 121163,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 13,
"selected": true,
"text": "<p>The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that th... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1898/"
] | What does the `explicit` keyword mean in C++? | The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a **single parameter** to convert from one type to another in order to get the right type for a parameter.
Here's an example class with a constructor that can be used for implicit conversions:
```
class Foo
{
private:
int m_foo;
public:
// single parameter constructor, can be used as an implicit conversion
Foo (int foo) : m_foo (foo) {}
int GetFoo () { return m_foo; }
};
```
Here's a simple function that takes a `Foo` object:
```
void DoBar (Foo foo)
{
int i = foo.GetFoo ();
}
```
and here's where the `DoBar` function is called:
```
int main ()
{
DoBar (42);
}
```
The argument is not a `Foo` object, but an `int`. However, there exists a constructor for `Foo` that takes an `int` so this constructor can be used to convert the parameter to the correct type.
The compiler is allowed to do this once for each parameter.
Prefixing the `explicit` keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call `DoBar (42)`. It is now necessary to call for conversion explicitly with `DoBar (Foo (42))`
The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:
* You have a `MyString` class with a constructor that constructs a string of the given size. You have a function `print(const MyString&)` (as well as an overload `print (char *string)`), and you call `print(3)` (when you *actually* intended to call `print("3")`). You expect it to print "3", but it prints an empty string of length 3 instead. |
121,167 | <p>What are some of the lesser-known but useful features and techniques that people are using in their Greasemonkey scripts?</p>
<p>(Please, just one feature per answer.)</p>
<p>Similar threads:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript">Hidden Features of JavaScript</a></li>
<li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden Features of Java</a></li>
<li><a href="https://stackoverflow.com/questions/75538/hidden-features-of-c">Hidden Features of C++</a></li>
<li><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a></li>
</ul>
| [
{
"answer_id": 121197,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 3,
"selected": false,
"text": "<p>Data can be persisted across page loads by storing it as a mozilla preference value via <code>GM_setValue(keyname, va... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] | What are some of the lesser-known but useful features and techniques that people are using in their Greasemonkey scripts?
(Please, just one feature per answer.)
Similar threads:
* [Hidden Features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden Features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden Features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) | Greasemonkey scripts often need to search for content on a page. Instead of digging through the DOM, try using XPath to locate nodes of interest. The `document.evaluate()` method lets you provide an XPath expression and will return a collection of matching nodes. Here's a nice [tutorial](http://www-xray.ast.cam.ac.uk/~jgraham/mozilla/xpath-tutorial.html) to get you started. As an example, here's a script I wrote that causes links in phpBB3 posts to open in a new tab (in the default skin):
```
// ==UserScript==
// @name New Tab in phpBB3
// @namespace http://robert.walkertribe.com/
// @description Makes links in posts in phpBB3 boards open new tabs.
// ==/UserScript==
var newWin = function(ev) {
var win = window.open(ev.target.href);
if (win) ev.preventDefault();
};
var links = document.evaluate(
"//div[@class='content']//a[not(@onclick) and not(@href='#')]",
document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < links.snapshotLength; i++) {
var link = links.snapshotItem(i);
link.addEventListener("click", newWin, true);
}
```
The XPath expression used in the code identifies all `a` elements that 1) do not have an `onclick` attribute, 2) whose `href` attribute is not set to `"#"`, and 3) are found inside `div`s whose `class` attribute is set to `"content"`. |
121,199 | <p>How is it possible in Eclipse JDT to convert a multiline selection to String. Like the following</p>
<p>From:</p>
<pre><code>xxxx
yyyy
zzz
</code></pre>
<p>To:</p>
<pre><code>"xxxx " +
"yyyy " +
"zzz"
</code></pre>
<p>I tried the following template </p>
<pre><code>"${line_selection}${cursor}"+
</code></pre>
<p>but that way I only get the whole block surrounded not each line separately. How can I achieve a multiline processing like commenting the selected block?</p>
| [
{
"answer_id": 121420,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 2,
"selected": false,
"text": "<p>This may not be exactly the answer you're looking for. You can easily achieve what you're asking by using t... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How is it possible in Eclipse JDT to convert a multiline selection to String. Like the following
From:
```
xxxx
yyyy
zzz
```
To:
```
"xxxx " +
"yyyy " +
"zzz"
```
I tried the following template
```
"${line_selection}${cursor}"+
```
but that way I only get the whole block surrounded not each line separately. How can I achieve a multiline processing like commenting the selected block? | Maybe this is not what you mean but...
If I'm on a line in Eclipse and I enter double quotation marks, then inside that paste a multiline selection (like your xyz example) it will paste out like this:
```
"xxxx\n" +
"yyyy\n" +
"zzz"
```
Then you could just find/replace in a selection for `"\n"` to `""`, if you didn't intend the newlines.
I think the option to enable this is in `Window/Preferences`, under `Java/Editor/Typing/`, check the box next to `"Escape text when pasting into a string literal"`. (`Eclipse 3.4 Ganymede`) |
121,202 | <p>I work with quite a bit of multi-platform C/C++ code, separated by common #defines (#if WIN, #if UNIX, etc). It would be nice if I could have vim automatically fold the sections I'm currently not interested in when I open a file. I've searched through the vim script archives, but I haven't found anything useful. Any suggestions? Places to start?</p>
| [
{
"answer_id": 121278,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 3,
"selected": false,
"text": "<p>Just add a folding region to your syntax\n<a href=\"http://vim.wikia.com/wiki/Syntax_folding_of_Vim_scripts#Syntax_defi... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21138/"
] | I work with quite a bit of multi-platform C/C++ code, separated by common #defines (#if WIN, #if UNIX, etc). It would be nice if I could have vim automatically fold the sections I'm currently not interested in when I open a file. I've searched through the vim script archives, but I haven't found anything useful. Any suggestions? Places to start? | Just add a folding region to your syntax
<http://vim.wikia.com/wiki/Syntax_folding_of_Vim_scripts#Syntax_definitions>
```
:syn region myFold start="\#IF" end="\#ENDIF" transparent fold
:syn sync fromstart
:set foldmethod=syntax
``` |
121,237 | <p>I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node?</p>
<p>So, given an XQuery method:</p>
<pre><code>define function foo($bar as node()*) as node() {
(: unimportant details :)
}
</code></pre>
<p>I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string.</p>
| [
{
"answer_id": 121249,
"author": "Sixty4Bit",
"author_id": 1681,
"author_profile": "https://Stackoverflow.com/users/1681",
"pm_score": 5,
"selected": true,
"text": "<p><strong>MarkLogic solutions:</strong></p>\n\n<p>The best way to convert a string into a node is to use:</p>\n\n<pre><cod... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
] | I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node?
So, given an XQuery method:
```
define function foo($bar as node()*) as node() {
(: unimportant details :)
}
```
I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string. | **MarkLogic solutions:**
The best way to convert a string into a node is to use:
```
xdmp:unquote($string).
```
Conversely if you want to convert a node into a string you would use:
```
xdmp:quote($node).
```
**Language agnostic solutions:**
Node to string is:
```
fn:string($node)
``` |
121,240 | <p>What is the best (cleanest, most efficient) way to write saturating addition in C?</p>
<p>The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows.</p>
<p>Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there).</p>
| [
{
"answer_id": 121263,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 3,
"selected": false,
"text": "<pre><code>uint32_t saturate_add32(uint32_t a, uint32_t b)\n{\n uint32_t sum = a + b;\n if ((sum < a) || (sum < ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8964/"
] | What is the best (cleanest, most efficient) way to write saturating addition in C?
The function or macro should add two unsigned inputs (need both 16- and 32-bit versions) and return all-bits-one (0xFFFF or 0xFFFFFFFF) if the sum overflows.
Target is x86 and ARM using gcc (4.1.2) and Visual Studio (for simulation only, so a fallback implementation is OK there). | You probably want portable C code here, which your compiler will turn into proper ARM assembly. ARM has conditional moves, and these can be conditional on overflow. The algorithm then becomes: add and conditionally set the destination to unsigned(-1), if overflow was detected.
```c
uint16_t add16(uint16_t a, uint16_t b)
{
uint16_t c = a + b;
if (c < a) /* Can only happen due to overflow */
c = -1;
return c;
}
```
Note that this differs from the other algorithms in that it corrects overflow, instead of relying on another calculation to detect overflow.
[x86-64 clang 3.7 -O3 output for adds32](https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%2C%22intel%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXO4MDoAWAfAFCgBmSAjEjQPS1IgQRICGAbgPYhxpIQBbTuyQB3EBnxJJCNMnBIBaVlAwIATmgDkSdhrQhOYUojLhkUEAGsEUAJ4AKAB4BKGu5oB9TwCMYIVXBPBCcABwQIDAcAQmjnFwAaKhcTBDMwZBgwSxt7eI8kbz8AjCCQ8MiYuNckgAYU4Fs5VPSLa1tHVwKaJxbzJCycjvyPXsawbDJiYnokAGVOdTU4RjAkRcR1dYooBFZMJB9WFaMkJwAOADYk8UkkAHNmAFZp%2FzAMSkvPDDY4Xk%2FPEoVGpNA43h8vj9WElwQCfj43ABvYg0WGQ%2FhIAC8bCQAGpDgBuFGMCgOCAoVhuWgAKiQAGFWGsjPYkPhWKFwms4DBkBhOOs9OoyFBOKIkNTaMSaCxsQBaShEmjqBAYGDqNYQIkAX2I4IAzAAmb6%2FXiGwHKVT6ME4M1QmE2o3wpHE%2FWOjHY1h4wnEkCk8mUpA0%2BmM9bZOys9mcpDc3n84QaYWi8WSjwypDyxVIZWq9X8bXTcjRtLmFYObwgPVXbxuAA%2BNaLrVL3guX0uABZqzMGAAVADyABFewAuJC7H4yficAShAIaJBWMBJySscf4ZCccLqRm8NjK1YgiBssD3PY%2BXbTWY8PZQFmHiJWQqeECXKueJBkRb8ITsJJ%2BVcrrQ%2BGZcNTBLd9PxDVhIhgFRGBfS5pFYdQTwwJJFx%2BBBcHuXAIzQURbCgXUHWNY5TSNFtPFCAArCBAWEa13ltNh7UYt0EWIRE6AYNB8EWEF%2BHUCQmBUWVQhXKQoBXBBIHDHxwyMZAIDsaBeSPaQ1yQNAfB8XR9EMYwPFdY0MGnLF0wVKVuis9xZk4gBBbsADJuw8esAEl3lsJAtRoNA7HeVgnDYS11RXEA9DQHCkG7DTOBkLZBQMIw%2BFuXiYFXEA%2BDEAIoEOZVWAfVL0wEfYBExHBbEs0qkAcAAiUiCk4gBSABtHwAF0Ela1h2vcetus6mhWo67yAB0wFGjBassgpasEYRIBoZqWp6rqWt4DBev69bME6gbvOm6ykBHHbNqQWrcXUWqapM0JEiQFbeouxyrpqykZo8E6Rtq%2B5rocBFAwYGA5HO9QBAQa6Py2T12x8CRdM0fSkgMSB5B%2BTAcoGOQ%2BENOH0ZAe4wFlEI1AmBAVhAARwewKSPpshhF34EVtP0OmaBcTMlRVNU1lu%2FMjKhP40DNCjqNorSfAYjAmOhAZiKdDiuM0kqbznCBOEQWUDAALwQX90tHIwTy2CBBNKCARLEu5JNJpSarbFhTgACX2fCbySPVHbWOyAFl%2BzYCYkAAIXUThjjdqBaDmKw7EkmwUnpzTtMYIDeY002hIt3KrfwGFsnaRRhHMqKJYDlZ5pEJDVOQZRwdHKSZNDYLcrpAAFABVNApVmUva71vvo04WQwC0eF8ofCdEE5RBG9OCdOCgFZ2BUHltmjA5TkZcMYPUQ8kBCCAEFCH5ff7SyBekadObYNABBq%2Bq%2FgKYbBoG8bJsO6zatLjxWo2l%2FTvam%2FKabNzqfifo9JIv9dofysidP%2B51MSvQcLde6j1zq4hen9d6R0vpPV%2BjVdiR0OaWWzDzS%2BoR%2BbyxNMLciVYxZPjAKESSh8pYyxYtLNiKROJKwtmsZUwNq6aVYHXeUWYED3EyiCfWPxeGjyQKEUO3JD7qWQMqNAMBVCrBxBkMUyoJGYA0FVW%2B98GpIGfpAx6QCYHdDmt%2BFgrVlCbQsT1axBQTo9XQZgt6CdrK4POvg%2F6qDHFPSQfKKkDB1YaJWAIgOoMBDXXVmATAW4cBNxasE6RhtjjgHuOZd8oc77gyEOocMmVowwAED4ZG%2FJMAbiZoyXJZACmaV4nFHJjAMByCgBQBQE4PxxRAcQjwpDcysHzOMSYrwkkEwyCsRxaopKeFIp4cEngbDsHAGCaZhNyZnDzgYHZKw7DOg8L6GqdhCDtzcgAOW7GaH2dkAAasougjLWFc259ynnXzeWcXEdhKHvDhEIv4AJlRCClsC2WaJjSEPcJxX5DhPSECQLUJwAAxTF6L0yHDcAAflRRirFx0cT4h8ASbyrwqHKD%2BGacFnBWFumhVQuFS0xE5jWEipAKK0VYr5di2UuKkAEt5fyzFJLPRkoJDqaYRFWLGhpXAOljKSLsKYgDbhswmlTiQAAJVwOfHA7YFVmSlsajALhWC4nJSQ7muZZQODQIQQghpaw1QFi4NA%2BY%2BgZBBXAT4SLfxuHdTgOELgHA1RVRapFLhcRRvDQiNwPKnBkFTRQEVKa00kocDGuNiaUgX0VWaDcUbmJy3lU6JACK7Wco9RGnN4JzXhspHGxtHZo2Ju5YStNPb03dt7am7NubAkuA5pSi8QMwBQ1VGAKSt4pwzl2HwPk0hRD8kSdgUoRhYI%2BC3JANcQETbflkL%2BCIrAYnq2nLOTQg8R4%2FHuKHCe%2BBMpyo4QqlcCy1BLNpUaOAJ53glNLcyitQrkSGWpRUsykrvSnNJI6yDKA2C1nrPBu%2BiHE1s1%2BQAPwbfLFw9Rr5NAQJhmtmkKnakDLSeZW4v2kUNMmV9wLqOLNIgCP90kMCAZhXactEJYUnPcNxsjd8PRehtbByN6i0NIaQHWGqUnUC4p8d0bDuGgWQnw0M9wRGSMcuExRoMzHaOgoQhKWVXZooHuQP%2BjQUlWSLEEmeRSGtkBDgcBZuYAB1OyuqkDnC0YaV9TE5grjsn8du2zZnnE8F5nzngwABDQKWpwaq3THKrS6alMySpoAfNiNF5xaiFeK7UTMF8MC1FNeGAAemcNwjlNLZf2FYMrVCPhVaQA1roDWDlgByy14kQVHLYiw71%2FrmZwzDaQKNpruXMxBVxNiAFxJ2s1mxBVzrZxMztexMg6gKBEOUDcIKvb3KUUAHYtOIqCrVirbqPiArfT8ELGAwtwAi718mZoEtQD4Ml1Lxp0tgd40xMbzWzIFdqFD6HpXMsgY27tmrdXNtg7m3Dp70hqCI8291xrhNxuDc6yN1HA2aCTeJ7N0nZw8RLe29QNb0hKtdbp6a9rB3kg4tO86pAeojuZmu0gW79RZOY%2B9RZz7cyP00f0sQLLhzPCKs8C7MAi44BUQQA4KhssWUuGBzQCDIm2DWuvlQ%2BMQoRRil20i6rUmXCOX%2Bjbipo7nW85%2BaRhwZvEyiAO7zlw1XUPc494KL3jlffEJlakkqmzdc6iAAAA%22%2C%22compiler%22%3A%22g530%22%2C%22options%22%3A%22-xc%20-Wall%20-fverbose-asm%20%20-O3%20-mtune%3Dhaswell%22%7D%5D%7D): significantly better than any other answer:
```asm
add edi, esi
mov eax, -1
cmovae eax, edi
ret
```
[ARMv7: `gcc 4.8 -O3 -mcpu=cortex-a15 -fverbose-asm` output for adds32](https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4DOAXO4MDoAWAfAFCgBmSAjEjQPS1IgQRICGAbgPYhxpIQBbTuyQB3EBnxJJCNMnBIBaVlAwIATmgDkSdhrQhOYUojLhkUEAGsEUAJ4AKAB4BKGu5oB9TwCMYIVXBPBCcABwQIDAcAQmjnFwAaKhcTBDMwZBgwSxt7eI8kbz8AjCCQ8MiYuNckgAYU4Fs5VPSLa1tHVwKaJxbzJCycjvyPXsawbDJiYnokAGVOdTU4RjAkRcR1dYooBFZMJB9WFaMkJwAOADYk8UkkAHNmAFZp%2FzAMSkvPDDY4Xk%2FPEoVGpNA43h8vj9WElwQCfj43ABvYg0WGQ%2FhIAC8bCQAGpDgBuFGMCgOCAoVhuWgAKiQAGFWGsjPYkPhWKFwms4DBkBhOOs9OoyFBOKIkNTaMSaCxsQBaShEmjqBAYGDqNYQIkAX2I4IAzAAmb6%2FXiGwHKVT6ME4M1QmE2o3wpHE%2FWOjHY1h4wnEkCk8mUpA0%2BmM9bZOys9mcpDc3n84QaYWi8WSjwypDyxVIZWq9X8bXTcjRtLmFYObwgPVXbxuAA%2BNaLrVL3guX0uABZqzMGAAVADyABFewAuJC7H4yficAShAIaJBWMBJySscf4ZCccLqRm8NjK1YgiBssD3PY%2BXbTWY8PZQFmHiJWQqeECXKueJBkRb8ITsJJ%2BVcrrQ%2BGZcNTBLd9PxDVhIhgFRGBfS5pFYdQTwwJJFx%2BBBcHuXAIzQURbCgXUHWNY5TSNFtPFCAArCBAWEa13ltNh7UYt0EWIRE6AYNB8EWEF%2BHUCQmBUWVQhXKQoBXBBIHDHxwyMZAIDsaBeSPaQ1yQNAfB8XR9EMYwPFdY0MGnLF0wVKVuis9xZk4gBBbsADJuw8esAEl3lsJAtRoNA7HeVgnDYS11RXEA9DQHCkG7DTOBkLZBQMIw%2BFuXiYFXEA%2BDEAIoEOZVWAfVL0wEfYBExHBbEs0qkAcAAiUiCk4gBSABtHwAF0Ela1h2vcetus6mhWo67yAB0wFGjBassgpasEYRIBoZqWp6rqWt4DBev69bME6gbvOm6ykBHHbNqQWrcXUWqapM0JEiQFbeouxyrpqykZo8E6Rtq%2B5rocBFAwYGA5HO9QBAQa6Py2T12x8CRdM0fSkgMSB5B%2BTAcoGOQ%2BENOH0ZAe4wFlEI1AmBAVhAARwewKSPpshhF34EVtP0OmaBcTMlRVNU1lu%2FMjKhP40DNCjqNorSfAYjAmOhAZiKdDiuM0kqbznCBOEQWUDAALwQX90tHIwTy2CBBNKCARLEu5JNJpSarbFhTgACX2fCbySPVHbWOyAFl%2BzYCYkAAIXUThjjdqBaDmKw7EkmwUnpzTtMYIDeY002hIt3KrfwGFsnaRRhHMqKJYDlZ5pEJDVOQZRwdHKSZNDYLcrpAAFABVNApVmUva71vvo04WQwC0eF8ofCdEE5RBG9OCdOCgFZ2BUHltmjA5TkZcMYPUQ8kBCCAEFCH5ff7SyBekadObYNABBq%2Bq%2FgKYbBoG8bJsO6zatLjxWo2l%2FTvam%2FKabNzqfifo9JIv9dofysidP%2B51MSvQcLde6j1zq4hen9d6R0vpPV%2BjVdiR0OaWWzDzS%2BoR%2BbyxNMLciVYxZPjAKESSh8pYyxYtLNiKROJKwtmsZUwNq6aVYHXeUWYED3EyiCfWPxeGjyQKEUO3JD7qWQMqNAMBVCrBxBkMUyoJGYA0FVW%2B98GpIGfpAx6QCYHdDmt%2BFgrVlCbQsT1axBQTo9XQZgt6CdrK4POvg%2F6qDHFPSQfKKkDB1YaJWAIgOoMBDXXVmATAW4cBNxasE6RhtjjgHuOZd8oc77gyEOocMmVowwAED4ZG%2FJMAbiZoyXJZACmaV4nFHJjAMByCgBQBQE4PxxRAcQjwpDcysHzOMSYrwkkEwyCsRxaopKeFIp4cEngbDsHAGCaZhNyZnDzgYHZKw7DOg8L6GqdhCDtzcgAOW7GaH2dkAAasougjLWFc259ynnXzeWcXEdhKHvDhEIv4AJlRCClsC2WaJjSEPcJxX5DhPSECQLUJwAAxTF6L0yHDcAAflRRirFx0cT4h8ASbyrwqHKD%2BGacFnBWFumhVQuFS0xE5jWEipAKK0VYr5di2UuKkAEt5fyzFJLPRkoJDqaYRFWLGhpXAOljKSLsKYgDbhswmlTiQAAJVwOfHA7YFVmSlsajALhWC4nJSQ7muZZQODQIQQghpaw1QFi4NA%2BY%2BgZBBXAT4SLfxuHdTgOELgHA1RVRapFLhcRRvDQiNwPKnBkFTRQEVKa00kocDGuNiaUgX0VWaDcUbmJy3lU6JACK7Wco9RGnN4JzXhspHGxtHZo2Ju5YStNPb03dt7am7NubAkuA5pSi8QMwBQ1VGAKSt4pwzl2HwPk0hRD8kSdgUoRhYI%2BC3JANcQETbflkL%2BCIrAYnq2nLOTQg8R4%2FHuKHCe%2BBMpyo4QqlcCy1BLNpUaOAJ53glNLcyitQrkSGWpRUsykrvSnNJI6yDKA2C1nrPBu%2BiHE1s1%2BQAPwbfLFw9Rr5NAQJhmtmkKnakDLSeZW4v2kUNMmV9wLqOLNIgCP90kMCAZhXactEJYUnPcNxsjd8PRehtbByN6i0NIaQHWGqUnUC4p8d0bDuGgWQnw0M9wRGSMcuExRoMzHaOgoQhKWVXZooHuQP%2BjQUlWSLEEmeRSGtkBDgcBZuYAB1OyuqkDnC0YaV9TE5grjsn8du2zZnnE8F5nzngwABDQKWpwaq3THKrS6alMySpoAfNiNF5xaiFeK7UTMF8MC1FNeGAAemcNwjlNLZf2FYMrVCPhVaQA1roDWDlgByy14kQVHLYiw71%2FrmZwzDaQKNpruXMxBVxNiAFxJ2s1mxBVzrZxMztexMg6gKBEOUDcIKvb3KUUAHYtOIqCrVirbqPiArfT8ELGAwtwAi718mZoEtQD4Ml1Lxp0tgd40xMbzWzIFdqFD6HpXMsgY27tmrdXNtg7m3Dp70hqCI8291xrhNxuDc6yN1HA2aCTeJ7N0nZw8RLe29QNb0hKtdbp6a9rB3kg4tO86pAeojuZmu0gW79RZOY%2B9RZz7cyP00f0sQLLhzPCKs8C7MAi44BUQQA4KhssWUuGBzQCDIm2DWuvlQ%2BMQoRRil20i6rUmXCOX%2Bjbipo7nW85%2BaRhwZvEyiAO7zlw1XUPc494KL3jlffEJlakkqmzdc6iAAAA%22%2C%22compiler%22%3A%22armhfg482%22%2C%22options%22%3A%22-xc%20-std%3Dgnu99%20-Wall%20-pedantic%20-Wextra%20-fverbose-asm%20%20-O3%20-march%3Darmv7%22%7D%5D%7D):
```asm
adds r0, r0, r1 @ c, a, b
it cs
movcs r0, #-1 @ conditional-move
bx lr
```
16bit: still doesn't use ARM's unsigned-saturating add instruction (`UADD16`)
```asm
add r1, r1, r0 @ tmp114, a
movw r3, #65535 @ tmp116,
uxth r1, r1 @ c, tmp114
cmp r0, r1 @ a, c
ite ls @
movls r0, r1 @,, c
movhi r0, r3 @,, tmp116
bx lr @
``` |
121,243 | <p>What are some hidden features of <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a>?</p>
<p>For example, undocumented system stored procedures, tricks to do things which are very useful but not documented enough?</p>
<hr>
<h2>Answers</h2>
<p><em>Thanks to everybody for all the great answers!</em></p>
<p><strong>Stored Procedures</strong></p>
<ul>
<li><strong>sp_msforeachtable:</strong> Runs a command with '?' replaced with each table name (v6.5 and up)</li>
<li><strong>sp_msforeachdb:</strong> Runs a command with '?' replaced with each database name (v7 and up)</li>
<li><strong>sp_who2:</strong> just like sp_who, but with a lot more info for troubleshooting blocks (v7 and up)</li>
<li><strong>sp_helptext:</strong> If you want the code of a stored procedure, view & UDF</li>
<li><strong>sp_tables:</strong> return a list of all tables and views of database in scope.</li>
<li><strong>sp_stored_procedures:</strong> return a list of all stored procedures</li>
<li><strong>xp_sscanf:</strong> Reads data from the string into the argument locations specified by each format argument.</li>
<li><strong>xp_fixeddrives:</strong>: Find the fixed drive with largest free space</li>
<li><strong>sp_help:</strong> If you want to know the table structure, indexes and constraints of a table. Also views and UDFs. Shortcut is Alt+F1</li>
</ul>
<p><strong>Snippets</strong></p>
<ul>
<li>Returning rows in random order</li>
<li>All database User Objects by Last Modified Date</li>
<li>Return Date Only</li>
<li>Find records which date falls somewhere inside the current week.</li>
<li>Find records which date occurred last week.</li>
<li>Returns the date for the beginning of the current week.</li>
<li>Returns the date for the beginning of last week.</li>
<li>See the text of a procedure that has been deployed to a server</li>
<li>Drop all connections to the database</li>
<li>Table Checksum</li>
<li>Row Checksum</li>
<li>Drop all the procedures in a database</li>
<li>Re-map the login Ids correctly after restore</li>
<li>Call Stored Procedures from an INSERT statement</li>
<li>Find Procedures By Keyword</li>
<li>Drop all the procedures in a database</li>
<li>Query the transaction log for a database programmatically.</li>
</ul>
<p><strong>Functions</strong></p>
<ul>
<li>HashBytes()</li>
<li>EncryptByKey</li>
<li>PIVOT command</li>
</ul>
<p><strong>Misc</strong></p>
<ul>
<li>Connection String extras</li>
<li>TableDiff.exe</li>
<li>Triggers for Logon Events (New in Service Pack 2)</li>
<li>Boosting performance with persisted-computed-columns (pcc).</li>
<li>DEFAULT_SCHEMA setting in sys.database_principles</li>
<li>Forced Parameterization</li>
<li>Vardecimal Storage Format</li>
<li>Figuring out the most popular queries in seconds</li>
<li>Scalable Shared Databases</li>
<li>Table/Stored Procedure Filter feature in SQL Management Studio</li>
<li>Trace flags</li>
<li>Number after a <code>GO</code> repeats the batch</li>
<li>Security using schemas</li>
<li>Encryption using built in encryption functions, views and base tables with triggers</li>
</ul>
| [
{
"answer_id": 121275,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 3,
"selected": false,
"text": "<p>Here are some features I find useful but a lot of people don't seem to know about:</p>\n\n<pre><code>sp_tables\n</code></... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
] | What are some hidden features of [SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server)?
For example, undocumented system stored procedures, tricks to do things which are very useful but not documented enough?
---
Answers
-------
*Thanks to everybody for all the great answers!*
**Stored Procedures**
* **sp\_msforeachtable:** Runs a command with '?' replaced with each table name (v6.5 and up)
* **sp\_msforeachdb:** Runs a command with '?' replaced with each database name (v7 and up)
* **sp\_who2:** just like sp\_who, but with a lot more info for troubleshooting blocks (v7 and up)
* **sp\_helptext:** If you want the code of a stored procedure, view & UDF
* **sp\_tables:** return a list of all tables and views of database in scope.
* **sp\_stored\_procedures:** return a list of all stored procedures
* **xp\_sscanf:** Reads data from the string into the argument locations specified by each format argument.
* **xp\_fixeddrives:**: Find the fixed drive with largest free space
* **sp\_help:** If you want to know the table structure, indexes and constraints of a table. Also views and UDFs. Shortcut is Alt+F1
**Snippets**
* Returning rows in random order
* All database User Objects by Last Modified Date
* Return Date Only
* Find records which date falls somewhere inside the current week.
* Find records which date occurred last week.
* Returns the date for the beginning of the current week.
* Returns the date for the beginning of last week.
* See the text of a procedure that has been deployed to a server
* Drop all connections to the database
* Table Checksum
* Row Checksum
* Drop all the procedures in a database
* Re-map the login Ids correctly after restore
* Call Stored Procedures from an INSERT statement
* Find Procedures By Keyword
* Drop all the procedures in a database
* Query the transaction log for a database programmatically.
**Functions**
* HashBytes()
* EncryptByKey
* PIVOT command
**Misc**
* Connection String extras
* TableDiff.exe
* Triggers for Logon Events (New in Service Pack 2)
* Boosting performance with persisted-computed-columns (pcc).
* DEFAULT\_SCHEMA setting in sys.database\_principles
* Forced Parameterization
* Vardecimal Storage Format
* Figuring out the most popular queries in seconds
* Scalable Shared Databases
* Table/Stored Procedure Filter feature in SQL Management Studio
* Trace flags
* Number after a `GO` repeats the batch
* Security using schemas
* Encryption using built in encryption functions, views and base tables with triggers | In Management Studio, you can put a number after a GO end-of-batch marker to cause the batch to be repeated that number of times:
```
PRINT 'X'
GO 10
```
Will print 'X' 10 times. This can save you from tedious copy/pasting when doing repetitive stuff. |
121,253 | <p>I'm having a strange problem in Visual Studio 2008 where my "Pending Checkins" window never updates. I open it up, and it says "Updating..." like usual, but I never see the "X remaining" message, and nothing happens. It just sits there doing nothing.</p>
<p>Checked-out stuff still shows as checked out in Solution Explorer. SourceSafe 2005 still works like normal.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 122020,
"author": "EvilEddie",
"author_id": 12986,
"author_profile": "https://Stackoverflow.com/users/12986",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried the Visual SourceSafe 2005 Update patch?</p>\n"
},
{
"answer_id": 192168,
"author": "Ryan ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] | I'm having a strange problem in Visual Studio 2008 where my "Pending Checkins" window never updates. I open it up, and it says "Updating..." like usual, but I never see the "X remaining" message, and nothing happens. It just sits there doing nothing.
Checked-out stuff still shows as checked out in Solution Explorer. SourceSafe 2005 still works like normal.
Any ideas? | Hooray! I found a solution. For anyone else that stumbles across this, here's the deal.
I discovered today that the Pending Checkins window wasn't broken for *all* solutions, but only for a particular one. Also, though I didn't realize it was related, every time I opened the solution, I was getting:
**"Some of the properties associated with the solution could not be read."**
The solution I found was [here](http://bloggingabout.net/blogs/rick/archive/2007/12/06/quot-some-of-the-properties-associated-with-the-solution-could-not-be-read-quot.aspx). It turns out that I had two
```
GlobalSection(SourceCodeControl) = preSolution
```
sections in the solution (.sln) file. I deleted the second one (which had a long list of projects, but also some gibberish in it), and the message went away, and my Pending Checkins window now works perfectly. |
121,274 | <p>How would I go about binding the following object, Car, to a gridview?</p>
<pre>
public class Car
{
long Id {get; set;}
Manufacturer Maker {get; set;}
}
public class Manufacturer
{
long Id {get; set;}
String Name {get; set;}
}
</pre>
<p>The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible? </p>
<p>What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers?</p>
| [
{
"answer_id": 121328,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 3,
"selected": false,
"text": "<pre><code> public class Manufacturer\n {\n long Id {get; set;}\n String Name {get; set;}\n\n ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
] | How would I go about binding the following object, Car, to a gridview?
```
public class Car
{
long Id {get; set;}
Manufacturer Maker {get; set;}
}
public class Manufacturer
{
long Id {get; set;}
String Name {get; set;}
}
```
The primitive types get bound easy but I have found no way of displaying anything for Maker. I would like for it to display the Manufacturer.Name. Is it even possible?
What would be a way to do it? Would I have to store ManufacturerId in Car as well and then setup an lookupEditRepository with list of Manufacturers? | Allright guys... This question was posted waaay back but I just found a fairly nice & simple way to do this by using reflection in the cell\_formatting event to go retrieve the nested properties.
Goes like this:
```
private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView grid = (DataGridView)sender;
DataGridViewRow row = grid.Rows[e.RowIndex];
DataGridViewColumn col = grid.Columns[e.ColumnIndex];
if (row.DataBoundItem != null && col.DataPropertyName.Contains("."))
{
string[] props = col.DataPropertyName.Split('.');
PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]);
object val = propInfo.GetValue(row.DataBoundItem, null);
for (int i = 1; i < props.Length; i++)
{
propInfo = val.GetType().GetProperty(props[i]);
val = propInfo.GetValue(val, null);
}
e.Value = val;
}
}
```
And that's it! You can now use the familiar syntax "ParentProp.ChildProp.GrandChildProp" in the DataPropertyName for your column. |
121,282 | <p>If I do something like:</p>
<pre><code>$ cat /bin/ls
</code></pre>
<p>into my terminal, I understand why I see a bunch of binary data, representing the ls executable. But afterwards, when I get my prompt back, my own keystrokes look crazy. I type "a" and I get a weird diagonal line. I type "b" and I get a degree symbol.</p>
<p>Why does this happen?</p>
| [
{
"answer_id": 121297,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 2,
"selected": false,
"text": "<p>You're getting some control characters piped into the shell that are telling the shell to alter its behavior and print ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] | If I do something like:
```
$ cat /bin/ls
```
into my terminal, I understand why I see a bunch of binary data, representing the ls executable. But afterwards, when I get my prompt back, my own keystrokes look crazy. I type "a" and I get a weird diagonal line. I type "b" and I get a degree symbol.
Why does this happen? | Because somewhere in your binary data were some control sequences that your terminal interpreted as requests to, for example, change the character set used to draw. You can restore everything to normal like so:
```
reset
``` |
121,309 | <p>In an ASP.NET 2.0 website, I have a string representing some well-formed XML. I am currently creating an XmlDocument object with it and running an XSL transformation for display in a Web form. Everything was operating fine until the XML input started to contain namespaces.</p>
<p>How can I read in this string and allow namespaces?</p>
<p>I've included the current code below. The string source comes from an HTML encoded node in a WordPress RSS feed.</p>
<pre><code>XPathNavigator myNav= myPost.CreateNavigator();
XmlNamespaceManager myManager = new XmlNamespaceManager(myNav.NameTable);
myManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
string myPost = HttpUtility.HtmlDecode("<post>" +
myNav.SelectSingleNode("//item[1]/content:encoded", myManager).InnerXml +
"</post>");
XmlDocument myDocument = new XmlDocument();
myDocument.LoadXml(myPost.ToString());
</code></pre>
<p>The error is on the last line:</p>
<p>"System.Xml.XmlException: 'w' is an undeclared namespace. Line 12, position 201. at System.Xml.XmlTextReaderImpl.Throw(Exception e) ..."</p>
| [
{
"answer_id": 121407,
"author": "ckarras",
"author_id": 5688,
"author_profile": "https://Stackoverflow.com/users/5688",
"pm_score": 1,
"selected": false,
"text": "<p>Your code looks right.</p>\n\n<p>The problem is probably in the xml document you're trying to load.\nIt must have element... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19626/"
] | In an ASP.NET 2.0 website, I have a string representing some well-formed XML. I am currently creating an XmlDocument object with it and running an XSL transformation for display in a Web form. Everything was operating fine until the XML input started to contain namespaces.
How can I read in this string and allow namespaces?
I've included the current code below. The string source comes from an HTML encoded node in a WordPress RSS feed.
```
XPathNavigator myNav= myPost.CreateNavigator();
XmlNamespaceManager myManager = new XmlNamespaceManager(myNav.NameTable);
myManager.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
string myPost = HttpUtility.HtmlDecode("<post>" +
myNav.SelectSingleNode("//item[1]/content:encoded", myManager).InnerXml +
"</post>");
XmlDocument myDocument = new XmlDocument();
myDocument.LoadXml(myPost.ToString());
```
The error is on the last line:
"System.Xml.XmlException: 'w' is an undeclared namespace. Line 12, position 201. at System.Xml.XmlTextReaderImpl.Throw(Exception e) ..." | Gut feel - one of the namespaces declared in //content:encoding is being dropped (probably because you're using the literal .InnerXml property)
What's 'w' namespace evaluate to in the myNav DOM? You'll want to add xmlns:w= to your post node. There will probably be others too. |
121,318 | <p>I need to have a script read the files coming in and check information for verification.</p>
<p>On the first line of the files to be read is a date but in numeric form. eg: 20080923
But before the date is other information, I need to read it from position 27. Meaning line 1 position 27, I need to get that number and see if it’s greater then another number.</p>
<p>I use the grep command to check other information but I use special characters to search, in this case the information before the date is always different, so I can’t use a character to search on. It has to be done by line 1 position 27.</p>
| [
{
"answer_id": 121336,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 4,
"selected": true,
"text": "<pre><code>sed 1q $file | cut -c27-34\n</code></pre>\n\n<p>The <code>sed</code> command reads the first line of th... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21151/"
] | I need to have a script read the files coming in and check information for verification.
On the first line of the files to be read is a date but in numeric form. eg: 20080923
But before the date is other information, I need to read it from position 27. Meaning line 1 position 27, I need to get that number and see if it’s greater then another number.
I use the grep command to check other information but I use special characters to search, in this case the information before the date is always different, so I can’t use a character to search on. It has to be done by line 1 position 27. | ```
sed 1q $file | cut -c27-34
```
The `sed` command reads the first line of the file and the `cut` command chops out characters 27-34 of the one line, which is where you said the date is.
*Added later:*
For the more general case - where you need to read line 24, for example, instead of the first line, you need a slightly more complex `sed` command:
```
sed -n -e 24p -e 24q | cut -c27-34
sed -n '24p;24q' | cut -c27-34
```
The `-n` option means 'do not print lines by default'; the `24p` means print line 24; the `24q` means quit after processing line 24. You could leave that out, in which case `sed` would continue processing the input, effectively ignoring it.
Finally, especially if you are going to validate the date, you might want to use Perl for the whole job (or Python, or Ruby, or Tcl, or any scripting language of your choice). |
121,324 | <p>I'm looking for a framework to generate Java source files.</p>
<p>Something like the following API:</p>
<pre><code>X clazz = Something.createClass("package name", "class name");
clazz.addSuperInterface("interface name");
clazz.addMethod("method name", returnType, argumentTypes, ...);
File targetDir = ...;
clazz.generate(targetDir);
</code></pre>
<p>Then, a java source file should be found in a sub-directory of the target directory.</p>
<p>Does anyone know such a framework?</p>
<hr>
<p><strong>EDIT</strong>:</p>
<ol>
<li>I really need the source files.</li>
<li>I also would like to fill out the code of the methods.</li>
<li>I'm looking for a high-level abstraction, not direct bytecode manipulation/generation.</li>
<li>I also need the "structure of the class" in a tree of objects.</li>
<li>The problem domain is general: to generate a large amount of very different classes, without a "common structure".</li>
</ol>
<hr>
<p><strong>SOLUTIONS</strong><br>
I have posted 2 answers based in your answers... <a href="https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136010">with CodeModel</a> and <a href="https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136016">with Eclipse JDT</a>.</p>
<p>I have used <a href="http://codemodel.java.net/" rel="noreferrer">CodeModel</a> in my solution, :-)</p>
| [
{
"answer_id": 121367,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 1,
"selected": false,
"text": "<p>If you REALLY need the source, I don't know of anything that generates source. You can however use <a href=\"http://as... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16135/"
] | I'm looking for a framework to generate Java source files.
Something like the following API:
```
X clazz = Something.createClass("package name", "class name");
clazz.addSuperInterface("interface name");
clazz.addMethod("method name", returnType, argumentTypes, ...);
File targetDir = ...;
clazz.generate(targetDir);
```
Then, a java source file should be found in a sub-directory of the target directory.
Does anyone know such a framework?
---
**EDIT**:
1. I really need the source files.
2. I also would like to fill out the code of the methods.
3. I'm looking for a high-level abstraction, not direct bytecode manipulation/generation.
4. I also need the "structure of the class" in a tree of objects.
5. The problem domain is general: to generate a large amount of very different classes, without a "common structure".
---
**SOLUTIONS**
I have posted 2 answers based in your answers... [with CodeModel](https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136010) and [with Eclipse JDT](https://stackoverflow.com/questions/121324/a-java-api-to-generate-java-source-files#136016).
I have used [CodeModel](http://codemodel.java.net/) in my solution, :-) | Sun provides an API called CodeModel for generating Java source files using an API. It's not the easiest thing to get information on, but it's there and it works extremely well.
The easiest way to get hold of it is as part of the JAXB 2 RI - the XJC schema-to-java generator uses CodeModel to generate its java source, and it's part of the XJC jars. You can use it just for the CodeModel.
Grab it from <http://codemodel.java.net/> |
121,326 | <p>What does it mean when it gives a backtrace with the following output?</p>
<pre><code>#0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2
#1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2
#2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2
#3 0x0000000000000000 in ?? ()
</code></pre>
<p>The program has crashed with a standard signal 11, segmentation fault.
My application is a multi-threaded FastCGI C++ program running on FreeBSD 6.3, using pthread as the threading library.</p>
<p>It has been compiled with -g and all the symbol tables for my source are loaded, according to info sources.</p>
<p>As is clear, none of my actual code appears in the trace but instead the error seems to originate from standard pthread libraries. In particular, what is ?? () ????</p>
<p><b>EDIT</b>: eventually tracked the crash down to a standard invalid memory access in my main code. Doesn't explain why the stack trace was corrupted, but that's a question for another day :)</p>
| [
{
"answer_id": 121361,
"author": "Hannes Ovrén",
"author_id": 13565,
"author_profile": "https://Stackoverflow.com/users/13565",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure you compile with debug symbols. (For gcc I think that is the -g option). Then you should be able to get ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10264/"
] | What does it mean when it gives a backtrace with the following output?
```
#0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2
#1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2
#2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2
#3 0x0000000000000000 in ?? ()
```
The program has crashed with a standard signal 11, segmentation fault.
My application is a multi-threaded FastCGI C++ program running on FreeBSD 6.3, using pthread as the threading library.
It has been compiled with -g and all the symbol tables for my source are loaded, according to info sources.
As is clear, none of my actual code appears in the trace but instead the error seems to originate from standard pthread libraries. In particular, what is ?? () ????
**EDIT**: eventually tracked the crash down to a standard invalid memory access in my main code. Doesn't explain why the stack trace was corrupted, but that's a question for another day :) | gdb wasn't able to extract the proper return address from pthread\_mutexattr\_init; it got an address of 0. The "??" is the result of looking up address 0 in the symbol table. It cannot find a symbolic name, so it prints a default "??"
Unfortunately right offhand I don't know why it could not extract the correct return address. |
121,382 | <p>Is there a way to comment out markup in an <code>.ASPX</code> page so that it isn't delivered to the client? I have tried the standard comments <code><!-- --></code> but this just gets delivered as a comment and doesn't prevent the control from rendering. </p>
| [
{
"answer_id": 121397,
"author": "BigJump",
"author_id": 8542,
"author_profile": "https://Stackoverflow.com/users/8542",
"pm_score": 3,
"selected": false,
"text": "<p>Another way assuming it's not server side code you want to comment out is...</p>\n\n<pre><code><asp:panel runat=\"serv... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
] | Is there a way to comment out markup in an `.ASPX` page so that it isn't delivered to the client? I have tried the standard comments `<!-- -->` but this just gets delivered as a comment and doesn't prevent the control from rendering. | ```
<%--
Commented out HTML/CODE/Markup. Anything with
this block will not be parsed/handled by ASP.NET.
<asp:Calendar runat="server"></asp:Calendar>
<%# Eval(“SomeProperty”) %>
--%>
```
[Source](http://weblogs.asp.net/scottgu/archive/2006/07/09/Tip_2F00_Trick_3A00_-Using-Server-Side-Comments-with-ASP.NET-2.0-.aspx) |
121,387 | <p>Table: </p>
<pre><code>UserId, Value, Date.
</code></pre>
<p>I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle)</p>
<p><strong>Update:</strong> Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date.</p>
| [
{
"answer_id": 121416,
"author": "jdmichal",
"author_id": 12275,
"author_profile": "https://Stackoverflow.com/users/12275",
"pm_score": 2,
"selected": false,
"text": "<p>I think something like this. (Forgive me for any syntax mistakes; I'm used to using HQL at this point!)</p>\n\n<p>EDIT... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21154/"
] | Table:
```
UserId, Value, Date.
```
I want to get the UserId, Value for the max(Date) for each UserId. That is, the Value for each UserId that has the latest date. Is there a way to do this simply in SQL? (Preferably Oracle)
**Update:** Apologies for any ambiguity: I need to get ALL the UserIds. But for each UserId, only that row where that user has the latest date. | This will retrieve all rows for which the my\_date column value is equal to the maximum value of my\_date for that userid. This may retrieve multiple rows for the userid where the maximum date is on multiple rows.
```
select userid,
my_date,
...
from
(
select userid,
my_date,
...
max(my_date) over (partition by userid) max_my_date
from users
)
where my_date = max_my_date
```
"Analytic functions rock"
Edit: With regard to the first comment ...
"using analytic queries and a self-join defeats the purpose of analytic queries"
There is no self-join in this code. There is instead a predicate placed on the result of the inline view that contains the analytic function -- a very different matter, and completely standard practice.
"The default window in Oracle is from the first row in the partition to the current one"
The windowing clause is only applicable in the presence of the order by clause. With no order by clause, no windowing clause is applied by default and none can be explicitly specified.
The code works. |
121,392 | <p>I have a bunch (hundreds) of files that are supposed to have Unix line endings. I strongly suspect that some of them have Windows line endings, and I want to programmatically figure out which ones do.</p>
<p>I know I can just run <pre>flip -u</pre> or something similar in a script to convert everything, but I want to be able to identify those files that need changing first.</p>
| [
{
"answer_id": 121415,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<p>Windows use char 13 & 10 for line ending, unix only one of them ( i don't rememeber which one ). So you can replace ch... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18177/"
] | I have a bunch (hundreds) of files that are supposed to have Unix line endings. I strongly suspect that some of them have Windows line endings, and I want to programmatically figure out which ones do.
I know I can just run
```
flip -u
```
or something similar in a script to convert everything, but I want to be able to identify those files that need changing first. | You could use grep
```
egrep -l $'\r'\$ *
``` |
121,396 | <p>When you call the <code>object.__repr__()</code> method in Python you get something like this back: </p>
<blockquote>
<pre><code><__main__.Test object at 0x2aba1c0cf890>
</code></pre>
</blockquote>
<p>Is there any way to get a hold of the memory address if you overload <code>__repr__()</code>, other then calling <code>super(Class, obj).__repr__()</code> and regexing it out? </p>
| [
{
"answer_id": 121422,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 6,
"selected": false,
"text": "<p>Just use </p>\n\n<pre><code>id(object)\n</code></pre>\n"
},
{
"answer_id": 121426,
"author": "Thomas Wo... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452521/"
] | When you call the `object.__repr__()` method in Python you get something like this back:
>
>
> ```
> <__main__.Test object at 0x2aba1c0cf890>
>
> ```
>
>
Is there any way to get a hold of the memory address if you overload `__repr__()`, other then calling `super(Class, obj).__repr__()` and regexing it out? | The [Python manual](https://docs.python.org/2/library/functions.html#id) has this to say about `id()`:
>
> Return the "identity'' of an object.
> This is an integer (or long integer)
> which is guaranteed to be unique and
> constant for this object during its
> lifetime. Two objects with
> non-overlapping lifetimes may have the
> same id() value. (Implementation note:
> this is the address of the object.)
>
>
>
So in CPython, this will be the address of the object. No such guarantee for any other Python interpreter, though.
Note that if you're writing a C extension, you have full access to the internals of the Python interpreter, including access to the addresses of objects directly. |
121,439 | <p>I'm running <code>Django 1.0</code> and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.</p>
<p>With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.</p>
<p>Any thoughts on how best to approach this issue?</p>
| [
{
"answer_id": 121474,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 5,
"selected": true,
"text": "<p>Automatically log your 500s, that way:</p>\n\n<ul>\n<li>You know when they occur.</li>\n<li>You don't need to rely o... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] | I'm running `Django 1.0` and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False.
With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers.
Any thoughts on how best to approach this issue? | Automatically log your 500s, that way:
* You know when they occur.
* You don't need to rely on users sending you stacktraces.
Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces, urls, etc. that the developers can subscribe to.
Showing stack traces to your users on the other hand could possibly leak information that malicious users could use to attack your site. Overly detailed error messages are one of the classic stepping stones to SQL injection attacks.
*Edit* (added code sample to capture traceback):
You can get the exception information from the sys.exc\_info call. While formatting the traceback for display comes from the traceback module:
```
import traceback
import sys
try:
raise Exception("Message")
except:
type, value, tb = sys.exc_info()
print >> sys.stderr, type.__name__, ":", value
print >> sys.stderr, '\n'.join(traceback.format_tb(tb))
```
Prints:
```
Exception : Message
File "exception.py", line 5, in <module>
raise Exception("Message")
``` |
121,453 | <p>There is a way to know the flash player version installed on the computer that runs our SWF file with Action Script 3.0?</p>
| [
{
"answer_id": 121486,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 2,
"selected": false,
"text": "<p>It's in <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/system/Capabilities.html#version\" rel=\... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
] | There is a way to know the flash player version installed on the computer that runs our SWF file with Action Script 3.0? | If you are programming from within the IDE the following will get you the version
```
trace(Capabilities.version);
```
If you are building a custom class the following should help.
Make sure that this following code goes into a file named VersionCheck.as
>
>
> ```
>
> package
> {
> import flash.system.Capabilities;
>
> public class VersionCheck
> {
> public function VersionCheck():void
> {
> trace(Capabilities.version);
> }
> }
> }
>
> ```
>
>
Hope this helps, always remember that all of the AS3 language can be studied online here <http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/>. |
121,493 | <p>I'm no crypto expert, but as I understand it, 3DES is a symmetric encryption algorithm, which means it doesnt use public/private keys.</p>
<p>Nevertheless, I have been tasked with encrypting data using a public key, (specifically, a .CER file).
If you ignore the whole symmetric/asymmetric thang, I should just be able to use the key data from the public key as the TripleDES key.
However, I'm having difficulty extracting the key bytes from the .CER file.
This is the code as it stands..</p>
<pre><code>TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
X509Certificate2 cert = new X509Certificate2(@"c:\temp\whatever.cer");
cryptoProvider.Key = cert.PublicKey.Key.
</code></pre>
<p>The simplest method I can find to extract the raw key bytes from the certificate is ToXmlString(bool), and then doing some hacky substringing upon the returned string.
However, this seems so hackish I feel I must be missing a simpler, more obvious way to do it.</p>
<p>Am I missing a simpler way to use a .cer file to provide the key data to the C# 3DES crypto class, or is hacking it out of the certificate xml string really the best way to go about this?</p>
| [
{
"answer_id": 121526,
"author": "jlew",
"author_id": 7450,
"author_profile": "https://Stackoverflow.com/users/7450",
"pm_score": 3,
"selected": true,
"text": "<p>cryptoProvider.Key = cert.GetPublicKey()?</p>\n"
},
{
"answer_id": 121527,
"author": "Seb Nilsson",
"author_i... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21002/"
] | I'm no crypto expert, but as I understand it, 3DES is a symmetric encryption algorithm, which means it doesnt use public/private keys.
Nevertheless, I have been tasked with encrypting data using a public key, (specifically, a .CER file).
If you ignore the whole symmetric/asymmetric thang, I should just be able to use the key data from the public key as the TripleDES key.
However, I'm having difficulty extracting the key bytes from the .CER file.
This is the code as it stands..
```
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
X509Certificate2 cert = new X509Certificate2(@"c:\temp\whatever.cer");
cryptoProvider.Key = cert.PublicKey.Key.
```
The simplest method I can find to extract the raw key bytes from the certificate is ToXmlString(bool), and then doing some hacky substringing upon the returned string.
However, this seems so hackish I feel I must be missing a simpler, more obvious way to do it.
Am I missing a simpler way to use a .cer file to provide the key data to the C# 3DES crypto class, or is hacking it out of the certificate xml string really the best way to go about this? | cryptoProvider.Key = cert.GetPublicKey()? |
121,499 | <p>Suppose I attach an <code>blur</code> function to an HTML input box like this:</p>
<pre><code><input id="myInput" onblur="function() { ... }"></input>
</code></pre>
<p>Is there a way to get the ID of the element which caused the <code>blur</code> event to fire (the element which was clicked) inside the function? How?</p>
<p>For example, suppose I have a span like this:</p>
<pre><code><span id="mySpan">Hello World</span>
</code></pre>
<p>If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was <code>mySpan</code> that was clicked?</p>
<p>PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked.</p>
<p>PPS: The background of this problem is that I want to trigger an AJAX autocompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the <code>blur</code> event on the input element. So I want to check in the <code>blur</code> function if one specific element has been clicked, and if so, ignore the blur event. </p>
| [
{
"answer_id": 121517,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Edit:</strong>\nA hacky way to do it would be to create a variable that keeps track of focus for every elem... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6264/"
] | Suppose I attach an `blur` function to an HTML input box like this:
```
<input id="myInput" onblur="function() { ... }"></input>
```
Is there a way to get the ID of the element which caused the `blur` event to fire (the element which was clicked) inside the function? How?
For example, suppose I have a span like this:
```
<span id="mySpan">Hello World</span>
```
If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was `mySpan` that was clicked?
PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked.
PPS: The background of this problem is that I want to trigger an AJAX autocompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the `blur` event on the input element. So I want to check in the `blur` function if one specific element has been clicked, and if so, ignore the blur event. | Hmm... In Firefox, you can use `explicitOriginalTarget` to pull the element that was clicked on. I expected `toElement` to do the same for IE, but it does not appear to work... However, you can pull the newly-focused element from the document:
```
function showBlur(ev)
{
var target = ev.explicitOriginalTarget||document.activeElement;
document.getElementById("focused").value =
target ? target.id||target.tagName||target : '';
}
...
<button id="btn1" onblur="showBlur(event)">Button 1</button>
<button id="btn2" onblur="showBlur(event)">Button 2</button>
<button id="btn3" onblur="showBlur(event)">Button 3</button>
<input id="focused" type="text" disabled="disabled" />
```
---
**Caveat:** This technique does *not* work for focus changes caused by *tabbing* through fields with the keyboard, and does not work at all in Chrome or Safari. The big problem with using `activeElement` (except in IE) is that it is not consistently updated until *after* the `blur` event has been processed, and may have no valid value at all during processing! This can be mitigated with a variation on [the technique Michiel ended up using](https://stackoverflow.com/questions/121499/when-onblur-occurs-how-can-i-find-out-which-element-focus-went-to/128452#128452):
```
function showBlur(ev)
{
// Use timeout to delay examination of activeElement until after blur/focus
// events have been processed.
setTimeout(function()
{
var target = document.activeElement;
document.getElementById("focused").value =
target ? target.id||target.tagName||target : '';
}, 1);
}
```
This should work in most modern browsers (tested in Chrome, IE, and Firefox), with the caveat that Chrome does not set focus on buttons that are *clicked* (vs. tabbed to). |
121,511 | <p>I have inherited a poorly written web application that seems to have errors when it tries to read in an xml document stored in the database that has an "&" in it. For example there will be a tag with the contents: "Prepaid & Charge". Is there some secret simple thing to do to have it not get an error parsing that character, or am I missing something obvious? </p>
<p>EDIT:
Are there any other characters that will cause this same type of parser error for not being well formed?</p>
| [
{
"answer_id": 121529,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 2,
"selected": false,
"text": "<p>You can replace & with <code>&amp;</code></p>\n\n<p>Or you might also be able to use <a href=\"http://en.wikipe... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13593/"
] | I have inherited a poorly written web application that seems to have errors when it tries to read in an xml document stored in the database that has an "&" in it. For example there will be a tag with the contents: "Prepaid & Charge". Is there some secret simple thing to do to have it not get an error parsing that character, or am I missing something obvious?
EDIT:
Are there any other characters that will cause this same type of parser error for not being well formed? | The problem is the xml is not well-formed. Properly generated xml would list the data like this:
>
> `Prepaid & Charge`
>
>
>
I've fixed the same problem before, and I did it with this regex:
```
Regex badAmpersand = new Regex("&(?![a-zA-Z]{2,6};|#[0-9]{2,4};)");
```
Combine that with a string constant defined like this:
```
const string goodAmpersand = "&";
```
Now you can say `badAmpersand.Replace(<your input>, goodAmpersand);`
Note a simple `String.Replace("&", "&")` isn't good enough, since you can't know in advance for a given document whether any & characters will be coded correctly, incorrectly, or even both in the same document.
The catches here are you have to do this to your xml document *before* loading it into your parser, which likely means an extra pass through the document. Also, it does not account for ampersands inside of a CDATA section. Finally, it *only* catches ampersands, not other illegal characters like <. **Update:** based on the comment, I need to update the expression for hex-coded (&#x...;) entities as well.
Regarding which characters can cause problems, the actual rules are a little complex. For example, certain characters are allowed in data, but not as the first letter of an element name. And there's no simple list of illegal characters. Instead, large (non-contiguous) swaths of UNICODE are [defined as legal](http://www.w3.org/TR/REC-xml#charsets), and anything outside that is illegal.
When it comes down to it, you have to trust your document source to have at least a certain amount of compliance and consistency. For example, I've found people are often smart enough to make sure the tags work properly and escape <, even if they don't know that & isn't allowed, hence your problem today. However, **the best thing would be to get this fixed at the source.**
Oh, and a note about the CDATA suggestion: I use that to make sure xml *I'm creating* is well-formed, but when dealing with existing xml from outside, I find the regex method easier. |
121,521 | <p>I use the on-demand (hosted) version of FogBugz. I would like to start using Mercurial for source control. I would like to integrate FogBugz and a BitBucket repository.
I gave it a bit of a try but things weren't going very well. </p>
<p>FogBugz requires that you hook up your Mercurial client to a fogbugz.py python script. TortoiseHg doesn't seem to have the hgext directory that they refer to in instructions.</p>
<p>So has anyone successfully done something similar?</p>
| [
{
"answer_id": 123314,
"author": "Stefan Rusek",
"author_id": 19704,
"author_profile": "https://Stackoverflow.com/users/19704",
"pm_score": 4,
"selected": true,
"text": "<p>From the sounds of it you are wanting to run the hook on your local machine. The hook and directions are intended f... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20498/"
] | I use the on-demand (hosted) version of FogBugz. I would like to start using Mercurial for source control. I would like to integrate FogBugz and a BitBucket repository.
I gave it a bit of a try but things weren't going very well.
FogBugz requires that you hook up your Mercurial client to a fogbugz.py python script. TortoiseHg doesn't seem to have the hgext directory that they refer to in instructions.
So has anyone successfully done something similar? | From the sounds of it you are wanting to run the hook on your local machine. The hook and directions are intended for use on the central server.
If you are the only one working in your repository or don't mind commit not showing up in FB until after you do a pull, then you can add the hook locally to your primary clone, If you are using your primary clone then you need to do something slightly different from what they say here:
<http://bugs.movabletype.org/help/topics/sourcecontrol/setup/Mercurial.html>
You can put your fogbugz.py anywhere you want, just add a path line to your [fogbugz] section of that repositories hgrc file:
```
[fogbugz]
path=C:\Program Files\TortoiseHg\scripts\fogbugz.py
```
Just make sure you have python installed. you may also wish to add a commit hook so that local commits to the repository also get into FB.
```
[hooks]
commit=python:hgext.fogbugz.hook
incoming=python:hgext.fogbugz.hook
```
On the Fogbugz install you will want change put the following in your for your logs url:
```
^REPO/log/^R2/^FILE
```
and the following for your diff url:
```
^REPO/diff/^R2/^FILE
```
When the hook script runs it connects to your FB install and sends it a few parameters. These parameters are stored in the DB and used to generate urls for diffs and log informaiton. The script sends the url of repo, this is in your baseurl setting in the [web] section. You want this url to be the url to your bitbucket repository. This will be used to replace **^REPO** from the url templates above. The hook script also passes the revision id and the file name to FB. These will replace ^R2 and ^FILE. So in summary this is the stuff you want to add to the hgrc file in your .hg directory:
```
[extensions]
hgext.fogbugz=
[fogbugz]
path=C:\Program Files\TortoiseHg\scripts\fogbugz.py
host=https://<YOURACCOUNT>.fogbugz.com/
script=cvsSubmit.asp
[hooks]
commit=python:hgext.fogbugz.hook
incoming=python:hgext.fogbugz.hook
[web]
baseurl=http://www.bitbucket.org/<YOURBITBUCKETACCOUNT>/<YOURPROJECT>/
```
One thing to remember is that FB may get notified of a checkin before you actually push those changes to bitbucket. If this is the cause do a push and things will work.
EDIT: added section about the FB server and the summary. |
121,579 | <p>I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing. </p>
<blockquote>
<p>Error Message: Validation of
viewstate MAC failed. If this
application is hosted by a Web Farm or
cluster, ensure that configuration
specifies the same validationKey and
validation algorithm. AutoGenerate
cannot be used in a cluster.</p>
<p>Stack Trace: at
System.Web.UI.ViewStateException.ThrowError(Exception
inner, String persistedState, String
errorPageMessage, Boolean
macValidationError) at
System.Web.UI.ObjectStateFormatter.Deserialize(String
inputString) at
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String
serializedState) at
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter
formatter, String serializedState) at
System.Web.UI.HiddenFieldPageStatePersister.Load()
at
System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) at
System.Web.UI.Page.ProcessRequest()
at
System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext
context) at
System.Web.UI.Page.ProcessRequest(HttpContext
context) at
ASP.generic_aspx.ProcessRequest(HttpContext
context) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)</p>
<p>Source: System.Web</p>
</blockquote>
<p>Anybody have any ideas on how I could resolve this? Thanks.</p>
| [
{
"answer_id": 121583,
"author": "Chris Driver",
"author_id": 5217,
"author_profile": "https://Stackoverflow.com/users/5217",
"pm_score": 5,
"selected": true,
"text": "<p>I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded.</p>\n\n<p... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21165/"
] | I don't know if anyone has seen this issue before but I'm just stumped. Here's the unhandled exception message that my error page is capturing.
>
> Error Message: Validation of
> viewstate MAC failed. If this
> application is hosted by a Web Farm or
> cluster, ensure that configuration
> specifies the same validationKey and
> validation algorithm. AutoGenerate
> cannot be used in a cluster.
>
>
> Stack Trace: at
> System.Web.UI.ViewStateException.ThrowError(Exception
> inner, String persistedState, String
> errorPageMessage, Boolean
> macValidationError) at
> System.Web.UI.ObjectStateFormatter.Deserialize(String
> inputString) at
> System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String
> serializedState) at
> System.Web.UI.Util.DeserializeWithAssert(IStateFormatter
> formatter, String serializedState) at
> System.Web.UI.HiddenFieldPageStatePersister.Load()
> at
> System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
> at System.Web.UI.Page.LoadAllState()
> at
> System.Web.UI.Page.ProcessRequestMain(Boolean
> includeStagesBeforeAsyncPoint, Boolean
> includeStagesAfterAsyncPoint) at
> System.Web.UI.Page.ProcessRequest(Boolean
> includeStagesBeforeAsyncPoint, Boolean
> includeStagesAfterAsyncPoint) at
> System.Web.UI.Page.ProcessRequest()
> at
> System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext
> context) at
> System.Web.UI.Page.ProcessRequest(HttpContext
> context) at
> ASP.generic\_aspx.ProcessRequest(HttpContext
> context) at
> System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
> at
> System.Web.HttpApplication.ExecuteStep(IExecutionStep
> step, Boolean& completedSynchronously)
>
>
> Source: System.Web
>
>
>
Anybody have any ideas on how I could resolve this? Thanks. | I seem to recall that this error can occur if you click a button/link etc before the page has fully loaded.
If this is the case, the error is caused by an ASP.net 2.0 feature called Event Validation. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered
form tag, you'll see something like this:
```
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v.........tS" />
```
When a postback occurs, ASP.net uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception that you've been seeing.
The problem you're seeing happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.net cannot validate your click.
One work around is of course to just disable event validation, but you have to be aware of the security implications. Alternatively, just never post back before the form has finished rendering. Of course, that's hard to tell your users, but perhaps you could disable the UI until the form has rendered?
from <http://forums.asp.net/p/955145/1173230.aspx> |
121,581 | <p>In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar)</p>
| [
{
"answer_id": 121596,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT DATEADD(mm, DATEDIFF(mm, 0, @date), 0)\n</code></pre>\n"
},
{
"answer_id": 121602,
"auth... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8479/"
] | In SQL Server what is the simplest/cleanest way to make a datetime representing the first of the month based on another datetime? eg I have a variable or column with 3-Mar-2005 14:23 and I want to get 1-Mar-2005 00:00 (as a datetime, not as varchar) | ```
Select DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)
```
To run this on a column, replace GetDate() with your column name.
The trick to this code is with DateDiff. DateDiff returns an integer. The second parameter (the 0) represents the 0 date in SQL Server, which is Jan 1, 1900. So, the datediff calculates the integer number of months since Jan 1, 1900, then adds that number of months to Jan 1, 1900. The net effect is removing the day (and time) portion of a datetime value. |
121,605 | <p>What is the best way to reduce the size of the viewstate hidden field in JSF?
I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user. </p>
<p>My Environment JSF 1.2, MyFaces, Tomcat, Tomahawk, RichFaces</p>
| [
{
"answer_id": 121624,
"author": "David Waters",
"author_id": 12148,
"author_profile": "https://Stackoverflow.com/users/12148",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using MyFaces you can try this setting to compress the viewstate before sending to the client.</p>\n\n<... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12148/"
] | What is the best way to reduce the size of the viewstate hidden field in JSF?
I have noticed that my view state is approximately 40k this goes down to the client and back to the server on every request and response espically coming to the server this is a significant slowdown for the user.
My Environment JSF 1.2, MyFaces, Tomcat, Tomahawk, RichFaces | Have you tried setting the state saving to server? This should only send an id to the client, and keep the full state on the server. Simply add the following to the file *web.xml* :
```
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
``` |
121,631 | <p>Is there a difference in performance (in oracle) between</p>
<pre><code>Select * from Table1 T1
Inner Join Table2 T2 On T1.ID = T2.ID
</code></pre>
<p>And</p>
<pre><code>Select * from Table1 T1, Table2 T2
Where T1.ID = T2.ID
</code></pre>
<p>?</p>
| [
{
"answer_id": 121648,
"author": "Craig Trader",
"author_id": 12895,
"author_profile": "https://Stackoverflow.com/users/12895",
"pm_score": 6,
"selected": false,
"text": "<p>If the query optimizer is doing its job right, there should be no difference between those queries. They are just... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | Is there a difference in performance (in oracle) between
```
Select * from Table1 T1
Inner Join Table2 T2 On T1.ID = T2.ID
```
And
```
Select * from Table1 T1, Table2 T2
Where T1.ID = T2.ID
```
? | No! The same execution plan, look at these two tables:
```
CREATE TABLE table1 (
id INT,
name VARCHAR(20)
);
CREATE TABLE table2 (
id INT,
name VARCHAR(20)
);
```
The execution plan for the query using the inner join:
```
-- with inner join
EXPLAIN PLAN FOR
SELECT * FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.id;
SELECT *
FROM TABLE (DBMS_XPLAN.DISPLAY);
-- 0 select statement
-- 1 hash join (access("T1"."ID"="T2"."ID"))
-- 2 table access full table1
-- 3 table access full table2
```
And the execution plan for the query using a WHERE clause.
```
-- with where clause
EXPLAIN PLAN FOR
SELECT * FROM table1 t1, table2 t2
WHERE t1.id = t2.id;
SELECT *
FROM TABLE (DBMS_XPLAN.DISPLAY);
-- 0 select statement
-- 1 hash join (access("T1"."ID"="T2"."ID"))
-- 2 table access full table1
-- 3 table access full table2
``` |
121,656 | <p>I have the following string and I would like to remove <code><bpt *>*</bpt></code> and <code><ept *>*</ept></code> (notice the additional tag content inside them that also needs to be removed) without using a XML parser (overhead too large for tiny strings).</p>
<pre><code>The big <bpt i="1" x="1" type="bold"><b></bpt>black<ept i="1"></b></ept> <bpt i="2" x="2" type="ulined"><u></bpt>cat<ept i="2"></u></ept> sleeps.
</code></pre>
<p>Any regex in VB.NET or C# will do.</p>
| [
{
"answer_id": 121727,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 1,
"selected": false,
"text": "<p>I presume you want to drop the tag entirely?</p>\n\n<pre><code>(<bpt .*?>.*?</bpt>)|(<ept .*?>.*?</... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] | I have the following string and I would like to remove `<bpt *>*</bpt>` and `<ept *>*</ept>` (notice the additional tag content inside them that also needs to be removed) without using a XML parser (overhead too large for tiny strings).
```
The big <bpt i="1" x="1" type="bold"><b></bpt>black<ept i="1"></b></ept> <bpt i="2" x="2" type="ulined"><u></bpt>cat<ept i="2"></u></ept> sleeps.
```
Any regex in VB.NET or C# will do. | If you just want to remove all the tags from the string, use this (C#):
```
try {
yourstring = Regex.Replace(yourstring, "(<[be]pt[^>]+>.+?</[be]pt>)", "");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
```
EDIT:
I decided to add on to my solution with a better option. The previous option would not work if there were embedded tags. This new solution should strip all <\*\*pt\*> tags, embedded or not. In addition, this solution uses a back reference to the original [be] match so that the exact matching end tag is found. This solution also creates a reusable Regex object for improved performance so that each iteration does not have to recompile the Regex:
```
bool FoundMatch = false;
try {
Regex regex = new Regex(@"<([be])pt[^>]+>.+?</\1pt>");
while(regex.IsMatch(yourstring) ) {
yourstring = regex.Replace(yourstring, "");
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
```
ADDITIONAL NOTES:
In the comments a user expressed worry that the '.' pattern matcher would be cpu intensive. While this is true in the case of a standalone greedy '.', the use of the non-greedy character '?' causes the regex engine to only look ahead until it finds the first match of the next character in the pattern versus a greedy '.' which requires the engine to look ahead all the way to the end of the string. I use [RegexBuddy](http://www.regexbuddy.com/) as a regex development tool, and it includes a debugger which lets you see the relative performance of different regex patterns. It also auto comments your regexes if desired, so I decided to include those comments here to explain the regex used above:
```
// <([be])pt[^>]+>.+?</\1pt>
//
// Match the character "<" literally «<»
// Match the regular expression below and capture its match into backreference number 1 «([be])»
// Match a single character present in the list "be" «[be]»
// Match the characters "pt" literally «pt»
// Match any character that is not a ">" «[^>]+»
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the character ">" literally «>»
// Match any single character that is not a line break character «.+?»
// Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Match the characters "</" literally «</»
// Match the same text as most recently matched by backreference number 1 «\1»
// Match the characters "pt>" literally «pt>»
``` |
121,662 | <p>Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever. </p>
<p>So, I've thought about it, and I don't know where to start. I am sending comps out this week to my xhtml guy and I want to have the implementation done at least in my mind before I send things out. </p>
<p>Something about System.Drawing sounds about right, but I've never worked with that before and it sounds hella complicated. Does anyone have an idea? </p>
<p><strong>UPDATE:</strong> The color of an image will be changing. So if I want image 1 to be green, and image 2 to be blue, I go into my admin screen and enter those hex values (probably will give them an interface for it) and then when someone else looks at their page they will see the changes they made. Kind of like customizing a facebook or myspace page (OMFGz soooo Werb 2.0)</p>
| [
{
"answer_id": 121692,
"author": "Aaron Jensen",
"author_id": 11229,
"author_profile": "https://Stackoverflow.com/users/11229",
"pm_score": 1,
"selected": false,
"text": "<p>What exactly will be changing? Depending on what's changing you may be able to overlay a transparent png on top of... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever.
So, I've thought about it, and I don't know where to start. I am sending comps out this week to my xhtml guy and I want to have the implementation done at least in my mind before I send things out.
Something about System.Drawing sounds about right, but I've never worked with that before and it sounds hella complicated. Does anyone have an idea?
**UPDATE:** The color of an image will be changing. So if I want image 1 to be green, and image 2 to be blue, I go into my admin screen and enter those hex values (probably will give them an interface for it) and then when someone else looks at their page they will see the changes they made. Kind of like customizing a facebook or myspace page (OMFGz soooo Werb 2.0) | I'm sort of intuiting that you'll have a black on white bitmap that you use as the base image. The client can then select any other color combination. This may not be exactly your situation, but it should get us started. (The code below is VB -- it's what I know, but converting to C# should be trivial for you.)
```
Imports System.Drawing
Private Function createImage(ByVal srcPath As String, ByVal fg As Color, ByVal bg As Color) As Bitmap
Dim img As New Bitmap(srcPath)
For x As Int16 = 0 To img.Width
For y As Int16 = 0 To img.Height
If img.GetPixel(x, y) = Color.Black Then
img.SetPixel(x, y, fg)
Else
img.SetPixel(x, y, bg)
End If
Next
Next
Return img
End Function
```
And then you can do whatever with the image... |
121,665 | <p>How does one invoke a groovy method that prints to stdout, appending the output to a string?</p>
| [
{
"answer_id": 121776,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 5,
"selected": true,
"text": "<p>This demonstrates how you can do this. Paste this into a Groovy script file and run it. You will see the first call ... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How does one invoke a groovy method that prints to stdout, appending the output to a string? | This demonstrates how you can do this. Paste this into a Groovy script file and run it. You will see the first call functions as normal. The second call produces no results. Finally, the last step in the main prints the results of the second call that were redirected to a ByteArrayOutputStream.
Have fun!
```
void doSomething() {
println "i did something"
}
println "normal call\n---------------"
doSomething()
println ""
def buf = new ByteArrayOutputStream()
def newOut = new PrintStream(buf)
def saveOut = System.out
println "redirected call\n---------------"
System.out = newOut
doSomething()
System.out = saveOut
println ""
println "results of call\n---------------"
println buf.toString()
``` |
121,676 | <p>Inside a .NET 3.5 web app running impersonation I am trying to execute a process via:</p>
<pre><code>var process = new Process
{ StartInfo =
{ CreateNoWindow = true,
FileName = "someFileName",
Domain = "someDomain",
Username = "someUserName",
Password = securePassword,
UseShellExecute = false
}
};
process.Start();
</code></pre>
<p>-Changing the trust mode to full in web.config did not fix.</p>
<p>-Note the var securePassword is a secureString set up earlier in the code.</p>
<p>This throws an exception with 'Access is Denied' as its message. If I remove the username and password information, the exception goes away, but the process starts as aspnet_wp instead of the user I need it to.</p>
<p>I've seen this issue in multiple forums and never seen a solution provided.
Any ideas?</p>
| [
{
"answer_id": 121721,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into the same problem that you did on a project. There <em>should</em> be a way to spawn a process out of y... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Inside a .NET 3.5 web app running impersonation I am trying to execute a process via:
```
var process = new Process
{ StartInfo =
{ CreateNoWindow = true,
FileName = "someFileName",
Domain = "someDomain",
Username = "someUserName",
Password = securePassword,
UseShellExecute = false
}
};
process.Start();
```
-Changing the trust mode to full in web.config did not fix.
-Note the var securePassword is a secureString set up earlier in the code.
This throws an exception with 'Access is Denied' as its message. If I remove the username and password information, the exception goes away, but the process starts as aspnet\_wp instead of the user I need it to.
I've seen this issue in multiple forums and never seen a solution provided.
Any ideas? | You can use ProcessStartInfo which allows you to specify credentials. The trick is that the password is a secure string, so you have to pass it as a byte array.
The code might look something like:
```
Dim startInfo As New ProcessStartInfo(programName)
With startInfo
.Domain = "test.local"
.WorkingDirectory = My.Application.Info.DirectoryPath
.UserName = "testuser"
Dim pwd As New Security.SecureString
For Each c As Char In "password"
pwd.AppendChar(c)
Next
.Password = pwd
'If you provide a value for the Password property, the UseShellExecute property must be false, or an InvalidOperationException will be thrown when the Process..::.Start(ProcessStartInfo) method is called.
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Hidden
End With
``` |
121,700 | <p>In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.</p>
<p>My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?</p>
<p>Psuedocode:
(read, don't scrutinize the semantics of the code, I know it won't compile)</p>
<pre><code>public DataSet GetData(int identifier)
{
dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
DataSet ds = dataAdapter.Fill(ds);
if (ds.table1.Rows.Count == 0)
throw new Exception("Data not found");
return ds;
}
</code></pre>
| [
{
"answer_id": 121746,
"author": "Richard Yorkshire",
"author_id": 21001,
"author_profile": "https://Stackoverflow.com/users/21001",
"pm_score": 2,
"selected": false,
"text": "<p>As far as ADO.net is concerned, a query that returns zero rows is not an error. If your application wishes to... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15766/"
] | In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.
My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?
Psuedocode:
(read, don't scrutinize the semantics of the code, I know it won't compile)
```
public DataSet GetData(int identifier)
{
dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
DataSet ds = dataAdapter.Fill(ds);
if (ds.table1.Rows.Count == 0)
throw new Exception("Data not found");
return ds;
}
``` | The [MSDN guidelines](http://msdn.microsoft.com/en-us/library/ms229021(VS.80).aspx) state:
* Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.
* Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exceptions. Otherwise, throw one of the existing exceptions.
* Do not create and throw new exceptions just to have your team's exception.
There is no hard and fast rule: but if you have a scenario for treating this exception differently, consider creating a custom exception type, such as DataNotFoundException [as suggested by Johan Buret](https://stackoverflow.com/questions/121700/what-exception-should-be-thrown-when-an-adonet-query-cannot-retrieve-the-reques#121809).
Otherwise you might consider throwing one of the existing exception types, such as System.Data.DataException or possibly even System.Collections.Generic.KeyNotFoundException. |
121,715 | <p>Java Newbie here. I have a JFrame that I added to my netbeans project, and I've added the following method to it, which creates a JTable. Problem is, for some reason when I call this method, the JTable isn't displayed. Any suggestions?</p>
<pre><code>public void showFromVectors(Vector colNames, Vector data) {
jt = new javax.swing.JTable(data, colNames);
sp = new javax.swing.JScrollPane(jt);
//NB: "this" refers to my class DBGridForm, which extends JFrame
this.add(sp,java.awt.BorderLayout.CENTER);
this.setSize(640,480);
}
</code></pre>
<p>The method is called in the following context:</p>
<pre><code>DBGridForm gf = new DBGridForm(); //DBGridForm extends JFrame
DBReader.outMatchesTable(gf);
gf.setVisible(true);
</code></pre>
<p>... where DBReader.outMatchesTable() is defined as</p>
<pre><code>static public void outMatchesTable(DBGridForm gf) {
DBReader ddb = new DBReader();
ddb.readMatchesTable(null);
gf.showFromVectors(ddb.lastRsltColNames, ddb.lastRsltData);
}
</code></pre>
<p>My guess is I'm overlooking something, either about the swing classes I'm using, or about Java. Any ideas?</p>
| [
{
"answer_id": 121777,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 2,
"selected": true,
"text": "<p>\"this\" in your context is unclear. Is it inside an applet? a JFrame?</p>\n\n<p>You may be having a layout issue, make s... | 2008/09/23 | [
"https://Stackoverflow.com/questions/121715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11820/"
] | Java Newbie here. I have a JFrame that I added to my netbeans project, and I've added the following method to it, which creates a JTable. Problem is, for some reason when I call this method, the JTable isn't displayed. Any suggestions?
```
public void showFromVectors(Vector colNames, Vector data) {
jt = new javax.swing.JTable(data, colNames);
sp = new javax.swing.JScrollPane(jt);
//NB: "this" refers to my class DBGridForm, which extends JFrame
this.add(sp,java.awt.BorderLayout.CENTER);
this.setSize(640,480);
}
```
The method is called in the following context:
```
DBGridForm gf = new DBGridForm(); //DBGridForm extends JFrame
DBReader.outMatchesTable(gf);
gf.setVisible(true);
```
... where DBReader.outMatchesTable() is defined as
```
static public void outMatchesTable(DBGridForm gf) {
DBReader ddb = new DBReader();
ddb.readMatchesTable(null);
gf.showFromVectors(ddb.lastRsltColNames, ddb.lastRsltData);
}
```
My guess is I'm overlooking something, either about the swing classes I'm using, or about Java. Any ideas? | "this" in your context is unclear. Is it inside an applet? a JFrame?
You may be having a layout issue, make sure you've called setLayout on your class with a new borderlayout.
In a swing application, you'd want to use getRootContentPane().add() instead of a raw add(), depending on the version.
Java tutorial on adding top-level content: <http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html> |