Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
When developing a C/C++ (=2?) plugin based framework with shared objects/dynamic libraries that need to support live swapping what examples would be helpful to look at for implementation details?
Thanks.
**Note:** live swapping is the key point here, no need to restart the system is a requirement | If you are on POSIX, `dlopen()`, `dlsym()` and `dlclose()` are all you need.
See `man dlsym` for details and examples.
There is a good [article](http://www.codepedia.com/1/LoadingDynamicLibraryC) about loading dynamic libraries, and plugin infrastructure is an example.
**EDIT** OP added Windows as requirement so this approach won't help since Windows isn't POSIX-compliant. However there are similar functions in WinAPI - see [here](http://www.ibm.com/developerworks/aix/library/au-porting/index.html). | You might want to try [Boost.Extension](http://boost-extension.blogspot.com/2007/09/what-is-boostextension.html) but beware : despite its name, it is not one of boost libraries.
Here is a [link to its documentation](http://boost-extension.redshoelace.com/docs/boost/extension/index.html). | Good patterns for a C/C++ plugin-based system? | [
"",
"c++",
"c",
"plugins",
""
] |
I have about thousand DIV tags structured this way:
```
<div id="1">
<div class="1"></div>
<div class="2"></div>
...
</div>
<div id="2">
<div class="1"></div>
<div class="2"></div>
...
</div>
```
If I want to now access a particular node, say 'div#10 div.5' - what is the fastest way to do it using javascript DOM traversal? I already have the index values "10" and "5" - I am just looking for the fastest way to achieve this.
Thanks a lot. | Without validation and assuming the child nodes are the only nodes and all in sequence;
```
document.getElementById('10').childNodes[4];
```
Watch out for whitespace that becomes a node <https://developer.mozilla.org/En/Whitespace_in_the_DOM> | If you've got about 1000 DIVs I assume this is auto generated html?
If so, is there any reason why you can't add an id to the inner DIVs too?
```
<div id="1">
<div id="1.1" class="1"></div>
<div id="1.2" class="2"></div>
...
</div>
<div id="2">
<div id="2.1" class="1"></div>
<div id="2.2" class="2"></div>
...
</div>
```
Then you can just use getElementById and not have to worry about ordering or spacing etc.
Since element ids have to be unique on the page then this should always be the fastest way to look up the element. | Fastest way to access a node | [
"",
"javascript",
"html",
"dom",
"traversal",
""
] |
How can I filter out the array entries with an odd or even index number?
```
Array
(
[0] => string1
[1] => string2
[2] => string3
[3] => string4
)
```
I want it remove the [0] and [2] entries from the array.
Or say I have 0,1,2,3,4,5,6,7,8,9; I would need to remove 0,2,4,6,8. | `foreach($arr as $key => $value) if($key&1) unset($arr[$key]);`
The above removes odd number positions from the array, to remove even number positions, use the following:
Instead `if($key&1)` you can use `if(!($key&1))` | Here's a "hax" solution:
Use array\_filter in combination with an "isodd" function.
array\_filter seems only to work on values, so you can first array\_flip and then use array\_filter.
```
array_flip(array_filter(array_flip($data), create_function('$a','return $a%2;')))
``` | How to filter an array based on odd or even index value | [
"",
"php",
"arrays",
""
] |
I would like to store a collection of custom objects in a user.config file and would like to add and remove items from the collection programmatically and then save the modified list back to the configuration file.
My items are of the following simple form:
```
class UserInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
```
In my app.config I already created a custom section:
```
<configuration>
<configSections>
<section name="userInfo" type="UserInfoConfigurationHandler, MyProgram"/>
</configSections>
<userInfo>
<User firstName="John" lastName="Doe" email="john@example.com" />
<User firstName="Jane" lastName="Doe" email="jane@example.com" />
</userInfo>
</configuration>
```
I am also able to read in the settings by implementing `IConfigurationSectionHandler`:
```
class UserInfoConfigurationHandler : IConfigurationSectionHandler
{
public UserInfoConfigurationHandler() { }
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
List<UserInfo> items = new List<UserInfo>();
System.Xml.XmlNodeList processesNodes = section.SelectNodes("User");
foreach (XmlNode processNode in processesNodes)
{
UserInfo item = new UserInfo();
item.FirstName = processNode.Attributes["firstName"].InnerText;
item.LastName = processNode.Attributes["lastName"].InnerText;
item.Email = processNode.Attributes["email"].InnerText;
items.Add(item);
}
return items;
}
}
```
I did all this following this [article](http://www.dotneat.net/2007/10/16/StoringACollectionOnYourAppconfigUsingSectionHandlers.aspx). However, using this approach I'm only able to **read** the settings from app.config into a `List<UserInfo>` collection, but I would also need to **write** a modified list back.
I was searching the documentation without success and now I'm kind of stuck. What am I missing? | I wouldn't store that kind of data in an app.config, at least not if it's meant to be updated programatically. Conceptually, it's for configuration settings, not application data so perhaps you want to store your username and password info in a separate XML file (assuming you can't or don't want to use a database)?
Having said that, then I think your best bet is to read in the app.config as a standard XML file, parse it, add the nodes you want and write it back. The built in ConfigurationManager API doesn't offer a way to write back new settings (which I suppose gives a hint as to Microsoft's intended use). | The way to add custom config (if you require more than just simple types) is to use a ConfigurationSection, within that for the schema you defined you need a ConfigurationElementCollection (set as default collection with no name), which contains a ConfigurationElement, as follows:
```
public class UserElement : ConfigurationElement
{
[ConfigurationProperty( "firstName", IsRequired = true )]
public string FirstName
{
get { return (string) base[ "firstName" ]; }
set { base[ "firstName" ] = value;}
}
[ConfigurationProperty( "lastName", IsRequired = true )]
public string LastName
{
get { return (string) base[ "lastName" ]; }
set { base[ "lastName" ] = value; }
}
[ConfigurationProperty( "email", IsRequired = true )]
public string Email
{
get { return (string) base[ "email" ]; }
set { base[ "email" ] = value; }
}
internal string Key
{
get { return string.Format( "{0}|{1}|{2}", FirstName, LastName, Email ); }
}
}
[ConfigurationCollection( typeof(UserElement), AddItemName = "user", CollectionType = ConfigurationElementCollectionType.BasicMap )]
public class UserElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new UserElement();
}
protected override object GetElementKey( ConfigurationElement element )
{
return ( (UserElement) element ).Key;
}
public void Add( UserElement element )
{
BaseAdd( element );
}
public void Clear()
{
BaseClear();
}
public int IndexOf( UserElement element )
{
return BaseIndexOf( element );
}
public void Remove( UserElement element )
{
if( BaseIndexOf( element ) >= 0 )
{
BaseRemove( element.Key );
}
}
public void RemoveAt( int index )
{
BaseRemoveAt( index );
}
public UserElement this[ int index ]
{
get { return (UserElement) BaseGet( index ); }
set
{
if( BaseGet( index ) != null )
{
BaseRemoveAt( index );
}
BaseAdd( index, value );
}
}
}
public class UserInfoSection : ConfigurationSection
{
private static readonly ConfigurationProperty _propUserInfo = new ConfigurationProperty(
null,
typeof(UserElementCollection),
null,
ConfigurationPropertyOptions.IsDefaultCollection
);
private static ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();
static UserInfoSection()
{
_properties.Add( _propUserInfo );
}
[ConfigurationProperty( "", Options = ConfigurationPropertyOptions.IsDefaultCollection )]
public UserElementCollection Users
{
get { return (UserElementCollection) base[ _propUserInfo ]; }
}
}
```
I've kept the UserElement class simple, although it really should follow the pattern of declaring each property fully as described in [this excellent CodeProject article](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx#writingasection). As you can see it represents the "user" elements in your config you provided.
The UserElementCollection class simply supports having more than one "user" element, including the ability to add/remove/clear items from the collection if you want to modify it at run-time.
Lastly there is the UserInfoSection which simply stats that it has a default collection of "user" elements.
Next up is a sample of the App.config file:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup>
<section
name="userInfo"
type="ConsoleApplication1.UserInfoSection, ConsoleApplication1"
allowDefinition="Everywhere"
allowExeDefinition="MachineToLocalUser"
/>
</sectionGroup>
</configSections>
<userInfo>
<user firstName="John" lastName="Doe" email="John.Doe@company.com" />
<user firstName="Jane" lastName="Doe" email="Jane.Doe@company.com" />
</userInfo>
</configuration>
```
As you can see, in this example I've included some userInfo/user elements in the App.config. I've also added settings to say they can be defined at machine/app/user/roaming-user levels.
Next we need to know how to update them at run-time, the following code shows an example:
```
Configuration userConfig = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.PerUserRoamingAndLocal );
var userInfoSection = userConfig.GetSection( "userInfo" ) as UserInfoSection;
var userElement = new UserElement();
userElement.FirstName = "Sample";
userElement.LastName = "User";
userElement.Email = "Sample.User@company.com";
userInfoSection.Users.Add( userElement );
userConfig.Save();
```
The above code will create a new user.config file if needed, buried deep inside the "Local Settings\Application Data" folder for the user.
If instead you want the new user added to the app.config file simply change the parameter for the OpenExeConfiguration() method to ConfigurationUserLevel.None.
As you can see, it's reasonably simple, although finding this information required a bit of digging. | How to store a collection of custom objects to an user.config file? | [
"",
"c#",
"configuration",
"collections",
"app-config",
""
] |
I need to test a program I wrote that receives XML as a text upload from a browser. I'm looking for a tool that will allow me to send the same content over and over instead of having to generate it new each time.
I am looking for an Application that can send a text file to a server
or
a way to do this with JavaScript and HTML
The solution to this problem dose not involve Ethereal / Wireshark (though it is a use full tool) | Have you seen [Selenium](http://seleniumhq.org/) ? You can automate your browser-side testing in this, and thus automate your XML submission | Use curl:
```
echo '<xml />' | curl -X POST -H 'Content-type: text/xml' -d @- http://myurl
``` | Send XML to server for testing | [
"",
"javascript",
"html",
"xml",
""
] |
I am trying to get a user's email address in AD without success.
```
String account = userAccount.Replace(@"Domain\", "");
DirectoryEntry entry = new DirectoryEntry();
try {
DirectorySearcher search = new DirectorySearcher(entry);
search.PropertiesToLoad.Add("mail"); // e-mail addressead
SearchResult result = search.FindOne();
if (result != null) {
return result.Properties["mail"][0].ToString();
} else {
return "Unknown User";
}
} catch (Exception ex) {
return ex.Message;
}
```
Can anyone see the issue or point in the right direction? | **Disclaimer:** This code doesn't search for a [single exact match](https://social.technet.microsoft.com/wiki/contents/articles/22653.active-directory-ambiguous-name-resolution.aspx), so for `domain\j_doe` it may return `domain\j_doe_from_external_department`'s email address if such similarly named account also exists. If such behaviour is undesirable, then either use a [samAccountName](https://learn.microsoft.com/en-us/windows/win32/ad/naming-properties#samaccountname) filter intead of an [anr](https://social.technet.microsoft.com/wiki/contents/articles/22653.active-directory-ambiguous-name-resolution.aspx) one used below or filter the [results](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.directorysearcher.findall?view=netframework-4.8) additionally.
I have used this code successfully (where "account" is the user logon name without the domain (domain\account):
```
// get a DirectorySearcher object
DirectorySearcher search = new DirectorySearcher(entry);
// specify the search filter
search.Filter = "(&(objectClass=user)(anr=" + account + "))";
// specify which property values to return in the search
search.PropertiesToLoad.Add("givenName"); // first name
search.PropertiesToLoad.Add("sn"); // last name
search.PropertiesToLoad.Add("mail"); // smtp mail address
// perform the search
SearchResult result = search.FindOne();
``` | You guys are working too hard:
```
// Look up the current user's email address
string eMail = UserPrincipal.Current.EmailAddress;
``` | How to get a user's e-mail address from Active Directory? | [
"",
"c#",
"active-directory",
""
] |
I have the following problem:
```
public function row2Partner($row){
echo $row->PartnerID;
}
public function main(){
$query = "SELECT PartnerID, PartnerName FROM Partner";
$result = mysql_query($query);
$this->row2Partner(mysql_fetch_object($result));
}
```
This gives me the error in r`ow2Partner()`:
Trying to get property of non-object
But `$row` is an Object! And if I do
echo `$row->PartnerID` in the main function, it works.
Any ideas?
Thx,
Martin | If your result returns more than one row, your object is going to be multi-dimensional. I'm pretty sure you can do something like this if you just want to echo the first one:
```
public function row2Partner($row){ echo $row[0]->PartnerID; }
```
If you are looking for only one result, I would also limit my query to just one...
```
SELECT PartnerID, PartnerName FROM Partner LIMIT 1
```
If you want to echo out all your rows (in the case of multiple) results, you can do this:
```
public function row2Partner($row){
foreach($row as $result) {
echo $result->PartnerID;
}
}
```
Hope that helps.
**PS**
Just as a sidenote, I tend to like to use associative arrays when dealing with MySQL results--it just makes more sense to me. In this case, you would just do this instead:
```
mysql_fetch_assoc($result)
``` | Are you sure that mysql\_query() has executed the query successfully, and also that there is actually a row being returned? It might be worth checking it, e.g.
```
//check query executed ok
if ($result = mysql_query($query)) {
//check there is actually a row
if ($row = mysql_fetch_object($result)) {
$this->row2Partner($row);
} else {
//no data
}
} else {
//error
die(mysql_error());
}
``` | Pass result of mysql_fetch_object() to a function does not work | [
"",
"php",
"mysql",
""
] |
I'm looking for a C# code generator which generate C# automatically to access stored procedures on Oracle Database.
For instance, if I have some packages on schema DEV like:
* PACKAGE1 with FUNC1, FUN2
* PACKAGE2 with FUNC3, FUN4
The generator creates code to run from C# the following code:
```
int a = PACKAGE1.FUNC1(12, 34, "hello");
```
Any clue? | [MyGeneration](http://www.mygenerationsoftware.com) is open source, is template driven, and the templates can be written in C#. So would meet your needs, or there might even by a template out their already. | [CodeFluent Entities](http://www.softfluent.com/products/codefluent-entities) is model-first tool that can be used to generate SQL Scripts for Oracle:
* Schema
* Tables
* Constraints (primary and foreign keys)
* Views
* Procedures (and associated Oracle Packages)
* Instances (data)
Application classes (C#) may also be generated with relative ease. | Any good C# code generator for using oracle stored procedures? | [
"",
"c#",
"oracle",
"stored-procedures",
"code-generation",
""
] |
I'm writing a Flex app on top of a Java web application using BlazeDS. BlazeDS has logging inside of it, but I want to set it up to Use the same logging framework I have in my application.
Is there a way to setup BlazeDS to use Log4J? Or am I stuck with the Flex logging stuff that's already baked into BlazeDS? | No, out of box BlazeDS does not support log4j or other frameworks directly.
However, it's really simple to add support for your favourite logging framework; I used the following to get the output into [SLF4J](http://www.slf4j.org/):
```
package example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import flex.messaging.log.AbstractTarget;
import flex.messaging.log.LogEvent;
public class Slf4jTarget extends AbstractTarget {
// log4j levels: OFF - FATAL - ERROR - WARN - INFO - DEBUG - TRACE - ALL
// blazeds levels: NONE - FATAL - ERROR - WARN - INFO - DEBUG - ALL
@Override
public void logEvent(LogEvent event) {
Logger log = LoggerFactory.getLogger(event.logger.getCategory());
if (event.level >= LogEvent.ERROR)
log.error(event.message, event.throwable);
else if (event.level >= LogEvent.WARN)
log.warn(event.message, event.throwable);
else if (event.level >= LogEvent.INFO)
log.info(event.message, event.throwable);
else if (event.level >= LogEvent.DEBUG)
log.debug(event.message, event.throwable);
else
log.trace(event.message, event.throwable);
}
}
```
.. and to use it, enable it in `services-config.xml`:
```
<?xml version="1.0" encoding="UTF-8"?>
<services-config>
<logging>
<target class="example.Slf4jTarget" level="Info">
</logging>
</services-config>
``` | **Use CommonsLoggingTarget.**
See <http://static.springsource.org/spring-flex/docs/1.0.x/javadoc-api/org/springframework/flex/core/CommonsLoggingTarget.html>.
Just be careful with setting log level in service-config.xml. If you set it to "All", and define "blazeds" logger in log4j.xml, then there will be a lot of redundant log messages generated by BlazeDS/LCDS, which might have significant performance impact. | How can I setup my BlazeDS implementation with Log4J? | [
"",
"java",
"apache-flex",
"logging",
"blazeds",
""
] |
```
SELECT
number, count(id)
FROM
tracking
WHERE
id IN (SELECT max(id) FROM tracking WHERE splitnr = 'a11' AND number >0 AND timestamp >= '2009-04-08 00:00:00' AND timestamp <= '2009-04-08 12:55:57' GROUP BY ident)
GROUP BY
number
``` | How about this:
```
SELECT number, count(id)
FROM tracking
INNER JOIN (SELECT max(id) ID FROM tracking
WHERE splitnr = 'a11' AND
number >0 AND timestamp >= '2009-04-08 00:00:00' AND
timestamp <= '2009-04-08 12:55:57'
GROUP BY ident
) MID ON (MID.ID=tracking.id)
WHERE
GROUP BY number
``` | Slightly hard to make sure that I've got it entirely right without seeing the data and knowing exactly what you're trying to achieve but personally I'd turn the sub-query into a view and then join on that, so:
```
create view vMaximumIDbyIdent
as
SELECT ident, max(id) maxid
FROM tracking
WHERE splitnr = 'a11' AND number >0
AND timestamp >= '2009-04-08 00:00:00'
AND timestamp <= '2009-04-08 12:55:57'
GROUP BY ident
then:
SELECT
number, count(id)
FROM
tracking,
vMaximumIDbyIdent
WHERE
tracking.id = vMaximumIDbyIdent.maxid
GROUP BY
number
```
More readable and maintainable. | Is it possible to convert this query to use a join instead of a subquery? | [
"",
"sql",
"mysql",
"join",
"subquery",
""
] |
I tried to get it to work using the [CXF User Guide](http://cwiki.apache.org/CXF20DOC/client-http-transport-including-ssl-support.html), but I've had no luck.
I'm trying to call the web service using java code. | This is covered by the JAX-WS Specification. Basically, set the username/password as properties on the request context:
```
((BindingProvider)proxy).getRequestContext().put(
BindingProvider.USERNAME_PROPERTY, "joe");
((BindingProvider)proxy).getRequestContext().put(
BindingProvider.PASSWORD_PROPERTY, "pswd");
```
The runtime puts them into the HTTP header. | You can provide your own Authenticator. That way it will work if the WDSL itself is protected by basic HTTP authentication.
```
@WebServiceRef(wsdlLocation = "https://laka/sito?wsdl")
static XxxService service;
public static void main(String[] args) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password".toCharArray());
}
});
service = new XxxService();
Xxx port = service.getXxxPort();
// invoke webservice and print response
XxxResponse resp = port.foo();
System.out.println(resp.toString());
}
``` | How do I consume a web service protected with HTTP basic authentication using the CXF framework? | [
"",
"java",
"web-services",
"cxf",
""
] |
I use the next code to retrieve data from a table in the database:
```
$check_sql = 'SELECT personID, name, DATE_FORMAT(persons.birthdate, "%d de %M, %Y"), birthplace, countryID FROM persons WHERE personID = ?';
if ($stmt->prepare($check_sql)) {
$stmt->bind_param('i', $pid);
$stmt->bind_result($personDB, $name, $birthdate, $birthplace, $countryID);
$stmt->execute();
$stmt->fetch();
}
```
Like you can see, at the same time I format the date from the 'birthdate' column to a more friendly display using the DATE\_FORMAT() MySQL function. Now, I want to display the month full names in Spanish, so I want to insert `SET lc_time_names = 'es_ES'` into the query..
How can I do it??? Can I add `SET lc_time_names` to the $check\_sql variable??
Thanks!! | ```
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$mysqli->query("SET lc_time_names = 'es_ES'");
$check_sql = 'SELECT personID, name, DATE_FORMAT(persons.birthdate, "%d de %M, %Y"), birthplace, countryID FROM persons WHERE personID = ?';
if ($stmt = $mysqli->prepare($check_sql)) {
$stmt->bind_param('i', $pid);
$stmt->bind_result($personDB, $name, $birthdate, $birthplace, $countryID);
$stmt->execute();
$stmt->fetch();
}
``` | Another option is to return the raw date/time and then format it in PHP.
Before you format the date, you can use the setlocale() function in PHP to get Spanish output.
This has the added benefit of not running a function in mysql, which can be slower. | PHP/MySQLi: SET lc_time_names and DATE_FORMAT() into a mysqli query? | [
"",
"php",
"mysql",
"database",
"mysqli",
""
] |
This question arise while trying to write test cases. Foo is a class within the framework library which I dont have source access to.
```
public class Foo{
public final Object getX(){
...
}
}
```
my applications will
```
public class Bar extends Foo{
public int process(){
Object value = getX();
...
}
}
```
The unit test case is unable to initalize as I can't create a Foo object due to other dependencies. The BarTest throws a null pointer as value is null.
```
public class BarTest extends TestCase{
public testProcess(){
Bar bar = new Bar();
int result = bar.process();
...
}
}
```
Is there a way i can use reflection api to set the getX() to non-final? or how should I go about testing? | you could create another method which you could override in your test:
```
public class Bar extends Foo {
protected Object doGetX() {
return getX();
}
public int process(){
Object value = doGetX();
...
}
}
```
then, you could override doGetX in BarTest. | As this was one of the top results for "override final method java" in google. I thought I would leave my solution. This class shows a simple solution using the example "Bagel" class and a free to use javassist library:
```
/**
* This class shows how you can override a final method of a super class using the Javassist's bytecode toolkit
* The library can be found here: http://jboss-javassist.github.io/javassist/
*
* The basic idea is that you get the super class and reset the modifiers so the modifiers of the method don't include final.
* Then you add in a new method to the sub class which overrides the now non final method of the super class.
*
* The only "catch" is you have to do the class manipulation before any calls to the class happen in your code. So put the
* manipulation as early in your code as you can otherwise you will get exceptions.
*/
package packagename;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;
/**
* A simple class to show how to use the library
*/
public class TestCt {
/**
* The starting point for the application
*/
public static void main(String[] args) {
// in order for us to override the final method we must manipulate the class using the Javassist library.
// we need to do this FIRST because once we initialize the class it will no longer be editable.
try
{
// get the super class
CtClass bagel = ClassPool.getDefault().get("packagename.TestCt$Bagel");
// get the method you want to override
CtMethod originalMethod = bagel.getDeclaredMethod("getDescription");
// set the modifier. This will remove the 'final' modifier from the method.
// If for whatever reason you needed more than one modifier just add them together
originalMethod.setModifiers(Modifier.PUBLIC);
// save the changes to the super class
bagel.toClass();
// get the subclass
CtClass bagelsolver = ClassPool.getDefault().get("packagename.TestCt$BagelWithOptions");
// create the method that will override the super class's method and include the options in the output
CtMethod overrideMethod = CtNewMethod.make("public String getDescription() { return super.getDescription() + \" with \" + getOptions(); }", bagelsolver);
// add the new method to the sub class
bagelsolver.addMethod(overrideMethod);
// save the changes to the sub class
bagelsolver.toClass();
}
catch (Exception e)
{
e.printStackTrace();
}
// now that we have edited the classes with the new methods, we can create an instance and see if it worked
// create a new instance of BagelWithOptions
BagelWithOptions myBagel = new BagelWithOptions();
// give it some options
myBagel.setOptions("cheese, bacon and eggs");
// print the description of the bagel to the console.
// This should now use our new code when calling getDescription() which will include the options in the output.
System.out.println("My bagel is: " + myBagel.getDescription());
// The output should be:
// **My bagel is: a plain bagel with cheese, bacon and eggs**
}
/**
* A plain bagel class which has a final method which we want to override
*/
public static class Bagel {
/**
* return a description for this bagel
*/
public final String getDescription() {
return "a plain bagel";
}
}
/**
* A sub class of bagel which adds some extra options for the bagel.
*/
public static class BagelWithOptions extends Bagel {
/**
* A string that will contain any extra options for the bagel
*/
String options;
/**
* Initiate the bagel with no extra options
*/
public BagelWithOptions() {
options = "nothing else";
}
/**
* Set the options for the bagel
* @param options - a string with the new options for this bagel
*/
public void setOptions(String options) {
this.options = options;
}
/**
* return the current options for this bagel
*/
public String getOptions() {
return options;
}
}
}
``` | override java final methods via reflection or other means? | [
"",
"java",
"reflection",
"methods",
"final",
""
] |
I developed a software (in C++) which needs to be continuously running. That basically means that it has to be restarted each time it stops.
I was thinking about using cron jobs to check every minutes if it is still alive, but there might be a cleaner way or standard way of doing this.
Thanks in advance | Fedora and Ubuntu use [upstart](http://upstart.ubuntu.com/ "upstart"), which has a the ability to automatically restart your deamon if it exits. | I believe the easiest way to do this is to have a script that will start your program and if it gets returned to it just restarts it.
```
#!/bin/sh
while true; do
./Your_program
done
``` | How to ensure that a program is running and restart it if needed? | [
"",
"c++",
"linux",
"cron",
"daemon",
""
] |
Does it matter which way I order the criteria in the ON clause for a JOIN?
```
select a.Name, b.Status from a
inner join b
on a.StatusID = b.ID
```
versus
```
select a.Name, b.Status from a
inner join b
on b.ID = a.StatusID
```
Is there any impact on performance? What if I had multiple criteria?
Is one order more maintainable than another? | `JOIN` order can be forced by putting the tables in the right order in the `FROM` clause:
1. MySQL has a special clause called `STRAIGHT_JOIN` which makes the order matter.
This will use an index on `b.id`:
```
SELECT a.Name, b.Status
FROM a
STRAIGHT_JOIN
b
ON b.ID = a.StatusID
```
And this will use an index on `a.StatusID`:
```
SELECT a.Name, b.Status
FROM b
STRAIGHT_JOIN
a
ON b.ID = a.StatusID
```
2. Oracle has a special hint `ORDERED` to enforce the `JOIN` order:
This will use an index on `b.id` or build a hash table on `b`:
```
SELECT /*+ ORDERED */
*
FROM a
JOIN b
ON b.ID = a.StatusID
```
And this will use an index on `a.StatusID` or build a hash table on `a`:
```
SELECT /*+ ORDERED */
*
FROM b
JOIN a
ON b.ID = a.StatusID
```
3. SQL Server has a hint called `FORCE ORDER` to do the same:
This will use an index on `b.id` or build a hash table on `b`:
```
SELECT *
FROM a
JOIN b
ON b.ID = a.StatusID
OPTION (FORCE ORDER)
```
And this will use an index on `a.StatusID` or build a hash table on `a`:
```
SELECT *
FROM b
JOIN a
ON b.ID = a.StatusID
OPTION (FORCE ORDER)
```
4. PostgreSQL guys, sorry. Your [**TODO list**](http://wiki.postgresql.org/wiki/Todo#Features_We_Do_Not_Want) says:
> **Optimizer hints (not wanted)**
>
> Optimizer hints are used to work around problems in the optimizer. We would rather have the problems reported and fixed.
As for the order in the comparison, it doesn't matter in any `RDBMS`, AFAIK.
Though I personally always try to estimate which column will be searched for and put this column in the left (for it to seem like an `lvalue`).
See [**this answer**](https://stackoverflow.com/questions/269093/how-do-i-remember-which-way-round-prior-should-go-in-connect-by-queries/754290#754290) for more detail. | No it does not.
What i do (for readability) is your 2nd example. | Does the order of tables referenced in the ON clause of the JOIN matter? | [
"",
"sql",
"mysql",
"sql-server",
"oracle",
""
] |
Why is the following code snippet valid in C#? This is a feature of the compiler or a bug?
```
class A
{
public class B : A
{
}
}
class C : A.B
{
public void Foo(C.B b)
{
}
}
class D : A
{
public void Foo(D.B.B.B.B b)
{
}
}
```
### See Also
> [.NET Nested Classes](https://stackoverflow.com/questions/455928/-net-nested-classes) | It's legal code, but quirky. I can dig out the bit in the spec about name resolution if you want - but it's definitely legal. I've had a conversation about a similar topic with Eric Lippert before. Strangely enough, that used D.B.B.B.B... too.
The conversation came up due to [this earlier question](https://stackoverflow.com/questions/265585/why-cant-a-class-extend-its-own-nested-class-in-c).
The relevant section of the C# 3.0 spec is 3.8, but it's too long and involved to be worth posting here. | 1. D is an A
2. A has a nested type B
3. B is an A
4. GOTO 2 | Is this C# compiler behaviour a bug or a feature? | [
"",
"c#",
"compiler-construction",
""
] |
I am using a modified version of the code [here](http://haacked.com/archive/2008/07/02/httpmodule-for-timing-requests.aspx). The difference is that I log it to a database and only if it is longer that 5000ms. The results have me worried. Several pages will occasionally log an execution time of minutes. Never will they consistently under perform, but according to log table, it is happening often enough that I need to get to the bottom of it.
So I'm throwing it out here to see what kind of ideas the community has. Perhaps it's due to app restarts? recompiles? Maybe some subtle flaw in the httpmodule that would cause it to misreport the time? | Run your application through a profiler to see which methods are taking up the most processing time. | Try keeping a close watch on the locks on your database, it could be a database locking issue, as that has happened to me and caused very similar symptoms. | What would cause my request timer to report such long request execution times? | [
"",
"c#",
"asp.net",
"http",
""
] |
I came across some code that boils down to the following:
```
enum BAR { /* enum values omitted */ }
class Foo{
public:
void set(const BAR& bar);
private:
uint32_t bits;
};
void Foo::set(const BAR& bar)
{
(uint32_t&)bits = bits | bar;
}
```
I don't understand the point of the c-style cast in the assignment in Foo::set. Why would you cast the lhs of an assignment? Am I crazy, or does this have a purpose? | In this case, I can't see any reason for the cast, as the thing being cast is of the same type as the cast. In general, it could be used to force a particular assignement operator to be used.
I will now repeat my mantra: If your code contains casts, there is probably something wrong with the code or the design and you should examine both with a view to removing the cast. | I agree with Neil Butterworth, the cast in this case isn't necessary and it is a definite "code smell". | Why would you cast the lhs of an assignment? | [
"",
"c++",
""
] |
I dodged a heated debate concerning nulls in the database today.
My opinion is that null is an excellent indicator of unspecified values. Everyone else in the team, that has an opinion, thinks zero and empty strings are the way to go.
Are they lazy or am I too strict? | They are lazy and do not understand the basic idea of a null in the database. Nulls are useful and have a purpose. They should neither be avoided nor used inappropriately. | null means no value while 0 doesn't, if you see a 0 you don't know the meaning, if you see a null you know it is a missing value
I think nulls are much clearer, 0 and '' are confusing since they don't clearly show the intent of the value stored | Is null harmful? | [
"",
"null",
"database",
"sql",
""
] |
JavaScript performance in Internet Explorer sucks. No news there. However there are some tips and tricks to speed it up. For example, there is this [three](http://blogs.msdn.com/ie/archive/2006/08/28/728654.aspx) [part](http://blogs.msdn.com/ie/archive/2006/11/16/ie-javascript-performance-recommendations-part-2-javascript-code-inefficiencies.aspx) [series](http://blogs.msdn.com/ie/archive/2007/01/04/ie-jscript-performance-recommendations-part-3-javascript-code-inefficiencies.aspx). Still I find myself unable to squeeze decent performance out of it. Perhaps some of you have an idea what else to do so it was speedier?
What I want to do is create a medium-size table from scratch in Javascript. Say, 300 rows, 10 cells each. It takes at about 5-6 seconds on my computer to do this. OK, granted, it's a 5 year old rig, but that's still too much. Here's my dummy code:
```
<html>
<body>
<script type="text/javascript">
function MakeTable(parent)
{
var i, j;
var table = document.createElement('table');
var insertRow = table.insertRow;
for ( i = 0; i < 300; i++ )
{
var row = insertRow(-1);
for ( j = 0; j < 10; j++ )
{
var cell = row.insertCell(-1);
cell.innerHTML = i + ' - ' + j;
}
}
parent.appendChild(table);
}
</script>
<div onclick="MakeTable(this);">Click Me!</div>
</body>
</html>
```
**Added:** Hmm, apparently string-concatenation (with array.join) is the only way to go. Well, sad, of course. Was hoping to do it the "proper" DOM-way. :) | Here is an interesting link I found when looking for an answer on this:
The page uses five different scripts / methods to generate a table.
According to their tests, using strings is by far faster than using DOM / Table elements.
[http://www.quirksmode.org/dom/innerhtml.htm](http://www.quirksmode.org/dom/innerhtml.html)l | One of the main reason's for IE's performance issues are DOM operations. You want to do your DOM operations as efficiently as possible. This can include, depending on your situation (benchmark!):
* Offline creation of your DOM structure; keep the top level element out of the document (create, but not append) then appending it to the document when it's ready, instead of appending every element into the DOM as you create it
* write innerHTML instead of DOM manipulation | Internet Explorer Javascript performance problem | [
"",
"javascript",
"internet-explorer",
"performance",
""
] |
When we save a level in our editor, we create a log file of any errors it contains. These consist basically of an error message and a path that allows the user to find the erronous item in a tree view.
What I want is to make that path a link, something like
< a href="editor://path/to/gameobject" > Click to see object in editor< /a >
The SO questions I've seen regarding this seems to point to this msdn page:
<http://msdn.microsoft.com/en-us/library/aa767914.aspx>
But from what I can tell, it will spawn a new instance of the application. What I want to do is to simply "call" our editor somehow. One way to do it, I guess, is to spawn it, and in the beginning check if there's already an instance running, and if so, send the commandline to it.
Is that the best way to do it? If so, any ideas on how to do it best? What are otherwise some ways that this could be done?
Also: does the msdn solution work across browsers? Our editor runs in Windows only, but people use IE, Fx, GC and Opera. | If you need the link to work in any viewer, yes, registering a protocol handler is the best way.
As for launching the editor, you could implement it as an [out-of-process COM server](http://msdn.microsoft.com/en-us/library/ms680076.aspx), but if you've already got command line parsing sorted, you might as well use [a window message](http://msdn.microsoft.com/en-us/library/ms649011.aspx) or named pipe to pass that to the editor. If you're sending a window message, you could use [FindWindow](http://msdn.microsoft.com/en-us/library/ms633499.aspx) (with a unique class name) to check for a running instance. | Sounds like you solved it already, by checking for a previous instance.
I would be surprised if the OS takes upon it to somehow "stamp" the association with data telling it to separate programs that should run multiple times from programs that should not. | How to send a link to an application, like Spotify does | [
"",
"c++",
"winapi",
"hyperlink",
"protocols",
"wtl",
""
] |
I'm building a Web Page that allows the user to pick a color and size. Once they have these selected I need to perform a lookup to see if inventory exists or not and update some UI elements based on this.
I was thinking that putting all the single product data into multidimensional JavaScript array (there is only 10-50 records for any page instance) and writing some client side routines around that, would be the way to go for two reasons. One because it keeps the UI fast and two it minimizes callbacks to the server. What i'm worried about with this solution is code smell.
As an alternative i'm thinking about using a more AJAX purist approach of using HTTP handlers and JSON, or perhaps a hybrid with a bit of both. My question is what are your thoughts as to the best solution to this problem using the ASP.Net 2.0 stack?
[Edit]
I also should mention that this page will be running in a SharePoint environment. | Assuming the data is static, I would vote option #1. Storing and retrieving data elements in a JavaScript array is relatively foolproof and entirely within your control. Calling back to the server introduces a lot of possible failure points. Besides, I think keeping the data in-memory within the page will require less code overall and be more readable to anyone with a more than rudimentary understanding of JavaScript. | i'm against Ajax for such tasks, and vote (and implemented) the first option.
As far as I understand, you won't create [Code smells](http://en.wikipedia.org/wiki/Code_smell) if the JS part is being written by your server-side.
From a user point-of-view, Ajax is an experience-killer for wireless browsing, since any little glitch or mis-service will fail or simply lengthen the interaction by factors of 20(!).
I've implemented even more records than yours in my site, and the users love it. Since some of my users use internet-caffee, or dubious hotel wifi, it wouldn't work otherwise.
Besides, Ajax makes your server-vs-client interaction code much more complex, IMO, which is the trickiest part in web programming. | Design Decision - Javascript array or http handler | [
"",
"asp.net",
"javascript",
"ajax",
"json",
""
] |
I want to create links to pages and content that are in protected directories. I didn't program the protected directories I set them up from the host admin page.
I want to be able to give links to user that will take them to page and login as well.
Also if there is a way I want to be able to embed content from the protected directories in other places and not have the password box shop up in order to display the content.
I am using PHP4
Thanks! | Depending on the authentication, you can use a URL like this:
```
http://username:password@yoursite.com/protected_dir
```
I know that works for simple protection via `.htaccess`. However, keep in mind that you will be sending that link with the password in clear text, and may be inadvertently seen by the wrong people. | > Also if there is a way I want to be
> able to embed content from the
> protected directories in other places
> and not have the password box shop up
> in order to display the content.
Read it with fsockopen. Here's an example od fsockopen with basic authentication
<http://pl.php.net/manual/en/function.fsockopen.php#32830> | Can I login to a protected directory via a link? | [
"",
"php",
"php4",
""
] |
What is the difference between Ctrl + Shift + R and Ctrl + Shift + T?
Do we have a blog with all eclipse tips/shortcuts? | Ctrl-Shift-R: Find a *resource*, which can include XML files, Ant scripts etc.
Ctrl-Shift-T: Find a *type*, regardless of the filename. (This can be handy if you're looking for a nested type, or basically if you don't want to see anything other than types...)
For Eclipse shortcuts, there are *lots* of [Eclipse keyboard cheat sheets](http://www.google.com/search?q=eclipse+keyboard+cheat+sheet). From the search, I like [this PDF](http://eclipse-tools.sourceforge.net/EclipseEmacsKeybindings_3_1.pdf), [this shorter list](http://www.n0sl33p.org/dev/eclipse_keys.html), and [this list with more explanations](http://www.rossenstoyanchev.org/write/prog/eclipse/eclipse3.html). | * Ctrl+shift+R is for Open Resource, it
searches for all types of files in
your projects.
* Ctrl+shift+T is for
Open Type, it looks for Java classes
and interfaces.
A great feature of the Open Type dialog is that you can search for say DataInputStream by typing DIS. | Eclipse commands | [
"",
"java",
"eclipse",
""
] |
When writing unit tests for a Java API there may be circumstances where you want to perform more detailed validation of an exception. I.e. more than is offered by the *@test* annotation offered by JUnit.
For example, consider an class that should catch an exception from some other Interface, wrap that exception and throw the wrapped exception. You may want to verify:
1. The exact method call that throws the wrapped exception.
2. That the wrapper exception has the original exception as its cause.
3. The message of the wrapper exception.
The main point here is that you want to be perf additional validation of an exception in a unit test (not a debate about whether you *should* verify things like the exception message).
What's a good approach for this? | In JUnit 4 it can be easily done using [ExpectedException](http://junit.org/javadoc/latest/org/junit/rules/ExpectedException.html) rule.
Here is example from javadocs:
```
// These tests all pass.
public static class HasExpectedException {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
@Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
@Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
thrown.expectMessage(startsWith("What"));
throw new NullPointerException("What happened?");
}
}
``` | As provided in [your answer](https://stackoverflow.com/questions/785618/in-java-how-can-i-validate-a-thrown-exception-with-junit/785632#785632), it's a good approach. In addition to this:
You could wrap the function `expectException` into a new Annotation, called `ExpectedException`.
An annotated method would look like this:
```
@Test
@ExpectedException(class=WrapperException.class, message="Exception Message", causeException)
public void testAnExceptionWrappingFunction() {
//whatever you test
}
```
This way would be more readable, but it's exactly the same approach.
Another reason is: I like Annotations :) | In Java how can I validate a thrown exception with JUnit? | [
"",
"java",
"exception",
"junit",
""
] |
I have an OutOfMemory (heap size) in eclipse using a third party plugin
The plug in is Adobe Livecycle work bench and during the out of memory the
plugin is retrieving via WS (using Axis) a list of around 70 workflow components
on my server
Here is a extract of my call stack in Eclipse
> ... at org.eclipse.equinox.launcher.Main.main(Main.java:1144)
>
> Caused by: java.lang.OutOfMemoryError: Java heap space; nested
> exception is: java.lang.OutOfMemoryError: Java heap space at
> org.apache.axis.message.SOAPFaultBuilder.createFault ...
I am using this eclipse.ini
> -showlocation
> -vm
> C:\bea920\jdk150\_04\bin\javaw.exe
> -vmargs
> -Xms512M
> -Xmx1024M
I don't use any commandline options
I have added -Xmx1024m to my only Installed JRE in Java/Installed JREs
It seems to me that :
-eclipse is not OutOfMemory itself
it displays only 300Mo out of 1024Mo used
it continues working properly
-the plugin launch its axis parsing without giving it enough memory
Questions :
- Are my suppositions right ?
- How do I find where and how to give more memory to the process launched by eclipse launcher ? | I was able to find were the problem is
* I used Fiddler with eclipse (using proxy settings)
* This way I was able to spot that the soap answer was an OutOfMemory
soapenv:Fault
faultcode soapenv:Server.generalException
faultstring java.lang.OutOfMemoryError: Java heap space; nested exception is:
**java.lang.OutOfMemoryError**: Java heap space
* So the problem was on the server
* I have now another problem : the server builds an answer which is to big for eclipse
Thank you for your answers | Have you changed your launched VM arguments from the preferences window? Try this:
```
Window->Preferences
Java->Installed JREs
(select your jre here)->Edit..
Default VM Arguments: -Xmx1024m (or whatever size you like)
```
Edit 1: Based on your comments, I see that you've already tried this. I assumed that you did not try it based on the portion of your question that reads "How do I find where and how to give more memory to the process launched by eclipse launcher ?". I guess we all know what happens when we assume!
Have you considered upping the memory to something larger just to see if you can get it to run (and possibly get some more info about what is causing it to crash)? Try -Xmx2048m or larger depending on your available memory.
Can you add some information to your question that gives us an idea of what the plugin does? Is this project a web service? etc.. | OutOfMemory in Eclipse in a Launched process | [
"",
"java",
"eclipse",
""
] |
I have a .NET application that I only allow to run a single process at a time of, however that app is used on Citrix boxes from time to time, and as such, can be run by multiple users on the same machine.
I want to check and make sure that the application is only running once per user session, because right now if user A is running the app, then user B gets the "App already in use" message, and should not.
This is what I have now that checks for the running process:
```
Process[] p = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
if (p.Length > 1)
{
#if !DEBUG
allowedToOpen &= false;
errorMessage +=
string.Format("{0} is already running.{1}", Constants.AssemblyTitle, Environment.NewLine);
#endif
}
``` | *EDIT:* Improved the answer according to [this cw question](https://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567#229567) ...
You can use a mutex for checking wether the app already runs:
```
using( var mutex = new Mutex( false, AppGuid ) )
{
try
{
try
{
if( !mutex.WaitOne( 0, false ) )
{
MessageBox.Show( "Another instance is already running." );
return;
}
}
catch( AbandonedMutexException )
{
// Log the fact the mutex was abandoned in another process,
// it will still get aquired
}
Application.Run(new Form1());
}
finally
{
mutex.ReleaseMutex();
}
}
```
Important is the `AppGuid` - you could make it depend on the user.
Maybe you like to read this article: [the misunderstood mutex](http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx) | As tanascius already say, you can use the Mutex.
> On a server that is running Terminal Services, a named system mutex can have two levels of visibility. If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created.
Source: [msdn, Mutex Class](http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx) | How can I check for a running process per user session? | [
"",
"c#",
".net",
""
] |
How do you get a class to interact with the form to show a message box? | ```
using System.Windows.Forms;
...
MessageBox.Show("Hello World!");
``` | ```
System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms
``` | Show a message box from a class in c#? | [
"",
"c#",
"class",
"messagebox",
""
] |
An application I'm modifying has a Web Service, and one of the web methods on that web methods is used to authenticate a user against active directory. So the current code called by the AuthenticateUser web method looks something like this:
```
string domainAndUsername = aDomain + @"\\" + username;
string ldsPath = buildLdsPath(searchBase);
DirectoryEntry entry = new DirectoryEntry(ldsPath, domainAndUsername,
password);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(sAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
// more code to validate the result, etc...
}
```
When I started looking at this code, the first thing that worried me is the arguments to the web method look like this:
```
[WebMethod]
public ResultObj AddRole(string roleToAdd, string username, string password)
{
// code that calls above Authentication fragment...
}
```
So the current web service is expecting a password string, presumably **sent in the clear** over the network as XML, when the request is made to the service.asmx page.
Has anyone dealt with this type of issue before? Are there alternative Active Directory authentication mechanisms I could use that would avoid having to pass in a plain-text password? The best option I could come up with on my own is to invoke the WebMethod using an encrypted password, and have the code on the other side decrypt it. However, I'd prefer a better solution--e.g.: is there some way to do search for a DirectoryEntry using a one-way hash instead of a password?
**Edit:**
*Additional Details:* To this point I haven't considered SSL as this is a tool that is internal to our company, so it seems like overkill, and possibly problematic (it'll be running on a company intranet, and not externally visible). The only reason I'm even worried about the security of sending plain-text passwords is the escalating amount of (possibly password-sniffing) malware present even on company intranets these days. | For our particular situation, because both the client and the web service are running on our company Intranet, a solution that may work for us is to handle the Authentication on the client end using the Integrated Windows NTLM authentication, and then then just have the client supply the credentials to the Web Service. Here is the client code:
```
public void AddRole(string roleName)
{
webSvc.Credentials = CredentialCache.DefaultCredentials;
// Invoke the WebMethod
webSvc.AddRole(roleName);
}
```
The web method will now look like this:
```
[WebMethod]
public ResultObj AddRole(string roleToAdd)
{
IIdentity identity = Thread.CurrentPrincipal.Identity;
if (!identity.IsAuthenticated)
{
throw new UnauthorizedAccessException(
ConfigurationManager.AppSettings["NotAuthorizedErrorMsg"]);
}
// Remaining code to add role....
}
```
Again, I must stress this solution will probably only work if the server trusts the client, and both talk to the same Active Directory server. For public Web Services, one of the other answers given is going to be a better solution.
For further information, see:
* [Microsoft Support Article on passing credentials](http://support.microsoft.com/kb/813834)
* [MSDN Article on Building Secure Applications](http://msdn.microsoft.com/en-us/library/aa302383.aspx)
* [MSDN Article on Windows Authentication](http://msdn.microsoft.com/en-us/library/aa480475.aspx) - includes info on correctly configuring the web service to use the Windows Principal and Identity objects needed. | If you have a public/private key combination, then the client could encrypt with the public key, and you decrypt with the private key.
However, that's too much work for the client, and not a very "web method" way of doing it.
Since you are sending the user name and password as parameters then you should resort to transport security, HTTPS, basically, which requires you to have a public/private key combination issued to you from a trusted certificate authority.
---
It should be noted that your association of SSL encrypted channel with an external facing site is incorrect. The point of wanting to encrypt a channel is to prevent man-in-the-middle attacks, exactly like you are trying to do here.
You could use a self-issued certificate, but that would require installing the public key of the certificate on each machine that is going to call your web method. It's easier to just get one from a trusted authority. | Secure password solution for a web service authenticating against Active Directory? | [
"",
"c#",
"web-services",
"authentication",
"active-directory",
""
] |
I have a sorted listbox and need to display each item's row number. In this demo I have a Person class with a Name string property. The listbox displays a a list of Persons sorted by Name. How can I add to the datatemplate of the listbox the row number???
XAML:
```
<Window x:Class="NumberedListBox.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<ListBox
ItemsSource="{Binding Path=PersonsListCollectionView}"
HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
```
Code behind:
```
using System;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Windows;
using System.ComponentModel;
namespace NumberedListBox
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Persons = new ObservableCollection<Person>();
Persons.Add(new Person() { Name = "Sally"});
Persons.Add(new Person() { Name = "Bob" });
Persons.Add(new Person() { Name = "Joe" });
Persons.Add(new Person() { Name = "Mary" });
PersonsListCollectionView = new ListCollectionView(Persons);
PersonsListCollectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
DataContext = this;
}
public ObservableCollection<Person> Persons { get; private set; }
public ListCollectionView PersonsListCollectionView { get; private set; }
}
public class Person
{
public string Name { get; set; }
}
}
``` | This should get you started:
<http://weblogs.asp.net/hpreishuber/archive/2008/11/18/rownumber-in-silverlight-datagrid-or-listbox.aspx>
It says it's for Silverlight, but I don't see why it wouldn't work for WPF. Basically, you bind a TextBlock to your data and use a custom value converter to output the current item's number. | Finally! If found a way much more elegant and probably with better performance either.
(see also [Accessing an ItemsControl item as it is added](https://stackoverflow.com/questions/2007177/accessing-an-itemscontrol-item-as-it-is-added/2007747#2007747))
We "misuse" the property `ItemsControl.AlternateIndex` for this. Originally it is intended to handle every other row within a `ListBox` differently. (see <http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx>)
**1. Set AlternatingCount to the amount of items contained in the ListBox**
```
<ListBox ItemsSource="{Binding Path=MyListItems}"
AlternationCount="{Binding Path=MyListItems.Count}"
ItemTemplate="{StaticResource MyItemTemplate}"
...
/>
```
**2. Bind to AlternatingIndex your DataTemplate**
```
<DataTemplate x:Key="MyItemTemplate" ... >
<StackPanel>
<Label Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplatedParent.(ItemsControl.AlternationIndex)}" />
...
</StackPanel>
</DataTemplate>
```
So this works without a converter, an extra `CollectionViewSource` and most importantly without brute-force-searching the source collection. | Numbered listbox | [
"",
"c#",
"wpf",
"listbox",
""
] |
*(For further background, this relates to the same piece of work as a [previous question](https://stackoverflow.com/questions/709882/javascript-namespaces-and-jquery-ajax))*
I'm creating a **JavaScript based webchat system using jQuery** to make life much easier. All the webchat JavaScript code is in an external js file, which is then referenced and instantiated by the html page.
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WebchatV3</title>
<script type="text/javascript" src="/JavaScript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="WebchatV3.js"></script>
<link rel="stylesheet" href="WebchatV3.css" />
</head>
<body>
<div id="WebchatSurround">
<div style="float:right;width:300px;">
<div id="MembersBox">
Members
<ul id="MembersList">
</ul>
</div>
<div id="QuestionsBox">
Questions
<div id="QuestionsList">
</div>
</div>
</div>
<div style="margin-right:310px;" id="ChatBox">
<div id="ChatData">
<ul id="ChatDataList"></ul>
</div>
<div id="ChatInput">
<div id="ChatInputCharRemainText">Characters remaining <span id="ChatInputCharRemain"></span></div>
<input type="text" maxlength="1000" id="ChatInputTextbox" />
</div>
</div>
</div>
<script type="text/javascript">
var webchat;
webchat = new AvonAndSomerset.WebchatV3(123, 'passcode', false);
</script>
</body>
</html>
```
In the JavaScript there is code to dynamically create a list of active chat members from a JSON query. This code creates a series of html DIVs and then injects this html into the 'QuestionsList' DIV present in the html.
Now here's the question :)
Within each question are elements with JavaScript onclick events that allows actions to be taken against the question shown. How can I create the onclick code without hard coding the reference to 'webchat' - is there an elegent and acceptable way?
My initial thoughts are to pass in the instance name of the 'webchat' instance when it's created, so it can then be used inside the JavaScript when creating dynamic JavaScript...
**Example of code with hard coded reference to instantited 'webchat':**
```
<div id="QuestionsBox">
Questions
<div id="QuestionsList">
<div class="Question">
<div class="QuestionInnerControls">
<img src="images/arrow_up.png" alt="" class="ControlIcon" onclick="webchat.Questions.Move(1,1);" >
<img src="images/arrow_down.png" alt="" class="ControlIcon" onclick="webchat.Questions.Move(1,-1);">
<img src="images/delete.png" alt="" class="ControlIcon" onclick="webchat.Questions.Delete(1);">
</div>
<div class="QuestionInnerText">
1) <b>Peter Bridger</b>: This is the question text
<br style="clear: right;">
</div>
</div>
</div>
</div>
``` | Thanks for your input everyone, I've decided to pass in the instance name of the Webchat when instancing it:
```
var webchat;
webchat = new AvonAndSomerset.WebchatV3(123, 'passcode', false , 'webchat' );
```
Then inside the JavaScript I'm referencing the passed in referenced when dynamically building html with JavaScript in it:
```
onclick="' + this.instanceName + '.popupMemberDetailsShow(' + this.Members.collection[i].memberId + ');
``` | While I think the live idea will most likely work for you, my initial thought was to create a template div in the initial stages of the code, and then use the clone(true) method to create dynamic copies of the template and its methods. Then within the javascript "loop" each copy could be customised as needed before being appended into the DOM.
<http://docs.jquery.com/Manipulation/clone#bool> | Javascript: Dynamically created html elements referencing an instantiated object | [
"",
"javascript",
"jquery",
"json",
"events",
"dom",
""
] |
I've been out of the C++ game for about 10 years and I want to get back in and start on a commercial app. What libraries are in use these days?
* User interface (e.g, [wxWidgets](http://www.wxwidgets.org/), [Qt](https://www.qt.io/))
* Database
* General purpose (e.g. [Boost](http://www.boost.org/), [Loki](http://loki-lib.sourceforge.net/), STL)
* Threading
* Testing
* Network/sockets
I looking to be cross-platform compatible (as much as possible out-of-the-box).
What libraries to do you rely on? What features do they provide that make them *"indispensable"*?
See [my answer](https://stackoverflow.com/questions/777764/what-modern-c-libraries-should-be-in-my-toolbox/782146#782146) below for a summary. | **Cross-platform libraries that are free for commercial (or non-commercial) applications**
*Feel free to expand this list*
---
* General Purpose
+ [Boost](http://www.boost.org/)
+ [Loki](http://loki-lib.sourceforge.net)
+ [MiLi](https://code.google.com/p/mili/)
+ [POCO](http://pocoproject.org/)
+ [STL](http://en.wikipedia.org/wiki/Standard_template_library) (of course)
+ [STXXL](http://stxxl.sourceforge.net/) (STL re-implementation for extra large data sets)
+ [Qt](http://www.qt.io/)
+ [ASL](http://stlab.adobe.com/)
+ [JUCE](http://www.juce.com)
---
* Audio
+ [FMOD](http://www.fmod.org/)
+ [Synthesis ToolKit](https://ccrma.stanford.edu/software/stk/)
* Database
+ [SOCI](http://soci.sourceforge.net)
+ [OTL](http://otl.sourceforge.net/)
+ [LMDB++](http://lmdbxx.sourceforge.net/)
* Design
+ IoC Frameworks
- [Hypodermic](https://github.com/ybainier/Hypodermic)
- [PocoCapsule](http://www.pocomatic.com/docs/whitepapers/pococapsule-cpp/)
- [Wallaroo](http://wallaroolib.sourceforge.net)
* Documents
+ [LibreOffice API](http://api.libreoffice.org/)
+ [PoDoFo](http://podofo.sourceforge.net/)
* Graphics
+ [Allegro](http://alleg.sourceforge.net/)
+ [OGRE](http://www.ogre3d.org/)
+ [SFML](http://www.sfml-dev.org/)
* GUI
+ [FLTK](http://www.fltk.org/)
+ [GTK](http://www.gtkmm.org/)
+ [Qt](http://www.qt.io/)
+ [Qwt](http://qwt.sourceforge.net/)
+ [wxWidgets](http://www.wxwidgets.org)
+ [VTK](http://vtk.org)
* Hashing
+ [MurmurHash3](https://code.google.com/p/smhasher/wiki/MurmurHash3)
* Imaging
+ [Boost.GIL](http://www.boost.org/doc/libs/1_38_0/libs/gil/doc/index.html)
+ [CImg](http://cimg.sourceforge.net)
+ [DevIL](http://openil.sourceforge.net/)
+ [EasyBMP](http://easybmp.sourceforge.net/)
+ [FreeImage](http://freeimage.sourceforge.net/)
+ [ITK](http://itk.org)
+ [OpenCV](http://opencv.willowgarage.com/)
* Logging
+ [Boost.Log](http://boost-log.sourceforge.net/libs/log/doc/html/index.html)
+ [log4cxx](http://logging.apache.org/log4cxx/index.html)
+ [Pantheios](http://www.pantheios.org/)
* Mocking
+ [Google Mock](https://code.google.com/p/googlemock/)
+ [Hippo Mocks](https://www.assembla.com/wiki/show/hippomocks)
+ [Turtle](http://turtle.sourceforge.net/) (C++ mock object library for Boost)
* Multimedia
+ [openframework](http://openframeworks.cc)
+ [Cinder](http://libcinder.org/)
+ [SDL](http://www.libsdl.org/)
* Networking
+ [ACE](http://www.cs.wustl.edu/%7Eschmidt/ACE.html)
+ [Boost.Asio](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html)
+ [ICE](http://www.zeroc.com/)
* Testing
+ [Boost.Test](http://www.boost.org/doc/libs/1_38_0/libs/test/doc/html/index.html)
+ [Google Test](http://googletest.googlecode.com/)
+ [UnitTest++](http://unittest-cpp.sourceforge.net/)
+ [doctest](https://github.com/onqtam/doctest)
* Threading
+ [Boost.Thread](http://www.boost.org/doc/libs/1_38_0/doc/html/thread.html)
* Version Control
+ [libgit2](http://libgit2.github.com/)
* Web Application Framework
+ [CppCMS](http://cppcms.com/)
+ [Wt](http://www.webtoolkit.eu/)
* XML
+ [Libxml2](http://xmlsoft.org/)
+ [pugixml](http://pugixml.org/)
+ [RapidXml](http://rapidxml.sourceforge.net/)
+ [TinyXML](http://www.grinninglizard.com/tinyxml/)
+ [Xerces-C++](http://xerces.apache.org/xerces-c/)
---
Links to additional lists of open source C++ libraries:
<http://en.cppreference.com/w/cpp/links/libs> | Sorry for repeating some of the stuff already written, but:
* UI: [Qt](http://qt.nokia.com/)
* Database: [SOCI](http://soci.sourceforge.net/)
* General purpose: [Boost](http://boost.org), [Loki](http://loki-lib.sourceforge.net/), [STLSoft Libraries](http://www.stlsoft.org/), [ASL](http://stlab.adobe.com/)
* Threading: [Boost.Thread](http://www.boost.org/doc/libs/1_38_0/doc/html/thread.html)
* Testing: [Boost.Test](http://www.boost.org/doc/libs/1_38_0/libs/test/doc/html/index.html)
* Build tools: [Boost.Build](http://www.boost.org/doc/tools/build/index.html), [SCons](http://www.scons.org/)
(Should at least get you started) | What modern C++ libraries should be in my toolbox? | [
"",
"c++",
""
] |
Say I have the following data
```
Name Value
===============
Small 10
Medium 100
Large 1000
```
Imagine that these represent the volumes of boxes. I have some items that I want to put in the boxes, and I want the smallest box possible. I need an SQL query that will:
1. Return the row with the smallest row greater than my query parameter
2. If there is no such row, then return the largest row.
It is easy to split this up in to two queries (i.e. query point 1 first and if no rows are returned, select the largest number from the table). However, I like to do things in one query if possible to eliminate overhead (both code and context switching), and it looks like it should be possible to do. It's probably very obvious, but the Sun has been shining on me all day and I can't think!
So for example, I want the query to return 10 if you use a parameter of 5, 100 if you use a parameter of 15 and 1000 if you use anything greater than 100 (including numbers greater than 1000).
I'm on Oracle 11g, so any special Oracle goodness is OK. | ```
SELECT *
FROM (
SELECT *
FROM (
SELECT *
FROM mytable
WHERE value > 10000
ORDER BY
value
)
UNION ALL
SELECT *
FROM (
SELECT *
FROM mytable
ORDER BY
value DESC
)
)
WHERE rownum = 1
```
This will both efficiently use an index on `mytable(value)` and `COUNT(STOPKEY)`.
See this article in my blog for performance details:
* [**Selecting lowest value**](http://explainextended.com/2009/04/24/selecting-lowest-value/) | ```
SELECT MAX(Value)
FROM Table
WHERE Value <= LEAST(@param,(SELECT MAX(Value) FROM Table))
```
I'm not that familiar with Oracle but I'm sure it has a LEAST function or something equivalent.
In any case, this query's subquery will be swift with the right index on the `Value` column.
In all seriousness you really should do this in two queries (or two steps in one stored procedure if you want to keep them in the same place), because the second query is unnecessary if the first query works. Combining them in one query necessarily gives you an unconditional second (or sub-) query. You have to query the table twice, so the question is whether you query it twice *always* or just when necessary. | Finding the lowest value in a table greater than a certain value | [
"",
"sql",
"oracle",
""
] |
Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:
```
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
```
I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) | No, but you can subclass dict to provide notification on change.
```
class ObservableDict( dict ):
def __init__( self, *args, **kw ):
self.observers= []
super( ObservableDict, self ).__init__( *args, **kw )
def observe( self, observer ):
self.observers.append( observer )
def __setitem__( self, key, value ):
for o in self.observers:
o.notify( self, key, self[key], value )
super( ObservableDict, self ).__setitem__( key, value )
def update( self, anotherDict ):
for k in anotherDict:
self[k]= anotherDict[k]
class Watcher( object ):
def notify( self, observable, key, old, new ):
print "Change to ", observable, "at", key
w= Watcher()
a= ObservableDict( {'a':'hamburger', 'b':'fries', 'c':'coke'} )
a.observe( w )
b = {'b':'fries', 'c':'pepsi'}
a.update( b )
```
Note that the superclass Watcher defined here doesn't check to see if there was a "real" change or not; it simply notes that there was a change. | ## one year later
I like the following solution:
```
>>> def dictdiff(d1, d2):
return dict(set(d2.iteritems()) - set(d1.iteritems()))
...
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> dictdiff(a, b)
{'c': 'pepsi', 'd': 'ice cream'}
``` | python dict update diff | [
"",
"python",
"diff",
"dictionary",
""
] |
We are trying to get WCF and Java talking to each other using SAML tokens issued from an STS. Despite the fact that both sides are compliant with the standards, WS-Security, WS-Trust, WS-Policy, etc., they don't seem to talk to each other and one or the other will throw cryptic exceptions or ignore security headers.
We are using .NET 3.5, WCF Federation binding on the MS side, and Axis2/Rampart/Rahas on the java side.
Has anyone ever been able to make this work? | Axis2 is incomplete in terms of WS standards compliance.
I recently (in the last month) went through a POC phase where Axis2 failed my WS-\* compliance tests (specifically WS-AT, WS-Coordination).
Have a look at "Project Metro". Sun and Microsoft collaborated on getting WCF and JAX-WS interop "right".
<https://metro.dev.java.net/> | I would also not recommand going for Axis2 on the Java side, if you can. Would be easier with Glassfish or JAX-WS apparently, althoug I never tested it.
I ran into those kind of issues as well when trying to make WCF and Axis2 cooperate. Check the version of the standard used in the WSDL file, those were not matching in our case. | WCF Interop with Axis2 using WS-Trust | [
"",
"java",
"wcf",
"interop",
"saml",
"sts-securitytokenservice",
""
] |
Simple question - why does the Decimal type define these constants? Why bother?
I'm looking for a reason why this is defined by the language, not possible uses or effects on the compiler. Why put this in there in the first place? The compiler can just as easily in-line 0m as it could Decimal.Zero, so I'm not buying it as a compiler shortcut. | Small clarification. They are actually static readonly values and not constants. That has a distinct difference in .Net because constant values are *inlined* by the various compilers and hence it's impossible to track their usage in a compiled assembly. Static readonly values however are not copied but instead referenced. This is advantageous to your question because it means the use of them can be analyzed.
If you use reflector and dig through the BCL, you'll notice that MinusOne and Zero are only used with in the VB runtime. It exists primarily to serve conversions between Decimal and Boolean values. Why MinusOne is used coincidentally came up on a separate thread just today ([link](https://stackoverflow.com/questions/745292/convert-boolean-to-integer-in-vb-net/745366#745366))
Oddly enough, if you look at the Decimal.One value you'll notice it's used nowhere.
As to why they are explicitly defined ... I doubt there is a hard and fast reason. There **appears** to be no specific performance and only a bit of a convenience measure that can be attributed to their existence. My *guess* is that they were added by someone during the development of the BCL for their convenience and just never removed.
**EDIT**
Dug into the `const` issue a bit more after a comment by @Paleta. The C# definition of `Decimal.One` uses the `const` modifier however it is emitted as a `static readonly` at the IL level. The C# compiler uses a couple of tricks to make this value virtually indistinguishable from a `const` (inlines literals for example). This would show up in a language which recognize this trick (VB.Net recognizes this but F# does not). | Some .NET languages do not support decimal literals, and it is more convenient (and faster) in these cases to write Decimal.ONE instead of new Decimal(1).
Java's BigInteger class has ZERO and ONE as well, for the same reason. | What is the purpose of Decimal.One, Decimal.Zero, Decimal.MinusOne in .Net | [
"",
"c#",
".net",
"vb.net",
"decimal",
"constants",
""
] |
What I'm trying to do is provide a form where a user can type or cut and past formatted text and be able to send it as an email (similar to outlook). This is required because it's closely resembles the current work flow and these emails aren't being saved anywhere besides people's inboxes. This is obviously a bandage on a bigger problem.
My current attempt has a RichTextBox that can receive RTF that is copy and pasted but when I try to send the email, it seems that the only options are plain text and HTML. After investigating options for an RTF to HTML library, it seems that they all cost at least $300 but after reviewing how difficult it would be to write the library myself, the money and time is better spent getting a third party option. I'm curious if there is a solution to this problem (sending an email with formatted text) without bringing in a third party library. | Most email clients can't display email in RTF, and that's just how it is. You can't change the email clients.
So, you need to send the email in HTML. There's no built-in WinForms control to export formatted text in HTML, unfortunately, so there's no way to accomplish this without third-party code. | I ended up finding a free solution:
<http://www.dreamincode.net/forums/showtopic48398.htm>
It's not a perfect translation but it's better than any of the pay packages out there. | How can I send emails that preserve the formatting that a user provides in RTF in a RichTextBox? | [
"",
"c#",
".net",
"html",
"richtextbox",
"rtf",
""
] |
Is it a good idea to store files in a different SQL Server 2005 database "FileDb" and point to it (files) in the "AppDb" by "FileId".
Please take in consideration that I have a dedicated server and I can create as many Sql Databases as I want.
# update:
Which perform better single database or multiple databsae? | You can use [filegroups](http://www.mssqltips.com/tip.asp?tip=1112) to separate your data files. You can create one separate filegroup for storing the file data. | I prefer to have a column which stores the file path + filename
I never liked the idea of storing it in the database because of the following reason:
bloats the database...backup and restore will take longer
image and text datatype is a pain in the neck to work with
In SQL Server 2008 you can use FILESTREAM which is still transactional but stores it as a file | Storing Files in a different Database? | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
Unfortunately an item can only be removed from the stack by "pop". The stack has no "remove" method or something similar, but I have a stack (yes I need a stack!) from which I need to remove some elements between.
Is there a trick to do this? | If you need to remove items that aren't on the top, then you need something other than a stack.
Try making your own implementation of a stack from a List. Then you get to implement your own push and pop functions (add & remove on the list), and your own special PopFromTheMiddle function.
For example
```
public class ItsAlmostAStack<T>
{
private List<T> items = new List<T>();
public void Push(T item)
{
items.Add(item);
}
public T Pop()
{
if (items.Count > 0)
{
T temp = items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return temp;
}
else
return default(T);
}
public void Remove(int itemAtPosition)
{
items.RemoveAt(itemAtPosition);
}
}
``` | Consider using different container. Maybe a LinkedList.
Then you can use
```
AddFirst
AddLast
RemoveLast
RemoveFirst
```
just like pop/push from stack and you can use
```
Remove
```
to remove any node from the middle of the list | How to remove a stack item which is not on the top of the stack in C# | [
"",
"c#",
"stack",
""
] |
There is a timer on the form and in its Tick event I've:
```
this.BackColor = ColorTranslator.FromHtml("#" + ColorCodesBack[_index]);
CurrentColor = ColorTranslator.FromHtml("#" + ColorCodesFore[_index]);
SolidBrush sb = new SolidBrush(CurrentColor);
g.FillEllipse(sb, this.Width/2 -200, this.Height/2 - 200, 200, 200);
g.DrawImage(b, 150, 150);
```
The problem is just background changes on every tick and I don't see a Circle on the form. | What you should do is put your code in the forms Paint event. That will cause your code to redraw ever time the form has to repaint. Like running your mouse over the form or moving the form. Also where are you declaring your graphic object? Because the only way it will be drawn on your form is if you do:
```
Graphics g = this.CreateGraphics();
```
If you use the paint event you won't even need a timer object. | You should combine this code with the same tick event that is changing the backgroud. Otherwise you effectively have a race condition as to which "tick" will be fired first. Combining them will solve that problem. | How-to draw a circle on a changing background | [
"",
"c#",
".net",
"winforms",
"graphics",
"timer",
""
] |
```
import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True
def work(self):
self.count+=1
time.sleep(1)
if(self.doSkip):
print "skipped"
self.doSkip = False
return
print self.count
t = test()
t.start()
while t.count<9:
time.sleep(2)
t.skip()
``` | Thread-safe in which way? I don't see any part you might want to protect here.
skip may reset the `doSkip` at any time, so there's not much point in locking it. You don't have any resources that are accessed at the same time - so IMHO nothing can be corrupted / unsafe in this code.
The only part that might run differently depending on locking / counting is how many "skip"s do you expect on every call to `.skip()`. If you want to ensure that every skip results in a skipped call to `.work()`, you should change `doSkip` into a counter that is protected by a lock on both increment and compare/decrement. Currently one thread might turn `doSkip` on after the check, but before the `doSkip` reset. It doesn't matter in this example, but in some real situation (with more code) it might make a difference. | Whenever the test of a mutex boolean ( e.g. if(self.doSkip) ) is separate from the set of the mutex boolean you will probably have threading problems.
The rule is that your thread will get swapped out at the most inconvenient time. That is, after the test and before the set. Moving them closer together reduces the window for screw-ups but does not eliminate them. You almost always need a specially created mechanism from the language or kernel to fully close that window.
The threading library has Semaphores that can be used to synchronize threads and/or create critical sections of code. | Is this Python code thread safe? | [
"",
"python",
"multithreading",
""
] |
I could Open and Write to the excel file, but when I try to save the file by passing a path to it, the save operation prompts with the Save dialog. I was expecting it to quitely Save the file at the specified path
The code is as below:
```
excelApp.Save(exportToDirectory);
excelApp.Quit();
```
where, **exportToDirectory** is: "C:\files\strings.xlsx".
PS: I have already checked with the excel version and similar issue.
Thanks | You need to use `Workbook.SaveAs` instead of `Application.Save`:
```
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Add(missing);
...
wb.SaveAs(@"C:\temp\test.xlsx", missing, missing, missing, missing,
missing, Excel.XlSaveAsAccessMode.xlExclusive,
missing, missing, missing, missing, missing);
``` | Setting the following properties might also help:
```
excelApp.DisplayAlerts = false;
excelApp.ScreenUpdating = false;
excelApp.Visible = false;
excelApp.UserControl = false;
excelApp.Interactive = false;
``` | C# and Excel Interop issue, Saving the excel file not smooth | [
"",
"c#",
"interop",
"excel-interop",
""
] |
When I programmed in C/C++, I often include pointer values in tracing. This helped correlate objects between trace messages. In C#, I don't have a pointer value available I can trace. Are there any good alternatives for traceable object IDs??
I don't know offhand how to get the underlying memory address, but even if I did that wouldn't help much as the GC could move objects around. | Add a class variable that is incremented on each constructor call. Assign this class-variable as your own index to the class.
```
class foo
{
private static int counter;
private int instance_counter;
public Foo()
{
instance_counter = counter;
counter++;
}
public string toString()
{
return "Foo "+instance_counter.toString();
}
}
```
may not compile out of the box, I have no compiler here. | A tip: inside Visual Studio, you can right click on the object in the locals/watch window, and select "Make Object ID" to give the object a unique tag.
<http://blogs.msdn.com/saraford/archive/2008/09/16/did-you-know-how-to-create-an-object-id-to-keep-track-of-your-objects-314.aspx> | debugging with pointers in C# | [
"",
"c#",
"pointers",
""
] |
I'm writing some code where I defined the following base class.
```
class Chorus{
public:
//Destructor
virtual ~Chorus();
//callback function
virtual int callback( void *outputBuffer, void *notUsed, unsigned int
nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData );
virtual void initializeDelayBuffer(void);
virtual void destroyDelayBuffer(void);
};
```
I want to use this as a base class and not actually do anything with it on its own. So I have two seperate classes which are derived from this class Chorus. I wanted to do this to simply provide some basic constraints as to what any derived Chorus class *MUST* have to be considered usable in my program.
When I build my project (Visual Studio 2008), I get unresolved external symbol errors on all the virtual functions from this Chorus class. I'm guessing it's the typical error where I didn't make forward declarations of these functions. But, since they are virtual and I don't want them to actually be defined to do anything until they are defined within the deriving classes, what do I do to resolve this issue? | If your intent is for them to be simply place holders for child classes to implement, then make them pure virtual functions by ending with = 0. For example
```
virtual void destroyDelayBuffer(void) = 0;
```
This makes the method "abstract" so to speak. The C++ compiler will not look for an actual definition of the method but instead will force all derived classes to implement these methods before an instance can be created. | You need to declare those function as pure virtual.
virtual void initializeDelayBuffer(void) = 0;
That will create an interface of sorts, which is what you want. | beginner c++: virtual functions in a base class | [
"",
"c++",
"visual-studio-2008",
"virtual",
"unresolved-external",
""
] |
We use a modified version of [Jiffy](http://code.google.com/p/jiffy-web/) to measure actual client-side performance.
The most important thing we do is measure the time between when the request was received and when the page load event fires in the browser.
On some pages we have `iframe` elements that point to external sites that we don't control - they sometimes take a long while to load. At the moment, the page load event for our page fires only after the `iframe` is completely loaded (and it's own load event fires).
I'd like to separate these measurements - have one measurement after everything including the `iframe` is loaded, but also one measurement without the `iframe` - that is, when the page load would have occured if we didn't have an `iframe`.
The only way I've managed to do this so far is to add the `iframe` to the DOM after the page load event, but that delays the loading of the iframe.
Any ideas?
EDIT: bounty is over, thanks for the help and ideas! I chose Jed's answer because it gave me a new idea - start loading the iframes, but "pause" them so they won't affect page load (by temporarily setting `src="about:blank"`). I'll try to add a more detailed summary of my results. | You can achieve this for multiple iframes without dynamically adding them by:
1. setting the `src` attribute for all frames to `about:blank` before body load,
2. letting the body load event fire,
3. adding an `onload` handler to capture the load time of each frame, and then
4. restoring the `src` attribute of each frame to its original value.
I've created a `frameTimer` module that consists of two methods:
1. an `init` method that needs to be called immediately before the `</body>` tag, and
2. a `measure` method to be called on page load, which takes a callback with the results.
The results object is a hash like this:
```
{
iframes: {
'http://google.co.jp/': 1241159345061,
'http://google.com/': 1241159345132,
'http://google.co.uk/': 1241159345183,
'http://google.co.kr/': 1241159345439
},
document: 1241159342970
}
```
It returns integers for each load time, but could be easily changed to just return the diff from the document body load.
Here's a working example of it in action, with this javascript file (`frameTimer.js`):
```
var frameTimer = ( function() {
var iframes, iframeCount, iframeSrc, results = { iframes: {} };
return {
init: function() {
iframes = document.getElementsByTagName("iframe"),
iframeCount = iframes.length,
iframeSrc = [];
for ( var i = 0; i < iframeCount; i++ ) {
iframeSrc[i] = iframes[i].src;
iframes[i].src = "about:blank";
}
},
measure: function( callback ) {
results.document = +new Date;
for ( var i = 0; i < iframeCount; i++ ) {
iframes[i].onload = function() {
results.iframes[ this.src ] = +new Date;
if (!--iframeCount)
callback( results )
};
iframes[i].src = iframeSrc[ i ];
}
}
};
})();
```
and this html file (`frameTimer.html`):
```
<html>
<head>
<script type="text/javascript" src="frameTimer.js"></script>
</head>
<body onload="frameTimer.measure( function( x ){ alert( x.toSource() ) } )">
<iframe src="http://google.com"></iframe>
<iframe src="http://google.co.jp"></iframe>
<iframe src="http://google.co.uk"></iframe>
<iframe src="http://google.co.kr"></iframe>
<script type="text/javascript">frameTimer.init()</script>
</body>
</html>
```
This could be done in a lot less code (and less obtrusively) with jQuery, but this is a pretty lightweight and dependency-free attempt. | I'm not familiar with jiffy *per se*, but in the past I've done similar measurements using a crude bespoke function, roughly like this (5 mins typing from memory):
```
<html>
<head>
<script>
var timer = {
measure: function(label)
{
this._timings[label] = new Date();
},
diff: function(a,b)
{
return (this._timings[b] - this._timings[a]);
},
_timings: {}
}
</script>
</head>
<body onload="alert(timer.diff('iframe.start','iframe.done'));">
<!-- lorem ipsum etc -->
<script>timer.measure('iframe.start');</script>
<iframe src="http://www.google.com" onload="timer.measure('iframe.done');"/>
<!-- lorem ipsum etc -->
</body>
</html>
```
From that you can see the relevant part is simply to note a datestamp immediately before the iframe is encountered, and then add an event handler to the iframes' onload event (which will work regardless of the domain of the iframe source and doesn't require modifying the content) to take another measurement (normally I'd add these events with addEventListener/attachEvent but you get the idea).
That gives you a timespan for the iframe you can subtract from the total to give you a reasonable idea of loadtime with and without iframe.
HTH | Measuring when only certain page elements have loaded | [
"",
"javascript",
"performance",
"dom-events",
"client-side",
""
] |
I need to draw 3d projections and i am using opengl wrapper for JAVA.
Problem:
- how to set view point in java opengl (for examle i want to my program to draw object on screen like i am looking at that object from (0,0,0) )
- how to set perspective point(point in 3d where look is heading to, for example i want may program to draw object on screen as i am looking from (0, 0, 0) to (1, 1, 3) )
I am familiarized with mathematical problem of this question, so i have calculated all of the coordinates for perspectives. I just need opengl java function or set off functions that can draw this new coordinates in perspective i want.
HELP!! :))) | [Nehe](http://nehe.gamedev.net/lesson.asp?index=01) have a port of most of their tutorials to Java. One of the first one should probably be doing what you need to get yourself started. | Does this [example](http://www.java-tips.org/other-api-tips/jogl/how-to-render-a-wireframe-cube.html) help you? The function you are perhaps looking for is [gluLookAt](http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/glu/lookat.html):
```
gluLookAt( GLdouble eyeX,
GLdouble eyeY,
GLdouble eyeZ,
GLdouble centerX,
GLdouble centerY,
GLdouble centerZ,
GLdouble upX,
GLdouble upY,
GLdouble upZ )
PARAMETERS
eyeX, eyeY, eyeZ
Specifies the position of the eye point.
centerX, centerY, centerZ
Specifies the position of the reference
point.
upX, upY, upZ
Specifies the direction of the up vector.
``` | 3d draw, setting perspective point, setting view point! | [
"",
"java",
"opengl",
""
] |
In C++ classes, why the semi-colon after the closing brace? I regularly forget it and get compiler errors, and hence lost time. Seems somewhat superfluous to me, which is unlikely to be the case. Do people really do things like:
```
class MyClass
{
.
.
.
} MyInstance;
```
I get it from a C compatibility point of view for structs and enums, but since classes aren't part of the C language I guess it's primarily there the keep consistency between similar declaration constructs.
What I was looking for was more related to design rationale rather than being able to change anything, although a good code completion IDE might trap this before compilation. | The semi-colon after the closing brace in a type declaration is required by the language. It's been that way since the earliest versions of C.
And yes, people do indeed do the declaration you just put up there. It's useful for creating scoped types inside of methods.
```
void Example() {
struct { int x; } s1;
s1.x = 42;
struct ADifferentType { int x; };
}
```
In this case, I think it's clear why the semi-colons are needed. As to why it's needed in the more general case of declaring in the header file I'm unsure. My *guess* is that it's historical and was done to make writing the compiler easier. | The [link](https://web.archive.org/web/20100906085102/http://cpptalk.net/confused-about-the-meaning-of-the-semicolon-vt11965.html) provided by @MichaelHaren appears to provide the *root cause*. The semicolon (as others have pointed out) is inherited from C. But that doesn't explain why C used it in the first place. The discussion includes this gem of an example:
```
struct fred { int x; long y; };
main()
{
return 0;
}
```
Older versions of C had an implicit int return type from a function unless declared otherwise. If we omit the `;` at the end of the structure definition, we're not only defining a new type `fred`, but also declaring that `main()` will return an instance of `fred`. I.e. the code would be parsed like this:
```
struct fred { int x; long y; } main()
{
return 0; /* invalid return type, expected fred type */
}
``` | Semicolon after class declaration braces | [
"",
"c++",
"class",
"oop",
"declaration",
""
] |
I am trying to get data from different sever, and the sever name might change. So I set the server name as a parameter. The idea of my sql store procedure is something like this
```
CREATE PROCEDURE [dbo].[GetData]
@ServerName
AS
BEGIN
SELECT * FROM @ServerName.ClientDataBase.dbo.Client
END
```
Does anyone know how to achieve this?
The database version is sql server 2005 | Use dynamic SQL, however evil this may be:
```
exec('select * from ' + @ServerName + '.ClientDatabase.dbo.Client')
``` | Look at using Synonym(s)
Create syntax (from MSDN):
```
CREATE SYNONYM [ schema_name_1. ] synonym_name FOR < object >
< object > :: =
{
[ server_name.[ database_name ] . [ schema_name_2 ].|
database_name . [ schema_name_2 ].| schema_name_2. ] object_name
}
``` | make server name as a variable | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
> **Update:** This issue is caused by bad memory usage, see **solution** at the bottom.
Here's some semi-pseudo code:
```
class ClassA
{
public:
virtual void VirtualFunction();
void SomeFunction();
}
class ClassB : public ClassA
{
public:
void VirtualFunction();
}
void ClassA::VirtualFunction()
{
// Intentionally empty (code smell?).
}
void ClassA::SomeFunction()
{
VirtualFunction();
}
void ClassB::VirtualFunction()
{
// I'd like this to be called from ClassA::SomeFunction()
std::cout << "Hello world!" << endl;
}
```
~~The C# equivalent is as follows:~~ Removed C# example, as it's not relevant to the actual problem.
Why isn't the `ClassB::VirtualFunction` function being called when called from `ClassA::SomeFunction`? Instead `ClassA::VirtualFunction` is being called...
When I [force implementation of the virtual function](https://stackoverflow.com/questions/738204/why-might-my-virtual-function-call-be-failing/738223#738223) ClassA::VirtualFunction, like so:
```
class ClassA
{
public:
virtual void VirtualFunction() = 0;
void SomeFunction();
}
class ClassB : public ClassA
{
public:
void VirtualFunction();
}
void ClassA::SomeFunction()
{
VirtualFunction();
}
void ClassB::VirtualFunction()
{
// I'd like this to be called from ClassA::SomeFunction()
std::cout << "Hello world!" << endl;
}
```
The following error occurs at runtime, despite the derrived function deffinately being declared and defined.
```
pure virtual method called
terminate called without an active exception
```
*Note:* It seems like the error can be caused even by bad memory usage. See self-answer for details.
### Update 1 - 4:
*Comments removed (not releavnt).*
### Solution:
[Posted as an answer.](https://stackoverflow.com/questions/738204/why-might-my-virtual-function-call-be-failing/738566#738566) | ```
class Base {
public:
virtual void f() { std::cout << "Base" << std::endl; }
void call() { f(); }
};
class Derived : public Base {
public:
virtual void f() { std::cout << "Derived" << std::endl; }
};
int main()
{
Derived d;
Base& b = d;
b.call(); // prints Derived
}
```
If in the Base class you do not want to implement the function you must declare so:
```
class Base {
public:
virtual void f() = 0; // pure virtual method
void call() { f(); }
};
```
And the compiler won't allow you to instantiate the class:
```
int main() {
//Base b; // error b has a pure virtual method
Derived d; // derive provides the implementation: ok
Base & b=d; // ok, the object is Derived, the reference is Base
b.call();
}
```
As a side note, **be careful not to call virtual functions from constructors** or destructors as you might get unexpected results. | If you're getting that 'pure virtual method called
terminate called without an active exception' error message, that means you're calling the virtual function from the constructor or destructor of classA (the base class), which you should not do. | Why might my virtual function call be failing? | [
"",
"c++",
"virtual-functions",
""
] |
I'm trying to write a bookmarklet to help some QA testers submit useful debugging information when they come across issues. Currently I can set window.location to a URL that provides this debugging information, but this resource is an XML document with an xml-stylesheet processing directive.
It would actually be more convenient if the testers were able to see either the raw XML data as plain text, or the default XML rendering for IE and Firefox.
Does anyone know a way to disable or override xml-stylesheet directives provided inside an XML document, using Internet Explorer or Firefox?
Edit: I've opened a bounty on this question. Requirements:
* Client-side code only, no user intervention allowed
* Solutions for both IE and Firefox needed (they can be different solutions)
* Disabling stylesheet processing and rendering it as text is acceptable
* Overriding stylesheet processing with a custom XSL is acceptable
* Rendering the XML with the browser default XML stylesheet is acceptable | **EDIT**: too bad, though all seemed fine in the preview, the clickable examples seem to mess up things... Maybe the layout is fine in the history.
I've heard, but cannot validate for IE, that both IE and Firefox support the "view-source:" pseudo-protocol. Firefox on Mac indeed understands it, but Safari does not.
The following bookmarklet will not trigger [the XSLT transformation](http://www.w3schools.com/xsl/cdcatalog_ex1.xsl) specified in [the XML](http://www.w3schools.com/xsl/cdcatalog_with_ex1.xml). And though Firefox will render this using some colours, it does not execute the default transformation it would normally use for [XML without any XSLT](http://www.w3schools.com/XML/cd_catalog.xml) (so, the result of view-source does NOT yield a collapsable document tree that Firefox would normally show):
```
javascript:(function(){
var u = 'http://www.w3schools.com/xsl/cdcatalog_with_ex1.xml';
var w = window.open();
w.document.location.href = 'view-source:' + u;
})()
```
When fetching the document using Ajax then one is not limited to the `alert` [oneporter](https://stackoverflow.com/questions/777784/is-there-a-way-to-have-browsers-ignore-or-override-xml-stylesheet-processing-inst/800549#800549) used, but can display it in a new window as well. Again: this will not invoke the XSLT transformation that is specified:
```
javascript:(function(){
var u = 'http://www.w3schools.com/xsl/cdcatalog_with_ex1.xml';
var w = window.open(); /* open right away for popup blockers */
var x = new XMLHttpRequest();
x.open('GET', u, true);
x.onreadystatechange = function(){
if(x.readyState == 4){
w.document.open('text/html');
/* hack to encode HTML entities */
var d = document.createElement('div');
var t = document.createTextNode(x.responseText);
d.appendChild(t);
w.document.write('<html><body><pre>'
+ d.innerHTML + '</pre></body></html>');
w.document.close();
w.focus();
}
};
x.send(null);
})()
``` | Can't you just do "View Source" in both browsers? | Is there a way to have browsers ignore or override xml-stylesheet processing instructions? | [
"",
"javascript",
"xml",
"xslt",
"browser",
"bookmarklet",
""
] |
### My code:
```
class Address{
public var $Street;
}
class Employee{
public var $ID:
public var $Name:
public var $Address;
}
$myEmployee = new Employee();
$myEmployee->Address = new Address();
```
How do I access the the street now?
```
$street = $myEmployee->$Address->Street;
$street = $myEmployee->Address->Street;
```
Both give me warnings in Eclipse. I was thinking of:
```
$street = $myEmployee['Address']->Street;
```
Is this correct? | As has been said, your suggestion to use:
```
$street = $myEmployee->Address->Street;
```
is perfectly valid. However, there are a few errors in your code which might have caused the problems. Firstly, public member variables are either declared like this:
```
public $id;
```
or this (deprecated):
```
var $id;
```
Your combination of the two is not valid PHP code.
Also, you have two colons (:) at line endings, which should be semicolons (;).
Hope that helps! | ```
$myEmployee->Address->Street;
```
It is valid and Eclipse's warning system is quite strange regarding things like this. I usually turn them off in instances like this and let PHP do the error reporting for me.
Also eclipse does not support auto completion for what you need to do. | Accessing a member of an object within a class in PHP | [
"",
"php",
"class",
"object",
""
] |
Using ASP.NET, how can I strip the HTML tags from a given string reliably (i.e. not using regex)? I am looking for something like PHP's `strip_tags`.
### Example:
`<ul><li>Hello</li></ul>`
### Output:
"Hello"
I am trying not to reinvent the wheel, but I have not found anything that meets my needs so far. | If it is just stripping *all* HTML tags from a string, this works ~~reliably~~ with regex as well. Replace:
```
<[^>]*(>|$)
```
with the empty string, globally. Don't forget to normalize the string afterwards, replacing:
```
[\s\r\n]+
```
with a single space, and trimming the result. Optionally replace any HTML character entities back to the actual characters.
**Note**:
1. There is a limitation: HTML and XML allow `>` in attribute values. This solution *will* return broken markup when encountering such values.
2. The solution is technically safe, as in: The result will never contain anything that could be used to do cross site scripting or to break a page layout. It is just not very clean.
3. As with all things HTML and regex:
**Use [a proper parser](http://html-agility-pack.net/?z=codeplex) if you must get it right under all circumstances.** | Go download HTMLAgilityPack, now! ;) [Download LInk](http://htmlagilitypack.codeplex.com/)
This allows you to load and parse HTML. Then you can navigate the DOM and extract the inner values of all attributes. Seriously, it will take you about 10 lines of code at the maximum. It is one of the greatest free .net libraries out there.
Here is a sample:
```
string htmlContents = new System.IO.StreamReader(resultsStream,Encoding.UTF8,true).ReadToEnd();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlContents);
if (doc == null) return null;
string output = "";
foreach (var node in doc.DocumentNode.ChildNodes)
{
output += node.InnerText;
}
``` | How can I strip HTML tags from a string in ASP.NET? | [
"",
"c#",
"asp.net",
"html",
"regex",
"string",
""
] |
I would like to create a similar effect to Apple's Safari 4 Beta Top Sites page -

when when you view it and a page's content has changed since you last visited, it displays a blue star in the top right hand corner to notify you.
I would like to do the very same, but only within my website and instead of an image I would like to append a '\*' or some other character to the menu item's link.
I'm sure you would use the jQuery Cookie Plugin, but my scripting is not that advanced and I do not know how to dynamically change the cookie's content. Have I explained properly? How would I do it?
Many thanks in advance | Server side:
Read the website f.ex every minute and save the timestamp if changed content.
Save the users' visit timestamp to the page
Ajax:
Check if the websites update timestamp is newer than your visitors' timestamp, if yes make the star class visible, when the user clicks on the link, make the star disappear and update the users timestamp.
--
Showing a star or an image or whatever with Jquery is not the big deal here, it's a oneliner, the complex problem is to detect website changes, because minor changes can occur, but the main content could not change. The easiest way to do this would be if the website provides rss, then there's probable that the important new content will be published via rss. | You're asking a very vague question. Have you even attempted this? Please try it first then ask for help along the way.
Also, this is not something you necessarily need jQuery for. You could do it completely on the backend. But it's hard to say which solution is best for you without know anymore details. | Use jQuery to append star to menu item if the linked page's content has changed since last visit | [
"",
"javascript",
"jquery",
"cookies",
"append",
""
] |
I have a simple windows service application I am trying to debug in VS 2008 IDE but each time I run the code, I get the error *"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."* . This error occurs at the `service.Stop()` line below:
```
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[]
{
new Service1()
};
if (Environment.UserInteractive)
{
Type type = typeof(ServiceBase);
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
MethodInfo method = type.GetMethod("OnStart", flags);
foreach (ServiceBase service in servicesToRun)
{
method.Invoke(service, new object[] { args });
}
Console.WriteLine("Press any key to exit");
Console.Read();
foreach (ServiceBase service in servicesToRun)
{
service.Stop();//ERROR OCCURS HERE!
}
}
else
{
ServiceBase.Run(servicesToRun);
}
}
}
```
Below is the simple windows service class
```
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
``` | If you want to take full management of starting the ServiceBase outside `ServiceBase.Run()`, then you should also do the same trick with stopping it:
```
MethodInfo stopMethod = type.GetMethod("OnStop", flags);
foreach (ServiceBase service in servicesToRun)
{
stopMethod.Invoke(service, new object[] { args });
}
``` | Does this happen when you're not debugging?
Also, is this an exception? If so, then you should post the complete exception, including Inner exceptions and stack traces. | Windows Service error: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." | [
"",
"c#",
"windows",
"visual-studio-2008",
"service",
""
] |
I have a hierarchy of classes. The base class uses some tuning parameters that are loadable from file (and reloadable during runtime). Each derived class may add some additional parameters. I am looking for a way to allocate a correctly sized parameters array in the base constructor, so that I don't have to deallocate and reallocate in the derived class. I was hoping for something like this, but it's not working (parameters always has 2 elements):
```
class Base
{ static int nParms;
virtual int getNParms() { return nParms;}
float *parameters;
public:
Base()
{ parameters= new float[this->getNParms()];
parameters[0] = globalReloadableX;
parameters[1] = globalReloadableY;
}
};
int Base::nParams =2;
class Derived : public Base
{ static int nParms;
virtual int getNParms() { return nParms;}
public:
Derived() : Base()
{ parameters[2] = globalReloadableZ;
}
}
int Derived::nParams =3;
```
I've seen [this question](https://stackoverflow.com/questions/594730/overriding-static-variables-when-subclassing), but the solution there doesn't quite work for me.
I also tried making parameters a regular array in each class:
```
class Base
{ float parameters[2]
...
class Derived : public Base
{ float parameters[3]
...
```
but that makes Derived have 2 separate arrays.
Any ideas? | Why not pass the required array size as a parameter in the constructor of the base class?
(The reason the virtual function doesn't call the derived class is because that is how C++ virtual functions work; conceptually, until the derived class constructor completes, the object's type is still the base class.) | What about making the size a parameter?
```
class Base
{ static int nParms;
virtual int getNParms() { return nParms;}
float *parameters;
public:
Base(int n = nParams)
{ parameters= new float[n];
parameters[0] = globalRelodableX;
parameters[1] = globalRelodableY;
}
};
int Base::nParams =2;
class Derived : public Base
{ static int nParms;
virtual int getNParms() { return nParms;}
public:
Derived() : Base(nParams)
{ parameters[2] = globalRelodableZ;
}
}
int Derived::nParams =3;
``` | How to allocate array in base constructor with size based on derived class? | [
"",
"c++",
"inheritance",
"static",
"constructor",
""
] |
Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database.
While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.
Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk? | **Don't walk, run to get a new host immediately**. If your host won't even get you the most basic of free databases, it's time for a change. There are many fish in the sea.
At the very least I'd recommend an xml data store rather than a csv. [My blog](http://chrisballance.com) uses an xml data provider and I haven't had any issues with performance at all. | Take a look at this: <http://www.netpromi.com/kirbybase_python.html> | Using CSV as a mutable database? | [
"",
"python",
"csv",
""
] |
I have a php script that does some processing (creates remittance advice PDFs, self-billing invoices, Sage CSV file etc...) and at the end outputs a screen with a form, in which the names and e-mail addresses of the people paid appear. User makes a selection of names by clicking check boxes and then there is a Send button which sends out emails with remittance advices and self-billing invoices attached. This all works nicely, BUT they now decided that when they click the Send button, they would like the e-mails to be sent NOT straight-away, but at 6.00pm.
Is it possible to set the dispatch time of the message in the SMTP header? Can the MS Exchange server be configured so that e-mails from a particular sender will be held until a certain time before they get sent? IT Support dept. claim it used to be possible in the old days of dial-up connections when it was simply cheaper to send stuff at night... but that this functionality was removed. Is this true? I have no idea how hard is the task at hand. It seems very straightforward and I guess it really is a task for the IT support guys to handle. But maybe I am wrong?
If this can not be set up at the Exchange server side, how could I go about achieving the requested functionality? And, no, this is not an exact duplicate of [this question](https://stackoverflow.com/questions/556667/delaying-the-sending-of-emails-in-c). I had a look at that but it didn't seem to answer my questions. Any help greatly appreciated!
**Edit**
---
Apache running on MS Windows Server 2003. Database is Oracle 10g. There will be no CRON set up. The email queue table would need to store all attachments too. I would like to avoid doing this at all cost. No way to specify dispatch time in header? | You could save those emails into a database. And then create a cronjob PHP file that executes every few minutes to check if there are emails to be sent in the "queue" database.
[Here's a tutorial](http://www.mikesparr.com/2007/08/29/creating-and-email-queue-using-sql-php-shell-and-cron/) on something like this. | Windows (non-server editions, at least) has a "Scheduled Tasks" control panel item similar to CRON. Just from looking at it briefly, you can probably write a PHP script which sends your mail "now," but run it using the CLI at whatever time you want to send the mail using Scheduled Tasks. | How to delay the dispatch of an e-mail? Click button to send NOW but wait until 6.00pm until the email gets actually sent | [
"",
"php",
"email",
"configuration",
"smtp",
"exchange-server",
""
] |
Let say I got this function :
```
void int Calculate(double[] array) {}
```
And in my main I got this array:
```
double[,] myArray = new double[3,3];
```
How can I call Calculate(...) ?
I try (that's don't compile) :
```
double[] mySingleArray = myArray[0];
```
What I want to avoid is unnecessary loop (for).
I declare a regular array, but if a jagged array or any other type of array works better, it's fine for me.
I use c# 3.5 | First, let's declare your Calculate() method like this:
```
int Calculate(IEnumerable<double> doubles)
```
Don't worry, you can still pass an array to that code. You might also need `IList<double>`, but 9 times out of 10 the IEnumerable is good enough. The main thing is that this will let us use the `yield` keyword to slice up your array in an efficient way:
```
public static IEnumerable<T> Slice(this T[,] values)
{
return Slice(values, 0, 0);
}
public static IEnumerable<T> Slice(this T[,] values, int index)
{
return Slice(values, 0, index);
}
public static IEnumerable<T> Slice(this T[,] values, int dimension, int index)
{
int length = values.GetUpperBound(dimension);
int[] point = new int[values.Rank];
point[dimension] = index;
dimension = 1 - dimension;// only works for rank == 2
for (int i = 0; i < length; i++)
{
point[dimension] = i;
yield return (T)values.GetValue(point);
}
}
```
It still needs some work because it only works with rank 2 arrays, but it should be fine for the example you posted.
Now you can call your calculate function like this:
```
Calculate(myArray.Slice(0));
```
Note that due to the way IEnumerable and the yield statement work the for loop in the code I posted is essentially free. It won't run until you actually iterate the items in your Calculate method, and even there runs in a "just-in-time" fashion so that the whole algorithm remains O(n).
It gets even more interesting when you share what your Calculate method is doing. You might be able to express it as a simple Aggregate + lambda expression. For example, let's say your calculate method returned the number of items > 5:
```
myArray.Slice(0).Count(x => x > 5);
```
Or say it summed all the items:
```
myArray.Slice().Sum();
``` | A jagged array works the way you want:
```
double[][] jaggedArray = new double[][100];
for (int i = 0; i < jaggedArray.Length; ++i)
jaggedArray[i] = new double[100];
myFunction(jaggedArray[0]);
```
You can have different sizes for each array in this way. | c# array function argument pass one dimension | [
"",
"c#",
".net",
"arrays",
".net-3.5",
""
] |
I am unable to decide which STL container to use in the following case:
1. I want to preserve the order of insertion of the elements
2. The elements in the container have to be unique.
Is there any readymade container available for this? I don't want to use a vector and then perform a `std::find` before doing a `push_back` every time. | [`Boost MultiIndex`](http://www.boost.org/doc/libs/1_38_0/libs/multi_index/doc/index.html) should be able to do exactly what you want - you can just use one sequenced index to get the "ordered by insertion order" requirement, and either a `hashed_unique` or `ordered_unique` index to get the uniqueness requirement. | There might be a good built in way to do this, but one rather simple way is to use both a hash\_map and a list. Check the hash\_map before each insertion, then insert into both. You'll want to encapsulate this in a class, probably. | Choosing a STL container with uniqueness and which keeps insertion ordering | [
"",
"c++",
"stl",
""
] |
> **Possible Duplicate:**
> [When should I use the new keyword in C++?](https://stackoverflow.com/questions/655065/when-should-i-use-the-new-keyword-in-c)
When should I use the "new" operator in C++? I'm coming from C#/Java background and instantiating objects is confusing for me.
If I've created a simple class called "Point", when I create a point should I:
```
Point p1 = Point(0,0);
```
or
```
Point* p1 = new Point(0, 0);
```
Can someone clarify for me when to use the new operator and when not to?
**Duplicate of:**
[When should I use the new keyword in C++?](https://stackoverflow.com/questions/655065/when-should-i-use-the-new-keyword-in-c)
**Related:**
[About constructors/destructors and new/delete operators in C++ for custom objects](https://stackoverflow.com/questions/392455/about-constructors-destructors-and-new-delete-operators-in-c-for-custom-objects)
[Proper stack and heap usage in C++?](https://stackoverflow.com/questions/599308/proper-stack-and-heap-usage-in-c) | You should use `new` when you wish an object to remain in existence until you `delete` it. If you do not use `new` then the object will be destroyed when it goes out of scope. Some examples of this are:
```
void foo()
{
Point p = Point(0,0);
} // p is now destroyed.
for (...)
{
Point p = Point(0,0);
} // p is destroyed after each loop
```
Some people will say that the use of `new` decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.
In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.
```
class Foo
{
Point p;
}; // p will be automatically destroyed when foo is.
```
Allocating (and freeing) objects with the use of `new` is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.
A second example of when to allocate via `new` is for arrays. You cannot\* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.
E.g.
```
void foo(int size)
{
Point* pointArray = new Point[size];
...
delete [] pointArray;
}
```
(\*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations). | Take a look at [this question](https://stackoverflow.com/questions/408670/stack-static-and-heap-in-c) and [this question](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) for some good answers on C++ object instantiation.
This basic idea is that objects instantiated on the heap (using new) need to be cleaned up manually, those instantiated on the stack (without new) are automatically cleaned up when they go out of scope.
```
void SomeFunc()
{
Point p1 = Point(0,0);
} // p1 is automatically freed
void SomeFunc2()
{
Point *p1 = new Point(0,0);
delete p1; // p1 is leaked unless it gets deleted
}
``` | When to use "new" and when not to, in C++? | [
"",
"c++",
"new-operator",
""
] |
Is there any significant difference between the following?
`SELECT a.name, b.name FROM a, b WHERE a.id = b.id AND a.id = 1`
AND
`SELECT a.name, b.name FROM a INNER JOIN b ON a.id = b.id WHERE a.id = 1`
Do SO users have a preference of one over the other? | There is no difference, but the readability of the second is much better when you have a big multi-join query with extra where clauses for filtering.
Separating the join clauses and the filter clauses is a Good Thing :) | The former is ANSI 89 syntax, the latter is ANSI 92.
For *that specific query* there is no difference. However, with the former you lose the ability to separate a filter from a join condition in complex queries, and the syntax to specify LEFT vs RIGHT vs INNER is often confusing, especially if you have to go back and forth between different db vendors. There are also certain kinds of join that cannot be written with the old syntax.
In fact, the former syntax has been **obsolete for more than 30 years** now, and *should not be used for new development*. | SQL JOIN: ON vs Equals | [
"",
"sql",
"join",
"equals",
""
] |
I need to determine the number of days in a month for a given date in SQL Server.
Is there a built-in function? If not, what should I use as the user-defined function? | You can use the following with the first day of the specified month:
```
datediff(day, @date, dateadd(month, 1, @date))
```
To make it work for every date:
```
datediff(day, dateadd(day, 1-day(@date), @date),
dateadd(month, 1, dateadd(day, 1-day(@date), @date)))
``` | In SQL Server 2012 you can use [EOMONTH (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/functions/eomonth-transact-sql) to get the last day of the month and then you can use [DAY (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/functions/day-transact-sql) to get the number of days in the month.
```
DECLARE @ADate DATETIME
SET @ADate = GETDATE()
SELECT DAY(EOMONTH(@ADate)) AS DaysInMonth
``` | How to determine the number of days in a month in SQL Server? | [
"",
"sql",
"sql-server",
"datetime",
"date",
"user-defined-functions",
""
] |
I've been having some trouble with vs2008 SP1 running in debug mode when I try to disable checked iterators. The following program reproduces the problem (a crash in the string destructor):
```
#define _HAS_ITERATOR_DEBUGGING 0
#include <sstream>
int do_stuff(std::string const& text)
{
std::string::const_iterator i(text.end());
return 0;
}
int main()
{
std::ostringstream os;
os << "some_text";
return do_stuff(os.str());
}
```
I'd found a [similar post](http://www.gamedev.net/community/forums/topic.asp?topic_id=374918) on gamdev.net that discussed having this problem in vs2005. The example program in that post compiles for me on 2008 SP1 as is - but when I modded it to use ostringstream, I was able to get the problem.
From poking around in the debugger, it looks like the library pops iterators off the stack, then later tries to use them in \_Orphan\_All, which is some kind of iterator checking cleanup code...
Can anyone else reproduce this problem or tell me what's going on?
Thanks! | I've just tried this in VS2008 on Windows XP and got a warning regarding a buffer overflow, both on a pre- and a post-SP1 VS2008.
Interestingly enough the problem seems to be centred around passing the string into do\_stuff either by reference or by value - if I use the original code, it complains about the buffer overflow but if I pass the string in by *value*, it runs fine. This is with the multithreaded debug DLL runtime. The error disappears when you like against the static MT Debug runtime.
In both cases, precompiled headers were turned off and the files that normally generate the precompiled headers have been removed from the project.
After reading [this article on MSDN](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=352680) I'm wondering if the problem stems from the fact that several C++ standard library classes are actually residing in the runtime library if you build with the debug DLL runtimes (just try to link a VS2008-generated binary against an earlier library and watch out for the unresolved externals to confirm this). | It looks like this a known bug in VS2005 that was fixed in VS2005 SP1:
* <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99655>
Looks like this was submitted by the guy who posted about it on gamedev.net.
I'm not sure how or why it would have crept back into VS2008 (do you have headers from VS2005 that might be getting inthe way or something?) | Problem when disabling checked iterators in vs2008 SP1 (_HAS_ITERATOR_DEBUGGING=0) | [
"",
"c++",
"visual-studio-2008",
"debugging",
"crash",
"iterator",
""
] |
This [link](http://linux.die.net/diveintopython/html/file_handling/os_module.html) is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6? | There isn't a built-in function to only list files, but it's easy enough to define in a couple of lines:
```
def listfiles(directory):
return [f for f in os.listdir(directory)
if os.path.isdir(os.path.join(directory, f))]
```
**EDIT**: fixed, thanks Stephan202 | If *a\_directory* is the directory you want to inspect, then:
`next(f1 for f in os.walk(a_directory))`
From the [os.walk()](http://docs.python.org/library/os.html#os.walk) reference:
> Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). | Is there a way to get all the directories but not files in a directory in Python? | [
"",
"python",
"directory",
""
] |
Should i use this form of switch statement:
```
switch(msg)
{
case WM_LBUTTONDOWN:
{
char szFileName[MAX_PATH];
HINSTANCE hInstance = GetModuleHandle(NULL);
GetModuleFileName(hInstance, (LPWCH)szFileName, MAX_PATH);
MessageBox(hwnd, (LPCWSTR)szFileName, L"This program is:", MB_OK | MB_ICONINFORMATION);
}
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
```
or make a function for the first case constant ? | There's nothing wrong with how you have it, but it's probably cleaner code to call a function so you can keep your functions a reasonable size. | Also, take a look at [message crackers](http://www.codeproject.com/KB/winsdk/msgcrackwizard.aspx) | Switch statement use | [
"",
"c++",
"c",
"windows",
"winapi",
""
] |
In WPF, is there an easy to allow overwriting of text in an textbox?
Thanks
Tony
EDIT: I guess i wasn't to clear. Sorry.
I have a TextBox that the user is allowed to type 6 characters. If the user types 6 characters and then for whatever reason put the cursor at the start or somewhere in the middle of the 6 characters and starts to type, I want what they are typing to overwrite characters. Basically act like overwrite mode in Word.
Thanks again. | Looking at it in Reflector, this seems to be controlled from the boolean TextBoxBase.TextEditor.\_OvertypeMode internal property. You can get at it through reflection:
```
// fetch TextEditor from myTextBox
PropertyInfo textEditorProperty = typeof(TextBox).GetProperty("TextEditor", BindingFlags.NonPublic | BindingFlags.Instance);
object textEditor = textEditorProperty.GetValue(myTextBox, null);
// set _OvertypeMode on the TextEditor
PropertyInfo overtypeModeProperty = textEditor.GetType().GetProperty("_OvertypeMode", BindingFlags.NonPublic | BindingFlags.Instance);
overtypeModeProperty.SetValue(textEditor, true, null);
``` | I would avoid reflection.
The cleanest solution is the following:
> EditingCommands.ToggleInsert.Execute(null, myTextBox); | WPF TextBox Overwrite | [
"",
"c#",
"wpf",
""
] |
I'd like to dynamically load and use a .Net assembly created in C# from a Delphi Win32 application. My classes and interfaces are marked as ComVisible, but I would like to avoid registering the assembly.
Is this possible?
P.S. I found here [link text](https://stackoverflow.com/questions/258875/hosting-the-net-runtime-in-a-delphi-program) another good discussion on the topic, but it is more around hosting the CLR. Which begs a question - why would you host CLR versus using ClrCreateManagedInstance? | Strangely enough, I couldn't find an answer on StackOverflow, and there is not much on the Net, especially for Delphi. I found the solution from examples posted [here](http://interop.managed-vcl.com/).
Here's what I got at the end:
```
function ClrCreateManagedInstance(pTypeName: PWideChar; const riid: TIID;
out ppObject): HRESULT; stdcall; external 'mscoree.dll';
procedure TMyDotNetInterop.InitDotNetAssemblyLibrary;
var
MyIntf: IMyIntf;
hr: HRESULT;
NetClassName: WideString;
begin
//Partial assembly name works but full assembly name is preffered.
NetClassName := 'MyCompany.MyDLLName.MyClassThatImplementsIMyIntf,
MyCompany.MyDLLName';
hr := ClrCreateManagedInstance(PWideChar(NetClassName), IMyIntf, MyIntf);
//Check for error. Possible exception is EOleException with ErrorCode
//FUSION_E_INVALID_NAME = $80131047 2148732999 : The given assembly name
//or codebase was invalid.
//COR_E_TYPELOAD = $80131522 - "Could not find or load a specific type
//(class, enum, etc)"
//E_NOINTERFACE = $80004002 - "Interface not supported".
OleCheck(hr);
end;
```
BTW, depending on the situation, you might want to load mscoree.dll dynamically, because it might be not present on the system (XP with no .Net Framework)
EDIT: Unfortunately, this was deprecated and stopped working with .Net4 as I just found out. This leaves only two options - [CLR hosting and unmanaged export](https://stackoverflow.com/questions/2048540/hosting-clr-in-delphi-with-without-jcl-example). Also, [debugging of .Net4 COM code is broken](https://stackoverflow.com/questions/6102882/debugging-net4-com-registered-assembly-from-win32-caller-in-visual-studio-2010). | Maybe using RegFreeCOM and a COm-Callable Wrapper.
<http://msdn.microsoft.com/en-us/magazine/cc188708.aspx> | How to use .Net assembly from Win32 without registration? | [
"",
"c#",
"delphi",
"interop",
""
] |
If `front()` returns a reference and the container is empty what do I get, an undefined reference? Does it mean I need to check `empty()` before each `front()`? | You get undefined behaviour - you need to check that the container contains something using empty() (which checks if the container is empty) before calling front(). | You get undefined behaviour.
To get range checking use at(0). If this fails you get a `out_of_range` exception. | What do I get from front() of empty std container? | [
"",
"c++",
"stl",
""
] |
I spent a lot of time programming in Java recently, and one thing I miss from scripting languages was the ability to test them in a console.
To quickly test a java program, I have to edit a file, then turn it to bytecode and execute it. Even using an IDE, it loses its fun after the 372 th time.
I would like to know if there is a product out there that features anything like an interactive console (I bet you need a JIT compiler) and some autocompletion (with relexivity, I suppose it's possible).
Maybe that's something very common that I just don't know about or something completely impossible, but its worst asking :-) | Yes; [jshell](https://docs.oracle.com/javase/9/jshell/introduction-jshell.htm#JSHEL-GUID-630F27C8-1195-4989-9F6B-2C51D46F52C8), and before that some close approximations are [Groovy](http://groovy-lang.org/), [Clojure](http://clojure.org/), [Scala](http://www.scala-lang.org/), and the [Bean Shell](http://www.beanshell.org/). | Funnily enough, you get an interactive console with [Jython](http://www.jython.org/Project/) ! You don't get *much* more Python-like. | Is there any Python-like interactive console for Java? | [
"",
"java",
"console",
""
] |
I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.
But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.
My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction *lower* than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.
I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <http://wiki.python.org/moin/GuiProgramming> ) is honestly somewhat depressing for someone used to Delphi or .NET.
Finally, I've got a couple of questions.
First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.
Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?
It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and *open source* gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution. | seems your complains are about wxPython, not about Python itself. try pyQt (or is it qtPython?)
but, both wxPython and pyQt are just Python bindings to a C / C++ (respectively) library, it's just as (conceptually) low level as the originals.
but, Qt is far superior to wx | PyQt is a binding to Qt SDK from Nokia, and PyQt itself is delivered by a company called [RiverBank](http://www.riverbankcomputing.co.uk/news).
If licence is not important for you you can use PyQt under GPL or you 'll pay some money for commercial licence.
PyQt is binding Qt 4.4 right now.
Qt is not just GUI, it's a complete C/C++ SDK that help with networking, xml, media, db and other stuff, and PyQt transfer all this to python.
With PyQt you'll use Qt Designer and you 'll transfer the .ui file to .py file by a simple command line.
You 'll find many resources on the web about PyQt and good support from different communities, and even published books on PyQt.
Many suggestions consider that RiverBank has no choice but to release the next version which 'll depend on Qt 4.5 under LGPL, we are waiting :).
Another solution is Jython with Java Swing, very easy and elegant to write (specially under JDK 6), but not enough resources on internet. | questions re: current state of GUI programming with Python | [
"",
"python",
"user-interface",
""
] |
I have started learning Qt recently.
I did not get quite clear how can I paint using `QPainter` class. Let`s say I want just to place a few points in the window:
```
class PointDrawer: public QWidget {
Q_OBJECT
private:
QPainter p;
public:
PointDrawer(QWidget* obj=0): QWidget(obj), p(this) {}
virtual void paintEvent(QPaintEvent*) {
p.setPen(QPen(Qt::black, 3));
int n = 8;
while(...) {
qreal fAngle = 2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal y = 50 + sin(fAngle) * 40;
p.drawPoint(QPointF(x, y));
i++;
}
}
}
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
PointDrawer drawer;
drawer.resize(200, 200);
drawer.show();
return app.exec();
}
```
And after that, I got nothing!
Can you please tell me where I am wrong? | I think the problem is your `QPainter` initialization.
You could just create the `QPainter` like in hydroes' answer, it would look like this then:
```
class PointDrawer: public QWidget {
Q_OBJECT
public:
PointDrawer(QWidget* obj=0): QWidget(obj) {}
virtual void paintEvent(QPaintEvent*) {
QPainter p(this);
p.setPen(QPen(Qt::black, 3));
int n = 8;
while(...) {
qreal fAngle = 2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal y = 50 + sin(fAngle) * 40;
p.drawPoint(QPointF(x, y));
i++;
}
}
}
```
It could also use something like this, but I don't really recommend it (I just prefer the other solution):
```
class PointDrawer: public QWidget {
Q_OBJECT
private:
QPainter p;
public:
PointDrawer(QWidget* obj=0): QWidget(obj) {}
virtual void paintEvent(QPaintEvent*) {
p.begin(this);
p.setPen(QPen(Qt::black, 3));
int n = 8;
while(...) {
qreal fAngle = 2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal y = 50 + sin(fAngle) * 40;
p.drawPoint(QPointF(x, y));
i++;
}
p.end();
}
}
```
The `QPainter::begin(this)` and `QPainter::end()` calls are essential in the second example. In the first example, you can think of `QPainter::begin(this)` being called in the constructor and `QPainter::end()` in the destructor
For the reason, I'm guessing:
As `QPaintDevice`s are usually double buffered in QT4, `QPainter::end()` might be where the image is transferred to the graphic memory. | ```
void SimpleExampleWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setPen(Qt::blue);
painter.setFont(QFont("Arial", 30));
painter.drawText(rect(), Qt::AlignCenter, "Qt");
}
```
<http://doc.qt.digia.com/4.4/qpainter.html> | How do I paint with QPainter? | [
"",
"c++",
"qt",
""
] |
We started using C# (.NET 3.0) and I wonder how you guys are using extension methods? When do you use them?
Also, I would appreciate if you also list all dark prerequisites for using them. | Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:
* Extension methods cannot be used to override existing methods
* An extension method with the same name and signature as an instance method will not be called
* The concept of extension methods cannot be applied to fields, properties or events
* Use extension methods sparingly....overuse can be a bad thing! | Times to use extension methods:
* when you don't control the types being extended
* where you don't want to force the implementor to provide code that can be done using the existing methods
For an example of the second point; you might have an extension method on `IList<T>` (for example, `Sort`) that can be written entirely using the existing `IList<T>` members... so why force anybody else to write anything? This is the foundation block of LINQ, and allowed Microsoft to provide *much* more functionality without breaking anything.
Times to **not** use extension methods:
* when polymorphism is critical; you cannot guarantee that your code will be the version that gets executed with an extension method, as methods directly on the type take precedence
* when you need access to private/protected members | When do you use extension methods, ext. methods vs. inheritance? | [
"",
"c#",
".net",
""
] |
I am trying to get the Y scroll index for a web page in the WebBrowser control but I can't access the values for the built in Scroll bar.
Any Ideas? | For IE in standards mode (with a doctype, as you say) `scrollTop` is a property of the `<html>` element, not the `<body>`:
```
HtmlDocument htmlDoc = this.webBrowser1.Document;
int scrollTop = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop;
```
(A nicer way to get to the `<html>` element would be good, if anyone knows of one.) | are you trying to target an HTML element to bring it into view? If that is what you are after you can do this...
htmlDoc.GetElementById("tag\_id\_string\_goes\_here").ScrollIntoView(true);
true aligns it with the top and false with the bottom of the element. You can also use ScrollRectangle to get the dimensions of the scrollable region. | getting the scroll value from a WebBrowser Control C# | [
"",
"c#",
"webbrowser-control",
"scrollbar",
""
] |
I experiencing a strange behavior of C#. Its some thing like this..
```
var date = DateTime.Now.ToString("MM/dd/yyyy");
```
I expecting out to be
```
04/24/2009
```
but in actuall its returning
```
04-24-2009
```
and my OS culture is en-GB, I'm using .Net 3.5 and WPF
any solutions please... ??? | According to the MSDN docs for custom date and time format strings, `/` is a placeholder:
> Represents the date separator defined
> in the current
> DateTimeFormatInfo.DateSeparator
> property. This separator is used to
> differentiate years, months, and days.
If you want a definite slash, use "MM'/'dd'/'yyyy":
```
DateTime.Now.ToString("MM'/'dd'/'yyyy")
``` | It uses the separator set up in the regional settings, since "/" is the substitute character for the separator.
You can create your own DateTimeFormat instance with different separators. | DateTime Format in C# | [
"",
"c#",
"wpf",
".net-3.5",
""
] |
How can I export `GridView.DataSource` to datatable or dataset? | You should convert first `DataSource` in `BindingSource`, look example
```
BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource
DataTable tCxC = (DataTable) bs.DataSource;
```
With the data of `tCxC` you can do anything. | Assuming your DataSource is of type DataTable, you can just do this:
```
myGridView.DataSource as DataTable
``` | How can I export a GridView.DataSource to a datatable or dataset? | [
"",
"c#",
"asp.net",
"gridview",
""
] |
Would really like to be able to decorate my class with an attribute of some sort that would enforce the use of a using statement so that the class will always be safely disposed and avoid memory leaks. Anyone know of such a technique? | Well, there's one way you could sort of do it - only allow access to your object via a static method which takes a delegate. As a very much simplified example (as obviously there are many different ways of opening a file - read/write etc):
```
public static void WorkWithFile(string filename, Action<FileStream> action)
{
using (FileStream stream = File.OpenRead(filename))
{
action(stream);
}
}
```
If the only things capable of creating an instance of your disposable object are methods within your own class, you can make sure they get used appropriately. Admittedly there's nothing to stop the delegate from taking a copy of the reference and trying to use it later, but that's not quite the same problem.
This technique severely limits what you can do with your object, of course - but in some cases it may be useful. | You could use [FxCop](http://msdn.microsoft.com/en-us/library/bb429476.aspx) to enforce this rule. See the Wikipedia for a [quick overview](http://en.wikipedia.org/wiki/FxCop). | Is it possible to enforce the use of a using statement in C# | [
"",
"c#",
"using",
""
] |
How do I get python to work with aptana studio?
~~I've downloaded a bunch of stuff, but none of them seem to give me a straight text editor where I can interpret code into an executable type thing. I know there's interactive mode in IDLE, but I want to actually use an editor. So I downloaded the pydev extensions for Aptana studio, but it wants me to configure a python interpreter (so I guess it actually doesn't have one). Where can I find a straight python interpreter that will work with this? or another IDE?~~ | It's easier than you think. First, there's a version of python on your machine by default. It's kind of out of date, though.
[MacPorts](http://macports.org) is a nice method to get lots of good stuff.
[ActiveState](http://ActiveState.com) has a [Python Mac package](http://www.activestate.com/activepython/) downloadable for free.
[Python.org](http://Python.org) will lead you to some other options as well. | To add the current Python version on Mac:
1. Add new interpreter via Aptana Studio 3/Preferences/PyDev/Interpreter-Python.
2. Give it name (check version using the Terminal and then `python` or `/usr/bin/python`.
3. Then add the path (2.7 in my case): `/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python`
If you install your own (2.6 in my case) use the following path instead:
`/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python`
Don't forget to hit the "Apply" button... | How to install Python on mac os x and windows with Aptana Studio? | [
"",
"python",
"aptana",
""
] |
I would like to check if this is a correct implementation of QuickSort, It seems to be doing the job, but Am I missing out anything?
```
public class QuickSort implements Sorter {
public void sort(Comparable[] items) {
QuickSort(items, 0, items.length - 1);
}
static void QuickSort(Comparable[] items, int a, int b) {
int lo = a;
int hi = b;
if (lo >= hi) {
return;
}
Comparable mid = items[(lo + hi) / 2];
Comparable T;
while (lo < hi) {
while (items[lo].compareTo(mid)<0) {
lo++;
}
while (mid.compareTo(items[hi])<0) {
hi--;
}
if (lo < hi) {
T = items[lo];
items[lo] = items[hi];
items[hi] = T;
}
}
QuickSort(items, a, lo);
QuickSort(items, lo == a ? lo + 1 : lo, b);
}
```
}
***fixed:***
```
private static void quickSort(Comparable[] items, int a, int b) {
int i = a;
int j = b;
Comparable x = items[(a+ b) / 2];
Comparable h;
do {
while (items[i].compareTo(x) < 0) {
i++;
}
while (items[j].compareTo(x) > 0) {
j--;
}
if (i <= j) {
h = items[i];
items[i] = items[j];
items[j] = h;
i++;
j--;
}
} while (i <= j);
if (a < j) {
quickSort(items, a, j);
}
if (i < b) {
quickSort(items, i, b);
}
}
``` | ```
public static void quicksort( Comparable [ ] a ) {
quicksort( a, 0, a.length - 1 );
}
private static final int CUTOFF = 10;
private static void quicksort( Comparable [ ] a, int low, int high ) {
if( low + CUTOFF > high )
insertionSort( a, low, high );
else {
int middle = ( low + high ) / 2;
if( a[ middle ].compareTo( a[ low ] ) < 0 )
swapReferences( a, low, middle );
if( a[ high ].compareTo( a[ low ] ) < 0 )
swapReferences( a, low, high );
if( a[ high ].compareTo( a[ middle ] ) < 0 )
swapReferences( a, middle, high );
swapReferences( a, middle, high - 1 );
Comparable pivot = a[ high - 1 ];
int i, j;
for( i = low, j = high - 1; ; ) {
while( a[ ++i ].compareTo( pivot ) < 0 )
;
while( pivot.compareTo( a[ --j ] ) < 0 )
;
if( i >= j )
break;
swapReferences( a, i, j );
}
swapReferences( a, i, high - 1
quicksort( a, low, i - 1 ); // Sort small elements
quicksort( a, i + 1, high ); // Sort large elements
}
}
public static final void swapReferences( Object [ ] a, int index1, int index2 )
{
Object tmp = a[ index1 ];
a[ index1 ] = a[ index2 ];
a[ index2 ] = tmp;
}
private static void insertionSort( Comparable [ ] a, int low, int high ) {
for( int p = low + 1; p <= high; p++ ) {
Comparable tmp = a[ p ];
int j;
for( j = p; j > low && tmp.compareTo( a[ j - 1 ] ) < 0; j-- )
a[ j ] = a[ j - 1 ];
a[ j ] = tmp;
}
}
```
From <http://java-blackberry.blogspot.com/2007/12/quick-sort-implementation-with-median.html> | 1 small point- there's a potential int overflow here:
(lo + hi) / 2 | Is this a correct implementation of quicksort? | [
"",
"java",
"quicksort",
""
] |
<http://pypi.python.org/pypi/simplejson>
I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..
I am on a Windows System | I would recommend [EasyInstall](http://pypi.python.org/pypi/setuptools#windows), a package management application for Python.
Once you've installed EasyInstall, you should be able to go to a command window and type:
```
easy_install simplejson
```
This may require putting easy\_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like `C:\Python25\Scripts`). | Really simple way is:
```
pip install simplejson
``` | How to install SimpleJson Package for Python | [
"",
"python",
"simplejson",
""
] |
I am creating a web app that uses Rails built-in helper functions to add ajax functionality to the site. I do not want the user to be able to use the app without JS as it will not function properly.
I need to be able to prevent this. How can I go about stopping the user from loading any of my pages without JS?
I have tried to use a tag in my layout. This detects the absence of JS but still renders the views. Putting the script tag around the yield prevents any view from being rendered.
Any ideas on how to do this? | You can have a `noscript` block in the `head` element with a meta refresh tag in it. Example:
```
<head>
<!-- title, scripts, css etc go here -->
<noscript>
<meta http-equiv="refresh" content="2;url=http://yoursite.com/nojswarning.html">
</noscript>
</head>
```
you can read more about meta refresh [here](http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm)
Hope this helps
**EDIT:** To clarify, the `noscript` tag runs only if JavaScript is turned off for the user. So in this case if the JS is turned off the user will be redirected to `http://yoursite.com/nojswarning.html`. of course you can change this to be any page on any site you want. | The simple answer is to have the entire app load via JS. That way, the app would never show for someone who has JS enabled.
An alternative would be to start your page with an iframe, which loads to a JS-checking page. All the page does is redirect the user to the app's true URL via JS. Thus, if the user doesn't have JS, they won't get redirected (and you can inform them that they need JS with <noscript> tags). (I say to use an iframe so you don't give non-JS users an easy URL to get to the app with.) | Ruby on Rails, Javascript detection | [
"",
"javascript",
"ruby-on-rails",
""
] |
I think it is MergeSort, which is O(n log n).
However, the following output disagrees:
```
-1,0000000099000391,0000000099000427
1,0000000099000427,0000000099000346
5,0000000099000391,0000000099000346
1,0000000099000427,0000000099000345
5,0000000099000391,0000000099000345
1,0000000099000346,0000000099000345
```
I am sorting a nodelist of 4 nodes by sequence number, and the sort is doing 6 comparisons.
I am puzzled because 6 > (4 log(4)). Can someone explain this to me?
[P.S. It is mergesort, but I still don't understand my results.](http://www.uni-ulm.de/admin/doku/jdk1.5/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator))
Thanks for the answers everyone. Thank you Tom for correcting my math. | O(n log n) doesn't mean that the number of comparisons will be equal to or less than n log n, just that the time taken will **scale** proportionally to n log n. Try doing tests with 8 nodes, or 16 nodes, or 32 nodes, and checking out the timing. | You sorted four nodes, so you didn't get merge sort; sort switched to insertion sort.
Per the Wikipedia article on [merge sort](https://en.wikipedia.org/wiki/Merge_sort#Comparison_with_other_sort_algorithms) (emphasis added):
> In [Java](https://en.wikipedia.org/wiki/Java_platform), the [Arrays.sort()](https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html#sort-java.lang.Object:A-) methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency **switch to [insertion sort](https://en.wikipedia.org/wiki/Insertion_sort) when fewer than seven array elements are being sorted**.
`Arrays.sort` is used indirectly by the collections classes.
Starting with Java 7, the Oracle implementation of Java switched to use the [timsort](http://svn.python.org/projects/python/trunk/Objects/listsort.txt) algorithm used by Python: [JDK-6804124](https://bugs.java.com/bugdatabase/view_bug?bug_id=6804124).
(The timsort monograph, linked above, is well worth reading.) | What sort does Java Collections.sort(nodes) use? | [
"",
"java",
"collections",
"sorting",
"time-complexity",
"mergesort",
""
] |
My question is how does one abstract a database connection from the model layer of an application? The primary concern is to be able to easily change from different types of databases. Maybe you start with a flat file, comma-delimited database. Then you want to move to a SQL database. Then later you decide an LDAP implementation would be better. How can a person easily plan for something like this?
For a simple example, let's say you have a user with a first name, last name, and email. A very simple PHP class representing it might look like this (please ignore the problems with public instance variables):
```
<?php
class User {
public $first;
public $last;
public $email;
}
?>
```
I have frequently seen where people have a DAO class which has the SQL embedded in it as such:
```
<?php
class UserDAO {
public $id;
public $fist;
public $last;
public $email;
public function create( &$db ) {
$sql = "INSERT INTO user VALUES( '$first', '$last', '$email' )";
$db->query( $sql );
}
}
?>
```
My problem with strategies like this is when you want to change your database, you have to change every DAO class' create, update, load, delete functions to deal with your new type of database. Even if you have a program to auto-generate them for you (which I am not particularly a fan of), you would have to edit this program to make it work now.
What are your suggestions for how to handle this?
My current idea is to create a super class for DAO objects with its own create, delete, update, load functions. However, these functions would take arrays of the attributes of the DAO and generate the query itself. In this manner, the only SQL is in the SuperDAO class rather than being scattered about several classes. Then if you wanted to change your database layer, you would only have to change how the SuperDAO class generates the queries. Advantages? Disadvantages? Foreseeable problems? The good, the bad, and the ugly? | Using an [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping) is usually the preferred way of abstracting the database. An incomplete list of PHP implementations is available on [Wikipedia](http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software#PHP). | You can use various frameworks such as PDO, PEAR::MDB2 or Zend\_Db, but to be honest in 12 years of PHP development, I've never had to transition from one type of data storage infrastructure to another.
Its exceedingly rare to even go from something quite similar like Sqlite, to MySQL. If you did do more than that, you'd have far larger problems anyway. | What's the best way to abstract the database from a PHP application? | [
"",
"php",
"database",
"design-patterns",
"orm",
"abstraction",
""
] |
Is there a way to generically retrieve process stats using Perl or Python? We could keep it Linux specific.
There are a few problems: I won't know the PID ahead of time, but I *can* run the process in question from the script itself. For example, I'd have no problem doing:
`./myscript.pl some/process/I/want/to/get/stats/for`
Basically, I'd like to, at the very least, get the memory consumption of the process, but the more information I can get the better (like run time of the process, average CPU usage of the process, etc.)
Thanks. | Have a look at the [Proc::ProcessTable](http://search.cpan.org/~durist/Proc-ProcessTable-0.45/ProcessTable.pm) module which returns quite a bit of information on the processes in the system. Call the "fields" method to get a list of details that you can extract from each process.
I recently discovered the above module which has just about replaced the Process module that I had written when writing a Perl kill program for Linux. You can have a look at my script [here](http://pastebin.com/f16edcba3).
It can be easily extended to extract further information from the ps command. For eg. the '**getbycmd**' method returns a list of pid's whose command line invocation matches the passed argument. You can then retrieve a specific process' details by calling '**getdetail**' by passing that PID to it like so,
```
my $psTable = Process->new();
# Get list of process owned by 'root'
for my $pid ( $psTable->getbyuser("root") ) {
$psDetail = $psList->getdetail( $pid );
# Do something with the psDetail..
}
``` | If you are `fork()`ing the child, you will know it's PID.
From within the parent you can then parse the files in `/proc/<PID/` to check the memory and CPU usage, albeit only for as long as the child process is running. | Is there a way to retrieve process stats using Perl or Python? | [
"",
"python",
"linux",
"perl",
"process",
""
] |
I am using sqlite in my C# project. MoMA complains about the DLLs and i am unsure what to do on the mac/linux side. What are things i generally need to do when porting external DLLs? | You could use the SQLite assembly that's shipped with Mono - it's derived from the one you are probably using now.
See <http://mono-project.com/SQLite> for more details | You might want to look at the C# reimplementation of [SQLite on googlecode](http://code.google.com/p/csharp-sqlite/). This started life as a [line-by-line port of the C++ SQLite](http://tirania.org/blog/archive/2009/Aug-06.html) but after lots of improvements now outperforms the original for many types of operation. | sqlite, mono, C# cross platform | [
"",
"c#",
"sqlite",
"mono",
"moma",
""
] |
i'm trying to control the VLC Media Player from C#. I tried getting a handle on the window with the FindWindow() command from .Net but as i found out the name of the window changes every time a file is played. The biggest problem i have is sending wm\_commands to vlc..This approach worked with Winamp and Windows Media Player but with VLC it appears that it won't work.
I read that VLC can be controlled from a browser but i don't whant that...i've seen in it's settings that it has some hot keys that can be called..but they can be changed and if i call them from my code somehow...and the user changes them..bummer...
i'm a little bit stuck..any help would be fantastic...
Sorin | I have some code that is able to [control it using sockets](http://gist.github.com/101357) on the [RC interface](http://getluky.net/2006/04/19/vlcs-awesome-rc-interface/). This worked to a degree but has a lot of quirks. go to full screen seems to do nothing for a few seconds after play is invoked. Overall it sort of works.
The other options are:
Write a DirectDraw filter (very hard) but once this is done VLC can be used instead of or in conjunction with FFMPEG. Existing code that drives media player could use vlc.
Write an interop wrapper for *libvlc*, recently the VLC team split out `libvlccore` from `libvlc` so to the best of my knowledge all the [interop](http://forum.videolan.org/viewtopic.php?f=32&t=52021&sid=5b966dc2463cb3b0dbeb5efdbbdb72f4&start=90) is out of date. Once you write a wrapper you could embed vlc in a windows app. (if you need to support x64 you need to compile these libs under x64.
Look through the VLC code and find out if there is a way to send these windows messages.
**EDIT** [This appears](http://forum.videolan.org/viewtopic.php?f=32&t=58438) to have come out this week. | As Eoin mentioned, `libvlc` can be used to interact with VLC. As a C# user, you may want to try the .NET bindings offered by the [`libvlc-sharp`](http://code.google.com/p/libvlc-sharp/) project.
**Edit:** Seems like this project has not been maintained for years. I will leave the link anyway, in case you wish to take a look at it and maybe put some of its source to use. | VLC remotely control from C# | [
"",
"c#",
"controls",
"vlc",
""
] |
Is there a way to list all fired events for specific WinForms controls without explicitly creating a handler for each possible event? For example, I might want to see the sequence of events that fire between a DataGridView and the BindingSource during various databinding actions. | You could use reflection, but it's going to be slightly tricky because of the various event handler signatures involved. Basically you'd have to get the `EventInfo` for each event in the type, and use the [`EventHandlerType`](http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.eventhandlertype.aspx) property to work out what delegate type to create before calling [`AddEventHandler`](http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx). `Delegate.CreateDelegate` works for everything that follows the normal event handler pattern though...
Here's a sample app. Note that it's not doing any checking - if you give it something with a "non-standard" event it will throw an exception. You could fairly easily use reflection to print out the event args too.
```
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Form form = new Form { Size = new Size(400, 200) };
Button button = new Button { Text = "Click me" };
form.Controls.Add(button);
EventSubscriber.SubscribeAll(button);
Application.Run(form);
}
}
class EventSubscriber
{
private static readonly MethodInfo HandleMethod =
typeof(EventSubscriber)
.GetMethod("HandleEvent",
BindingFlags.Instance |
BindingFlags.NonPublic);
private readonly EventInfo evt;
private EventSubscriber(EventInfo evt)
{
this.evt = evt;
}
private void HandleEvent(object sender, EventArgs args)
{
Console.WriteLine("Event {0} fired", evt.Name);
}
private void Subscribe(object target)
{
Delegate handler = Delegate.CreateDelegate(
evt.EventHandlerType, this, HandleMethod);
evt.AddEventHandler(target, handler);
}
public static void SubscribeAll(object target)
{
foreach (EventInfo evt in target.GetType().GetEvents())
{
EventSubscriber subscriber = new EventSubscriber(evt);
subscriber.Subscribe(target);
}
}
}
}
``` | I think you could use Reflection to do this. | Watch control to determine events being fired? | [
"",
"c#",
"winforms",
"events",
""
] |
I need to write a webpage which starts with a blank map of the US and colors the states according to data it receives from various Ajax requests. The map needs to change over time without the page reloading, and the user can click on various controls to instantly change how the map is colored. This all needs to be done locally, so I can't make use of Google maps or any similar internet service.
I'd hope to do this in the browser with Javascript. Is there a good library for doing this? Or any general suggestions for how to best implement this? | I would take a plugin like this just change it to do "highlighting" based on your dynamic data:
* <http://plugins.jquery.com/project/maphilight>
* Demo of plugin: <http://davidlynch.org/js/maphilight/docs/demo_usa.html>
Currently it highlights on mouseover, but highlighting using data given should be very straightforward.
The fact it comes with a map of the US and highlighting ready to go set is just gravy. | Sounds like a job for [Raphaël](http://raphaeljs.com/index.html) | Dynamically coloring a US map with Javascript | [
"",
"javascript",
"maps",
""
] |
I have been working on a small web app using the Stripes framework. Now that the Google App Engine has added support for Java, I am wondering if I can convert it to run in the Google App Engine to save costs on hosting. | Yes, it supports servlets, so it should support [Stripes](http://www.stripesframework.org/display/stripes/Home) just fine.
According to the App Engine [documentation](http://code.google.com/appengine/docs/java/overview.html),
> App Engine uses the Java Servlet
> standard for web applications. You
> provide your app's servlet classes,
> JavaServer Pages (JSPs), static files
> and data files, along with the
> deployment descriptor (the web.xml
> file) and other configuration files,
> in a standard WAR directory structure.
> App Engine serves requests by invoking
> servlets according to the deployment
> descriptor. | There seems to be [a little snag (and workaround)](http://www.nabble.com/Stripes-and-Google-App-Engine-td22948917.html) because of the missing access to a local temporary directory. You need to provide your own file upload facility (or disable the feature). | Can you use Java EE frameworks with the Google App Engine? | [
"",
"java",
"google-app-engine",
"stripes",
""
] |
I have a web-based application and a client, both written in Java. For what it's worth, the client and server are both on Windows. The client issues HTTP GETs via [Apache HttpClient](http://hc.apache.org/httpclient-3.x/). The server blocks for up to a minute and if no messages have arrived for the client within that minute, the server returns HTTP 204 No Content. Otherwise, as soon as a message is ready for the client, it is returned with the body of an HTTP 200 OK.
**Here is what has me puzzled:** Intermittently for a specific subset of clients -- always clients with demonstrably flaky network connections -- the client issues a GET, the server receives and processes the GET, but the client sits forever. Enabling debugging logs for the client, I see that HttpClient is still waiting for the very first line of the response.
There is no Exception thrown on the server, at least nothing logged anywhere, not by Tomcat, not by my webapp. According to debugging logs, there is every sign that the server successfully responded to the client. However, the client shows no sign of having received anything. The client hangs indefinitely in [HttpClient.executeMethod](http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpClient.html#executeMethod(org.apache.commons.httpclient.HttpMethod)). This becomes obvious after the session times out and the client takes action that causes another Thread to issue an HTTP POST. Of course, the POST fails because the session has expired. In some cases, *hours* have elapsed between the session expiring and the client issuing a POST and discovering this fact. For this entire time, `executeMethod` is still waiting for the HTTP response line.
When I use WireShark to see what is really going on at the wire level, this failure does not occur. That is, this failure will occur within a few hours for specific clients, but when WireShark is running at both ends, these same clients will run overnight, 14 hours, without a failure.
Has anyone else encountered something like this? What in the world can cause it? I thought that TCP/IP guaranteed packet delivery even across short term network glitches. If I set an SO\_TIMEOUT and immediately retry the request upon timeout, the retry always succeeds. (Of course, I first [abort](http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpMethod.html#abort()) the timed-out request and release the connection to ensure that a new socket will be used.)
Thoughts? Ideas? Is there some TCP/IP setting available to Java or a registry setting in Windows that will enable more aggressive TCP/IP retries on lost packets? | Are you absolutely sure that the server has successfully sent the response to the clients that seem to fail? By this I mean the server has sent the response and the client has ack'ed that response back to the server. You should see this using wireshark on the server side. If you are sure this has occured on the server side and the client still does not see anything, you need to look further up the chain from the server. Are there any proxy/reverse proxy servers or NAT involved?
The TCP transport is considered to be a reliable protocol, but it does not guarantee delivery. The TCP/IP stack of your OS will try pretty hard to get packets to the other end using TCP retransmissions. You should see these in wireshark on the server side if this is happening. If you see excessive TCP retransmissions, it is usually a network infrastructure issue - i.e. bad or misconfigured hardware/interfaces. TCP retransmissions works great for short network interruptions, but performs poorly on a network with a longer interruption. This is because the TCP/IP stack will only send retransmissions after a timer expires. This timer typically doubles after each unsuccessful retransmission. This is by design to avoid flooding an already problematic network with retransmissions. As you might imagine, this usually causes applications all sorts of timeout issues.
Depending on your network topology, you may also need to place probes/wireshark/tcpdump at other intermediate locations in the network. This will probably take some time to find out where the packets have gone.
If I were you I would keep monitoring with wireshark on all ends until the problem re-occurs. It mostly likely will. But, it sounds like what you will ultimately find is what you already mentioned - flaky hardware. If fixing the flaky hardware is out of the question, you may need to just build in extra application level timeouts and retries to attempt to deal with the issue in software. It sounds like you started going down this path. | If you are using long running GETs, you should timeout on the client side at twice the server timeout, as you have discovered.
On a TCP where the client send a message and expects a response, if the server were to crash, and restart (lets say for the point of examples) then the client would still be waiting on the socket to get a response from the Server yet the server is no longer listening on that socket.
The client will only discover the socket is closed on the server end once it sends more data on that socket, and the server rejects this new data, and closes the socket.
This is why you should have client side time-outs on requests.
But as your server is not crashing, if the server was multi threaded, and thread socket for that client closed, but at that time ( duration minutes) the client has an connectivity outage, then the end socket hand-shaking my be lost, and as you are not sending more data to the server from the client, your client is once again left hanging. This would tie in to your flaking connection observation. | What can cause TCP/IP to drop packets without dropping the connection? | [
"",
"java",
"http",
"tomcat",
"tcp",
""
] |
I came across this kind of code once in a while - I suspect the creator is/was afraid that table delete would iterate over the table and "cost performance" (which imho will not be done either way)... is there any real benefit one might get/consider/imagine from not using the the table delete here?
```
myClass** table = new myClass* [size];
... //some code that does not reallocate or change the value of the table pointer ;)
delete table; // no [] intentionally
``` | There's really no reason to write like that and a serious reason to never do so.
It's true that for types with trivial destructors (like raw pointers in your case) there's no need to know the actual number of elements in the array and so the compiler might decide to map *new[]* and *delete[]* onto *new* and *delete* to reduce the overhead. If it decides this way you can't stop it without extra steps taken, so this compiler optimization will take place without your notice and will be free.
At the same time someone using your code might wish to overload the global operators *new* and *delete* (and *new[]* and *delete[]* as well). If that happens you run into big trouble because this is when you may really need the difference between the *delete* and *delete[]*.
Add to this that this compiler-dependent optimization is unportable.
So this is the case when you get no benefits displacing *delete[]* with *delete* but risk big time relying into undefined behaviour. | If you do this, you will get what the C++ Standard calls undefined behaviour - anything could happen. | Why would you write something like this? (intentionally not using delete [] on an array) | [
"",
"c++",
"coding-style",
""
] |
I'm using a 2D matrix in one of my projects. It's something like it is suggested at [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.10).
The neat thing is that you can use it like this:
```
int main()
{
Matrix m(10,10);
m(5,8) = 106.15;
std::cout << m(5,8);
...
}
```
Now, I have a graph composed of vertices and each vertex has a public (just for simplicity of the example) pointer to 2D matrix like above. Now I do have a pretty ugly syntax to access it.
```
(*sampleVertex.some2DTable)(0,0) = 0; //bad
sampleVertex.some2DTable->operator()(0,0) = 0; //even worse...
```
Probably I'm missing some syntactic sugar here due to my inexperience with operator overloading. Is there a better solution? | 1. Consider using references instead of pointers (provided, it can't be null and you can initialize in the constructor).
2. Consider making a getter or an instance of a matrix wrapper class for a vertex that returns a reference to 2D matrix (provided, it can't be null).
```
sampleVertex.some2DTable()(0,0) = 0;
sampleVertex.some2DTableWrap(0,0) = 0;
```
However, to me it sounds like a non-issue to justify going through all the trouble. | If you have a pointer to a Matrix, e.g. as a function parameter that you can't make a reference (legacy code, e.g.), you can still make a reference to it (pseudo code):
```
struct Matrix {
void operator () (int u, int v) {
}
};
int main () {
Matrix *m;
Matrix &r = *m;
r (1,1);
}
``` | 2D matrix and overloading operator() / ugly syntax | [
"",
"c++",
"matrix",
"operator-overloading",
"syntactic-sugar",
""
] |
How do I split a string with multiple separators in JavaScript?
I'm trying to split on both *commas* and *spaces*, but AFAIK JavaScript's `split()` function only supports one separator. | Pass in a regexp as the parameter:
```
js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!
```
**Edited to add:**
You can get the last element by selecting the length of the array minus 1:
```
>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"
```
... and if the pattern doesn't match:
```
>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"
``` | You can pass a regex into JavaScript's [`split()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/split) method. For example:
```
"1,2 3".split(/,| /)
["1", "2", "3"]
```
Or, if you want to allow **multiple separators** together to act as one only:
```
"1, 2, , 3".split(/(?:,| )+/)
["1", "2", "3"]
```
You have to use the non-capturing `(?:)` parenthesis, because
otherwise it gets spliced back into the result. Or you can be smart
like Aaron and use a character class.
Examples tested in Safari and Firefox. | How do I split a string with multiple separators in JavaScript? | [
"",
"javascript",
"regex",
"split",
""
] |
When trying to use a custom JSP tag library, I have a variable defined in JSP that I would like to be evaluated before being passed to the tag library. However, I cannot seem to get it to work. Here's a simplified version of my JSP:
```
<% int index = 8; %>
<foo:myTag myAttribute="something_<%= index %>"/>
```
The `doStartTag()` method of my `TagHandler` uses the pageContext's output stream to write based on the inputted attribute:
```
public int doStartTag() {
...
out.println("Foo: " + this.myAttribute);
}
```
However, the output I see in my final markup is:
```
Foo: something_<%= index %>
```
instead of what I want:
```
Foo: something_8
```
My tag library definition for the attribute is:
```
<attribute>
<name>myAttribute</name>
<required>true</required>
</attribute>
```
I have tried to configure the attribute with `rtexprvalue` both `true` and `false`, but neither worked. Is there a way I can configure the attribute so that it's evaluated before being sent to the Handler? Or am I going about this totally wrong?
I'm relatively new to JSP tags, so I'm open to alternatives for solving this problem. Also, I realize that using scriptlets in JSP is frowned upon, but I'm working with some legacy code here so I'm kind of stuck with it for now.
**Edit:**
I have also tried:
```
<foo:myTag myAttribute="something_${index}"/>
```
which does not work either - it just outputs `something_${index}`. | I don't believe that you can use a `<%= ... %>` within an attribute in a custom tag, unless your `<%= ... %>` is the entire contents of the attribute value. Does the following work for you?
```
<% int index = 8; %>
<% String attribValue = "something_" + index; %>
<foo:myTag myAttribute="<%= attribValue %>"/>
```
EDIT: I believe the `<% ... %>` within the custom tag attribute can only contain a variable name. not any Java expression. | To keep your JSP code clean and neat, avoid scripting when possible. I think this is the preferred way to do it:
```
<foo:myTag >
<jsp:attribute name="myAttribute">
something_${index}
</jsp:attribute>
</foo:myTag >
```
if your tag also contains a body, you'll have to change it from
```
<foo:myTag myAttribute="<%= attribValue %>">
body
</foo:myTag >
```
to
```
<foo:myTag >
<jsp:attribute name="myAttribute">
something_${index}
</jsp:attribute>
<jsp:body>
body
</jsp:body>
</foo:myTag >
``` | Evaluate variable before passing to JSP Tag Handler | [
"",
"java",
"jsp",
"jsp-tags",
""
] |
Specifically, I'm looking for similarly clean notation to the `Collection<T>.TrueForAll` / `Exists`, etc.
It feels smelly to have to write a foreach loop to inspect the return of a method on each object, so I'm hoping there's a better Java idiom for it. | [Predicates](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/base/class-use/Predicate.html) are provided in the [Google Collections](http://code.google.com/p/google-collections/) library. | [Functional Java](http://functionaljava.org) provides first-class functions. A predicate is expressed as `F<T, Boolean>`. For example, here's a program that tests an array for the existence of a string that is all lowercase letters.
```
import fj.F;
import fj.data.Array;
import static fj.data.Array.array;
import static fj.function.Strings.matches;
public final class List_exists {
public static void main(final String[] args) {
final Array<String> a = array("Hello", "There", "how", "ARE", "yOU?");
final boolean b = a.exists(matches.f("^[a-z]*$"));
System.out.println(b); // true
}
}
``` | Is there a Java 1.5 equivalent to the Predicate<T> methods in .Net? | [
"",
"java",
".net",
"collections",
"predicate",
""
] |
I'm using the Excel COM interop to insert images (specifically EPS) into a spreadsheet. The images are inserted fine, but Excel ignores all the visible/background settings and steals the focus the display a dialog box saying something like "importing image". The dialog box only stays a fraction of a section, but it makes the screen flicker, and worse, when I'm inserting many images at once, it can monopolize the system for several seconds (including stealing keystrokes from the foreground process).
I'm setting the background options as follows:
```
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.ScreenUpdating = false;
xlApp.DisplayAlerts = false;
Excel.Worksheet worksheet;
//....
worksheet.Pictures(Type.Missing).Insert(filename,Type.Missing); //steals focus
```
How can I get Excel to stay in the background here like it belongs? | I suspect this is caused by a component that Microsoft licensed that is badly behaved.
The only way to deal with situations like this is by intercepting the appropriate low-level Windows message and blocking it using a [Win32 hook](http://msdn.microsoft.com/en-us/library/ms997537.aspx)
The easiest way to do this, and, believe me, it's not pretty, is to use the CBT hook. CBT stands for "Computer Based Training." It is an ancient and nearly obsolete technology intended to make it possible to create training apps which watch what you're doing and respond accordingly. The only thing it's good for any more is hooking and preventing window activation in code you don't have access to. You could intercept the HCBT\_ACTIVATE code and prevent a window from activating.
This would probably need to be done in C or C++. | Contrary to common sense, setting `xlApp.ScreenUpdating = true;` prevents focus steal! ([source](https://social.msdn.microsoft.com/Forums/office/en-US/7ec7ee04-9408-4205-a16e-741e624a8ab7/excel-automation-application-steals-focus?forum=exceldev)) | How to keep Excel interop from stealing focus while inserting images | [
"",
"c#",
"excel",
"com",
"interop",
""
] |
Something that's confused me - an example:
Thing.java:
```
import java.util.Date;
class Thing {
static Date getDate() {return new Date();}
}
```
(same package) TestUsesThing.java:
```
// not importing Date here.
public class TestUsesThing {
public static void main(String[] args) {
System.out.println(Thing.getDate().getTime()); // okay
// Date date = new Date(); // naturally this wouldn't be okay
}
}
```
Why is it not necessary to import Date to be able to call getTime() on one of them? | Importing in Java is only necessary so the compiler knows what a `Date` is if you type
```
Date date = new Date();
```
Importing is not like `#include` in C/C++; all types on the classpath are *available*, but you `import` them just to keep from having to write the fully qualified name. And in this case, it's unnecessary. | Good question !!
I think the result is the difference between how java compiler handles expressions vs statements.
```
Date d = new Date(); // a statement
```
where as
```
new Thing().getDate().getTime()
```
is an expression as it occurs inside println method call. When you call getDate on new Thing() the compiler tries to handle the expression by looking at the type info for Thing class, which is where it gets the declaration of type Date.
But when you try to use Date separately in a statement like
```
Date d = new Thing().getDate();
```
you are assigning the result to a type in the current scope (class TestUsesThing ), compiler tries to resolve the type within that scope. As a result, you see the compiler error for unknown type. | Why is import of class not needed when calling method on instance (Java) | [
"",
"java",
"compiler-construction",
""
] |
Tomcat has an option to use APR for handling connections. What are the benefits of using that? Does anyone have firsthand experience with it? | If you don't plan to use a web server (for serving static content) in front of Tomcat then APR is supposed to improve things.
I've only indirectly used it via [JBoss Web](http://www.jboss.org/jbossweb/) but I always prefer to have an Apache httpd fronting Tomcat, so I think APR then is irrelevant. | Does [this](http://www.mbaworld.com/docs/apr.html) answer yor question re. benefits?
> Tomcat can use the Apache Portable Runtime to provide *superior scalability, performance, and better integration with native server technologies*. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number generation, system status, etc), and native process handling (shared memory, NT pipes and Unix sockets).
>
> These features allows making Tomcat a general purpose webserver, will enable much better integration with other native web technologies, and overall make Java much more viable as a full fledged webserver platform rather than simply a backend focused technology.
(my emphasis) | What is the benefit (if any) of using APR with Tomcat? | [
"",
"java",
"apache",
"tomcat",
"apr",
""
] |
I'm beginning a project with a client to build a web application and I'm a little stuck on which solution to go with.
I've used Joomla for many clients in the past, but this client has specific requests that I KNOW I'm going to have to build myself.
The problem I'm facing is that I work full time under the .NET spectrum and while I am a novice developer in PHP, and I've been studying Joomla's plug in architecture for about a month now, I am a lot more comfortable building something in ASP.NET than I am in PHP.
**My question is, what OS projects are out there that have a similar community following as Joomla/Mambo/Drupal, along with a plug in architecture that is somewhat akin to Joomla as well?**
I don't really have the time to build out a full blown CMS system in ASP.NET, but if something already exists that can give me X% (25%, 50%, something) of what Joomla has that will at least get me on the right path. Joomla just has too many extensions and too much of a community backing for me to pass it up if there's not something comparable in the ASP.NET realm. | I've use (and struggled with) [DotNetNuke](http://www.dotnetnuke.com/). | N2 looks quite nice, I haven't been using it though: <http://n2cms.com/> | What alternatives are there in OS projects for c# similar to Joomla/Mambo/Drupal? | [
"",
"c#",
"asp.net",
"drupal",
"joomla",
""
] |
I have a table with 3 fields like this:
```
ProfessorID StudentID Mark
P1 S1 9
P1 S2 8
P1 S3 10
P2 S1 7
P2 S2 2
P2 S3 4
P3 S4 5
P4 S1 6
```
A professor can teach many students, and vice versa, a student can learn from many professor. When a student learns from a professor, he gets his mark.
My problem is showing list of professors who teach at least 2 students, and 2 students who get best marks from those professors. In example, the query result of this table is:
```
ProfessorID StudentID Mark
P1 S1 9
P1 S3 10
P2 S1 7
P2 S3 4
```
I've tried some solutions but they don't work **right**.
How can I do this correctly? | ```
declare @table table (ProfessorID nvarchar(2), StudentID nvarchar(2),Mark int)
insert into @table
select 'P1', 'S1', 9
union all
select 'P1', 'S2', 8
union all
select 'P1', 'S3', 10
union all
select 'P2', 'S1', 7
union all
select 'P2', 'S2', 2
union all
select 'P2', 'S3', 4
union all
select 'P3', 'S4', 5
union all
select 'P4', 'S1', 6
select *
from @table o
where o.StudentID IN (select top 2 s.StudentID from @table s where s.ProfessorId = o.ProfessorId order by Mark DESC)
and o.ProfessorID IN (select p.ProfessorID from @table p group by p.ProfessorID having count(*) >= 2)
``` | Asuming you want it in SQL 2005 (or 2008), this will work as well
```
select *
from
(
select *
,rank() over (partition by professorid order by mark desc) as ranking
,(select count(distinct studentid)
from marks m2
where m2.professorid = m1.professorid
group by professorid
) as students
from marks m1
) subs
where ranking < 3
and students > 2
```
-Edoode | How to get the two best students of each professor in SQL? | [
"",
"sql",
"t-sql",
""
] |
I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy
```
if element.isdigit():
newelement = int(element)
```
Floating point numbers are more difficult. Right now I'm using `partition('.')` to split the string and checking to make sure that one or both sides are digits.
```
partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit())
or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit())
or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
newelement = float(element)
```
This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in [this question](https://stackoverflow.com/questions/354038/checking-if-string-is-a-number-python).
Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches? | I would just use..
```
try:
float(element)
except ValueError:
print "Not a float"
```
..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.
Another option would be a regular expression:
```
import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
print "Not float"
``` | ## Python3 method to check for float:
```
def is_float(element: any) -> bool:
#If you expect None to be passed:
if element is None:
return False
try:
float(element)
return True
except ValueError:
return False
```
Python2 version of the above: [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int/20929983#20929983)
Always do unit testing. What is and is not a float may surprise you:
```
Command to parse Is it a float? Comment
-------------------------------------- --------------- ------------
print(isfloat("")) False
print(isfloat("1234567")) True
print(isfloat("1_2_3.4")) True 123.4, underscores ignored
print(isfloat("NaN")) True nan is also float
print(isfloat("123.456")) True
print(isfloat("123.E4")) True
print(isfloat(".1")) True
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777")) True This is same as Inf
print(isfloat("-iNF")) True
print(isfloat("1.797693e+308")) True
print(isfloat("infinity")) True
print(isfloat("1,234")) False
print(isfloat("NULL")) False case insensitive
print(isfloat("NaNananana BATMAN")) False
print(isfloat(",1")) False
print(isfloat("123.EE4")) False
print(isfloat("infinity and BEYOND")) False
print(isfloat("12.34.56")) False Two dots not allowed.
print(isfloat("#56")) False
print(isfloat("56%")) False
print(isfloat("0E0")) True
print(isfloat("x86E0")) False
print(isfloat("86-5")) False
print(isfloat("True")) False Boolean is not a float.
print(isfloat(True)) True Boolean is a float
print(isfloat("+1e1^5")) False
print(isfloat("+1e1")) True
print(isfloat("+1e1.3")) False
print(isfloat("+1.3P1")) False
print(isfloat("-+1")) False
print(isfloat("(1)")) False brackets not interpreted
```
Sinking exceptions like this is bad, because killing canaries is bad because the float method can fail for reasons other than user input. Do not be using code like this on life critical software. Also python has been changing its contract on what unicode strings can be promoted to float so expect this behavior of this code to change on major version updates. | Checking if a string can be converted to float in Python | [
"",
"python",
"string",
"type-conversion",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.