Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
Is there a C# equivalent for the VB.NET `FormatNumber` function?
I.e.:
```
JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
```
|
In both C# and VB.NET you can use either the [.ToString()](http://www.java2s.com/Code/CSharp/Development-Class/UseToStringtoformatvalues.htm) function or the [String.Format()](http://www.java2s.com/Code/CSharp/Development-Class/UseStringFormattoformatavalue.htm) method to format the text.
Using the .ToString() method your example could be written as:
```
JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00")
```
Alternatively using the String.Format() it could written as:
```
JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate))
```
In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists.
Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required.
See "[String.Format("{0}", "formatting string"};](http://idunno.org/archive/2004/14/01/122.aspx)" or "[String Format for Int](http://www.csharp-examples.net/string-format-int/)" for more information and examples on how to use String.Format and the different formatting options.
|
Yes, the .ToString(string) methods.
For instance,
```
int number = 32;
string formatted = number.ToString("D4");
Console.WriteLine(formatted);
// Shows 0032
```
Note that in C# you don't use a number to specify a format, but you use a character or a sequence of characters.
Formatting numbers and dates in C# takes some minutes to learn, but once you understand the principle, you can quickly get anything you want from looking at the reference.
Here's a couple MSDN articles to get you started :
[Standard Numeric Format Strings](http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx)
[Formatting Types](http://msdn.microsoft.com/en-us/library/fbxft59x.aspx)
|
VB.NET FormatNumber equivalent in C#?
|
[
"",
"c#",
".net",
"vb.net",
""
] |
What modes are the best?
And any tips or tricks that make developing java in emacs a bit better.
|
For anything else than casual Java editing, many people recommend the [Java Development Environment for Emacs.](http://jdee.sourceforge.net/)
|
[Eclim](http://eclim.org/) is a project that uses eclipse running in headless mode to provide features to Emacs such as in-line error checking, auto import management, basic refactoring, etc.
It's much easier than JDEE to set up and when paired with something like YASnippet I find myself more productive than I was in Eclipse. I currently have to go back for step through debugging and some project management, but I am pretty happy with it. If combined with something like JDIbug I think I would have even less reason to ever use eclipse directly.
Hope this helps
|
What is the best way to do Java development in Emacs?
|
[
"",
"java",
"emacs",
""
] |
I want to implement a two-pass cache system:
* The first pass generates a PHP file, with all of the common stuff (e.g. news items), hardcoded. The database then has a cache table to link these with the pages (eg "index.php page=1 style=default"), the database also stores an uptodate field, which if false causes the first pass to rerun the next time the page is viewed.
* The second pass fills in the minor details, such as how long ago something(?) was, and mutable items like "You are logged in as...".
However I'm not sure on a efficient implementation, that supports both cached and non-cached (e.g., search) pages, without a lot of code and several queries.
Right now each time the page is loaded the PHP script is run regenerating the page. For pages like search this is fine, because most searches are different, but for other pages such as the index this is virtually the same for each hit, yet generates a large number of queries and is quite a long script.
The problem is some parts of the page do change on a per-user basis, such as the "You are logged in as..." section, so simply saving the generated pages would still result in 10,000's of nearly identical pages.
The main concern is with reducing the load on the server, since I'm on shared hosting and at this point can't afford to upgrade, but the site is using a sizeable portion of the servers CPU + putting a fair load on the MySQL server.
So basically minimising how much has to be done for each page request, and not regenerating stuff like the news items on the index all the time seems a good start, compared to say search which is a far less static page.
I actually considered hard coding the news items as plain HTML, but then that means maintaining them in several places (since they may be used for searches and the comments are on a page dedicated to that news item (i.e. news.php), etc).
|
I second Ken's rec of PEAR's [Cache\_Lite](http://pear.php.net/package/Cache_Lite) library, you can use it to easily cache either parts of pages or entire pages.
If you're running your own server(s), I'd strongly recommend [memcached](http://www.danga.com/memcached/) instead. It's much faster since it runs entirely in memory and is used extensively by a lot of high-volume sites. It's a very easy, stable, trouble-free daemon to run. In terms of your PHP code, you'd use it much the same way as Cache\_Lite, to cache various page sections or full pages (or other arbitrary blobs of data), and it's very easy to use since PHP has a [memcache interface built in](http://www.php.net/manual/en/intro.memcache.php).
For super high-traffic full-page caching, take a look at doing [Varnish](http://varnish.projects.linpro.no/) or [Squid](http://www.squid-cache.org/) as a caching reverse proxy server. (Pages that get served by Varnish are going to come out easily 100x faster than anything that hits the PHP interpreter.)
Keep in mind with caching, you really only need to cache things that are being frequently accessed. Sometimes it can be a trap to develop a really sophisticated caching strategy when you don't really need it. For a page like your home page that's getting hit several times a second, you definitely want to optimize it for speed; for a page that gets maybe a few hits an hour, like a month-old blog post, it's a bad idea to cache it, you only waste your time and make things more complicated and bug-prone.
|
I recommend to don't reinvent the wheel... there are some template engines that support caching, like [Smarty](http://www.smarty.net/)
|
Creating a two-pass PHP cache system with mutable items
|
[
"",
"php",
"caching",
""
] |
Everyone I talk to who knows (knew) about it claims it was the greatest thing since sliced bread. Why did it fail? Or, if it didn't fail, who's using it now?
|
Check out [GigaSpaces](http://www.gigaspaces.com). It's a quite successful Jini/Javaspaces implementation.
I think Jini has a great model, but it is stuck with Java. Web-services is more appealing because it works with standarized protocols, even though Jini service discovery is more natural.
|
Things have definitely quited down for the idea. Which is strange since you'd think its goals are even more relevant now.
<http://www.jini.org/wiki/Category:News>
|
Is JINI at all active anymore?
|
[
"",
"java",
"jini",
""
] |
I have a handful of projects that all use one project for the data model. Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it.
I'd like to have a modelContext.xml file and another for my ui.xml, etc.
Can I do this?
|
From the [Spring Docs (v 2.5.5 Section 3.2.2.1.)](http://static.springframework.org/spring/docs/2.5.5/reference/beans.html#beans-definition):
> It can often be useful to split up
> container definitions into multiple
> XML files. One way to then load an
> application context which is
> configured from all these XML
> fragments is to use the application
> context constructor which takes
> multiple Resource locations. With a
> bean factory, a bean definition reader
> can be used multiple times to read
> definitions from each file in turn.
>
> Generally, the Spring team prefers the
> above approach, since it keeps
> container configuration files unaware
> of the fact that they are being
> combined with others. An alternate
> approach is to use one or more
> occurrences of the element
> to load bean definitions from another
> file (or files). Let's look at a
> sample:
>
> ```
> <import resource="services.xml"/>
> <import resource="resources/messageSource.xml"/>
> <import resource="/resources/themeSource.xml"/>
>
> <bean id="bean1" class="..."/>
> <bean id="bean2" class="..."/>
> ```
>
> In this example, external bean
> definitions are being loaded from 3
> files, services.xml,
> messageSource.xml, and
> themeSource.xml. All location paths
> are considered relative to the
> definition file doing the importing,
> so services.xml in this case must be
> in the same directory or classpath
> location as the file doing the
> importing, while messageSource.xml and
> themeSource.xml must be in a resources
> location below the location of the
> importing file. As you can see, a
> leading slash is actually ignored, but
> given that these are considered
> relative paths, it is probably better
> form not to use the slash at all. The
> contents of the files being imported
> must be valid XML bean definition
> files according to the Spring Schema
> or DTD, including the top level
> element.
|
We do this in our projects at work, using the classpath\* resource loader in Spring. For a certain app, all appcontext files containing the application id will be loaded:
```
classpath*:springconfig/spring-appname-*.xml
```
|
Can I compose a Spring Configuration File from smaller ones?
|
[
"",
"java",
"spring",
""
] |
I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty.
Currently I'm doing something like this:
```
IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld");
if (hostEntry.AddressList.Count() < 1)
{
// can that ever happen?
throw new ArgumentException("hostName has no assigned IP-Address");
}
TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234);
```
My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that.
|
No, you'll not see an empty address list: even if you query a DNS label that does exist, but has no A or AAAA (IPv6) records, a SocketException ("No Such Host is Known") will be thrown.
You can verify this by looking at the function `InternalGetHostByName(string hostName, bool includeIPv6)` in DNS.cs from the .NET Reference Source release. With the exception of some platform-specific precautions, DNS lookups are a simple wrapper around the Winsock [gethostbyname](http://msdn.microsoft.com/en-us/library/ms738524.aspx) function.
Gethostbyname will either fail, or return an address list. An empty address list is never returned, because the function will fail with WSANO\_DATA ("Valid name, no data record of requested type") in this case, which translates to the socket exception we already saw in .NET.
*EDIT May 2012, prompted by responses stating that an empty list is returned anyway:* do note that this answer only applies to Win32, and that platforms like WinCE may behave quite differently. If you're seeing 'empty list' behavior on Win32, and the request you're making is against a publicly available DNS server, please post your code...
|
Just for the records.
Thanks to mdb's [accepted answer](https://stackoverflow.com/questions/156585/can-dnsgethostentry-ever-return-an-iphostentry-with-an-empty-addresslist#156638) I took a look at the [description of the WSANO\_DATA error](http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx):
> The requested name is valid and was found in the database, but it does
> not have the correct associated data being resolved for. The usual example
> for this is a host name-to-address translation attempt (using gethostbyname or
> WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record
> is returned but no A record—indicating the host itself exists, but is not
> directly reachable.
So this pretty much answers my question :)
|
Can Dns.GetHostEntry ever return an IPHostEntry with an empty AddressList?
|
[
"",
"c#",
"dns",
""
] |
We are using fmt:setBundle to load a resource bundle from a database (we extended the ResourceBundle class to do that).
When we modify a value in database, we have to reload the web server to display the new value on the web app.
Is there any simple way to use the new value without restarting the web server ?
(We do **not** want to always look up the value from database but we would like to invalidate the cache, for example by calling a special 'admin' URL)
EDIT : We are using JDK 1.4, so I would prefer a solution on that version. :)
|
As others have pointed out in the comments, you might want to look into Spring - particularly the [ReloadableResourceBundleMessageSource](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/support/ReloadableResourceBundleMessageSource.html).
|
If you're using JDK 1.6 you can use the callback methods `getTimeToLive()` and `needsReload()` in [ResourceBundle.Control](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.Control.html) to control if the bundle cache needs to be loaded with new values from the database.
|
In Java, how to reload dynamically resources bundles in a web application?
|
[
"",
"java",
"resources",
"resourcebundle",
""
] |
I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)
```
System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
```
What is the problem with my regular expression?
|
The problem is the space in the name of the capture. Remove the space and it works fine.
From the MSDN documentation:
"The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name')."
It does not matter if you use angle brackets <> or single quotes '' to indicate a group name.
|
The reference for the MSDN documentation mentioned by vengafoo is here:
[Regular Expression Grouping Constructs](http://msdn.microsoft.com/en-us/library/bs2twtah.aspx)
> **`(?<name> subexpression)`**
> Captures the matched subexpression into a group name or number name. The string used
> for name must not contain any punctuation and cannot begin with a
> number. **You can use single quotes instead of angle brackets; for example, (?'name').**
|
Invalid group name: Group names must begin with a word character
|
[
"",
"c#",
"regex",
"exception",
""
] |
I see `__all__` in `__init__.py` files. What does it do?
|
It's a list of public objects of that module, as interpreted by `import *`. It overrides the default of hiding everything that begins with an underscore.
|
Linked to, but not explicitly mentioned here, is exactly when `__all__` is used. It is a list of strings defining what symbols in a module will be exported when `from <module> import *` is used on the module.
For example, the following code in a `foo.py` explicitly exports the symbols `bar` and `baz`:
```
__all__ = ['bar', 'baz']
waz = 5
bar = 10
def baz(): return 'baz'
```
These symbols can then be imported like so:
```
from foo import *
print(bar)
print(baz)
# The following will trigger an exception, as "waz" is not exported by the module
print(waz)
```
If the `__all__` above is commented out, this code will then execute to completion, as the default behaviour of `import *` is to import all symbols that do not begin with an underscore, from the given namespace.
Reference: <https://docs.python.org/tutorial/modules.html#importing-from-a-package>
**NOTE:** `__all__` affects the `from <module> import *` behavior only. Members that are not mentioned in `__all__` are still accessible from outside the module and can be imported with `from <module> import <member>`.
|
What does __all__ mean in Python?
|
[
"",
"python",
"syntax",
"namespaces",
""
] |
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]
}
}
```
|
Here's a transliteration of Mat's implementation into C# for Lucene.NET, along with a snippet for wiring a text box using jQuery's autocomplete feature.
```
<input id="search-input" name="query" placeholder="Search database." type="text" />
```
... JQuery Autocomplete:
```
// don't navigate away from the field when pressing tab on a selected item
$( "#search-input" ).keydown(function (event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
});
$( "#search-input" ).autocomplete({
source: '@Url.Action("SuggestTerms")', // <-- ASP.NET MVC Razor syntax
minLength: 2,
delay: 500,
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = this.value.split(/\s+/);
terms.pop(); // remove dropdown item
terms.push(ui.item.value.trim()); // add completed item
this.value = terms.join(" ");
return false;
},
});
```
... here's the ASP.NET MVC Controller code:
```
//
// GET: /MyApp/SuggestTerms?term=something
public JsonResult SuggestTerms(string term)
{
if (string.IsNullOrWhiteSpace(term))
return Json(new string[] {});
term = term.Split().Last();
// Fetch suggestions
string[] suggestions = SearchSvc.SuggestTermsFor(term).ToArray();
return Json(suggestions, JsonRequestBehavior.AllowGet);
}
```
... and here's Mat's code in C#:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Store;
using Lucene.Net.Index;
using Lucene.Net.Search;
using SpellChecker.Net.Search.Spell;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Analysis.NGram;
using Lucene.Net.Documents;
namespace Cipher.Services
{
/// <summary>
/// Search term auto-completer, works for single terms (so use on the last term of the query).
/// Returns more popular terms first.
/// <br/>
/// Author: Mat Mannion, M.Mannion@warwick.ac.uk
/// <seealso cref="http://stackoverflow.com/questions/120180/how-to-do-query-auto-completion-suggestions-in-lucene"/>
/// </summary>
///
public class SearchAutoComplete {
public int MaxResults { get; set; }
private class AutoCompleteAnalyzer : Analyzer
{
public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
{
TokenStream result = new StandardTokenizer(kLuceneVersion, reader);
result = new StandardFilter(result);
result = new LowerCaseFilter(result);
result = new ASCIIFoldingFilter(result);
result = new StopFilter(false, result, StopFilter.MakeStopSet(kEnglishStopWords));
result = new EdgeNGramTokenFilter(
result, Lucene.Net.Analysis.NGram.EdgeNGramTokenFilter.DEFAULT_SIDE,1, 20);
return result;
}
}
private static readonly Lucene.Net.Util.Version kLuceneVersion = Lucene.Net.Util.Version.LUCENE_29;
private static readonly String kGrammedWordsField = "words";
private static readonly String kSourceWordField = "sourceWord";
private static readonly String kCountField = "count";
private static readonly String[] kEnglishStopWords = {
"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 readonly Directory m_directory;
private IndexReader m_reader;
private IndexSearcher m_searcher;
public SearchAutoComplete(string autoCompleteDir) :
this(FSDirectory.Open(new System.IO.DirectoryInfo(autoCompleteDir)))
{
}
public SearchAutoComplete(Directory autoCompleteDir, int maxResults = 8)
{
this.m_directory = autoCompleteDir;
MaxResults = maxResults;
ReplaceSearcher();
}
/// <summary>
/// Find terms matching the given partial word that appear in the highest number of documents.</summary>
/// <param name="term">A word or part of a word</param>
/// <returns>A list of suggested completions</returns>
public IEnumerable<String> SuggestTermsFor(string term)
{
if (m_searcher == null)
return new string[] { };
// get the top terms for query
Query query = new TermQuery(new Term(kGrammedWordsField, term.ToLower()));
Sort sort = new Sort(new SortField(kCountField, SortField.INT));
TopDocs docs = m_searcher.Search(query, null, MaxResults, sort);
string[] suggestions = docs.ScoreDocs.Select(doc =>
m_reader.Document(doc.Doc).Get(kSourceWordField)).ToArray();
return suggestions;
}
/// <summary>
/// Open the index in the given directory and create a new index of word frequency for the
/// given index.</summary>
/// <param name="sourceDirectory">Directory containing the index to count words in.</param>
/// <param name="fieldToAutocomplete">The field in the index that should be analyzed.</param>
public void BuildAutoCompleteIndex(Directory sourceDirectory, String fieldToAutocomplete)
{
// build a dictionary (from the spell package)
using (IndexReader sourceReader = IndexReader.Open(sourceDirectory, true))
{
LuceneDictionary dict = new LuceneDictionary(sourceReader, fieldToAutocomplete);
// code from
// org.apache.lucene.search.spell.SpellChecker.indexDictionary(
// Dictionary)
//IndexWriter.Unlock(m_directory);
// use a custom analyzer so we can do EdgeNGramFiltering
var analyzer = new AutoCompleteAnalyzer();
using (var writer = new IndexWriter(m_directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED))
{
writer.MergeFactor = 300;
writer.SetMaxBufferedDocs(150);
// go through every word, storing the original word (incl. n-grams)
// and the number of times it occurs
foreach (string word in dict)
{
if (word.Length < 3)
continue; // too short we bail but "too long" is fine...
// ok index the word
// use the number of documents this word appears in
int freq = sourceReader.DocFreq(new Term(fieldToAutocomplete, word));
var doc = MakeDocument(fieldToAutocomplete, word, freq);
writer.AddDocument(doc);
}
writer.Optimize();
}
}
// re-open our reader
ReplaceSearcher();
}
private static Document MakeDocument(String fieldToAutocomplete, string word, int frequency)
{
var doc = new Document();
doc.Add(new Field(kSourceWordField, word, Field.Store.YES,
Field.Index.NOT_ANALYZED)); // orig term
doc.Add(new Field(kGrammedWordsField, word, Field.Store.YES,
Field.Index.ANALYZED)); // grammed
doc.Add(new Field(kCountField,
frequency.ToString(), Field.Store.NO,
Field.Index.NOT_ANALYZED)); // count
return doc;
}
private void ReplaceSearcher()
{
if (IndexReader.IndexExists(m_directory))
{
if (m_reader == null)
m_reader = IndexReader.Open(m_directory, true);
else
m_reader.Reopen();
m_searcher = new IndexSearcher(m_reader);
}
else
{
m_searcher = null;
}
}
}
}
```
|
How to do query auto-completion/suggestions in Lucene?
|
[
"",
"java",
"autocomplete",
"lucene",
""
] |
As a temporary quick fix to mitigate the major risk while working on the permanent fix for XSS Vulnerability in a very large code base, I'm looking for a pre-existing XSS prevention blacklist that does a reasonable job of protecting against XSS.
Preferably a set of Regular Expressions. I'm aware of plenty of cheat sheets for testing and smoke tests etc, what I'm looking for is pre-tuned regexps for blocking the attacks.
I am fully aware that the best way is [output escaping](https://stackoverflow.com/questions/71328/what-are-the-best-practices-for-avoid-xss-attacks-in-a-php-site#71444) or if you need some markup from users to use whitelisting. But, with the size of the code base, we need something in quick to reduce the immediate footprint of the vulnerability and raise the bar whilst working on the real solution.
Is anyone aware of a good set?
|
I realise this may not be a direct answer to your question, but ASP.NET developers in a similar situation may find this useful:
[Microsoft Anti-Cross Site Scripting Library V1.5](http://www.microsoft.com/downloads/details.aspx?FamilyId=EFB9C819-53FF-4F82-BFAF-E11625130C25&displaylang=en)
> This library differs from most encoding libraries in that it uses the "principle of inclusions" technique to provide protection against XSS attacks. This approach works by first defining a valid or allowable set of characters, and encodes anything outside this set (invalid characters or potential attacks). The principle of inclusions approach provides a high degree of protection against XSS attacks and is suitable for Web applications with high security requirements.
|
Here is one: <http://ha.ckers.org/xss.html> but i don't know if it's complete.
CAL9000 is another list where you could find something like that.
|
XSS Blacklist - Is anyone aware of a reasonable one?
|
[
"",
"javascript",
"html",
"security",
"xss",
""
] |
I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from.
Is this possible?
|
Yes. This can be done using the DataGridViewComboBoxCell.
Here is an example method to add the items to just one cell, rather than the whole column.
```
private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd)
{
DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex];
// You might pass a boolean to determine whether to clear or not.
dgvcbc.Items.Clear();
foreach (object itemToAdd in itemsToAdd)
{
dgvcbc.Items.Add(itemToAdd);
}
}
```
|
```
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == DataGridViewComboBoxColumnNumber)
{
setCellComboBoxItems(myDataGridView, e.RowIndex, e.ColumnIndex, someObj);
}
}
```
|
DataGridViewComboBoxColumn adding different items to each row .
|
[
"",
"c#",
"winforms",
"datagridview",
""
] |
How can I set the background color of a specific item in a *System.Windows.Forms.ListBox*?
I would like to be able to set multiple ones if possible.
|
Probably the only way to accomplish that is to draw the items yourself.
Set the `DrawMode` to `OwnerDrawFixed` and code something like this on the DrawItem event:
```
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Graphics g = e.Graphics;
g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);
// Print text
e.DrawFocusRectangle();
}
```
The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).
|
Thanks for the [answer by Grad van Horck](https://stackoverflow.com/a/91758/447356). It guided me in the correct direction.
To support text (not just background color), here is my fully working code:
```
//global brushes with ordinary/selected colors
private SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.White);
private SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
private SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.White);
private SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Gray);
//custom method to draw the items, don't forget to set DrawMode of the ListBox to OwnerDrawFixed
private void lbReports_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
int index = e.Index;
if (index >= 0 && index < lbReports.Items.Count)
{
string text = lbReports.Items[index].ToString();
Graphics g = e.Graphics;
//background:
SolidBrush backgroundBrush;
if (selected)
backgroundBrush = reportsBackgroundBrushSelected;
else if ((index % 2) == 0)
backgroundBrush = reportsBackgroundBrush1;
else
backgroundBrush = reportsBackgroundBrush2;
g.FillRectangle(backgroundBrush, e.Bounds);
//text:
SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
g.DrawString(text, e.Font, foregroundBrush, lbReports.GetItemRectangle(index).Location);
}
e.DrawFocusRectangle();
}
```
The above adds to the given code and will show the proper text plus highlight the selected item.
|
Background color of a ListBox item (Windows Forms)
|
[
"",
"c#",
"winforms",
"listbox",
"colors",
""
] |
I have inherited a project that uses LLBLGen Pro for the DB layer. The DB model requires that when a entry is deleted a flag (DeletedDate is set to the current time). The last programmer ignored this requirement and has used regular deletes throughout the entire application.
Is there a way to set the code generator to do this automatically or do I have to overload each delete operator for the Entities that requires it?
|
I implemented this in SQL Server 2005 using INSTEAD OF triggers on delete for any soft delete table. The triggers set the delete flag and perform clean-up. The beauty of this solution is that it correctly handles deletes issued by any system that accesses the database. INSTEAD OF is relatively new in SQL Server, I know there's an Oracle equivalent.
This solution also plays nicely with our O/R mapper -- I created views that filter out soft deleted records and mapped those. The views are also used for all reporting.
|
You could create custom task in LLBLGen that would override those for you when you are generating entities. Check out their template studio and template examples on the website.
|
LLBLGen: How can I softdelete a entry
|
[
"",
"c#",
"llblgenpro",
""
] |
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...
}
};
```
|
Probably this one here:
```
node instanceof HTMLElement
```
That should work in most browsers. Otherwise you have to duck-type it (eg. `typeof x.nodeType != 'undefined'`)
|
What's the best way to detect if a given Javascript object is a DOM Element?
|
[
"",
"javascript",
"dom",
"cross-browser",
""
] |
In other words, is it correct to use:
```
public class CustomerList : System.Collections.Generic.List<Customer>
{
/// supposed to be empty
}
```
instead of:
```
using CustomerList = System.Collections.Generic.List<Customer>
```
I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.
Please note that the intention in this case would never be to extend the class, just to create an alias.
|
Don't do it. When people read:
```
List<Customer>
```
they immediately understand it. When they read:
```
CustomerList
```
they have to go and figure out what a CustomerList is, and that makes your code harder to read. Unless you are the only one working on your codebase, writing readable code is a good idea.
|
well, unless you are adding some functionality to the base class there is no point in creating a wrapper object. I would go with number two if you really need to, but why not just create a variable?
```
List<Customer> customerList = new List<Customer>();
```
|
Is it correct to use inheritance instead of name aliasing in c#?
|
[
"",
"c#",
"inheritance",
"alias",
"typedef",
""
] |
I am wanting to find the distance between two different points. This I know can be accomplished with the great circle distance.
<http://www.meridianworlddata.com/Distance-calculation.asp>
Once done, with a point and distance I would like to find the point that distance north, and that distance east in order to create a box around the point.
|
We've had some success using [OpenMap](http://openmap-java.org/) to plot a lot of positional data. There's a [LatLonPoint](http://openmap-java.org/api/com/bbn/openmap/proj/coords/LatLonPoint.html) class that has some basic functionality, including distance.
|
Here is a Java implementation of [Haversine](http://en.wikipedia.org/wiki/Haversine_formula) formula. I use this in a project to calculate distance in miles between lat/longs.
```
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75; // miles (or 6371.0 kilometers)
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
* Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
return dist;
}
```
|
How can I measure distance and create a bounding box based on two latitude+longitude points in Java?
|
[
"",
"java",
"geocoding",
"latitude-longitude",
""
] |
I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing.
|
```
select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual;
```
Give the time in 24 hour format.
More options are described [here](http://www.oradev.com/oracle_date_format.jsp).
|
If you want all queries in your session to show the full datetime, then do
```
alter session set NLS_DATE_FORMAT='DD/MM/YYYY HH24:MI:SS'
```
at the start of your session.
|
How can I get Datetime to display in military time in oracle?
|
[
"",
"sql",
"oracle",
""
] |
How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0).
I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.
|
```
using System.IO;
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady && d.DriveType == DriveType.Removable)
{
// This is the drive you want...
}
}
```
The DriveInfo class documentation is here:
<http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx>
|
this is VB.NET code to check for any removable drives or CDRom drives attached to the computer:
```
Me.lstDrives.Items.Clear()
For Each item As DriveInfo In My.Computer.FileSystem.Drives
If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then
Me.lstDrives.Items.Add(item.Name)
End If
Next
```
it won't be that hard to modify this code into a c# equivalent, and more *driveType*'s are available.
[From MSDN:](http://msdn.microsoft.com/en-us/library/system.io.drivetype.aspx)
* **Unknown:** The type of drive is unknown.
* **NoRootDirectory:** The drive does not have a root directory.
* **Removable:** The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
* **Fixed:** The drive is a fixed disk.
* **Network:** The drive is a network drive.
* **CDRom:** The drive is an optical disc device, such as a CD or DVD-ROM.
* **Ram:** The drive is a RAM disk.
|
How to discover USB storage devices and writable CD/DVD drives (C#)
|
[
"",
"c#",
".net-2.0",
""
] |
I am looking for an open-source project involving c++ GUI(s) working with a database. I have not done it before, and am looking for a way to get my feet wet. Which can I work on?
|
How about this one <http://sourceforge.net/projects/sqlitebrowser/>:
> SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface.
|
Do a project you can get **involved** in and passionate about. Hopefully a product you use every day.
|
Which open-source C++ database GUI project should I help with?
|
[
"",
"c++",
"database",
"qt",
"open-source",
"qt4",
""
] |
How can I specify the filename when dumping data into the response stream?
Right now I'm doing the following:
```
byte[] data= GetFoo();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();
```
With the code above, I get "foo.aspx.pdf" as the filename to save. I seem to remember being able to add a header to the response to specify the filename to save.
|
Add a content-disposition to the header:
```
Response.AddHeader("content-disposition", @"attachment;filename=""MyFile.pdf""");
```
|
FYI... if you use "inline" instead of "attachment" the file will open automatically in IE. Instead of prompting the user with a Open/Save dialogue.
```
Response.AppendHeader("content-disposition", string.Format("inline;FileName=\"{0}\"", fileName));
```
|
Specifying filename for dynamic PDF in asp.net
|
[
"",
"c#",
"asp.net",
"response",
""
] |
Is it a good idea for me to use Qt Jambi in Java as a toolkit?
I see that Qt Jambi is hard to learn, and Swing is easier than Qt Jambi, but I think that Qt Jambi is more powerful.
|
Two years ago, I started a Java Desktop Application and used Swing as a GUI framweork. Up to that point, I had experience with C++/MFC (*shudder*) and C++/Qt (*very nice*).
After trying to get along with Swing for a while (including reading lots of tutorials and even a book) I came to the following conclusion:
**Swing is much more difficult and clumsy than Qt for three reasons:**
1. A lot of simple stuff requires more code than it should.
2. Some things that Qt brings for free are almost impossible to achieve in a reasonable amount of time.
3. Swing doesn't bring a WYSIWYG GUI Editor and I could not find a free one that comes close to Qt's Designer.
I then threw away the Swing GUI, switched to Qt Jambi and was really impressed by it. One weekend later I had a nice Qt GUI and lived happily ever after.
|
If you think being familiar with Qt would be useful in the future, when you might want to develop in C++ (or change some Qt-based software), I think it would be nice.
|
Should I use Qt Jambi in Java?
|
[
"",
"java",
"user-interface",
"qt",
"qt-jambi",
""
] |
How do I initialize an automatic download of a file in Internet Explorer?
For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads.
In Firefox this is easy, you just need to include a meta tag in the header, `<meta http-equiv="Refresh" content="n;url">` where n is the number of seconds and `url` is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?
|
[SourceForge](http://en.wikipedia.org/wiki/SourceForge) uses an `<iframe>` element with the `src=""` attribute pointing to the file to download.
```
<iframe width="1" height="1" frameborder="0" src="[File location]"></iframe>
```
(Side effect: no redirect, no JavaScript, original URL remains unchanged.)
|
I *hate* when sites complicate download so much and [use hacks instead of a good old link](http://adactio.com/journal/6022/).
### Dead simple version:
```
<a href="file.zip">Start automatic download!</a>
```
It works! In every browser!
---
If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a `download` attribute that forces download of the file. It also allows you to override filename ([although there is a better way to do it](https://stackoverflow.com/a/216777/27009)):
```
<a href="report-generator.php" download="result.xls">Download</a>
```
### Version with a "thanks" page:
If you want to display "thanks" after download, then use:
```
<a href="file.zip"
onclick="if (event.button==0)
setTimeout(function(){document.body.innerHTML='thanks!'},500)">
Start automatic download!
</a>
```
Function in that `setTimeout` might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch `window.location` or activate other links).
The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets `:visited` color, doesn't re-download if page is left open after browser restart, etc.
[That's what I use for ImageOptim](https://imageoptim.com)
|
How to start automatic download of a file in Internet Explorer?
|
[
"",
"javascript",
"html",
"internet-explorer",
"meta-tags",
""
] |
Do you have a common base class for Hibernate entities, i.e. a MappedSuperclass with id, version and other common properties? Are there any drawbacks?
Example:
```
@MappedSuperclass()
public class BaseEntity {
private Long id;
private Long version;
...
@Id @GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
@Version
public Long getVersion() {return version;}
...
// Common properties
@Temporal(TemporalType.TIMESTAMP)
public Date creationDate() {return creationDate;}
...
}
@Entity
public class Customer extends BaseEntity {
private String customerName;
...
}
```
|
This works fine for us. As well as the ID and creation date, we also have a modified date. We also have an intermediate *TaggedBaseEntity* that implements a *Taggable* interface, because some of our web application's entities have tags, like questions on Stack Overflow.
|
The one that I use is primarily to implement hashCode() and equals(). I also added a method to pretty print the entity. In response to DR above, most of this can be overridden, but in my implementation you are stuck with an ID of type Long.
```
public abstract class BaseEntity implements Serializable {
public abstract Long getId();
public abstract void setId(Long id);
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
return result;
}
/**
* @see java.lang.Object#equals(Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseEntity other = (BaseEntity) obj;
if (getId() == null) {
if (other.getId() != null)
return false;
} else if (!getId().equals(other.getId()))
return false;
return true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new StringBuilder(getClass().getSimpleName()).append(":").append(getId()).toString();
}
/**
* Prints complete information by calling all public getters on the entity.
*/
public String print() {
final String EQUALS = "=";
final String DELIMITER = ", ";
final String ENTITY_FORMAT = "(id={0})";
StringBuffer sb = new StringBuffer("{");
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(this);
PropertyDescriptor property = null;
int i = 0;
while ( i < properties.length) {
property = properties[i];
sb.append(property.getName());
sb.append(EQUALS);
try {
Object value = PropertyUtils.getProperty(this, property.getName());
if (value instanceof BaseEntity) {
BaseEntity entityValue = (BaseEntity) value;
String objectValueString = MessageFormat.format(ENTITY_FORMAT, entityValue.getId());
sb.append(objectValueString);
} else {
sb.append(value);
}
} catch (IllegalAccessException e) {
// do nothing
} catch (InvocationTargetException e) {
// do nothing
} catch (NoSuchMethodException e) {
// do nothing
}
i++;
if (i < properties.length) {
sb.append(DELIMITER);
}
}
sb.append("}");
return sb.toString();
}
}
```
|
Do you have a common base class for Hibernate entities?
|
[
"",
"java",
"hibernate",
"entities",
"base-class",
""
] |
Once I've created a variable in the immediate window in C# (VS2008), is there any way to delete it so I can create a new variable with the same name but a different type? Apart from restarting the program that is.
The reason would be to keep the immediate window's namespace clean, since it's difficult to keep track of variable declarations once they scroll off the visible part of the window.
|
I don't think it is possible to do what you are asking.
|
You could make a dictionary to hold your immediate window "variables". Then you can remove items from the dictionary when you're done with them.
|
Delete variables in immediate window in C#
|
[
"",
"c#",
""
] |
I have a function in Python which is iterating over the attributes returned from `dir(obj)`, and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use `callable()` for this, but I don't want to include classes. The best I've come up with so far is:
```
isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))
```
Is there a more future-proof way to do this check?
**Edit:** I misspoke before when I said: "Normally you could use `callable()` for this, but I don't want to disqualify classes." I actually *do* want to disqualify classes. I want to match *only* functions, not classes.
|
The inspect module has exactly what you want:
```
inspect.isroutine( obj )
```
FYI, the code is:
```
def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object))
```
|
If you want to exclude classes and other random objects that may have a `__call__` method, and only check for functions and methods, these three functions in the [`inspect` module](http://docs.python.org/lib/module-inspect.html)
```
inspect.isfunction(obj)
inspect.isbuiltin(obj)
inspect.ismethod(obj)
```
should do what you want in a future-proof way.
|
Is there a common way to check in Python if an object is any function type?
|
[
"",
"python",
"types",
""
] |
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.
|
```
$a = array( 'Кръстев', 'Делян1', 'делян1', 'Делян2', 'делян3', 'кръстев' );
$col = new \Collator('bg_BG');
$col->asort( $a );
var_dump( $a );
```
Prints:
```
array
2 => string 'делян1' (length=11)
1 => string 'Делян1' (length=11)
3 => string 'Делян2' (length=11)
4 => string 'делян3' (length=11)
5 => string 'кръстев' (length=14)
0 => string 'Кръстев' (length=14)
```
The `Collator` class is defined in [PECL intl extension](http://www.php.net/manual/en/book.intl.php). It is distributed with PHP 5.3 sources but might be disabled for some builds. E.g. in Debian it is in package php5-intl .
`Collator::compare` is useful for `usort`.
|
How to sort an array of UTF-8 strings?
|
[
"",
"php",
"arrays",
"sorting",
"utf-8",
""
] |
Which browsers other than Firefox support Array.forEach()? [Mozilla say it's an extension to the standard](http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach#Compatibility) and I realise it's trivial to add to the array prototype, I'm just wondering what other browsers support it?
|
The [JavaScript](http://en.wikipedia.org/wiki/JavaScript "JavaScript - Wikipedia, the free encyclopedia") article of Wikipedia lists the JS versions by browser. forEach is [part of JavaScript 1.6](http://developer.mozilla.org/en/New_in_JavaScript_1.6 "New in JavaScript 1.6"). So it is supported indeed by most browsers, except Opera 9.02 (which I just tested). Opera 9.5 (which I just installed!) supports it, along with indexOf for Array.
Surprisingly, it is not official. I don't see its support in the page [ECMAScript support in Opera 9.5](http://www.opera.com/docs/specs/opera95/js/ecma/). Perhaps it is an overlook or perhaps only a partial support they don't want to advertise.
|
I just checked this for another question: [JavaScript for...in vs for](https://stackoverflow.com/questions/242841/javascript-foreach-vs-for/6442930#6442930).
On kangax's [ECMAScript 5 compatibility table](http://kangax.github.com/es5-compat-table/), Array.forEach gets a 'yes' for all browsers except IE8.
As of September 2011, IE browser share on desktop devices is [less than 40%](http://en.wikipedia.org/wiki/Usage_share_of_web_browsers#Summary_table), and [at least 8% of browsers are IE 9](http://marketshare.hitslink.com/browser-market-share.aspx?qprid=2&qpcustomd=0).
In other words, Array.forEach is now supported by around 70% of desktop browsers. Obviously, this figure varies considerably, depending on territory and other factors -- some regions or countries (such as Brasil) have a higher proportion of Chrome users, for example, and some (such as China) have far more users on IE6 and IE8.
I haven't checked, but mobile support (on WebKit and Opera browsers) may be even higher.
|
Which web browsers natively support Array.forEach()
|
[
"",
"javascript",
"cross-browser",
""
] |
In my environment here I use Java to serialize the result set to XML.
It happens basically like this:
```
//foreach column of each row
xmlHandler.startElement(uri, lname, "column", attributes);
String chars = rs.getString(i);
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endElement(uri, lname, "column");
```
The XML looks like this in Firefox:
```
<row num="69004">
<column num="1">10069</column>
<column num="2">sd</column>
<column num="3">FCVolume </column>
</row>
```
But when I parse the XML I get the a
> org.xml.sax.SAXParseException: Character reference "****" is an
> invalid XML character.
My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?
|
I found an interesting list in the [Xml Spec](http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets):
According to that List its discouraged to use the Character #26 (Hex: *#x1A*).
> The characters defined in the
> following ranges are also discouraged.
> They are either control characters or
> permanently undefined Unicode
> characters
See the [complete ranges](http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets).
This code replaces all non-valid Xml Utf8 from a String:
```
public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer(); // Used to hold the output.
char current; // Used to reference the current character.
if (in == null || ("".equals(in))) return ""; // vacancy test.
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i);
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF)))
out.append(current);
}
return out.toString();
}
```
its taken from [Invalid XML Characters: when valid UTF8 does not mean valid XML](http://cse-mjmcl.cse.bris.ac.uk/blog/2007/02/14/1171465494443.html)
But with that I had the still UTF-8 compatility issue:
```
org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence
```
After reading [XML - returning XML as UTF-8 from a servlet](http://www.velocityreviews.com/forums/t166758-returning-xml-as-utf8-from-a-servlet.html) I just tried out what happens if I set the Contenttype like this:
```
response.setContentType("text/xml;charset=utf-8");
```
And it worked ....
|
[Extensible Markup Language (XML) 1.0](http://www.w3.org/TR/REC-xml/#syntax) says:
> The ampersand character (&) and the
> left angle bracket (<) must not appear
> in their literal form, except when
> used as markup delimiters, or within a
> comment, a processing instruction, or
> a CDATA section. If they are needed
> elsewhere, they must be escaped using
> either numeric character references or
> the strings "&" and "<"
> respectively. The right angle bracket
> (>) may be represented using the
> string ">", and must, for
> compatibility, be escaped using either
> ">" or a character reference when
> it appears in the string "]]>" in
> content, when that string is not
> marking the end of a CDATA section.
You can skip the encoding if you use CDATA:
```
<column num="1"><![CDATA[10069]]></column>
<column num="2"><![CDATA[sd&]]></column>
```
|
How to encode characters from Oracle to XML?
|
[
"",
"java",
"xml",
"oracle",
"encoding",
""
] |
If I hit a page which calls `session_start()`, how long would I have to wait before I get a new session ID when I refresh the page?
|
Check out php.ini the value set for session.gc\_maxlifetime is the ID lifetime in seconds.
I believe the default is 1440 seconds (24 mins)
<http://www.php.net/manual/en/session.configuration.php>
**Edit:** As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here:
[How do I expire a PHP session after 30 minutes?](https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes)
|
The default in the php.ini for the `session.gc_maxlifetime` directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:
<http://www.php.net/manual/en/session.configuration.php>
You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:
```
php_value session.gc_maxlifetime "3600"
```
Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they *should* be kept). See the [note](http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime) on the manual page or [this site](https://web.archive.org/web/20130303043400/https://www.leftontheweb.com/message/php-session-expiry) for a better explanation.
The answer to this is to move your sessions to another directory using session.save\_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.
|
What is the default lifetime of a session?
|
[
"",
"php",
"session",
""
] |
I'm having a problem with my Seam code and I can't seem to figure out what I'm doing wrong. It's doing my head in :) Here's an excerpt of the stack trace:
```
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field com.oobjects.sso.manager.home.PresenceHome.customerId to java.lang.String
```
I'm trying to get a parameter set on my URL passed into one of my beans. To do this, I've got the following set up in my pages.xml:
```
<page view-id="/customer/presences.xhtml">
<begin-conversation flush-mode="MANUAL" join="true" />
<param name="customerId" value="#{presenceHome.customerId}" />
<raise-event type="PresenceHome.init" />
<navigation>
<rule if-outcome="persisted">
<end-conversation />
<redirect view-id="/customer/presences.xhtml" />
</rule>
</navigation>
</page>
```
My bean starts like this:
```
@Name("presenceHome")
@Scope(ScopeType.CONVERSATION)
public class PresenceHome extends EntityHome<Presence> implements Serializable {
@In
private CustomerDao customerDao;
@In(required = false)
private Long presenceId;
@In(required = false)
private Long customerId;
private Customer customer;
// Getters, setters and other methods follow. They return the correct types defined above
}
```
Finally the link I use to link one one page to the next looks like this:
```
<s:link styleClass="#{selected == 'presences' ? 'selected' : ''}"
view="/customer/presences.xhtml" title="Presences" propagation="none">
<f:param name="customerId" value="#{customerId}" />
Presences
</s:link>
```
All this seems to work fine. When I hover over the link above in my page, I get a URL ending in something like "?customerId=123". So the parameter is being passed over and it's something that can be easily converted into a Long type. But for some reason, it's not. I've done similar things to this before in other projects and it's worked then. I just can't see what it isn't working now.
If I remove the element from my page declaration, I get through to the page fine.
So, does anyone have any thoughts?
|
You want to add a converter to your pages.xml file. Like this:
```
<param name="customerId"
value="#{presenceHome.customerId}"
converterId="javax.faces.Long" />
```
See the seampay example provided with seam for more details.
|
try:
...
`<f:param name="customerId" value="#{customerId.toString()}" />`
...
|
Seam Problem: Could not set field value by reflection
|
[
"",
"java",
"seam",
""
] |
In a follow-up to a [previous question](https://stackoverflow.com/questions/54789/what-is-the-correct-net-exception-to-throw-when-try-to-insert-a-duplicate-objec) regarding exceptions, what are best practices for creating a custom exception in .NET?
More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?
|
Inherit from `System.Exception`. `System.ApplicationException` is useless and the design guidelines say "**Do not** throw or derive from `System.ApplicationException`."
See <http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx>
|
In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices.
Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo class, I can choose between:
1. `throw new Exception("Bar happened in Foo");`
2. `throw new FooException("Bar happened");`
3. `throw new FooBarException();`
where
```
class FooException : Exception
{
public FooException(string message) ...
}
```
and
```
class FooBarException : FooException
{
public FooBarException()
: base ("Bar happened")
{
}
}
```
I prefer the 3rd option, because I see it as being an OO solution.
|
What are some best practices for creating my own custom exception?
|
[
"",
"c#",
".net",
"exception",
""
] |
**Is there a better way of binding a list of base class to a UI other than downcasting e.g:**
```
static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
foreach (Animal a in list)
{
DoPigStuff(a as Pig);
DoDogStuff(a as Dog);
}
}
static void DoPigStuff(Pig p)
{
if (p != null)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
}
static void DoDogStuff(Dog d) {
if (d != null)
{
Image1.src = d.Image;
}
}
class Animal {
public String Name { get; set; }
}
class Pig : Animal{
public int TailLength { get; set; }
public Pig(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
}
class Dog : Animal {
public String Image { get; set; }
public Dog(String image)
{
Name = "Mr Dog";
Image = image;
}
}
```
|
When faced with this type of problem, I follow the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern).
```
interface IVisitor
{
void DoPigStuff(Piggy p);
void DoDogStuff(Doggy d);
}
class GuiVisitor : IVisitor
{
void DoPigStuff(Piggy p)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
void DoDogStuff(Doggy d)
{
Image1.src = d.Image;
}
}
abstract class Animal
{
public String Name { get; set; }
public abstract void Visit(IVisitor visitor);
}
class Piggy : Animal
{
public int TailLength { get; set; }
public Piggy(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
public void Visit(IVisitor visitor)
{
visitor.DoPigStuff(this);
}
}
class Doggy : Animal
{
public String Image { get; set; }
public Doggy(String image)
{
Name = "Mr Dog";
Image = image;
}
public void Visit(IVisitor visitor)
{
visitor.DoDogStuff(this);
}
}
public class AnimalProgram
{
static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
IVisitor visitor = new GuiVisitor();
foreach (Animal a in list)
{
a.Visit(visitor);
}
}
}
```
Thus the visitor pattern simulates double dispatch in a conventional single-dispatch object-oriented language such as Java, Smalltalk, C#, and C++.
The only advantage of this code over [jop](https://stackoverflow.com/questions/147129/c-downcasting-when-binding-to-and-interface#147383)'s is that the IVisitor interface can be implemented on a different class later when you need to add a new type of visitor (like a **XmlSerializeVisitor** or a **FeedAnimalVisitor**).
|
Why not make Animal include an abstract method that Pig and Dog are forced to implement
```
public class Animal
{
public abstract void DoStuff();
}
public Dog : Animal
{
public override void DoStuff()
{
// Do dog specific stuff here
}
}
public Pig : Animal
{
public override void DoStuff()
{
// Do pig specific stuff here
}
}
```
This way each specific class takes responsibility for its actions, making your code simpler. You also won't need to cast inside your foreach loop.
|
c# downcasting when binding to and interface
|
[
"",
"c#",
"casting",
"oop",
""
] |
I'm not asking this question because of the merits of garbage collection first of all. My main reason for asking this is that I do know that Bjarne Stroustrup has said that C++ will have a garbage collector at some point in time.
With that said, why hasn't it been added? There are already some garbage collectors for C++. Is this just one of those "easier said than done" type things? Or are there other reasons it hasn't been added (and won't be added in C++11)?
Cross links:
* [Garbage collectors for C++](https://stackoverflow.com/questions/81062/garbage-collectors-for-c)
Just to clarify, I understand the reasons why C++ didn't have a garbage collector when it was first created. I'm wondering why the collector can't be added in.
|
Implicit garbage collection could have been added in, but it just didn't make the cut. Probably due to not just implementation complications, but also due to people not being able to come to a general consensus fast enough.
A quote from Bjarne Stroustrup himself:
> I had hoped that a garbage collector
> which could be optionally enabled
> would be part of C++0x, but there were
> enough technical problems that I have
> to make do with just a detailed
> specification of how such a collector
> integrates with the rest of the
> language, if provided. As is the case
> with essentially all C++0x features,
> an experimental implementation exists.
There is a good discussion of the topic [here](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=222).
**General overview:**
C++ is very powerful and allows you to do almost anything. For this reason it doesn't automatically push many things onto you that might impact performance. Garbage collection can be easily implemented with smart pointers (objects that wrap pointers with a reference count, which auto delete themselves when the reference count reaches 0).
C++ was built with competitors in mind that did not have garbage collection. Efficiency was the main concern that C++ had to fend off criticism from in comparison to C and others.
There are 2 types of garbage collection...
**Explicit garbage collection:**
C++0x has garbage collection via pointers created with shared\_ptr
If you want it you can use it, if you don't want it you aren't forced into using it.
For versions before C++0x, boost:shared\_ptr exists and serves the same purpose.
**Implicit garbage collection:**
It does not have transparent garbage collection though. It will be a focus point for future C++ specs though.
**Why Tr1 doesn't have implicit garbage collection?**
There are a lot of things that tr1 of C++0x should have had, Bjarne Stroustrup in previous interviews stated that tr1 didn't have as much as he would have liked.
|
To add to the debate here.
There are known issues with garbage collection, and understanding them helps understanding why there is none in C++.
**1. Performance ?**
The first complaint is often about performance, but most people don't really realize what they are talking about. As illustrated by Martin Beckett the problem may not be performance per se, but the predictability of performance.
There are currently 2 families of GC that are widely deployed:
* Mark-And-Sweep kind
* Reference-Counting kind
The **Mark And Sweep** is faster (less impact on overall performance) but it suffers from a "freeze the world" syndrome: i.e. when the GC kicks in, everything else is stopped until the GC has made its cleanup. If you wish to build a server that answers in a few milliseconds... some transactions will not live up to your expectations :)
The problem of **Reference Counting** is different: reference-counting adds overhead, especially in Multi-Threading environments because you need to have an atomic count. Furthermore there is the problem of reference cycles so you need a clever algorithm to detect those cycles and eliminate them (generally implement by a "freeze the world" too, though less frequent). In general, as of today, this kind (even though normally more responsive or rather, freezing less often) is slower than the Mark And Sweep.
I have seen a paper by Eiffel implementers that were trying to implement a Reference Counting Garbage Collector that would have a similar global performance to Mark And Sweep without the "Freeze The World" aspect. It required a separate thread for the GC (typical). The algorithm was a bit frightening (at the end) but the paper made a good job of introducing the concepts one at a time and showing the evolution of the algorithm from the "simple" version to the full-fledged one. Recommended reading if only I could put my hands back on the PDF file...
**2. Resources Acquisition Is Initialization (RAII)**
It's a common idiom in C++ that you will wrap the ownership of resources within an object to ensure that they are properly released. It's mostly used for memory since we don't have garbage collection, but it's also useful nonetheless for many other situations:
* locks (multi-thread, file handle, ...)
* connections (to a database, another server, ...)
The idea is to properly control the lifetime of the object:
* it should be alive as long as you need it
* it should be killed when you're done with it
The problem of GC is that if it helps with the former and ultimately guarantees that later... this "ultimate" may not be sufficient. If you release a lock, you'd really like that it be released now, so that it does not block any further calls!
Languages with GC have two work arounds:
* don't use GC when stack allocation is sufficient: it's normally for performance issues, but in our case it really helps since the scope defines the lifetime
* `using` construct... but it's explicit (weak) RAII while in C++ RAII is implicit so that the user CANNOT unwittingly make the error (by omitting the `using` keyword)
**3. Smart Pointers**
Smart pointers often appear as a silver bullet to handle memory in C++. Often times I have heard: we don't need GC after all, since we have smart pointers.
One could not be more wrong.
Smart pointers do help: `auto_ptr` and `unique_ptr` use RAII concepts, extremely useful indeed. They are so simple that you can write them by yourself quite easily.
When one need to share ownership however it gets more difficult: you might share among multiple threads and there are a few subtle issues with the handling of the count. Therefore, one naturally goes toward `shared_ptr`.
It's great, that's what Boost for after all, but it's not a silver bullet. In fact, the main issue with `shared_ptr` is that it emulates a GC implemented by Reference Counting but you need to implement the cycle detection all by yourself... Urg
Of course there is this `weak_ptr` thingy, but I have unfortunately already seen memory leaks despite the use of `shared_ptr` because of those cycles... and when you are in a Multi Threaded environment, it's extremely difficult to detect!
**4. What's the solution ?**
There is no silver bullet, but as always, it's definitely feasible. In the absence of GC one need to be clear on ownership:
* prefer having a single owner at one given time, if possible
* if not, make sure that your class diagram does not have any cycle pertaining to ownership and break them with subtle application of `weak_ptr`
So indeed, it would be great to have a GC... however it's no trivial issue. And in the mean time, we just need to roll up our sleeves.
|
Why doesn't C++ have a garbage collector?
|
[
"",
"c++",
"garbage-collection",
"c++11",
""
] |
I've been using the following code to open Office Documents, PDF, etc. on my windows machines using Java and it's working fine, except for some reason when a filename has embedded it within it multiple contiguous spaces like "File[SPACE][SPACE]Test.doc".
How can I make this work? I'm not averse to canning the whole piece of code... but I'd rather not replace it with a third party library that calls JNI.
```
public static void openDocument(String path) throws IOException {
// Make forward slashes backslashes (for windows)
// Double quote any path segments with spaces in them
path = path.replace("/", "\\").replaceAll(
"\\\\([^\\\\\\\\\"]* [^\\\\\\\\\"]*)", "\\\\\\\"$1\"");
String command = "C:\\Windows\\System32\\cmd.exe /c start " + path + "";
Runtime.getRuntime().exec(command);
}
```
**EDIT:** When I run it with the errant file windows complains about finding the file. But... when I run the command line directly from the command line it runs just fine.
|
If you are using Java 6 you can just use the [open method of java.awt.Desktop](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#open(java.io.File)) to launch the file using the default application for the current platform.
|
Not sure if this will help you much... I use java 1.5+'s [ProcessBuilder](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html) to launch external shell scripts in a java program. Basically I do the following: ( although this may not apply because you don't want to capture the commands output; you actually wanna fire up the document - but, maybe this will spark something that you can use )
```
List<String> command = new ArrayList<String>();
command.add(someExecutable);
command.add(someArguemnt0);
command.add(someArgument1);
command.add(someArgument2);
ProcessBuilder builder = new ProcessBuilder(command);
try {
final Process process = builder.start();
...
} catch (IOException ioe) {}
```
|
Better way of opening a Document from Java?
|
[
"",
"java",
"windows",
"process",
""
] |
I'm attempting to display a "LargeIcon" view in a listview control, however the images I specify are blurry. This is what I have so far:
[alt text http://img220.imageshack.us/img220/1005/blurryiconsql3.jpg](http://img220.imageshack.us/img220/1005/blurryiconsql3.jpg)
The .png files are 48x48 and that's what I have it set to display at in the ImageList properties. There's one thing that I've noticed (which is probably the cause) but I don't know how to change it. Inside the "Images Collection Editor" where you choose what images you want for the ImageList control, it looks like it's setting the wrong size for each image.
[alt text http://img83.imageshack.us/img83/5218/imagepropertiesmf9.jpg](http://img83.imageshack.us/img83/5218/imagepropertiesmf9.jpg)
As you can see the "PhysicalDimension" and the "Size" is set to 16x16 and not abled to be manipulated. Does anyone have any ideas? Many thanks!
|
When adding a .PNG Icon format size the editor tends to pick the first entry size in that file, so it picks up the 16x16 entry and it's stretching that out. That's why you see the 16x16 in the properties there. As suggested, the support for PNG is poor, I'm often found myself rolling over to another format as well to avoid this.
You can open the file in **[Paint.Net](http://www.getpaint.net/)** if you need a free editor or something more fully featured like Photoshop or Fireworks and extract the exact size you want.
|
Be sure to set ImageList.ImageSize to 48 x 48 too.
|
Listview icons show up blurry (C#)
|
[
"",
"c#",
"listview",
"imagelist",
"blurry",
""
] |
I have string like this
```
/c SomeText\MoreText "Some Text\More Text\Lol" SomeText
```
I want to tokenize it, however I can't just split on the spaces. I've come up with somewhat ugly parser that works, but I'm wondering if anyone has a more elegant design.
This is in C# btw.
**EDIT:** My ugly version, while ugly, is O(N) and may actually be faster than using a RegEx.
```
private string[] tokenize(string input)
{
string[] tokens = input.Split(' ');
List<String> output = new List<String>();
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i].StartsWith("\""))
{
string temp = tokens[i];
int k = 0;
for (k = i + 1; k < tokens.Length; k++)
{
if (tokens[k].EndsWith("\""))
{
temp += " " + tokens[k];
break;
}
else
{
temp += " " + tokens[k];
}
}
output.Add(temp);
i = k + 1;
}
else
{
output.Add(tokens[i]);
}
}
return output.ToArray();
}
```
|
The computer term for what you're doing is [lexical analysis](http://en.wikipedia.org/wiki/Lexical_analysis); read that for a good summary of this common task.
Based on your example, I'm guessing that you want whitespace to separate your words, but stuff in quotation marks should be treated as a "word" without the quotes.
The simplest way to do this is to define a word as a regular expression:
```
([^"^\s]+)\s*|"([^"]+)"\s*
```
This expression states that a "word" is either (1) non-quote, non-whitespace text surrounded by whitespace, or (2) non-quote text surrounded by quotes (followed by some whitespace). Note the use of capturing parentheses to highlight the desired text.
Armed with that regex, your algorithm is simple: search your text for the next "word" as defined by the capturing parentheses, and return it. Repeat that until you run out of "words".
Here's the simplest bit of working code I could come up with, in VB.NET. Note that we have to check *both* groups for data since there are two sets of capturing parentheses.
```
Dim token As String
Dim r As Regex = New Regex("([^""^\s]+)\s*|""([^""]+)""\s*")
Dim m As Match = r.Match("this is a ""test string""")
While m.Success
token = m.Groups(1).ToString
If token.length = 0 And m.Groups.Count > 1 Then
token = m.Groups(2).ToString
End If
m = m.NextMatch
End While
```
Note 1: [Will's](https://stackoverflow.com/users/1228/will) answer, above, is the same idea as this one. Hopefully this answer explains the details behind the scene a little better :)
|
The Microsoft.VisualBasic.FileIO namespace (in Microsoft.VisualBasic.dll) has a TextFieldParser you can use to split on space delimeted text. It handles strings within quotes (i.e., "this is one token" thisistokentwo) well.
Note, just because the DLL says VisualBasic doesn't mean you can only use it in a VB project. Its part of the entire Framework.
|
Best way to parse Space Separated Text
|
[
"",
"c#",
"string",
"tokenize",
""
] |
What is the difference between old style and new style classes in Python? When should I use one or the other?
|
From *[New-style and classic classes](http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes)*:
> **Up to Python 2.1, old-style classes were the only flavour available to the user.**
>
> The concept of (old-style) class is unrelated to the concept of type:
> if `x` is an instance of an old-style class, then `x.__class__`
> designates the class of `x`, but `type(x)` is always `<type
> 'instance'>`.
>
> This reflects the fact that all old-style instances, independently of
> their class, are implemented with a single built-in type, called
> instance.
>
> **New-style classes were introduced in Python 2.2 to unify the concepts of class and type**.
> A new-style class is simply a user-defined type, no more, no less.
>
> If x is an instance of a new-style class, then `type(x)` is typically
> the same as `x.__class__` (although this is not guaranteed – a
> new-style class instance is permitted to override the value returned
> for `x.__class__`).
>
> **The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model**.
>
> It also has a number of immediate benefits, like the ability to
> subclass most built-in types, or the introduction of "descriptors",
> which enable computed properties.
>
> **For compatibility reasons, classes are still old-style by default**.
>
> New-style classes are created by specifying another new-style class
> (i.e. a type) as a parent class, or the "top-level type" object if no
> other parent is needed.
>
> The behaviour of new-style classes differs from that of old-style
> classes in a number of important details in addition to what type
> returns.
>
> Some of these changes are fundamental to the new object model, like
> the way special methods are invoked. Others are "fixes" that could not
> be implemented before for compatibility concerns, like the method
> resolution order in case of multiple inheritance.
>
> **Python 3 only has new-style classes**.
>
> No matter if you subclass from `object` or not, classes are new-style
> in Python 3.
|
**Declaration-wise:**
New-style classes inherit from *object*, or from another new-style class.
```
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass):
pass
```
Old-style classes don't.
```
class OldStyleClass():
pass
```
**Python 3 Note:**
Python 3 doesn't support old style classes, so either form noted above results in a new-style class.
|
What is the difference between old style and new style classes in Python?
|
[
"",
"python",
"class",
"oop",
"types",
"new-style-class",
""
] |
Backgrounder:
The [PIMPL Idiom](http://en.wikipedia.org/wiki/Opaque_pointer) (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.
This hides internal implementation details and data from the user of the library.
When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?
To illustrate, this code puts the `Purr()` implementation on the impl class and wraps it as well.
**Why not implement Purr directly on the public class?**
```
// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}
```
|
* Because you want `Purr()` to be able to use private members of `CatImpl`. `Cat::Purr()` would not be allowed such an access without a `friend` declaration.
* Because you then don't mix responsibilities: one class implements, one class forwards.
|
I think most people refer to this as the *Handle Body* idiom. See James Coplien's book *[Advanced C++ Programming Styles and Idioms](https://rads.stackoverflow.com/amzn/click/com/0201548550)*. It's also known as the [Cheshire Cat](http://en.wikipedia.org/wiki/Cheshire_Cat) because of [Lewis Caroll's](https://en.wikipedia.org/wiki/Lewis_Carroll) character that fades away until only the grin remains.
The example code should be distributed across two sets of source files. Then only *Cat.h* is the file that is shipped with the product.
*CatImpl.h* is included by *Cat.cpp* and *CatImpl.cpp* contains the implementation for *CatImpl::Purr()*. This won't be visible to the public using your product.
Basically the idea is to hide as much as possible of the implementation from prying eyes.
This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer's code is compiled against and linked to.
We did this with the rewrite of [IONA's](https://en.wikipedia.org/wiki/IONA_Technologies) [Orbix](https://en.wikipedia.org/wiki/Orbix_(software)) 3.3 product in 2000.
As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won't have to recompile everything that uses *Cat* if you just want to change the implementation of *Purr()*.
This technique is used in a methodology called [design by contract](http://en.wikipedia.org/wiki/Design_by_contract).
|
Why should the "PIMPL" idiom be used?
|
[
"",
"c++",
"oop",
"information-hiding",
"pimpl-idiom",
""
] |
The workflow is like this:
1. I receive a scan of a coupon with data (firstname, lastname, zip, city + misc information) on it.
2. Before I create a new customer, I have to search the database if the customer might exist already.
Now my question: What's the best way to find an existing customer, when there is no unique ID available?
PS: I do have a unique ID in the database, just not on the coupons we receive ;)
|
We are using the [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) algorithm to check users for duplication. However we have quite strict rules to enter the data itself, so we have to check only for misstyping, case differences and such.
|
See this previous question: [Parse usable Street Address, City, State, Zip from a string](https://stackoverflow.com/questions/16413/parse-usable-street-address-city-state-zip-from-a-string#16444).
[Soundex](http://en.wikipedia.org/wiki/Soundex) would help you if you require similiar matches.
|
How can I find similar address records?
|
[
"",
"sql",
"database",
""
] |
I'm not sure how I should express this, but I'll give it a try.
I recently started coding my portfolio in object-oriented PHP and I'm wondering if it's according to best practices to use a single page where the content changes depending on SQL data and the $\_GET variable?
If so/not, why?
Edit: Take a look at my next post, more in-depth details.
|
Are you asking about using the front controller pattern, where a single file serves all of your requests? Often this is done with an index.php and mod\_rewrite getting all of the requests with the rest of the URL being given to it as a parameter in the query string.
<http://www.onlamp.com/pub/a/php/2004/07/08/front_controller.html>
I would tend to recommend this pattern be used for applications, because it gives you a single place to handle things like authentication, and often you'll need to integrate things at a tighter level where having new features be classes that are registered with the controller via some mechanism makes a lot of sense.
The concerns about the URLs others have mentioned aren't really accurate, because there is no real relationship between URL structure and file structure, unless you're using ancient techniques of building websites. A good chunk of apache functionality is based on the concept that file/directory structure and URL structure are distinct concepts (alias module, rewrite module, content negotiation, so on and so forth)
|
* Not scalable
* Hard to manage code
* Parser has to parse everything
* Perfect example of Code Smell
* One error crashes your whole site
|
Pros and cons of using one file for entire webpage?
|
[
"",
"php",
"file",
""
] |
I'm using a C# MailMessage to attach a wave file (8K) to an email message. I'd like to provide a player within the body of that email message that will play that wave file if the user chooses to do so. I've tried using the embedded <object> version of WMP, and a cid: reference to the file, but Outlook 2003 rejects the object tag and won't run it. If it helps, I know my users will be on Outlook 2003.
|
If you know the message recipients are running Outlook (which implies you're using this internally), you might be able to accomplish something even better by incorporating your player controls into a [custom Outlook form](http://www.outlookcode.com/article.aspx?id=35).
|
If it don't support objects tags, then try the Embed tag instead:
<http://www.mioplanet.com/rsc/embed_mediaplayer.htm>
I don't know it if works, but it is worth a shot :)
|
How do I embed Media Player in a C# MailMessage to play an Attachment
|
[
"",
"c#",
".net",
"wmp",
"embedded-control",
""
] |
I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method:
```
public static T GetItem<T>(string key, Func<T> defaultValue)
{
if (HttpContext.Current.Session[key] == null)
{
HttpContext.Current.Session[key] = defaultValue.Invoke();
}
return (T)HttpContext.Current.Session[key];
}
```
Now, how do I actually use this, passing in the Func<T> as an inline method parameter?
|
Since that is a func, a lambda would be the simplest way:
```
Foo foo = GetItem<Foo>("abc", () => new Foo("blah"));
```
Where [new Foo("blah")] is the func that is invoked as a default.
You could also simplify to:
```
return ((T)HttpContext.Current.Session[key]) ?? defaultValue();
```
Where ?? is the null-coalescing operator - if the first arg is non-null, it is returned; otherwise the right hand is evaluated and returned (so defaultValue() isn't invoked unless the item is null).
Finally, if you just want to use the default constructor, then you could add a "new()" constraint:
```
public static T GetItem<T>(string key)
where T : new()
{
return ((T)HttpContext.Current.Session[key]) ?? new T();
}
```
This is still lazy - the new() is only used if the item was null.
|
Why don't you pass the default value directly? What use is the functor?
By the way, `defaultValue.Invoke()` is quite verbose. It's also possible to just write `defaultValue()`.
|
C# - How do I define an inline method Func<T> as a parameter?
|
[
"",
"c#",
"generics",
"func",
"inline-method",
""
] |
Which tools do you use to convert between C# and VB.NET?
|
This has been asked so many times. Like here: [What is the best C# to VB.net converter?](https://stackoverflow.com/questions/88359/what-is-the-best-c-to-vbnet-converter)
|
Check out [Code Converter](http://converter.telerik.com/) by Telerik.
|
C# VB.NET Conversion
|
[
"",
"c#",
".net",
"vb.net",
""
] |
To create a new event handler on a control you can do this
```
c.Click += new EventHandler(mainFormButton_Click);
```
or this
```
c.Click += mainFormButton_Click;
```
and to remove an event handler you can do this
```
c.Click -= mainFormButton_Click;
```
But how do you remove all event handlers from an event?
|
I found a solution on the [MSDN forums](http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/576f69e7-55aa-4574-8d31-417422954689/). The sample code below will remove all `Click` events from `button1`.
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
button1.Click += button1_Click2;
button2.Click += button2_Click;
}
private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Hello");
private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World");
private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1);
private void RemoveClickEvent(Button b)
{
FieldInfo f1 = typeof(Control).GetField("EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
object obj = f1.GetValue(b);
PropertyInfo pi = b.GetType().GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
list.RemoveHandler(obj, list[obj]);
}
}
```
|
You guys are making this WAY too hard on yourselves. It's this easy:
```
void OnFormClosing(object sender, FormClosingEventArgs e)
{
foreach(Delegate d in FindClicked.GetInvocationList())
{
FindClicked -= (FindClickedHandler)d;
}
}
```
|
How to remove all event handlers from an event
|
[
"",
"c#",
".net",
"winforms",
"events",
""
] |
I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?
|
I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp.
**EDIT:** now with code snippet!
```
INSERT INTO TABLE_2
SELECT DISTINCT * FROM TABLE_1
GO
DELETE FROM TABLE_1
GO
INSERT INTO TABLE_1
SELECT * FROM TABLE_2
GO
```
|
The following example works as well when your PK is just a subset of all table columns.
(Note: I like the approach with inserting another surrogate id column more. But maybe this solution comes handy as well.)
First find the duplicate rows:
```
SELECT col1, col2, count(*)
FROM t1
GROUP BY col1, col2
HAVING count(*) > 1
```
If there are only few, you can delete them manually:
```
set rowcount 1
delete from t1
where col1=1 and col2=1
```
The value of "rowcount" should be n-1 times the number of duplicates. In this example there are 2 dulpicates, therefore rowcount is 1. If you get several duplicate rows, you have to do this for every unique primary key.
If you have many duplicates, then copy every key once into anoher table:
```
SELECT col1, col2, col3=count(*)
INTO holdkey
FROM t1
GROUP BY col1, col2
HAVING count(*) > 1
```
Then copy the keys, but eliminate the duplicates.
```
SELECT DISTINCT t1.*
INTO holddups
FROM t1, holdkey
WHERE t1.col1 = holdkey.col1
AND t1.col2 = holdkey.col2
```
In your keys you have now unique keys. Check if you don't get any result:
```
SELECT col1, col2, count(*)
FROM holddups
GROUP BY col1, col2
```
Delete the duplicates from the original table:
```
DELETE t1
FROM t1, holdkey
WHERE t1.col1 = holdkey.col1
AND t1.col2 = holdkey.col2
```
Insert the original rows:
```
INSERT t1 SELECT * FROM holddups
```
btw and for completeness: In Oracle there is a hidden field you could use (rowid):
```
DELETE FROM our_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM our_table
GROUP BY column1, column2, column3... ;
```
see: [Microsoft Knowledge Site](http://support.microsoft.com/kb/139444)
|
How can I delete duplicate rows in a table
|
[
"",
"sql",
"sql-server",
"database",
""
] |
I use a custom Matrix class in my application, and I frequently add multiple matrices:
```
Matrix result = a + b + c + d; // a, b, c and d are also Matrices
```
However, this creates an intermediate matrix for each addition operation. Since this is simple addition, it is possible to avoid the intermediate objects and create the result by adding the elements of all 4 matrices at once. How can I accomplish this?
NOTE: I know I can define multiple functions like `Add3Matrices(a, b, c)`, `Add4Matrices(a, b, c, d)`, etc. but I want to keep the elegancy of `result = a + b + c + d`.
|
You could limit yourself to a single small intermediate by using lazy evaluation. Something like
```
public class LazyMatrix
{
public static implicit operator Matrix(LazyMatrix l)
{
Matrix m = new Matrix();
foreach (Matrix x in l.Pending)
{
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
m.Contents[i, j] += x.Contents[i, j];
}
return m;
}
public List<Matrix> Pending = new List<Matrix>();
}
public class Matrix
{
public int[,] Contents = { { 0, 0 }, { 0, 0 } };
public static LazyMatrix operator+(Matrix a, Matrix b)
{
LazyMatrix l = new LazyMatrix();
l.Pending.Add(a);
l.Pending.Add(b);
return l;
}
public static LazyMatrix operator+(Matrix a, LazyMatrix b)
{
b.Pending.Add(a);
return b;
}
}
class Program
{
static void Main(string[] args)
{
Matrix a = new Matrix();
Matrix b = new Matrix();
Matrix c = new Matrix();
Matrix d = new Matrix();
a.Contents[0, 0] = 1;
b.Contents[1, 0] = 4;
c.Contents[0, 1] = 9;
d.Contents[1, 1] = 16;
Matrix m = a + b + c + d;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
System.Console.Write(m.Contents[i, j]);
System.Console.Write(" ");
}
System.Console.WriteLine();
}
System.Console.ReadLine();
}
}
```
|
In C++ it is possible to use [Template Metaprograms](http://en.wikipedia.org/wiki/Template_metaprogramming) and also [here](http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html), using templates to do exactly this. However, the template programing is non-trivial. I don't know if a similar technique is available in C#, quite possibly not.
This technique, in c++ does exactly what you want. The disadvantage is that if something is not quite right then the compiler error messages tend to run to several pages and are almost impossible to decipher.
Without such techniques I suspect you are limited to functions such as Add3Matrices.
But for C# this link might be exactly what you need: [Efficient Matrix Programming in C#](http://www.codeproject.com/KB/recipes/dynmatrixmath.aspx) although it seems to work slightly differently to C++ template expressions.
|
How to prevent creating intermediate objects in cascading operators?
|
[
"",
"c#",
".net",
"operators",
""
] |
I am searching for a way to compress JavaScript code for the iPhone. Is there a way to avoid using a lot of CPU time on the small and rather slow device?
|
Use [JSMin](http://www.crockford.com/javascript/jsmin.html) and avoid [packer](http://dean.edwards.name/packer/) which is really more CPU consuming and slower to "deflate"
|
Use the [YUI Compressor](http://www.julienlecomte.net/yuicompressor/)
|
What is the best way to pack JavaScript code without getting performance flaws?
|
[
"",
"javascript",
"iphone",
"compression",
""
] |
If I have a Java source file (\*.java) or a class file (\*.class), how can I convert it to a .exe file?
I also need an installer for my program.
|
### [javapackager](https://docs.oracle.com/javase/10/tools/javapackager.htm)
> The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version.
>
> – Oracle's documentation
The `javapackager` utility ships with the JDK. It can generate .exe files with the `-native exe` flag, among many other things.
### [WinRun4J](https://winrun4j.sourceforge.net/)
> WinRun4j is a java launcher for windows. It is an alternative to javaw.exe and provides the following benefits:
>
> * Uses an INI file for specifying classpath, main class, vm args, program args.
> * Custom executable name that appears in task manager.
> * Additional JVM args for more flexible memory use.
> * Built-in icon replacer for custom icon.
> * *[more bullet points follow]*
>
> – WinRun4J's webpage
WinRun4J is an open source utility. It has *many* features.
### [packr](https://github.com/libgdx/packr)
> Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications.
>
> – packr README
packr is another open source tool.
### [JSmooth](https://jsmooth.sourceforge.net/)
> JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself.
>
> – JSmooth's website
JSmooth is open source and has features, but it is very old. The last release was in 2007.
### [JexePack](https://www.duckware.com/jexepack/index.html)
> *JexePack* is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single *compressed* 32-bit Windows EXE, which runs using Sun's Java Runtime Environment. Both console and windowed applications are supported.
>
> – JexePack's website
JexePack is trialware. Payment is required for production use, and exe files created with this tool will display "reminders" without payment. Also, the last release was in 2013.
### [InstallAnywhere](https://www.flexera.com/products/installation/installanywhere.html)
> InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship.
>
> – InstallAnywhere's website
InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It's probably capable of creating .exe files.
### Executable JAR files
As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by [adding an entry point to the JAR manifest](https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html).
---
# For more information
An excellent source of information on this topic is this article, "[Convert Java to EXE – Why, When, When Not and How](https://web.archive.org/web/20181117071040/https://www.excelsior-usa.com/articles/java-to-exe.html)", by Dmitry Leskov
See also the companion page "[Best JAR to EXE Conversion Tools, Free and Commercial](https://web.archive.org/web/20160808182011/https://www.excelsior-usa.com/articles/best-jar-to-exe-conversion-tools-free-commercial.html)"
|
# [Launch4j](http://launch4j.sourceforge.net/)
> Launch4j is a cross-platform tool for wrapping Java applications distributed as jars in lightweight Windows native executables. The executable can be configured to search for a certain JRE version or use a bundled one, and it's possible to set runtime options, like the initial/max heap size. The wrapper also provides better user experience through an application icon, a native pre-JRE splash screen, a custom process name, and a Java download page in case the appropriate JRE cannot be found.
>
> – Launch4j's website
|
How can I convert my Java program to an .exe file?
|
[
"",
"java",
"installation",
"exe",
""
] |
In C++ the storage class specifier static allocates memory from the data area. What does "data area" mean?
|
In addition to what Konrad said, declaring a variable as static basically means that the memory for it gets allocated with the program as it is loaded, as opposed to on the heap or the stack. Historically, using only static variables in a critical applications meant that the memory footprint of the application would not change at run-time and hence it was less likely to fail due to resource limitations. Don't know if this is still true of modern operating systems.
If you get your compiler to generate a mapfile as part of its output, you can have a look see at what is in all the various sections, including data.
|
I'm not familiar with the term “data area” but memory is often divided into “code section” and “data section”. Code resides in the former, data in the latter. I presume this is what's meant here.
Classically, there's no distinction between the two. However, many modern operating systems can prohibit the execution of code int he data segment (provided the CPU supports this distinction). This sometimes goes by the catch phrase of “NX flag”, as in “no execution” and can effectively prevent some cases of malicious code injection.
/EDIT: Notice that the C++ standard doesn't mention a “data area”.
|
What is data area?
|
[
"",
"c++",
"memory",
"static",
"storage",
""
] |
In a [question answer](https://stackoverflow.com/questions/9033#9099) I find the following coding tip:-
2) simple lambdas with one parameter:
```
x => x.ToString() //simplify so many calls
```
As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples.
I've researched lambdas so I **think** I know what they do, however I **may** not fully understand so a **little** unpacking might also be in order.
|
When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate "inline" in a very concise manner. For instance, here's code to find a particular person in a list, by their name:
```
List<Person> list = new List<Person>();
// [..] Populate list here
Person jon = list.Find(p => p.Name == "Jon");
```
In C# 2.0 you could use an anonymous method which was a little bit more longwinded, but not *too* bad:
```
List<Person> list = new List<Person>();
// [..] Populate list here
Person jon = list.Find(delegate(Person p) { return p.Name == "Jon"; });
```
In C# 1.0 you'd have to create a whole extra method. In addition, if you wanted to parameterise it, you'd have to create a different type, whereas anonymous methods and lambda expressions capture their executing environment (local variables etc) so they act like closures:
```
public Person FindByName(List<Person> list, String name)
{
return list.Find(p => p.Name == name); // The "name" variable is captured
}
```
There's more about this in [my article about closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx).
While passing delegates into methods isn't terribly common in C# 2.0 and .NET 2.0, it's a large part of the basis of LINQ - so you tend to use it a lot in C# 3.0 with .NET 3.5.
|
This basically expands to:
```
private string Lambda(object x) {
return x.ToString();
}
```
|
Explain x => x.ToString() //simplify so many calls
|
[
"",
"c#",
".net-3.5",
"lambda",
""
] |
Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to `display: none;`, the table with shrinks to fit the contents of the visible rows.
|
If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:
```
table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";
```
However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:
```
table {
table-layout: fixed;
}
```
|
CSS rule [`visibility: collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#Values) was designed exactly for that.
```
tbody.collapsed > tr {
visibility: collapse;
}
```
After adding this CSS you could trigger visibility from JS with:
```
tbody.classList.toggle('collapsed');
```
|
How to hide table rows without resizing overall width?
|
[
"",
"javascript",
"html",
"css",
"xhtml",
"html-table",
""
] |
Ok, here's one for the JavaScript gurus:
In my app, one of the controllers passes a TreeMap to it's JSP. This map has car manufacturer's names as keys and Lists of Car objects as values. These Car objects are simple beans containing the car's name, id, year of production etc.
So, the map looks something like this (this is just an example, to clarify things a bit):
Key: Porsche
Value: List containing three Car objects(for example 911,Carrera,Boxter with their respectable years of production and ids)
Key: Fiat
Value: List containing two Car objects(for example, Punto and Uno)
etc...
Now, in my JSP i have two comboboxes. One should receive a list of car manufacturers(keys from the map - this part I know how to do), and the other one should **dynamicaly change** to display the names of the cars when the user selects a certain manufacturer from the first combobox. So, for example, user selects a "Porsche" in the first combobox, and the second immediately displays "911, Carrera, Boxter"...
After spending a couple of days trying to find out how to do this, I'm ready to admit defeat. I tried out a lot of different things but every time I hit a wall somewehere along the way. Can anybody suggest how I should approach this one?
Yes, I'm a JavaScript newbie, if anybody was wondering...
EDIT: I've retagged this as a code-challenge. Kudos to anybody who solves this one without using any JavaScript framework (like JQuery).
|
Well anyway, as i said, i finally managed to do it by myself, so here's my answer...
I receive the map from my controller like this (I'm using Spring, don't know how this works with other frameworks):
```
<c:set var="manufacturersAndModels" scope="page" value="${MANUFACTURERS_AND_MODELS_MAP}"/>
```
These are my combos:
```
<select id="manufacturersList" name="manufacturersList" onchange="populateModelsCombo(this.options[this.selectedIndex].index);" >
<c:forEach var="manufacturersItem" items="<%= manufacturers%>">
<option value='<c:out value="${manufacturersItem}" />'><c:out value="${manufacturersItem}" /></option>
</c:forEach>
</select>
```
```
select id="modelsList" name="modelsList"
<c:forEach var="model" items="<%= models %>" >
<option value='<c:out value="${model}" />'><c:out value="${model}" /></option>
</c:forEach>
</select>
```
I imported the following classes (some names have, of course, been changed):
```
<%@ page import="org.mycompany.Car,java.util.Map,java.util.TreeMap,java.util.List,java.util.ArrayList,java.util.Set,java.util.Iterator;" %>
```
And here's the code that does all the hard work:
```
<script type="text/javascript">
<%
Map mansAndModels = new TreeMap();
mansAndModels = (TreeMap) pageContext.getAttribute("manufacturersAndModels");
Set manufacturers = mansAndModels.keySet(); //We'll use this one to populate the first combo
Object[] manufacturersArray = manufacturers.toArray();
List cars;
List models = new ArrayList(); //We'll populate the second combo the first time the page is displayed with this list
//initial second combo population
cars = (List) mansAndModels.get(manufacturersArray[0]);
for(Iterator iter = cars.iterator(); iter.hasNext();) {
Car car = (Car) iter.next();
models.add(car.getModel());
}
%>
function populateModelsCombo(key) {
var modelsArray = new Array();
//Here goes the tricky part, we populate a two-dimensional javascript array with values from the map
<%
for(int i = 0; i < manufacturersArray.length; i++) {
cars = (List) mansAndModels.get(manufacturersArray[i]);
Iterator carsIterator = cars.iterator();
%>
singleManufacturerModelsArray = new Array();
<%
for(int j = 0; carsIterator.hasNext(); j++) {
Car car = (Car) carsIterator.next();
%>
singleManufacturerModelsArray[<%= j%>] = "<%= car.getModel()%>";
<%
}
%>
modelsArray[<%= i%>] = singleManufacturerModelsArray;
<%
}
%>
var modelsList = document.getElementById("modelsList");
//Empty the second combo
while(modelsList.hasChildNodes()) {
modelsList.removeChild(modelsList.childNodes[0]);
}
//Populate the second combo with new values
for (i = 0; i < modelsArray[key].length; i++) {
modelsList.options[i] = new Option(modelsArray[key][i], modelsArray[key][i]);
}
}
```
|
I just love a challenge.
No jQuery, just plain javascript, tested on Safari.
I'd like to add the following remarks in advance:
* It's faily long due to the error
checking.
* Two parts are generated;
the first script node with the Map
and the contents of the manufacterer
SELECT
* Works on My Machine (TM)
(Safari/OS X)
* There is no (css)
styling applied. I have bad taste so
it's no use anyway.
.
```
<body>
<script>
// DYNAMIC
// Generate in JSP
// You can put the script tag in the body
var modelsPerManufacturer = {
'porsche' : [ 'boxter', '911', 'carrera' ],
'fiat': [ 'punto', 'uno' ]
};
</script>
<script>
// STATIC
function setSelectOptionsForModels(modelArray) {
var selectBox = document.myForm.models;
for (i = selectBox.length - 1; i>= 0; i--) {
// Bottom-up for less flicker
selectBox.remove(i);
}
for (i = 0; i< modelArray.length; i++) {
var text = modelArray[i];
var opt = new Option(text,text, false, false);
selectBox.add(opt);
}
}
function setModels() {
var index = document.myForm.manufacturer.selectedIndex;
if (index == -1) {
return;
}
var manufacturerOption = document.myForm.manufacturer.options[index];
if (!manufacturerOption) {
// Strange, the form does not have an option with given index.
return;
}
manufacturer = manufacturerOption.value;
var modelsForManufacturer = modelsPerManufacturer[manufacturer];
if (!modelsForManufacturer) {
// This modelsForManufacturer is not in the modelsPerManufacturer map
return; // or alert
}
setSelectOptionsForModels(modelsForManufacturer);
}
function modelSelected() {
var index = document.myForm.models.selectedIndex;
if (index == -1) {
return;
}
alert("You selected " + document.myForm.models.options[index].value);
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer" size="5">
<!-- Options generated by the JSP -->
<!-- value is index of the modelsPerManufacturer map -->
<option value="porsche">Porsche</option>
<option value="fiat">Fiat</option>
</select>
<select onChange="modelSelected()" id="models" size="5">
<!-- Filled dynamically by setModels -->
</select>
</form>
</body>
```
|
Dynamicaly populating a combobox with values from a Map based on what's selected in another combobox
|
[
"",
"javascript",
"combobox",
"maps",
""
] |
I have several sources of tables with personal data, like this:
```
SOURCE 1
ID, FIRST_NAME, LAST_NAME, FIELD1, ...
1, jhon, gates ...
SOURCE 2
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
1, jon, gate ...
SOURCE 3
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
2, jhon, ballmer ...
```
So, assuming that records with ID 1, from sources 1 and 2, are the same person, my problem **is how to determine if a record in every source, represents the same person**. Additionally, sure not every records exists in all sources. All the names, are written in spanish, mainly.
In this case, the exact matching needs to be relaxed because we assume *the data sources has not been rigurously checked* against the official bureau of identification of the country. Also we need to assume *typos are common*, because the nature of the processes to collect the data. What is more, the amount of records is around 2 or 3 millions in every source...
Our team had thought in something like this: first, force exact matching in selected fields like ID NUMBER, and NAMES to know how hard the problem can be. Second, relaxing the matching criteria, and count how much records more can be matched, but is here where the problem arises: **how to do to relax the matching criteria without generating too noise neither restricting too much?**
What tool can be more effective to handle this?, for example, do you know about some especific extension in some database engine to support this matching?
Do you know about clever algorithms like [soundex](http://en.wikipedia.org/wiki/Soundex) to handle this approximate matching, but for spanish texts?
Any help would be appreciated!
Thanks.
|
The crux of the problem is to compute one or more measures of distance between each pair of entries and then consider them to be the same when one of the distances is less than a certain acceptable threshold. The key is to setup the analysis and then vary the acceptable distance until you reach what you consider to be the best trade-off between false-positives and false-negatives.
One distance measurement could be phonetic. Another you might consider is the [Levenshtein or edit distance](http://en.wikipedia.org/wiki/Levenshtein_distance) between the entires, which would attempt to measure typos.
If you have a reasonable idea of how many persons you should have, then your goal is to find the sweet spot where you are getting about the right number of persons. Make your matching too fuzzy and you'll have too few. Make it to restrictive and you'll have too many.
If you know roughly how many entries a person should have, then you can use that as the metric to see when you are getting close. Or you can divide the number of records into the average number of records for each person and get a rough number of persons that you're shooting for.
If you don't have any numbers to use, then you're left picking out groups of records from your analysis and checking by hand whether they look like the same person or not. So it's guess and check.
I hope that helps.
|
This sounds like a [Customer Data Integration](http://en.wikipedia.org/wiki/Customer_Data_Integration) problem. Search on that term and you might find some more information. Also, have a poke around inside [The Data Warehousing Institude](http://www.tdwi.org/), and you might find some answers there as well.
**Edit:** In addition, [here's](http://www.javalobby.org/java/forums/t16936.html) an article that might interest you on spanish phonetic matching.
|
how to determine if a record in every source, represents the same person
|
[
"",
"sql",
"algorithm",
"etl",
"textmatching",
"record-linkage",
""
] |
What's the easiest way to print a stacktrace from a debugging printout? Often during testing you would like to know the callstack leading up to the situation provoking a debug message.
|
[Thread.dumpStack();](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#dumpStack())
|
If you're using log4j
```
Exception e = new Exception();
log.error("error here", e);
```
will print the stacktrace to your log.
|
How do I in java add a stacktrace to my debugging printout
|
[
"",
"java",
"debugging",
""
] |
Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing
```
$result = mysql_query("SELECT id FROM table");
$total = mysql_num_rows($result)
```
I was told this was not very efficient or fast, if you have a lot of records in the table.
|
You were told correctly. mysql can do this count for you which is much more efficient.
```
$result = mysql_query( "select count(id) as num_rows from table" );
$row = mysql_fetch_object( $result );
$total = $row->num_rows;
```
|
You should use [SQL's built in COUNT function](http://dev.mysql.com/doc/refman/5.0/en/counting-rows.html):
```
$result = mysql_query("SELECT COUNT(id) FROM table");
```
|
Whats the best way to get total # of records in a mysql table with php?
|
[
"",
"php",
"mysql",
""
] |
In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this:
```
Foo<?> x;
```
Is there an equivalent construct to this question-mark, in C#?
|
The short answer is no. There isn't an equivalent feature in C#.
A workaround, from [C# from a Java developer's perspective](http://www.25hoursaday.com/CsharpVsJava.html#generics) by Dare Obasanjo:
In certain cases, one may need create a method that can operate on data structures containing any type as opposed to those that contain a specific type (e.g. a method to print all the objects in a data structure) while still taking advantage of the benefits of strong typing in generics. The mechanism for specifying this in C# is via a feature called generic type inferencing while in Java this is done using wildcard types. The following code samples show how both approaches lead to the same result.
C# Code
```
using System;
using System.Collections;
using System.Collections.Generic;
class Test{
//Prints the contents of any generic Stack by
//using generic type inference
public static void PrintStackContents<T>(Stack<T> s){
while(s.Count != 0){
Console.WriteLine(s.Pop());
}
}
public static void Main(String[] args){
Stack<int> s2 = new Stack<int>();
s2.Push(4);
s2.Push(5);
s2.Push(6);
PrintStackContents(s2);
Stack<string> s1 = new Stack<string>();
s1.Push("One");
s1.Push("Two");
s1.Push("Three");
PrintStackContents(s1);
}
}
```
Java Code
```
import java.util.*;
class Test{
//Prints the contents of any generic Stack by
//specifying wildcard type
public static void PrintStackContents(Stack<?> s){
while(!s.empty()){
System.out.println(s.pop());
}
}
public static void main(String[] args){
Stack <Integer> s2 = new Stack <Integer>();
s2.push(4);
s2.push(5);
s2.push(6);
PrintStackContents(s2);
Stack<String> s1 = new Stack<String>();
s1.push("One");
s1.push("Two");
s1.push("Three");
PrintStackContents(s1);
}
}
```
|
AFAIK you can not do that in C#. What the BCL does and there are plenties of examples there is to create a class that is not generic and then create a generic class that inherits the base behavior from the previous one. See example below.
```
class Foo
{
}
class Foo<T> : Foo
{
}
```
The you can write something like this:
```
Foo t = new Foo<int>();
```
|
Is there an "anonymous" generic tag in C#, like '?' in Java?
|
[
"",
"c#",
"generics",
"syntax",
""
] |
I'm writing a shell for a project of mine, which by design parses commands that looks like this:
COMMAND\_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com
My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.
Any ideas how can this be solved? Any existing library for this?
|
You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split().
```
args = {}
for arg in shlex.split(cmdln_args):
key, value = arg.split('=', 1)
args[key] = value
```
|
1. Try to follow "[Standards for Command Line Interfaces](http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Interfaces)"
2. Convert your arguments (as Thomas suggested) to OptionParser format.
```
parser.parse_args(["--"+p if "=" in p else p for p in sys.argv[1:]])
```
If command-line arguments are not in sys.argv or a similar list but in a string then (as ironfroggy suggested) use `shlex.split()`.
```
parser.parse_args(["--"+p if "=" in p else p for p in shlex.split(argsline)])
```
|
Customized command line parsing in Python
|
[
"",
"python",
"parsing",
"shell",
"command-line",
"arguments",
""
] |
I have the situation where i use GIS software which stores the information about GIS objects into separate database table for each type/class of GIS object (road, river, building, sea, ...) and keeps the metadata table in which it stores info about the class name and its DB table.
Those GIS objects of different classes share some parameters, i.e. Description and ID. I'd like to represent all of these different GIS classes with one common C# class (let's call it GisObject), which is enough for what i need to do from the non-GIS part of the application which lists GIS objects of the given GIS class.
The problem for me is how to map those objects using NHibernate to explain to the NHibernate when creating a C# GisObject to receive and **use the table name as a parameter** which will be read from the meta table (it can be in two steps, i can manually fetch the table name in first step and then pass it down to the NHibernate when pulling GisObject data).
Has anybody dealt with this kind of situation, and can it be done at all?
|
@Brian Chiasson
Unfortunately, it's not an option to create all classes of GIS data because classes are created dynamically in the application. Every GIS data of the same type should be a class, but my user has the possibility to get new set of data and put it in the database. I can't know in front which classes my user will have in the application. Therefore, the in-front per-class mapping model doesn't work because tomorrow there will be another new database table, and a need to create new class with new mapping.
@all
There might be a possibility to write my own custom query in the XML config file of my GisObject class, then in the data access class fetching that query using the
```
string qs = getSession().getNamedQuery(queryName);
```
and use the string replace to inject database name (by replacing some placeholder string) which i will pass as a parameter.
```
qs = qs.replace(":tablename:", tableName);
```
How do you feel about that solution? I know it might be a security risk in an uncontrolled environment where the table name would be fetched as the user input, but in this case, i have a meta table containing right and valid table names for the GIS data classes which i will read before calling the query for fetching data for the specific class of GIS objects.
|
It sounds like the simplest thing to do here may be to create an abstract base class with all of the common GIS members and then to inherit the other X classes that will have nothing more than the necessary NHibernate mappings. I would then use the Factory pattern to create the object of the specific type using your metadata.
|
(N)Hibernate - is it possible to dynamically map multiple tables to the one class
|
[
"",
"c#",
"nhibernate",
"hibernate",
"orm",
"gis",
""
] |
Using C# .NET 2.0, I have a composite data class that does have the `[Serializable]` attribute on it. I am creating an `XMLSerializer` class and passing that into the constructor:
```
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
```
I am getting an exception saying:
> There was an error reflecting type.
Inside the data class there is another composite object. Does this also need to have the `[Serializable]` attribute, or by having it on the top object, does it recursively apply it to all objects inside?
|
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [`[XmlIgnore]`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlignoreattribute) attribute.
`XmlSerializer` does not use the [`[Serializable]`](https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute) attribute, so I doubt that is the problem.
|
Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
|
XmlSerializer - There was an error reflecting type
|
[
"",
"c#",
".net",
"xml",
"serialization",
".net-2.0",
""
] |
How would retrieve all customer's birthdays for a given month in SQL? What about MySQL?
I was thinking of using the following with SQL server.
```
select c.name
from cust c
where datename(m,c.birthdate) = datename(m,@suppliedDate)
order by c.name
```
|
don't forget the 29th February...
```
SELECT c.name
FROM cust c
WHERE (
MONTH(c.birthdate) = MONTH(@suppliedDate)
AND DAY(c.birthdate) = DAY(@suppliedDate)
) OR (
MONTH(c.birthdate) = 2 AND DAY(c.birthdate) = 29
AND MONTH(@suppliedDate) = 3 AND DAY(@suppliedDate) = 1
AND (YEAR(@suppliedDate) % 4 = 0) AND ((YEAR(@suppliedDate) % 100 != 0) OR (YEAR(@suppliedDate) % 400 = 0))
)
```
|
If you're asking for all birthdays in a given *month*, then you should supply the *month*, not a *date*:
```
SELECT c.name
FROM cust c
WHERE datepart(m,c.birthdate) = @SuppliedMonth
```
|
Monthly Birthday SQL Query
|
[
"",
"sql",
"mysql",
""
] |
The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a `file > 4GB`?
```
fpos_t currentpos;
sok=fseek(fp,0,SEEK_END);
assert(sok==0,"Seek error!");
fgetpos(fp,¤tpos);
m_filesize=currentpos;
```
|
If you're in Windows, you want [GetFileSizeEx (MSDN)](http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx). The return value is a 64bit int.
On linux [stat64 (manpage)](http://www.manpagez.com/man/2/stat64/) is correct. fstat if you're working with a FILE\*.
|
Ignore all the answers with "64" appearing in them. On Linux, you should add `-D_FILE_OFFSET_BITS=64` to your CFLAGS and use the `fseeko` and `ftello` functions which take/return `off_t` values instead of `long`. These are not part of C but POSIX. Other (non-Linux) POSIX systems may need different options to ensure that `off_t` is 64-bit; check your documentation.
|
Determining the size of a file larger than 4GB
|
[
"",
"c++",
"c",
"fseek",
"fgetpos",
""
] |
I am going to work on a project where a fairly large web app needs to tweaked to handle several languages. The thing runs with a hand crafted PHP code but it's pretty clean.
I was wondering what would be the best way to do that?
1. Making something on my own, trying to fit the actual architecture.
2. Rewriting a good part of it using a framework (e.g., Symfony) that will manage i18n for me?
For option 1, where should I store the i18n data? \*.po, xliff, pure DB?
I thought about an alternative: using Symfony only for the translation, but setting the controller to load the website as it already is. Quick, but dirty. On the other hand, it allows us to make the next modification, moving slowly to full Symfony: this web site is really a good candidate for that.
But maybe there are some standalone translation engines that would do the job better than an entire web framework. It's a bit like using a bazooka to kill a fly...
|
There are a number of ways of tackling this. None of them "the best way" and all of them with problems in the short term or the long term.
The very first thing to say is that multi lingual sites are not easy, translators and lovely people but hard to work with and most programmers see the problem as a technical one only. There is also another dimension, outside the scope of this answer, as to whether you are translating or localising. This involves looking at the target audiences cultural mores and then tailoring language, style, layout, colour, typeface etc., to that culture. Finally do not use MT, Machine Translation, for anything serious or if it needs to be accurate and when acquiring translators ensure that they are translating from a foreign language into their native language which means that they understand all the nuances of the target language.
Right. Solutions. On the basis that you do not want to rewrite the site then simply clone the site you have and translate the copies to the target language. Assuming the code base is stable you can use a VCS to manage any code changes. You can tweak individual parts of the site to fit the target language, for example French text is on average 30% larger than the equivalent English text so using one site to deliver this means you may (will) have formatting problems and need to swap a different css file in and out depending on the language. It might seem a clunky way to do it but then how long are the sites going to exist? The management overhead of doing it this way may well be less than other options.
Second way without rebuilding. Replace all content in the current site with tags and then put the different language in file or db tables, sniff the users desired language (do you have registered users who can make a preference or do you want to get the browser language tag, or is it going to be URL dot-com dot-fr, dot-de that make the choice) and then replace the tags with the target language. Then you need to address the sizing issues and the image issues separately. This solution is in effect when frameworks like Symfony and Zend do to implement l10n.
Then you could rebuild with a framework or with gettext and possibly have a cleaner solution but remember frameworks were designed to solve other problems, not translation and the translation component has come into the framework as partial solution not the full one.
The big problem with all the solutions is ongoing maintenance. Because not only do you have a code base but also multiple language bases to maintain. Unless you all in one solution is really clever and effective then to ongoing task will be difficult.
|
Work with languages files.
1. Replace each text string by a variable
2. Create one language file per language and in it define each variable with their corresponding text. (french.inc, dutch.inc ...)
3. Include the right file in each page.
That's for small sites.
If getting bigger, replace the files by a DB. :)
|
How would you transform a pre-existing web app into a multilingual one?
|
[
"",
"php",
"symfony",
"internationalization",
""
] |
How do you trace/profile your .NET applications?
The MSDN online help mentions Visual Studio Team (which I do not possess) and there is the Windows Performance Toolkit. But, are there other solutions you can recommend? Preferably (of course) a solution that works without changing the code (manually) and that can be integrated in Visual Studio.
|
See also [this question](https://stackoverflow.com/questions/49912/best-dotnet-memory-and-performance-profiler). JetBrains dotTrace is the best .NET profiler I have found (and I have tried pretty much every one there is), because it is the only one that has low enough overhead to handle a processor-intensive application. It is also simple, accurate and well-designed - highly recommended!
|
Happy birthday:
<http://www.jetbrains.com/profiler/>
|
Profiling C# / .NET applications
|
[
"",
"c#",
".net",
"visual-studio",
"profiling",
"profiler",
""
] |
I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!)
I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation.
It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?).
So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report.
|
On the data dictionary side there are a lot of tools you can use to such as [Schema Spy](http://schemaspy.sourceforge.net/)
To look at what queries are running look at views sys.v\_$sql and sys.v\_$sqltext. You will also need access to sys.all\_users
One thing to note that queries that use parameters will show up once with entries like
```
and TABLETYPE=’:b16’
```
while others that dont will show up multiple times such as:
```
and TABLETYPE=’MT’
```
An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the **WHERE rownum <= 20** and maybe add **ORDER BY module**. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)
```
SELECT
module,
sql_text,
username,
disk_reads_per_exec,
buffer_gets,
disk_reads,
parse_calls,
sorts,
executions,
rows_processed,
hit_ratio,
first_load_time,
sharable_mem,
persistent_mem,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
(SELECT
module,
sql_text ,
u.username ,
round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec,
s.disk_reads ,
s.buffer_gets ,
s.parse_calls ,
s.sorts ,
s.executions ,
s.rows_processed ,
100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio,
s.first_load_time ,
sharable_mem ,
persistent_mem ,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
sys.v_$sql s,
sys.all_users u
WHERE
s.parsing_user_id=u.user_id
and UPPER(u.username) not in ('SYS','SYSTEM')
ORDER BY
4 desc)
WHERE
rownum <= 20;
```
Note that if the query is long .. you will have to query v\_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH\_VALUE and pick up all the pieces. Eg:
```
SELECT
*
FROM
sys.v_$sqltext
WHERE
address = 'C0000000372B3C28'
and hash_value = '1272580459'
ORDER BY
address, hash_value, command_type, piece
;
```
|
Sorry for the short answer but it is late. Google "oracle event 10046 sql trace". It would be best to trace an individual session because figuring which SQL belongs to which session from v$sql is no easy if it is shared sql and being used by multiple users.
If you want to impress your Oracle DBA friends, learn how to set an oracle trace with event 10046, interpret the meaning of the wait events and find the top cpu consumers.
Quest had a free product that allowed you to capture the SQL as it went out from the client side but not sure if it works with your product/version of Oracle. Google "quest oracle sql monitor" for this.
Good night.
|
How to see the actual Oracle SQL statement that is being executed
|
[
"",
"sql",
"oracle",
""
] |
As compared to say:
```
REPLICATE(@padchar, @len - LEN(@str)) + @str
```
|
This is simply an inefficient use of SQL, no matter how you do it.
perhaps something like
```
right('XXXXXXXXXXXX'+ rtrim(@str), @n)
```
where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length).
But as I said you should really avoid doing this in your database.
|
I know this was originally asked back in 2008, but there are some new functions that were introduced with SQL Server 2012. The [FORMAT function](https://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx) simplifies padding left with zeros nicely. It will also perform the conversion for you:
```
declare @n as int = 2
select FORMAT(@n, 'd10') as padWithZeros
```
**Update:**
I wanted to test the actual efficiency of the FORMAT function myself. I was quite surprised to find the efficiency was not very good compared to the original answer from [AlexCuse](https://stackoverflow.com/users/794/alexcuse). Although I find the FORMAT function cleaner, it is not very efficient in terms of execution time. The Tally table I used has 64,000 records. Kudos to [Martin Smith](https://stackoverflow.com/users/73226/martin-smith) for pointing out execution time efficiency.
```
SET STATISTICS TIME ON
select FORMAT(N, 'd10') as padWithZeros from Tally
SET STATISTICS TIME OFF
```
SQL Server Execution Times:
CPU time = 2157 ms, elapsed time = 2696 ms.
```
SET STATISTICS TIME ON
select right('0000000000'+ rtrim(cast(N as varchar(5))), 10) from Tally
SET STATISTICS TIME OFF
```
SQL Server Execution Times:
> CPU time = 31 ms, elapsed time = 235 ms.
|
Most efficient T-SQL way to pad a varchar on the left to a certain length?
|
[
"",
"sql",
"sql-server",
"t-sql",
""
] |
I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.
**included.xhtml**
```
<ui:component>
<h:inputText id="contained_field"/>
<h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>
```
**example\_containing.xhtml**
```
<h:form id="containing_form">
<ui:include src="/included.xhtml"/>
</h:form>
```
How may I determine the ID of the form in the `update` method at runtime? Or better yet, the ID of the input field directly.
|
Bind the button to your backing bean, then use getParent() until you find the nearest form.
|
Programmatically I would use jsight's method. You can know the id of your elements (unless you let JSF create them, I don't know the means for numbering in the ids) by looking at it. h:form is a naming container so as long as you don't have it wrapped in another naming container it will be containingForm:containedfield The ':' is the naming separator by default is JSF and the ids are created like this, roughly anyway, (parentNamingContainerId:)\*componentId
|
Determine the ID of the JSF container form
|
[
"",
"java",
"jsf",
"seam",
"facelets",
""
] |
I am working on developing an on-screen keyboard with java. This keyboard has a `JComponent` for every possible key. When a mouse down is detected on the button, I want to send a specific keyboard code to the application currently on focus. The keyboard itself is within a `JFrame` with no decorations and set to always-on-top.
I found that the Robot class can be used to simulate these keyboard events on the native queue. However, in this case, selecting the `JComponent` would mean that the key-press is received on the `JFrame`, and I wouldn't be able to receive it in the other application
How can I keep my on-screen keyboard "Always-without-focus"? Is it maybe possible to use another approach to send the key-press?
|
Apparently the only way to do this is to have a JNI layer that will make the conversion from java to native. Java has no easy way to provide such funcionality.
This could be an interesting concept for a small, third party library for someone who wants to learn JNI...
|
I found [jnativehook](http://code.google.com/p/jnativehook/) when I was trying to control a gamebot with actual keyboard and mouse commands (to be more "human-like").
|
Sending a keyboard event from java to any application (on-screen-keyboard)
|
[
"",
"java",
"events",
"swing",
"keyboard",
"java-native-interface",
""
] |
I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help.
I would like to expose an iterator for a class like this:
```
template <class T>
class MyContainer
{
public:
// Here is the problem:
// typedef for MyIterator without exposing std::vector publicly?
MyIterator Begin() { return mHiddenContainerImpl.begin(); }
MyIterator End() { return mHiddenContainerImpl.end(); }
private:
std::vector<T> mHiddenContainerImpl;
};
```
Am I trying at something that isn't a problem? Should I just typedef std::vector< T >::iterator? I am hoping on just depending on the iterator, not the implementing container...
|
You may find the following article interesting as it addresses exactly the problem you have posted: [On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It](http://www.artima.com/cppsource/type_erasure.html)
|
I have done the following before so that I got an iterator that was independent of the container. This may have been overkill since I could also have used an API where the caller passes in a `vector<T*>&` that should be populated with all the elements and then the caller can just iterate from the vector directly.
```
template <class T>
class IterImpl
{
public:
virtual T* next() = 0;
};
template <class T>
class Iter
{
public:
Iter( IterImpl<T>* pImpl ):mpImpl(pImpl) {};
Iter( Iter<T>& rIter ):mpImpl(pImpl)
{
rIter.mpImpl = 0; // take ownership
}
~Iter() {
delete mpImpl; // does nothing if it is 0
}
T* next() {
return mpImpl->next();
}
private:
IterImpl<T>* mpImpl;
};
template <class C, class T>
class IterImplStl : public IterImpl<T>
{
public:
IterImplStl( C& rC )
:mrC( rC ),
curr( rC.begin() )
{}
virtual T* next()
{
if ( curr == mrC.end() ) return 0;
typename T* pResult = &*curr;
++curr;
return pResult;
}
private:
C& mrC;
typename C::iterator curr;
};
class Widget;
// in the base clase we do not need to include widget
class TestBase
{
public:
virtual Iter<Widget> getIter() = 0;
};
#include <vector>
class Widget
{
public:
int px;
int py;
};
class Test : public TestBase
{
public:
typedef std::vector<Widget> WidgetVec;
virtual Iter<Widget> getIter() {
return Iter<Widget>( new IterImplStl<WidgetVec, Widget>( mVec ) );
}
void add( int px, int py )
{
mVec.push_back( Widget() );
mVec.back().px = px;
mVec.back().py = py;
}
private:
WidgetVec mVec;
};
void testFn()
{
Test t;
t.add( 3, 4 );
t.add( 2, 5 );
TestBase* tB = &t;
Iter<Widget> iter = tB->getIter();
Widget* pW;
while ( pW = iter.next() )
{
std::cout << "px: " << pW->px << " py: " << pW->py << std::endl;
}
}
```
|
How can I expose iterators without exposing the container used?
|
[
"",
"c++",
"stl",
"iterator",
"encapsulation",
""
] |
I have a website laid out in tables. (a long mortgage form)
in each table cell is one HTML object. (text box, radio buttons, etc)
What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)?
|
This is the table I tested my code on:
```
<table id="myTable">
<tr>
<td><input type="text" value="hello" /></td>
<td><input type="checkbox" name="foo" value="2" /></td>
<td><input type="button" value="hi" /></td>
</tr>
</table>
```
Here is the code that worked:
```
// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
if(element.attachEvent) {
element.attachEvent(eventToHandle, eventHandler);
} else if(element.addEventListener) {
element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
} else {
element[eventToHandle] = eventHandler;
}
}
attachEventHandler(window, "onload", function() {
var myTable = document.getElementById("myTable");
var myTableCells = myTable.getElementsByTagName("td");
for(var cellIndex = 0; cellIndex < myTableCells.length; cellIndex++) {
var currentTableCell = myTableCells[cellIndex];
var originalBackgroundColor = currentTableCell.style.backgroundColor;
for(var childIndex = 0; childIndex < currentTableCell.childNodes.length; childIndex++) {
var currentChildNode = currentTableCell.childNodes[childIndex];
attachEventHandler(currentChildNode, "onfocus", function(e) {
(e.srcElement || e.target).parentNode.style.backgroundColor = "red";
});
attachEventHandler(currentChildNode, "onblur", function(e) {
(e.srcElement || e.target).parentNode.style.backgroundColor = originalBackgroundColor;
});
}
}
});
```
There are probably things here you could clean up, but I whipped this together quickly. This works even if there are multiple things in each cell.
This would be much easier, it should go without saying, if you used a library to assist you in this work - [**jQuery**](http://jquery.com) and [**MochiKit**](http://MochiKit.com) are the two I favor, though there are others that would work just as well.
---
Between the time I started writing this answer and the time I posted it, someone posted code that shows how you would do something like this in jQuery - as you can see, much shorter! Although I love libraries, I know some people either can't or will not use a library - in those cases my code should do the job.
|
Use jQuery to make your life easier, and you can do something like this:
```
$('#mytableid input').focus( function() {
$(this).addClass('highlight');
}).blur( function() {
$(this).removeClass('highlight');
});
```
This is basically saying when any input element in your table is under focus add the "highlight" class to it, and once it loses focus remove the class.
Setup your css as:
```
input.highlight { background-color: red; }
```
and you should be set.
|
JavaScript highlight table cell on tab in field
|
[
"",
"javascript",
"html",
""
] |
I'm just meddling in the ways of the RESTful web service in C# using ASP.Net 2.0 and have managed (via a class library, a reference to dll produced by the former and some adjustment of my web.config) to coax out a URI format like so:
http: //localhost/DevelopmentProject/testhandler/?input=thisismyinput
Which unremarkably just returns the input as a piece of text with the enlightening prefix "Your Input Was: "
I was under the impression that I could get the URI to become further ensmoothened to something more along the lines of:
http: //localhost/DevelopmentProject/testhandler/thisismyinput
and have the same result but have no idea how to get rid of the pesky "?input="
The entry to the httphandlers section of my web.config is (spaces added so code displays):
< add verb="\*" path="testhandler/\*" type="HandlerLib.testhandler, HandlerLib"/ >
I am running IIS 5.1 on the local machine, will this introduce a problem?
Essentially where am I going wrong?
Thanks.
|
I kinda cheated.
Try:
[My Article About How I Got Round It](http://www.codeproject.com/KB/aspnet/RestServicesInASPNET2.aspx)
|
One solution is to use UrlRewriting to rewrite the Url to what you need.
I use <http://urlrewriter.net/> to do all my rewriting, and you could setup something like this in your scenario
```
<rewriter>
<rewrite
url="DevelopmentProject/testhandler/([\w]+)"
to="DevelopmentProject/testhandler/?input=$1" />
</rewriter>
```
This would remain "http: //localhost/DevelopmentProject/testhandler/thisismyinput" in your browser address bar, yet process as "http: //localhost/DevelopmentProject/testhandler/?input=thisismyinput"
|
How do I "smoothly" format HttpHandler URI?
|
[
"",
"c#",
"asp.net",
"rest",
"httphandler",
"web-services",
""
] |
I need something in between a full text search and an index search:
I want to search for text in one column of my table (probably there will be an index on the column, too, if that matters).
Problem is, I want to search for words in the column, but I don't want to match parts.
For example, my column might contain business names:
*Mighty Muck Miller and Partners Inc.
Boy & Butter Breakfast company*
Now if I search for "*Miller*" I want to find the first line. But if I search for "*iller*" I don't want to find it, because there is no word starting with "iller". Searching for "*Break*" should find "*Boy & Butter Breakfast company*", though, since one word is starting with "*Break*".
So if I try and use
```
WHERE BusinessName LIKE %Break%
```
it will find too many hits.
Is there any way to Search for Words separated by whitespace **or other delimiters**?
(LINQ would be best, plain SQL would do, too)
**Important:** Spaces are by far not the only delimiters! Slashes, colons, dots, all non-alphanumerical characters should be considered for this to work!
|
SQL Server 2000 or above.
```
SELECT *
FROM dbo.TblBusinessNames
WHERE BusinessName like '%[^A-z^0-9]Break%' -- In the middle of a sentence
OR BusinessName like 'Break%' -- At the beginning of a sentence
```
Keyword Reference for **LIKE**: <http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx>
|
Your word delimiters are going to be many: space, tab, beginning of line, parentheses, periods, commas, exclamation/question marks etc. So, a pretty simple solution is to use a regex in your WHERE clause. (And it's going to be a lot more efficient than just ORing every possible delimiter you can think of.)
Since you mentioned LINQ, here's an article that describes how to do [efficient regex querying with SQL Server](http://msdn.microsoft.com/en-us/magazine/cc163473.aspx).
Complicated WHERE clauses like this always raise a red flag with me as far as performance is concerned, so I definitely suggest benchmarking whatever you end up with, you may decide to build a search index for the column after all.
**EDIT:** Saw you edited your question. When [writing your regex](http://regexlib.com/CheatSheet.aspx), it's easy to just have it use any non-alphanum character as a delimiter, i.e. [^0-9a-zA-Z], or \W for any non-word character, \b for any word boundary and \B for any non-word boundary. Or, instead of matching delimiters, just match any word, i.e. \w+. Here's [another example](http://www.sqlteam.com/article/regular-expressions-in-t-sql) of someone doing regex searches with SQL Server (more complicated than what you'd need).
|
Search for words in SQL Server index
|
[
"",
"sql",
"sql-server",
"linq",
"full-text-search",
""
] |
I have a JLabel (actually, it is a JXLabel).
I have put an icon and text on it.
`<icon><text>`
Now I wand to add some spacing on the left side of the component, like this:
`<space><icon><text>`
I DON'T accept suggestion to move the JLabel or add spacing by modifying the image.
I just want to know how to do it with plain java code.
|
I have found the solution!
```
setBorder(new EmptyBorder(0,10,0,0));
```
Thanks everyone!
|
The like this: is not very clear, but you can add spacing by adding a transparent border of a certain width to the label
|
How to add a horizontal gap with a JLabel
|
[
"",
"java",
"swing",
"jlabel",
"swingx",
""
] |
Should I stick with Sun's Java code conventions for PHP code?
|
For PHP, i'd suggest to follow [Zends suggestions](http://framework.zend.com/manual/1.12/en/manual.html)
As you might know, [Zend is the most widely used framework!](https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why)
|
You should be following one of the PSR standards for PHP approved by the [Framework Interop Group](http://www.php-fig.org/)
* [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) - Aims to provide a standard file, class and namespace convention..
* [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) - Aims to ensure a high level of technical interoperability between shared PHP code.
* [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) - Provides a Coding Style Guide for projects looking to standardise their code.
* [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) - Describes a common interface for logging libraries; the `LoggerInterface` exposes eight methods to write logs to the eight RFC 5424 levels.
* [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md) - Describes a specification for autoloading classes from file paths. It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0.
|
Which Coding convention to follow for PHP?
|
[
"",
"php",
"coding-style",
""
] |
How do you convert between hexadecimal numbers and decimal numbers in C#?
|
To convert from decimal to hex do...
```
string hexValue = decValue.ToString("X");
```
To convert from hex to decimal do either...
```
int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
```
or
```
int decValue = Convert.ToInt32(hexValue, 16);
```
|
Hex -> decimal:
```
Convert.ToInt64(hexString, 16);
```
Decimal -> Hex
```
string.Format("{0:x}", intValue);
```
|
How to convert numbers between hexadecimal and decimal
|
[
"",
"c#",
"hex",
"type-conversion",
"decimal",
""
] |
I recently started learning [Emacs](http://www.gnu.org/software/emacs/). I went through the tutorial, read some introductory articles, so far so good.
Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.
I read all information I could find but most of it seems fairly outdated and I'm still confused.
The questions:
1. What is their difference?
2. Which mode should I install and use?
3. Are there other Emacs add-ons that are essential for Python development?
Relevant links:
* [EmacsEditor](http://wiki.python.org/moin/EmacsEditor) @ wiki.python.org
* [PythonMode](http://www.emacswiki.org/cgi-bin/wiki/PythonMode) @ emacswiki.org
|
If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it didn't work very nicely in the past, but there are updates available that fix some of the issues (for instance, on the emacswiki page you link), and you would hope some were integrated upstream by now. If I were the GNU Emacs kind, I would use python.el until I found specific reasons not to.
The python-mode.el's single biggest problem as far as I've seen is that it doesn't quite understand triple-quoted strings. It treats them as single-quoted, meaning that a single quote inside a triple-quoted string will throw off the syntax highlighting: it'll think the string has ended there. You may also need to change your auto-mode-alist to turn on python-mode for .py files; I don't remember if that's still the case but my init.el has been setting auto-mode-alist for many years now.
As for other addons, nothing I would consider 'essential'. XEmacs's func-menu is sometimes useful, it gives you a little function/class browser menu for the current file. I don't remember if GNU Emacs has anything similar. I have a rst-mode for reStructuredText editing, as that's used in some projects. Tying into whatever VC you use, if any, may be useful to you, but there is builtin support for most and easily downloaded .el files for the others.
|
[This site](http://www.rwdev.eu/articles/emacspyeng) has a description of how to get Python code completion in Emacs.
[Ropemacs](http://rope.sourceforge.net/ropemacs.html) is a way to get Rope to work in emacs. I haven't had extensive experience with either, but they're worth looking into.
|
Emacs and Python
|
[
"",
"python",
"emacs",
""
] |
I have an enum that looks as follows:
```
public enum TransactionStatus { Open = 'O', Closed = 'C'};
```
and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed.
now because the data comes out of the database as an object I am having a heck of a time writing comparison code.
The best I can do is to write:
```
protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) {
return ((char)enum_status).ToString() == obj_status.ToString();
}
```
However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. [Supposedly all enums inherit from System.Enum](http://blogs.msdn.com/abhinaba/archive/2006/01/14/enumerting-all-values-of-an-enum.aspx) but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question.
I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing?
|
```
static void Main(string[] args)
{
object val = 'O';
Console.WriteLine(EnumEqual(TransactionStatus.Open, val));
val = 'R';
Console.WriteLine(EnumEqual(DirectionStatus.Left, val));
Console.ReadLine();
}
public static bool EnumEqual(Enum e, object boxedValue)
{
return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue));
}
public enum TransactionStatus { Open = 'O', Closed = 'C' };
public enum DirectionStatus { Left = 'L', Right = 'R' };
```
|
Enums are generally messy in C# so when using .NET 2.0 its common to wrap the syntax with generics to avoid having to write such clumsy code.
In .NET 1.1 you can do something like the below, although it's not much tidier than the original snippet:
```
protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status)
{
return (enum_status == Enum.Parse(typeof(TransactionStatus), obj_status.ToString()));
}
```
This is about the same amount of code but you are now doing enum rather than string comparison.
You could also use the debugger/documentation to see if `obj_status` really is an object or whether you can safely cast it to a string.
|
I need a helper method to compare a char Enum and a char boxed to an object
|
[
"",
"c#",
"enums",
"casting",
""
] |
I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.
My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the [split loop](http://www.refactoring.com/catalog/splitLoop.html) refactoring in mind), looks rather bloated:
(alt 1)
```
r = xrange(1, 10)
twos = 0
threes = 0
for v in r:
if v % 2 == 0:
twos+=1
if v % 3 == 0:
threes+=1
print twos
print threes
```
This looks rather nice, but has the drawback of expanding the expression to a list:
(alt 2)
```
r = xrange(1, 10)
print len([1 for v in r if v % 2 == 0])
print len([1 for v in r if v % 3 == 0])
```
What I would really like is something like a function like this:
(alt 3)
```
def count(iterable):
n = 0
for i in iterable:
n += 1
return n
r = xrange(1, 10)
print count(1 for v in r if v % 2 == 0)
print count(1 for v in r if v % 3 == 0)
```
But this looks a lot like something that could be done without a function. The final variant is this:
(alt 4)
```
r = xrange(1, 10)
print sum(1 for v in r if v % 2 == 0)
print sum(1 for v in r if v % 3 == 0)
```
and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.
So, my question to you is:
Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.
To clear up some confusion below:
* In reality my filter predicates are more complex than just this simple test.
* The objects I iterate over are larger and more complex than just numbers
* My filter functions are more different and hard to parameterize into one predicate
|
Having to iterate over the list multiple times isn't elegant IMHO.
I'd probably create a function that allows doing:
```
twos, threes = countmatching(xrange(1,10),
lambda a: a % 2 == 0,
lambda a: a % 3 == 0)
```
A starting point would be something like this:
```
def countmatching(iterable, *predicates):
v = [0] * len(predicates)
for e in iterable:
for i,p in enumerate(predicates):
if p(e):
v[i] += 1
return tuple(v)
```
Btw, "itertools recipes" has a recipe for doing much like your alt4.
```
def quantify(seq, pred=None):
"Count how many times the predicate is true in the sequence"
return sum(imap(pred, seq))
```
|
Alt 4! But maybe you should refactor the code to a function that takes an argument which should contain the divisible number (two and three). And then you could have a better functionname.
```
def methodName(divNumber, r):
return sum(1 for v in r if v % divNumber == 0)
print methodName(2, xrange(1, 10))
print methodName(3, xrange(1, 10))
```
|
Most pythonic way of counting matching elements in something iterable
|
[
"",
"python",
"list-comprehension",
""
] |
The problem itself is simple, but I can't figure out a solution that does it in one query, and here's my "abstraction" of the problem to allow for a simpler explanation:
**I will let my original explenation stand, but here's a set of sample data and the result i expect:**
Ok, so here's some sample data, i separated pairs by a blank line
```
-------------
| Key | Col | (Together they from a Unique Pair)
--------------
| 1 Foo |
| 1 Bar |
| |
| 2 Foo |
| |
| 3 Bar |
| |
| 4 Foo |
| 4 Bar |
--------------
```
And the result I would expect, **after running the query once**, it need to be able to select this result set in one query:
```
1 - Foo
2 - Foo
3 - Bar
4 - Foo
```
*Original explenation:*
I have a table, call it `TABLE` where I have a two columns say `ID` and `NAME` which together form the primary key of the table. Now I want to select something where `ID=1` and then first checks if it can find a row where `NAME` has the value "John", if "John" does not exist it should look for a row where `NAME` is "Bruce" - but only return "John" if both "Bruce" and "John" exists or only "John" exists of course.
Also note that it should be able to return several rows per query that match the above criteria but with different ID/Name-combinations of course, and that the above explanation is just a simplification of the real problem.
I could be completely blinded by my own code and line of thought but I just can't figure this out.
|
This is fairly similar to what you wrote, but should be fairly speedy as NOT EXISTS is more efficient, in this case, than NOT IN...
```
mysql> select * from foo;
+----+-----+
| id | col |
+----+-----+
| 1 | Bar |
| 1 | Foo |
| 2 | Foo |
| 3 | Bar |
| 4 | Bar |
| 4 | Foo |
+----+-----+
SELECT id
, col
FROM foo f1
WHERE col = 'Foo'
OR ( col = 'Bar' AND NOT EXISTS( SELECT *
FROM foo f2
WHERE f1.id = f2.id
AND f2.col = 'Foo'
)
);
+----+-----+
| id | col |
+----+-----+
| 1 | Foo |
| 2 | Foo |
| 3 | Bar |
| 4 | Foo |
+----+-----+
```
|
You can join the initial table to itself with an OUTER JOIN like this:
```
create table #mytest
(
id int,
Name varchar(20)
);
go
insert into #mytest values (1,'Foo');
insert into #mytest values (1,'Bar');
insert into #mytest values (2,'Foo');
insert into #mytest values (3,'Bar');
insert into #mytest values (4,'Foo');
insert into #mytest values (4,'Bar');
go
select distinct
sc.id,
isnull(fc.Name, sc.Name) sel_name
from
#mytest sc
LEFT OUTER JOIN #mytest fc
on (fc.id = sc.id
and fc.Name = 'Foo')
```
like that.
|
Selecting unique rows in a set of two possibilities
|
[
"",
"sql",
"mysql",
"sql-server",
"database",
"postgresql",
""
] |
I have an `ArrayList<String>` that I'd like to return a copy of. `ArrayList` has a clone method which has the following signature:
```
public Object clone()
```
After I call this method, how do I cast the returned Object back to `ArrayList<String>`?
|
```
ArrayList newArrayList = (ArrayList) oldArrayList.clone();
```
|
Why would you want to clone? Creating a new list usually makes more sense.
```
List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);
```
Job done.
|
How do I clone a generic List in Java?
|
[
"",
"java",
"generics",
"arraylist",
"clone",
""
] |
Is there anyway in Java to delete data (e.g., a variable value, object) and be sure it can't be recovered from memory? Does assigning `null` to a variable in Java delete the value from memory? Any ideas? Answers applicable to other languages are also acceptable.
|
Due to the wonders virtual memory, it is nearly impossible to delete something from memory in a completely irretrievable manner. Your best bet is to zero out the value fields; however:
* This does not mean that an old (unzeroed) copy of the object won't be left on an unused swap page, which could persist across reboots.
* Neither does it stop someone from attaching a debugger to your application and poking around before the object gets zeroed or crashing the VM and poking around in the heap dump.
|
Store sensitive data in an array, then "zero" it out as soon as possible.
Any data in RAM can be copied to the disk by a virtual memory system. Data in RAM (or a core dump) can also be inspected by debugging tools. To minimize the chance of this happening, you should strive for the following
* keep the time window a secret is
present in memory as short as
possible
* be careful about IO pipelines (e.g.,
BufferedInputStream) that internally
buffer data
* keep the references to the secret on the stack and out of the heap
* don't use immutable types, like
`String`, to hold secrets
The cryptographic APIs in Java use this approach, and any APIs you create should support it too. For example, [`KeyStore.load`](http://java.sun.com/j2se/1.5.0/docs/api/java/security/KeyStore.html#load(java.io.InputStream,%20char[])) allows a caller to clear a password `char[]`, and when the call completes, as does the [KeySpec for password-based encryption.](http://java.sun.com/j2se/1.5.0/docs/api/javax/crypto/spec/PBEKeySpec.html#clearPassword())
Ideally, you would use a `finally` block to zero the array, like this:
```
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream is = …
char[] pw = System.console().readPassword();
try {
ks.load(is, pw);
}
finally {
Arrays.fill(pw, '\0');
}
```
|
Irretrievably destroying data in Java
|
[
"",
"java",
"security",
""
] |
I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:
```
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
(SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);
```
I tried but get a syntax error message.
What would you do if you want to do this?
|
No "VALUES", no parenthesis:
```
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
```
|
You have two syntax options:
**Option 1**
```
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
CREATE TABLE Table2 (
id int identity(1, 1) not null,
LongIntColumn2 int,
CurrencyColumn2 money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1
```
**Option 2**
```
CREATE TABLE Table1 (
id int identity(1, 1) not null,
LongIntColumn1 int,
CurrencyColumn money
)
INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1
```
Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).
|
How to do INSERT into a table records extracted from another table
|
[
"",
"sql",
"ms-access",
""
] |
Can you create websites with Chinese characters in PHP?
UPDATE: Perhaps I should have said - is it straight forward. Because some languages like Java make it extremely easy. Perhaps localisation in PHP isn't as easy as Java???
|
Yes on both counts. Read [this guide](http://www.herongyang.com/PHP-Chinese/) on building Chinese websites in PHP.
|
Yes, but you need to know what you are doing...
Read this [article](http://www.phpwact.org/php/i18n/charsets) (search for *PHP's Problem with Character Encoding*) for starters.
|
Is PHP international?
|
[
"",
"php",
"localization",
""
] |
I was reading a book on programming skills wherein the author asks the interviewee, "How do you crash a JVM?" I thought that you could do so by writing an infinite for-loop that would eventually use up all the memory.
Anybody has any idea?
|
The closest thing to a single "answer" is `System.exit()` which terminates the JVM immediately without proper cleanup. But apart from that, native code and resource exhaustion are the most likely answers. Alternatively you can go looking on Sun's bug tracker for bugs in your version of the JVM, some of which allow for repeatable crash scenarios. We used to get semi-regular crashes when approaching the 4 Gb memory limit under the 32-bit versions (we generally use 64-bit now).
|
I wouldn't call throwing an OutOfMemoryError or StackOverflowError a crash. These are just normal exceptions. To really crash a VM there are 3 ways:
1. Use JNI and crash in the native code.
2. If no security manager is installed you can use reflection to crash the VM. This is VM specific, but normally a VM stores a bunch of pointers to native resources in private fields (e.g. a pointer to the native thread object is stored in a long field in **java.lang.Thread**). Just change them via reflection and the VM will crash sooner or later.
3. All VMs have bugs, so you just have to trigger one.
For the last method I have a short example, which will crash a Sun Hotspot VM quiet nicely:
```
public class Crash {
public static void main(String[] args) {
Object[] o = null;
while (true) {
o = new Object[] {o};
}
}
}
```
This leads to a stack overflow in the GC so you will get no StackOverflowError but a real crash including a hs\_err\* file.
|
How do you crash a JVM?
|
[
"",
"java",
"jvm",
""
] |
What's the best way to store a linked list in a MySQL database so that inserts are simple (i.e. you don't have to re-index a bunch of stuff every time) and such that the list can easily be pulled out in order?
|
Store an integer column in your table called 'position'. Record a 0 for the first item in your list, a 1 for the second item, etc. Index that column in your database, and when you want to pull your values out, sort by that column.
```
alter table linked_list add column position integer not null default 0;
alter table linked_list add index position_index (position);
select * from linked_list order by position;
```
To insert a value at index 3, modify the positions of rows 3 and above, and then insert:
```
update linked_list set position = position + 1 where position >= 3;
insert into linked_list (my_value, position) values ("new value", 3);
```
|
Using Adrian's solution, but instead of incrementing by 1, increment by 10 or even 100. Then insertions can be calculated at half of the difference of what you're inserting between without having to update everything below the insertion. Pick a number large enough to handle your average number of insertions - if its too small then you'll have to fall back to updating all rows with a higher position during an insertion.
|
Linked List in SQL
|
[
"",
"sql",
"data-structures",
""
] |
I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "*true*" in case the value of this specified column **isn't null** and "*false*" in case the value **is null**.
How can I select such a boolean with T-SQL?
|
You have to use a **CASE** statement for this:
```
SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName;
```
|
Or you can do like this:
```
SELECT RealColumn, CAST(0 AS bit) AS FakeBitColumn FROM tblTable
```
|
How to output a boolean in T-SQL based on the content of a column?
|
[
"",
"sql",
"sql-server-2000",
""
] |
I maintain a Java Swing application.
For backwards compatibility with java 5 (for Apple machines), we maintain two codebases, 1 using features from Java 6, another without those features.
The code is largely the same, except for 3-4 classes that uses Java 6 features.
I wish to just maintain 1 codebase. Is there a way during compilation, to get the Java 5 compiler to 'ignore' some parts of my code?
I do not wish to simply comment/uncomment parts of my code, depending on the version of my java compiler.
|
Assuming that the classes have similar functionality with 1.5 vs. 6.0 differences in implementation you could merge them into one class. Then, without editing the source to comment/uncomment, you can rely on the optimization that the compiler always do. If an if expression is always false, the code in the if statement will not be included in the compilation.
You can make a static variable in one of your classes to determine which version you want to run:
```
public static final boolean COMPILED_IN_JAVA_6 = false;
```
And then have the affected classes check that static variable and put the different sections of code in a simple if statement
```
if (VersionUtil.COMPILED_IN_JAVA_6) {
// Java 6 stuff goes here
} else {
// Java 1.5 stuff goes here
}
```
Then when you want to compile the other version you just have to change that one variable and recompile. It might make the java file larger but it will consolidate your code and eliminate any code duplication that you have. Your editor may complain about unreachable code or whatever but the compiler should blissfully ignore it.
|
The suggestions about using custom class loaders and dynamically commented code are a bit incredulous when it comes to maintenance and the preservation of the sanity of whichever poor soul picks up the project after you shuffle to pastures new.
The solution is easy. Pull the affected classes out into two separate, independent projects - make sure the package names are the same, and just compile into jars that you can then consume in your main project. If you keep the package names the same, and the method signatures the same, no problems - just drop whichever version of the jar you need into your deployment script. I would assume you run separate build scripts or have separate targets in the same script - ant and maven can both easily handle conditionally grabbing files and copying them.
|
Java Compilation - Is there a way to tell the compiler to ignore parts of my code?
|
[
"",
"java",
"swing",
"compilation",
""
] |
As far as i know it is not possible to do the following in C# 2.0
```
public class Father
{
public virtual Father SomePropertyName
{
get
{
return this;
}
}
}
public class Child : Father
{
public override Child SomePropertyName
{
get
{
return this;
}
}
}
```
I workaround the problem by creating the property in the derived class as "new", but of course that is not polymorphic.
```
public new Child SomePropertyName
```
Is there any solution in 2.0?
What about any features in 3.5 that address this matter?
|
This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code:
```
class B {
S Get();
Set(S);
}
class D : B {
T Get();
Set(T);
}
```
For the `Get` methods, covariance means that `T` must either be `S` or a type derived from `S`. Otherwise, if you had a reference to an object of type `D` stored in a variable typed `B`, when you called `B.Get()` you wouldn't get an object representable as an `S` back -- breaking the type system.
For the `Set` methods, contravariance means that `T` must either be `S` or a type that `S` derives from. Otherwise, if you had a reference to an object of type `D` stored in a variable typed `B`, when you called `B.Set(X)`, where `X` was of type `S` but not of type `T`, `D::Set(T)` would get an object of a type it did not expect.
In C#, there was a conscious decision to disallow changing the type when overloading properties, even when they have only one of the getter/setter pair, because it would otherwise have very inconsistent behavior (*"You mean, I can change the type on the one with a getter, but not one with both a getter and setter? Why not?!?"* -- Anonymous Alternate Universe Newbie).
|
You can re-declare (new), but you can't re-declare and override at the same time (with the same name).
One option is to use a protected method to hide the detail - this allows both polymorphism and hiding at the same time:
```
public class Father
{
public Father SomePropertyName
{
get {
return SomePropertyImpl();
}
}
protected virtual Father SomePropertyImpl()
{
// base-class version
}
}
public class Child : Father
{
public new Child SomePropertyName
{
get
{ // since we know our local SomePropertyImpl actually returns a Child
return (Child)SomePropertyImpl();
}
}
protected override Father SomePropertyImpl()
{
// do something different, might return a Child
// but typed as Father for the return
}
}
```
|
Can I Override with derived types?
|
[
"",
"c#",
".net",
"inheritance",
"covariance",
""
] |
I'd like to capture the output of [`var_dump`](https://www.php.net/manual/en/function.var-dump.php) to a string.
The PHP documentation says;
> As with anything that outputs its result directly to the browser, the [output-control functions](https://www.php.net/manual/en/ref.outcontrol.php) can be used to capture the output of this function, and save it in a string (for example).
What would be an example of how that might work?
`print_r()` isn't a valid possibility, because it's not going to give me the information that I need.
|
Use output buffering:
```
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
```
|
# Try [`var_export`](http://php.net/var_export)
You may want to check out [`var_export`](http://php.net/var_export) — while it doesn't provide the same output as `var_dump` it does provide a second `$return` parameter which will cause it to return its output rather than print it:
```
$debug = var_export($my_var, true);
```
## Why?
I prefer this one-liner to using `ob_start` and `ob_get_clean()`. I also find that the output is a little easier to read, since it's just PHP code.
The difference between `var_dump` and `var_export` is that `var_export` returns a *"parsable string representation of a variable"* while `var_dump` simply dumps information about a variable. What this means in practice is that `var_export` gives you valid PHP code (but may not give you quite as much information about the variable, especially if you're working with [resources](http://php.net/manual/en/language.types.resource.php)).
### Demo:
```
$demo = array(
"bool" => false,
"int" => 1,
"float" => 3.14,
"string" => "hello world",
"array" => array(),
"object" => new stdClass(),
"resource" => tmpfile(),
"null" => null,
);
// var_export -- nice, one-liner
$debug_export = var_export($demo, true);
// var_dump
ob_start();
var_dump($demo);
$debug_dump = ob_get_clean();
// print_r -- included for completeness, though not recommended
$debug_printr = print_r($demo, true);
```
## The difference in output:
### var\_export (`$debug_export` in above example):
```
array (
'bool' => false,
'int' => 1,
'float' => 3.1400000000000001,
'string' => 'hello world',
'array' =>
array (
),
'object' =>
stdClass::__set_state(array(
)),
'resource' => NULL, // Note that this resource pointer is now NULL
'null' => NULL,
)
```
### var\_dump (`$debug_dump` in above example):
```
array(8) {
["bool"]=>
bool(false)
["int"]=>
int(1)
["float"]=>
float(3.14)
["string"]=>
string(11) "hello world"
["array"]=>
array(0) {
}
["object"]=>
object(stdClass)#1 (0) {
}
["resource"]=>
resource(4) of type (stream)
["null"]=>
NULL
}
```
### print\_r (`$debug_printr` in above example):
```
Array
(
[bool] =>
[int] => 1
[float] => 3.14
[string] => hello world
[array] => Array
(
)
[object] => stdClass Object
(
)
[resource] => Resource id #4
[null] =>
)
```
## Caveat: `var_export` does not handle circular references
If you're trying to dump a variable with circular references, calling `var_export` will result in a PHP warning:
```
$circular = array();
$circular['self'] =& $circular;
var_export($circular);
```
Results in:
```
Warning: var_export does not handle circular references in example.php on line 3
array (
'self' =>
array (
'self' => NULL,
),
)
```
Both `var_dump` and `print_r`, on the other hand, will output the string `*RECURSION*` when encountering circular references.
|
How can I capture the result of var_dump to a string?
|
[
"",
"php",
"string",
"var-dump",
""
] |
I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator.
So far I'm torn between:
* Sun's umem
* Google's tcmalloc
* Intel's threading building blocks allocator
* Emery Berger's hoard
From what I've found hoard might be the fastest, but I hadn't heard of it before today, so I'm skeptical if its really as good as it seems. Anyone have personal experience trying out these allocators?
|
I've used tcmalloc and read about Hoard. Both have similar implementations and both achieve roughly linear performance scaling with respect to the number of threads/CPUs (according to the graphs on their respective sites).
So: if performance is really that incredibly crucial, then do performance/load testing. Otherwise, just roll a dice and pick one of the listed (weighted by ease of use on your target platform).
And from [trshiv's link](http://developers.sun.com/solaris/articles/multiproc/multiproc.html), it looks like Hoard, tcmalloc, and ptmalloc are all roughly comparable for speed. Overall, tt looks like ptmalloc is optimized for taking as little room as possible, Hoard is optimized for a trade-off of speed + memory usage, and tcmalloc is optimized for pure speed.
|
The only way to really tell which memory allocator is right for your application is to try a few out. All of the allocators mentioned were written by smart folks and will beat the others on one particular microbenchmark or another. If all your application does all day long is malloc one 8 byte chunk in thread A and free it in thread B, and doesn't need to handle anything else at all, you could probably write a memory allocator that beats the pants off any of those listed so far. It just won't be very useful for much else. :)
I have some experience using Hoard where I work (enough so that one of the more obscure bugs addressed in the recent 3.8 release was found as a result of that experience). It's a very good allocator - but how good, for you, depends on your workload. And you do have to pay for Hoard (though it's not too expensive) in order to use it in a commercial project without GPL'ing your code.
A very slightly adapted ptmalloc2 has been the allocator behind glibc's malloc for quite a while now, and so it's incredibly widely used and tested. If stability is important above all things, it might be a good choice, but you didn't mention it in your list, so I'll assume it's out. For certain workloads, it's terrible - but the same is true of any general purpose malloc.
If you're willing to pay for it (and the price is reasonable, in my experience), [SmartHeap SMP](http://www.microquill.com/smartheapsmp/index.html "SmartHeap SMP") is also a good choice. Most of the other allocators mentioned are designed as drop-in malloc/free new/delete replacements that can be LD\_PRELOAD'd. SmartHeap can be used that way as well, but it also includes an entire allocation-related API that lets you fine-tune your allocators to your heart's content. In tests that we've done (again, very specific to a particular application), SmartHeap was about the same as Hoard for performance when acting as a drop-in malloc replacement; the real difference between the two is the degree of customization. You can get better performance the less general-purpose you need your allocator to be.
And depending on your use case, a general-purpose multithreaded allocator might not be what you want to use at all; if you're constantly malloc & free'ing objects that are all the same size, you might want to just write a simple slab allocator. Slab allocation is used in several places in the Linux kernel that fit that description. (I would give you a couple more useful links, but I'm a "new user" and Stack Overflow has decided that new users are not allowed to be *too* helpful all in one answer. Google can help out well enough, though.)
|
Multithreaded Memory Allocators for C/C++
|
[
"",
"c++",
"c",
"memory",
"malloc",
"allocation",
""
] |
The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging...
```
System.Diagnostics.EventLog.WriteEntry("MyEventSource", "My Special Message")
```
Is there a way to set the user information in the resulting event log entry using .NET?
|
Toughie ...
I looked for a way to fill the user field with a .NET method. Unfortunately there is none, and you must import the plain old Win32 API [ReportEvent function](<http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx)> with a `DLLImportAttribute`
You must also redeclare the function with the right types, as [Platform Invoke Data Types](http://msdn.microsoft.com/en-us/library/ac7ay120.aspx) says
So
```
BOOL ReportEvent(
__in HANDLE hEventLog,
__in WORD wType,
__in WORD wCategory,
__in DWORD dwEventID,
__in PSID lpUserSid,
__in WORD wNumStrings,
__in DWORD dwDataSize,
__in LPCTSTR *lpStrings,
__in LPVOID lpRawData
);
```
becomes
```
[DllImport("Advapi32.dll", EntryPoint="ReportEventW", SetLastError=true,
CharSet=CharSet.Unicode)]
bool WriteEvent(
IntPtr hEventLog, //Where to find it ?
ushort wType,
ushort wCategory,
ulong dwEventID,
IntPtr lpUserSid, // We'll leave this struct alone, so just feed it a pointer
ushort wNumStrings,
ushort dwDataSize,
string[] lpStrings,
IntPtr lpRawData
);
```
You also want to look at [OpenEventLog](<http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx)> and [ConvertStringSidToSid](<http://msdn.microsoft.com/en-us/library/aa376402(VS.85).aspx)>
Oh, and you're writing unmanaged code now... Watch out for memory leaks.Good luck :p
|
You need to add it yourself into the event message.
Use the System.Security.Principal namespace to get the current identity of the thread logging the event.
|
.NET : How to set user information in an EventLog Entry?
|
[
"",
"c#",
".net",
"vb.net",
"event-log",
""
] |
I've got a CSV file containing latitude and longitude values, such as:
> "25°36'55.57""E","45°39'12.52""N"
Anyone have a quick and simple piece of C# code to convert this to double values?
Thanks
|
If you mean C# code to do this:
result = 25 + (36 / 60) + (55.57 / 3600)
First you'll need to parse the expression with Regex or some other mechanism and split it into the individual parts. Then:
```
String hour = "25";
String minute = "36";
String second = "55.57";
Double result = (hour) + (minute) / 60 + (second) / 3600;
```
And of course a switch to flip sign depending on N/S or E/S. Wikipedia has a little on that:
> For calculations, the West/East suffix is replaced by a negative sign in the western hemisphere. Confusingly, the convention of negative for East is also sometimes seen. The preferred convention -- that East be positive -- is consistent with a right-handed Cartesian coordinate system with the North Pole up. A specific longitude may then be combined with a specific latitude (usually positive in the northern hemisphere) to give a precise position on the Earth's surface.
> (<http://en.wikipedia.org/wiki/Longitude>)
|
Thanks for all the quick answers. Based on the answer by amdfan, I put this code together that does the job in C#.
```
/// <summary>The regular expression parser used to parse the lat/long</summary>
private static Regex Parser = new Regex("^(?<deg>[-+0-9]+)[^0-9]+(?<min>[0-9]+)[^0-9]+(?<sec>[0-9.,]+)[^0-9.,ENSW]+(?<pos>[ENSW]*)$");
/// <summary>Parses the lat lon value.</summary>
/// <param name="value">The value.</param>
/// <remarks>It must have at least 3 parts 'degrees' 'minutes' 'seconds'. If it
/// has E/W and N/S this is used to change the sign.</remarks>
/// <returns></returns>
public static double ParseLatLonValue(string value)
{
// If it starts and finishes with a quote, strip them off
if (value.StartsWith("\"") && value.EndsWith("\""))
{
value = value.Substring(1, value.Length - 2).Replace("\"\"", "\"");
}
// Now parse using the regex parser
Match match = Parser.Match(value);
if (!match.Success)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, "Lat/long value of '{0}' is not recognised", value));
}
// Convert - adjust the sign if necessary
double deg = double.Parse(match.Groups["deg"].Value);
double min = double.Parse(match.Groups["min"].Value);
double sec = double.Parse(match.Groups["sec"].Value);
double result = deg + (min / 60) + (sec / 3600);
if (match.Groups["pos"].Success)
{
char ch = match.Groups["pos"].Value[0];
result = ((ch == 'S') || (ch == 'W')) ? -result : result;
}
return result;
}
```
|
What's the easiest way to convert latitude and longitude to double values
|
[
"",
"c#",
"gis",
""
] |
I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.
Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?
|
You can do something like this (using the [Commons](http://commons.apache.org/fileupload/) library):
```
public class UploadFileServiceImpl extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/plain");
try
{
FileItem uploadItem = getFileItem(request);
if (uploadItem == null)
{
// ERROR
}
// Add logic here
}
catch (Exception ex)
{
response.getWriter().write("Error: file upload failure: " + ex.getMessage());
}
}
private FileItem getFileItem(HttpServletRequest request) throws FileUploadException
{
DiskFileItemFactory factory = new DiskFileItemFactory();
// Add here your own limit
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
ServletFileUpload upload = new ServletFileUpload(factory);
// Add here your own limit
upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
List<?> items = upload.parseRequest(request);
Iterator<?> it = items.iterator();
while (it.hasNext())
{
FileItem item = (FileItem) it.next();
// Search here for file item
if (!item.isFormField() &&
// Check field name to get to file item ...
{
return item;
}
}
return null;
}
}
```
|
With JavaEE 6 / Servlet 3.0 the preferred way of doing that would be to use the [@MultipartConfig annotation](http://docs.oracle.com/javaee/6/tutorial/doc/gmhal.html) on your servlet like this:
```
@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024,
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
public class UploadFileServiceImpl extends HttpServlet ...
```
|
Aborting upload from a servlet to limit file size
|
[
"",
"java",
"http",
"servlets",
"upload",
""
] |
(MFC Question) What's the best way to determine the current displayed client area in a CScrollView? I only need the size of the visible portion, so GetClientRect() won't work here.
|
You do need to use GetClientRect(), but I think you're asking the wrong question. It is not so that in a scrolled view there is a very big client window that is physically scrolled. Instead, when you scroll, the DC's viewportext and mapping mode are adjusted, which make it seem like your view is bigger than it actually is. So, if you want to draw a line from the top left corner of the bottom right corner of the current viewport, you do need GetViewPortOrg() and GetViewportExt(). If these return the wrong values, something is wrong in your use of CScrollView. Did you call SetScrollSizes()?
|
Inside your OnDraw() function, you could call pDC->GetViewportOrg and pDC->GetViewportExt.
**EDIT**: Sorry, I forgot that Viewport extents are only scaling factors. I agree that what you really need here is the client rect.
|
CScrollView and window size
|
[
"",
"c++",
"winapi",
"mfc",
""
] |
Is it possible to split the information in a .csproj across more than one file? A bit like a project version of the `partial class` feature.
|
You can not have more than one master csproj. But because the underneath wiring of the csproj is done using msbuild you can simply have multiple partial csproj that import each other. The solution file would see the most *derived* csproj.
**project1.csproj**
```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
....
</Project>
```
**project2.csproj**
```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="project1.csproj" />
...
</Project>
```
**project.csproj** - this is the main project that is referred by the solution file.
```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="project2.csproj" />
...
</Project>
```
Bottom line is that using msbuild **Import** feature you can have partial csproj files where each one would contain definitions that the main project (project.csproj in my example) would use.
---
Visual Studio will show a **Security Warning for *project*** dialog when you open your changed solution or project file. Choose the option **Load Project Normally** and press **OK**. When opening the solution again later the warning will not be shown because the configuration to **Load Project Normally** is stored in the **suo** file.
|
Yes, you can split information across several files. You can use [Import Element (MSBuild)](http://msdn.microsoft.com/en-us/library/92x05xfs.aspx).
Note that Visual Studio will give you [annoying security warning](http://msdn.microsoft.com/en-us/library/ms228217.aspx) if you will try to open project file that includes other project files.
Useful linky from MSDN:
[How to: Use the Same Target in Multiple Project Files](http://msdn.microsoft.com/en-us/library/ms171464.aspx)
Note that external files have **.targets** extension by conventions.
|
Partial .csproj Files
|
[
"",
"c#",
"csproj",
""
] |
I am developing an online strategy game using .Net v2. Although the game is primarily strategic, it does have some tactical elements that require reasonable network performance. I plan to use TCP packets for strategic data and UDP packets for tactical data.
{EDIT} I forgot to mention that I am leaning away from WCF and .NET 3+ for a couple of reasons. First, because I want to keep my download small and most of my customers already have .NET 2.0. Second, because I would like to have the option of porting to Mac and Linux and am unsure of WCF availability in Mono. {/EDIT}
I am looking for network library recommendations. I have found a few options, such as GarageGames' Torque Network Library (C++), RakNet (C++), and the lidgren network library (C#):
<http://www.opentnl.org/>
<http://www.jenkinssoftware.com/>
<http://code.google.com/p/lidgren-network/>
Does anyone have real-world experience with these or other libraries?
---
I just stumbled on RakNetDotNet:
<http://code.google.com/p/raknetdotnet/>
This *might* be what I'm looking for...
|
Why limit yourself to .NET 2.0. .NET 3.0 (or 3.5) contains WCF and is a solid, performant communications subsystem with good security. .NET 3.0 is just .NET 2.0 with additional libraries (WCF, WF, WPF).
|
Microsoft's own .NET based [XNA](http://creators.xna.com/) allows you to create networked games on Windows and XBox 360.
|
C# Game Network Library
|
[
"",
"c#",
"network-programming",
""
] |
I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?
|
You will need to use some P/Inovke interop code to do this. Look for the Win32 API `SendMessage` function and the `EM_SETCUEBANNER` message.
|
Its better to post the code instead of link. I am posting this from [here](http://www.ageektrapped.com/blog/wp-content/uploads/code/cuebanner.cs)
```
//Copyright (c) 2008 Jason Kemp
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;
public static class Win32Utility
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg,
int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
[DllImport("user32.dll")]
private static extern bool SendMessage(IntPtr hwnd, int msg, int wParam, StringBuilder lParam);
[DllImport("user32.dll")]
private static extern bool GetComboBoxInfo(IntPtr hwnd, ref COMBOBOXINFO pcbi);
[StructLayout(LayoutKind.Sequential)]
private struct COMBOBOXINFO
{
public int cbSize;
public RECT rcItem;
public RECT rcButton;
public IntPtr stateButton;
public IntPtr hwndCombo;
public IntPtr hwndItem;
public IntPtr hwndList;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
private const int EM_SETCUEBANNER = 0x1501;
private const int EM_GETCUEBANNER = 0x1502;
public static void SetCueText(Control control, string text)
{
if (control is ComboBox)
{
COMBOBOXINFO info = GetComboBoxInfo(control);
SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, text);
}
else
{
SendMessage(control.Handle, EM_SETCUEBANNER, 0, text);
}
}
private static COMBOBOXINFO GetComboBoxInfo(Control control)
{
COMBOBOXINFO info = new COMBOBOXINFO();
//a combobox is made up of three controls, a button, a list and textbox;
//we want the textbox
info.cbSize = Marshal.SizeOf(info);
GetComboBoxInfo(control.Handle, ref info);
return info;
}
public static string GetCueText(Control control)
{
StringBuilder builder = new StringBuilder();
if (control is ComboBox)
{
COMBOBOXINFO info = new COMBOBOXINFO();
//a combobox is made up of two controls, a list and textbox;
//we want the textbox
info.cbSize = Marshal.SizeOf(info);
GetComboBoxInfo(control.Handle, ref info);
SendMessage(info.hwndItem, EM_GETCUEBANNER, 0, builder);
}
else
{
SendMessage(control.Handle, EM_GETCUEBANNER, 0, builder);
}
return builder.ToString();
}
}
```
|
Showing a hint for a C# winforms edit control
|
[
"",
"c#",
"winforms",
"user-interface",
""
] |
Pros. and cons? how long do you use it? What about jambi?
|
I've used Qt on a couple of projects I did in c++ on several platforms over a period of seven years. I think it works pretty well and definitely was quicker for me to develop a decent GUI app on the Mac than plodding through a language I didn't know (Objective-C) at the time.
I think the signal/slot mechanism is a bit funky but isn't horrible. Once you're use it for a bit, it's not a show stopper. The connection stuff is easy to bungle up (or at least it was) and it's always good to check the return on those because your app will go merrily on its way and not tell you that it didn't work.
I've never used jambi.
|
I have been using Qt for several years now for commercial development and have been very happy with it.
One of the nice things with Qt is that it provides a large set of libraries as well as the GUI stuff (eg XML parsing, threads, networking), all in a consistent style and all multi-platform. This means we rarely need to use other libraries, though we do use boost for some things.
Another very important factor for us was internationalization. In a previous, MFC based application we had to maintain 2 localized versions, for the two languages we support. In our Qt based app we just have the one version.
* The Qt translation system, using linguist is easy to use and makes supporting multiple languages easy (of course you still have to translate the strings which is a lot of work!)
* The GUI layout system where the widgets resize themselves according to a layout makes everything much easier. In different languages the length of the strings are different. With fixed size widgets (like MFC) each dialog needs to be adjusted for each language, otherwise parts of labels get cut off. With Qt they resize themselves. Of course, there are cases when it does not work exactly right but it still makes everything much easier.
* QString does everything in Unicode and handles the conversions from different codecs very easily.
One thing that has been very valuable is the access to the source, although e this is certainly not unique to Qt. On several occasions the ability to check the Qt source has explained some strange behaviour or given a clue how to achieve something.
We have found a few bugs in Qt, some of which have been fixed after reporting to Trolltech. In other cases they have suggested a work around. These have all been fairly obscure and not had a major impact on our development.
One of the main downsides to Qt would be the lack of 3rd party libraries for use in commercial applications. However, Qt is fairly complete so for us it has not been a big problem, though that will depend on which type of application you are developing.
I have not used Jambi either.
|
Do you use Qt and why do you use it?
|
[
"",
"c++",
"qt",
"qt-jambi",
""
] |
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.)
The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.
Is there something that will take any python object and display it in a more rational manner. e.g.
```
[0, 1,
[a, b, c],
2, 3, 4]
```
instead of:
```
[0, 1, [a, b, c], 2, 3, 4]
```
I know that's not a very good example, but I think you get the idea.
|
```
from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)
```
Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.
|
Somtimes [YAML](http://pyyaml.org/) can be good for this.
```
import yaml
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
print yaml.dump(a)
```
Produces:
```
- 0
- 1
- [a, b, c]
- 2
- 3
- 4
```
|
Is there a pretty printer for python data?
|
[
"",
"python",
"prettify",
""
] |
I discovered that you can start your variable name with a '@' character in C#.
In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this:
```
public ArrayList @params {
get { return this.paramsField; }
set { this.paramsField = value; }
}
```
I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?
|
Straight from the [C# Language Specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/), [Identifiers (C#)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#identifiers)
:
> The prefix "@" enables the use of
> keywords as identifiers, which is
> useful when interfacing with other
> programming languages. The character @
> is not actually part of the
> identifier, so the identifier might be
> seen in other languages as a normal
> identifier, without the prefix. An
> identifier with an @ prefix is called
> a verbatim identifier.
|
It just lets you use a reserved word as a variable name. Not recommended IMHO (except in cases like you have).
|
What's the use/meaning of the @ character in variable names in C#?
|
[
"",
"c#",
"variables",
"naming",
"specifications",
"reserved-words",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.