Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
How are objects stored in memory in C++?
For a regular class such as
```
class Object
{
public:
int i1;
int i2;
char i3;
int i4;
private:
};
```
Using a pointer of Object as an array can be used to access i1 as follows?
```
((Object*)&myObject)[0] === i1?
```
Other questions on SO seem to suggest that casting a struct to a pointer will point to the first member for POD-types. How is this different for classes with constructors if at all?
Also in what way is it different for non-POD types?
Edit:
In memory therefore would the above class be laid out like the following?
```
[i1 - 4bytes][i2 - 4bytes][i3 - 1byte][padding - 3bytes][i4 - 4bytes]
``` | Almost. You cast to an Object\*, and neglected to take an address. Let's re-ask as the following:
```
((int*)&myObject)[0] == i1
```
You have to be really careful with assumptions like this. As you've defined the structure, this should be true in any compiler you're likely to come across. But all sorts of other properties of the object (which you may have omitted from your example) will, as others said, make it non-POD and could (possibly in a compiler-dependent way) make the above statement not true.
Note that I wouldn't be so quick to tell you it would work if you had asked about i3 -- in that case, even for plain POD, alignment or endianness could easily screw you up.
In any case, you should be avoiding this kind of thing, if possible. Even if it works fine now, if you (or anybody else who doesn't understand that you're doing this trick) ever changes the structure order or adds new fields, this trick will fail in all the places you've used it, which may be hard to find.
Answer to your edit: If that's your entire class definition, and you're using one of the mainstream compilers with default options, and running on an x86 processor, then yes, you've probably guessed the right memory layout. But choice of compiler, compiler options, and different CPU architecture could easily invalidate your assumptions. | Classes without virtual members and without inheritance are laid out in memory just like structs. But, when you start getting levels of inheritance things can get tricky and it can be hard to figure out what order things are in memory (particularly multiple inheritance).
When you have virtual members, they have a "vtable" in memory which contains pointers to the actual function which gets created based on the inheritance hierarchy of the class.
The bottom line is: don't access classes this way at all if you can avoid it (and also don't memset them or memcpy them). If you must do this (why?) then take care that you know exactly how your class objects are going to be in memory and be careful to avoid inheritance. | How are objects stored in memory in C++? | [
"",
"c++",
"memory",
"memory-management",
""
] |
I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO\_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:
```
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
```
According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?
**EDIT:**
When I run:
```
"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
```
I get:
```
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
``` | [Edit: added "select" before references to last\_insert\_id()]
What about running "`select last_insert_id();`" after your insert?
```
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "
+ bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ");";
+ "select last_insert_id();"
int id = Convert.ToInt32(comm.ExecuteScalar());
```
---
**Edit:** As duffymo mentioned, you really would be well served using parameterized queries [like this](http://weblogs.asp.net/cumpsd/archive/2004/04/05/107456.aspx).
---
**Edit:** Until you switch over to a parameterized version, you might find peace with string.Format:
```
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
``` | ```
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
``` | Get the id of inserted row using C# | [
"",
"c#",
"mysql",
"last-insert-id",
""
] |
What do you see as benefits for one over the other? As far as I know, it's just preference. I have way more experience with C# than I do with Visual Basic and was wondering if I should dabble in Visual Basic for certain types of projects? | I personally prefer C#, I love the syntax and I feel really comfortable with the language.
Some say that [C# programmers are paid better](http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=503) than VB programmers, but I think you should try both languages and see on which you fell better.
* [Top 10 reasons C# is better than VB.NET](http://www.vbrad.com/article.aspx?id=63)
* [Top 10 reasons VB.NET is better than C#](http://www.vbrad.com/article.aspx?id=65) | VB4 was my first language, with VB6 being the last time I touched it. I have moved to c# and wouldnt consider going back. VB just feels too fat and fluffy for me (preference).
All the .NET languages compile to IL though...
Note: c# is "closer" to java... | Do you prefer C# or Visual Basic .Net? | [
"",
"c#",
".net",
"vb.net",
""
] |
Inspired by this [question](https://stackoverflow.com/questions/404899/scope-of-variables-in-a-delegate) I began wondering why the following examples are all illegal in c#:
```
VoidFunction t = delegate { int i = 0; };
int i = 1;
```
and
```
{
int i = 0;
}
int i = 1;
```
I'm just wondering if anyone knew the exact reason why the language was designed this way? Is it to discourage bad programming practice, and if so why not just issue a warning?, for performance reasons (compiling and when running) or what is the reason? | This behavior is covered in section 3 of the C# language specification. Here is the quote from the spec
> Similarly, any expression that
> occurs as the body of an anonymous
> function in the form of a
> lambda-expression creates a
> declaration space which contains the
> parameters of the anonymous function.
> It is an error for two members of a
> local variable declaration space to
> have the same name. It is an error for
> the local variable declaration space
> of a block and a nested local variable
> declaration space to contain elements
> with the same name. Thus, within a
> nested declaration space it is not
> possible to declare a local variable
> or constant with the same name as a
> local variable or constant in an
> enclosing declaration space.
I think the easier way to read this is that for the purpose of variable declaration (and many other block related functions) a lambda/anonymous delegate block are treated no different than a normal block.
As to why the the language was designed this way the spec does not explicitly state. My opinion though is simplicity. If the code is treated as just another block then it makes code analysis routines easier. You can preserve all of your existing routines to analyze the block for semantical errors and name resolution. This is particularly important when you consider variable lifting. Lambdas will eventually be a different function but they still have access to all in scope variables at the declaration point. | I think it is done this way so that the inner scope can access variables declared in the outer scope. If you were allowed to over-write variables existing in the outer scope, there may be confusion about what behavior was intended. So they may have decided to resolve the issue by preventing it from happening. | Why is the scope of if and delegates this way in c# | [
"",
"c#",
"language-design",
""
] |
I want to format an int as a currency in C#, but with no fractions. For example, 100000 should be "$100,000", instead of "$100,000.00" (which 100000.ToString("C") gives).
I know I can do this with 100000.ToString("$#,0"), but that's $-specific. Is there a way to do it with the currency ("C") formatter? | Use format "C0". | Possible to use n0 which provide commas like 1,234. Currency sign won't be there | How to format an int as currency in C#? | [
"",
"c#",
"formatting",
"currency",
""
] |
According to [MSDN](http://msdn.microsoft.com/en-us/library/system.drawing.aspx), it is not a particularly good idea to use classes within the **System.Drawing** namespace in a Windows Service or ASP.NET Service. Now I am developing a class library which might need to access this particular namespace (for measuring fonts) but it cannot be guaranteed that the host process is not a service.
Now there is a less optimal method I can fall back to if System.Drawing is unavailable, but if it is possible, I would rather use classes in System.Drawing. So what I would like to do is to determine at runtume if System.Drawing is safe or not, and if it is, use it, otherwise fall back to the suboptimal option.
My problem is: **How could I possibly detect if System.Drawing is safe to use?**
I think I should either
* Detect if the current process is a Windows Service or ASP.NET service
* Detect if GDI is available
* Or maybe there is a way to ask System.Drawing.dll itself if it is safe to use
Unfortunately, I cannot come up with a way to implement any of these approaches. Does anyone have any idea? | To clear up any confusion, System.Drawing does *work* under ASP.NET and Services, it's just not *supported*. There can be issues with high load (running out of unmanaged resources), memory or resource leaks (badly implemented or called dispose patterns) and/or dialogs being popped when there's no desktop to show them on.
Testing will take care of the latter, and monitoring will alert you to the former. But, if/when you have a problem, don't expect to be able to call PSS and ask for a fix.
So, what are you options? Well, if you don't need a completely supported route, and you don't expect extreme load - a lot of folks have disregarded the MSDN caveat and used System.Drawing with success. A few of them have been bitten, but there's alot more success than failure stories.
If you want something supported, then you need to know if you're running interactively or not. Personally, I'd probably just leave it up to the hosting app to set a non-interactive flag somewhere or other. After all, the app is in the best position to determine if they're in a hosted environment and/or want to risk the GDI+ issues.
But, if you want to automagically detect your environment, I suppose there's worse answers than are offered [right here on SO](https://stackoverflow.com/questions/200163/am-i-running-as-a-service#200183) for a service. To summarize, you can either check the EntryAssembly to see if it inherits from ServiceBase, or try to access System.Console. For ASP.NET, along the same lines, detecting HttpContext.Current should be sufficient.
I'd *think* there'd be a managed or p/invoke way to look for a desktop (which is really the defining factor in all this, I think) and/or something off the AppDomain which would clue you in. But I'm not sure what it is, and MSDN is less than enlightening on it.
Edit: Trolling MSDN, I recalled that it's actually a [Window Station](http://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook/WhatIsAWindowStation.html) (which hosts a desktop) that's the important bit here. With that info, I was able to find [GetProcessWindowStation()](http://msdn.microsoft.com/en-us/library/ms683225(VS.85).aspx) which returns a handle to the current window station. Passing that handle to [GetUserObjectInformation()](http://msdn.microsoft.com/en-us/library/ms683238(VS.85).aspx) will get you a [USEROBJECTFLAGS](http://msdn.microsoft.com/en-us/library/ms686892(VS.85).aspx) struct with should have a dwFlags with WSF\_VISIBLE if you have a visible desktop.
Alternatively, [EnumWindowsStations](http://msdn.microsoft.com/en-us/library/ms682644(VS.85).aspx) will give you a list of stations which you could check - WinSta0 is the interactive one.
But, yeah, I still think just having the app set a property or something is the *much* easier route....
Edit again: 7 years later, I get clued into [Environment.UserInteractive](https://msdn.microsoft.com/en-us/library/system.environment.userinteractive(v=vs.110).aspx) where MS [does the exact GetProcessWindowStation dance](http://referencesource.microsoft.com/#mscorlib/system/environment.cs,7d2f1469d916fc63) I described above for you....I'd still recommend delegating to the hosting app (they may well *want* the faster, but slightly riskier System.Drawing path), but UserInteractive seems a good default to have without having it pinvoke it yourself. | Even though it's not officially supported, I've used the System.Drawing classes extensively on a high-volume web server (both web application and web services) for years without it causing any performance or reliability problems.
I think the only way to determine if the code is safe to use is to test, monitor, and wrap any object with external resources in using{} statements. | System.Drawing in Windows or ASP.NET services | [
"",
"c#",
".net",
"windows-services",
"system.drawing",
""
] |
I know there is a method for a Python list to return the first index of something:
```
>>> xs = [1, 2, 3]
>>> xs.index(2)
1
```
Is there something like that for NumPy arrays? | Yes, given an array, `array`, and a value, `item` to search for, you can use [`np.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) as:
```
itemindex = numpy.where(array == item)
```
The result is a tuple with first all the row indices, then all the column indices.
For example, if an array is two dimensions and it contained your item at two locations then
```
array[itemindex[0][0]][itemindex[1][0]]
```
would be equal to your item and so would be:
```
array[itemindex[0][1]][itemindex[1][1]]
``` | If you need the index of the first occurrence of **only one value**, you can use `nonzero` (or `where`, which amounts to the same thing in this case):
```
>>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8])
>>> nonzero(t == 8)
(array([6, 8, 9]),)
>>> nonzero(t == 8)[0][0]
6
```
If you need the first index of each of **many values**, you could obviously do the same as above repeatedly, but there is a trick that may be faster. The following finds the indices of the first element of each *subsequence*:
```
>>> nonzero(r_[1, diff(t)[:-1]])
(array([0, 3, 5, 6, 7, 8]),)
```
Notice that it finds the beginning of both subsequence of 3s and both subsequences of 8s:
[**1**, 1, 1, **2**, 2, **3**, **8**, **3**, **8**, 8]
So it's slightly different than finding the first *occurrence* of each value. In your program, you may be able to work with a sorted version of `t` to get what you want:
```
>>> st = sorted(t)
>>> nonzero(r_[1, diff(st)[:-1]])
(array([0, 3, 5, 7]),)
``` | Is there a NumPy function to return the first index of something in an array? | [
"",
"python",
"arrays",
"numpy",
""
] |
I'm writing a webapp that will only be used by authenticated users. Some temporary databases and log files will be created during each user session. I'd like to erase all these temp files when the session is finished.
Obviously, a logout or window close event would be sufficient to close the session, but in some cases the user may keep the browser open long after he's finished.
Another approach would be to time user sessions or delete the temp files during routine maintenance.
How do you go about it? | User sessions should have a timeout value and should be closed when the timeout expires or the user logs out. Log out is an obvious time to do this and the time out needs to be there in case the user navigates away from your application without logging out. | A cron job to clean up any expired session data in the database is a good thing. Depending on how long your sessions last, and how big your database is, you might want to cleanup more often than once per day. But one cleanup pass per day is usually fine. | when to delete user's session | [
"",
"python",
"session",
""
] |
Is it possible to generate the database tables and c# classes from NHibernate config files? Afterwards, is it possible to change the config files and update the tables and config files non-destructively?
Do you recommend any tools to do this? (preferably free...) | As mentioned by Joachim, it's the "hbm2ddl.auto" setting that you're looking for.
You can set it by code like this:
```
var cfg = new NHibernate.Cfg.Configuration();
cfg.SetProperty("hbm2ddl.auto", "create");
cfg.Configure();
```
And you can also set it in your App.config file:
```
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="hbm2ddl.auto">create</property>
``` | Yes it is possible to generate the database tables and C# classes from the NHibernate config files. Let me explain with this example here .
1 : Address.hbm.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-mapping
xmlns="urn:nhibernate-mapping-2.0"
default-cascade="none">
<class
name="Your.Domain.AddressImpl, Your.Domain"
table="[ADDRESS]"
dynamic-insert="true"
dynamic-update="true"
lazy="true">
<id name="Id" type="long" unsaved-value="0">
<column name="ID" sql-type="NUMERIC(19,0)"/>
<generator class="native"> </generator>
</id>
<property name="Address1" type="string">
<column name="ADDRESS1" not-null="true" unique="false" sql-type="VARCHAR(100)"/>
</property>
<property name="Address2" type="string">
<column name="ADDRESS2" not-null="true" unique="false" sql-type="VARCHAR(100)"/>
</property>
<property name="City" type="string">
<column name="CITY" not-null="true" unique="false" sql-type="VARCHAR(100)"/>
</property>
<property name="State" type="string">
<column name="STATE" not-null="true" unique="false" sql-type="VARCHAR(100)"/>
</property>
<property name="Zipcode" type="string">
<column name="ZIPCODE" not-null="true" unique="false" sql-type="VARCHAR(100)"/>
</property>
</class>
</hibernate-mapping>
```
Step 2 :
Just by the looking at the configuration file , you Address object siply looks like the following
```
using System;
namespace Your.Domain
{
public partial class Address
{
#region Attributes and Associations
private string _address1;
private string _address2;
private string _city;
private long _id;
private string _state;
private string _zipcode;
#endregion
#region Properties
/// <summary>
///
/// </summary>
public virtual string Address1
{
get { return _address1; }
set { this._address1 = value; }
}
/// <summary>
///
/// </summary>
public virtual string Address2
{
get { return _address2; }
set { this._address2 = value; }
}
/// <summary>
///
/// </summary>
public virtual string City
{
get { return _city; }
set { this._city = value; }
}
/// <summary>
///
/// </summary>
public virtual long Id
{
get { return _id; }
set { this._id = value; }
}
/// <summary>
///
/// </summary>
public virtual string State
{
get { return _state; }
set { this._state = value; }
}
/// <summary>
///
/// </summary>
public virtual string Zipcode
{
get { return _zipcode; }
set { this._zipcode = value; }
}
#endregion
}
}
```
Step 3 : And again if you look at the "Column" name property and its data type that is actually refers to the Actual backend database table called "Address".
There are also huge amount of tools that help you to generate all these artifacts for you based on different input such as UML, Or Actual Database schema etc. | Generate Database from NHibernate config files | [
"",
"c#",
"nhibernate",
""
] |
Simply put, I have a table with, among other things, a column for timestamps. I want to get the row with the most recent (i.e. greatest value) timestamp. Currently I'm doing this:
```
SELECT * FROM table ORDER BY timestamp DESC LIMIT 1
```
But I'd much rather do something like this:
```
SELECT * FROM table WHERE timestamp=max(timestamp)
```
However, SQLite rejects this query:
```
SQL error: misuse of aggregate function max()
```
The [documentation](http://www.sqlite.org/lang_expr.html) confirms this behavior (bottom of page):
> Aggregate functions may only be used in a SELECT statement.
My question is: is it possible to write a query to get the row with the greatest timestamp without ordering the select and limiting the number of returned rows to 1? This seems like it should be possible, but I guess my SQL-fu isn't up to snuff. | ```
SELECT * from foo where timestamp = (select max(timestamp) from foo)
```
or, if SQLite insists on treating subselects as sets,
```
SELECT * from foo where timestamp in (select max(timestamp) from foo)
``` | There are many ways to skin a cat.
If you have an Identity Column that has an auto-increment functionality, a faster query would result if you return the last record by ID, due to the indexing of the column, unless of course you wish to put an index on the timestamp column.
```
SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1
``` | Aggregate functions in WHERE clause in SQLite | [
"",
"sql",
"sqlite",
"where-clause",
"aggregate-functions",
""
] |
I have a problem with a flash object placing itself on top over everything in IE6 and IE7.
Firefox renders the page correctly.
I bet somebody else has had this problem and found some kinda solution to it. | Because Flash runs inside an ActiveX control in IE browsers, it doens't follow the stack rules since ActiveX controls are always rendered on to of normal HTML content (except for drop down, annoyingly).
There is a workaround though to force Flash to obey, set the wmode="transparent" in your object tag, and optionally the embedded tag too. | [wmode=transparent](https://stackoverflow.com/search?q=wmode+transparent) is the way to go. | Problem with flash positioning itself over a javascript lightwindow in IE6 & IE7 | [
"",
"javascript",
"flash",
"internet-explorer",
""
] |
Is there a way to get the name of the currently executing method in Java? | `Thread.currentThread().getStackTrace()` will usually contain the method you’re calling it from but there are pitfalls (see [Javadoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#getStackTrace())):
> Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method. | Technically this will work...
```
String name = new Object(){}.getClass().getEnclosingMethod().getName();
```
However, a new anonymous inner class will be created during compile time (e.g. `YourClass$1.class`). So this will create a `.class` file for each method that deploys this trick. Additionally, an otherwise unused object instance is created on each invocation during runtime. So this may be an acceptable debug trick, but it does come with significant overhead.
An advantage of this trick is that `getEnclosingMethod()` returns `java.lang.reflect.Method` which can be used to retrieve all other information of the method including annotations and parameter names. This makes it possible to distinguish between specific methods with the same name (method overload).
Note that according to the JavaDoc of `getEnclosingMethod()` this trick should not throw a `SecurityException` as inner classes should be loaded using the same class loader. So there is no need to check the access conditions even if a security manager is present.
**Please be aware**: It is required to use `getEnclosingConstructor()` for constructors. During blocks outside of (named) methods, `getEnclosingMethod()` returns `null`. | Getting the name of the currently executing method | [
"",
"java",
"reflection",
"methods",
""
] |
I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.
Has anyone done anything like that? Do you known a Perl or Python library that does that?
Lingua::EN::Tagger is exactly what I asked however I needed a library that could work for french text too. | You could try using the perl module [Lingua::EN::Tagger](http://search.cpan.org/~acoburn/Lingua-EN-Tagger-0.15/Tagger.pm) for a quick and easy solution.
A more complicated module [Lingua::EN::Semtags::Engine](http://code.google.com/p/lingua-en-semtags-engine/) uses Lingua::EN::Tagger with a WordNet database to get a more structured output. Both are pretty easy to use, just check out the documentation on CPAN or use perldoc after you install the module. | The name for the "high frequency English words" is [stop words](http://en.wikipedia.org/wiki/Stop_words) and there are many lists available. I'm not aware of any python or perl libraries, but you could encode your stop word list in a binary tree or hash (or you could use python's frozenset), then as you read each word from the input text, check if it is in your 'stop list' and filter it out.
Note that after you remove the stop words, you'll need to do some [stemming](http://en.wikipedia.org/wiki/Stemming) to normalize the resulting text (remove plurals, -ings, -eds), then remove all the duplicate "keywords". | What is a simple way to generate keywords from a text? | [
"",
"python",
"perl",
"metadata",
""
] |
Is there any GUI toolkit for Python with form designer similar to Delphi, eg where one can drag and drop controls to form, move them around etc. | I recommend [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/intro) (now from Nokia), which uses [Qt Designer](http://www.qtsoftware.com/products/appdev/developer-tools/developer-tools?currentflipperobject=73543fa58dda72c632a376b97104ff78). Qt designer produces XML files (.ui) which you can either convert to Python modules using a utility called `pyuic`, or load dynamically from your Python program.
You *do* have to write your Python code in a different editor, i.e. Designer is only the GUI designer part and not a complete IDE. They have an IDE in beta called Qt Creator, but I don't think it supports Python very well at this stage.
If you'd rather go with [wxPython](http://www.wxpython.org/), [wxGlade](http://wxglade.sourceforge.net/) will output Python code. | Use Glade + PyGTk to do GUI programming in Python. Glade is a tool which allows you to create graphical interfaces by dragging and dropping widgets. In turn Glade generates the interface definition in XML which you can hook up with your code using libglade. Check the website of [Glade](http://glade.gnome.org/) for more info. | Delphi-like GUI designer for Python | [
"",
"python",
"user-interface",
"form-designer",
""
] |
In a C++ physics simulation, I have a class called Circle, and Square. These are Shapes, and have a method called push(), which applies force to it. There is then a special case of Circle, call it SpecialCircle, in which push() should exhibit slightly different properties. But in fact, there is also SpecialSquare() which should exhibit the same force properties. So I'd like to have an abstract base class called Shape which takes care of Circles and Squares, but then I'd also like an abstract base class called Special, which applies special properties to force().
What's the best way to design this class structure?
So far, I've got:
```
class Shape {
virtual void push();
};
class Circle : public Shape {};
class Square : public Shape {};
class Special {
virtual void push();
};
class SpecialCircle : public Circle, Special {};
class SpecialSquare : public Square, Special {};
```
Of course, the above won't compile, since Special::push() and Shape::push() conflict. I get "error: request for member ‘push’ is ambiguous", as expected.
How can I re-organize my class structure so that Circle and Square can share certain properties with each other, but SpecialCircle and SpecialSquare can still inherit from Shape, and also inherit modified functionality from Special?
Thanks.
ps., is this the diamond inheritance problem? | Another solution (it may or may not fit your needs, it depends on the details of your implementation):
* Have the class Behavior, and let NormalBehavior and SpecialBehavior inherit from it.
* Have the class Shape, and let Square and Circle inherit from it. Let Shape be an aggregate type, with a Behavior member (i.e. you pass a Behavior object to the various Shape constructors). In other words, let a Shape have a Behavior.
* Delegate the actual differences in the behavior of shapes to methods of the Behavior hierarchy.
Conversely, you can:
* Have the class PhysicalObject, and let NormalObject and SpecialObject inherit from it;
* Have the class Shape, and let Square and Circle inherit from it;
* Let a PhysicalObject have a Shape.
Prefer aggregation over inheritance. This is an application of the [Bridge pattern](http://en.wikipedia.org/wiki/Bridge_pattern). The advantage of this strategy with respect to having Square, SpecialSquare, Circle, and SpecialCircle, is that tomorrow you'll have to add Rectangle, Hexagon and so on, and for each shape you add you'll have to implement *two* classes (duplicated code is evil); this is, in my opinion, the real issue that Bridge addresses. | It's said that every problem in software can be solved by adding an additional layer of indirection.
Herb Sutter has an excellent article on how to solve your problem: [Multiple Inheritance - Part III](http://www.gotw.ca/gotw/039.htm)
In short, you use intermediate classes to 'rename' the virtual functions. As Herb says:
> Renaming Virtual Functions
>
> If the two inherited functions had different signatures, there would be no problem: We would just override them independently as usual. The trick, then, is to somehow change the signature of at least one of the two inherited functions.
>
> The way to change a base class function's signature is to create an intermediate class which derives from the base class, declares a new virtual function, and overrides the inherited version to call the new function
Here's a long example using your classes:
```
class Shape {
public:
virtual void push() = 0;
};
class Circle : public Shape
{
public:
void push() {
printf( "Circle::push()\n");
}
};
class Square : public Shape
{
public:
void push() {
printf( "Square::push()\n");
}
};
class Special {
public:
virtual void push() = 0;
};
class Circle2: public Circle
{
public:
virtual void pushCircle() = 0;
void push() {
pushCircle();
}
};
class Square2: public Square
{
public:
virtual void pushSquare() = 0;
void push() {
pushSquare();
}
};
class Special2 : public Special
{
public:
virtual void pushSpecial() = 0;
void push() {
pushSpecial();
}
};
class SpecialCircle : public Circle2, public Special2
{
public:
void pushSpecial() {
printf( "SpecialCircle::pushSpecial()\n");
}
void pushCircle() {
printf( "SpecialCircle::pushCircle()\n");
}
};
class SpecialSquare : public Square2, public Special2
{
public:
void pushSpecial() {
printf( "SpecialSquare::pushSpecial()\n");
}
void pushSquare() {
printf( "SpecialSquare::pushSquare()\n");
}
};
int main( int argc, char* argv[])
{
SpecialCircle sc;
SpecialSquare ss;
// sc.push(); // can't be called - ambiguous
// ss.push();
sc.pushCircle();
ss.pushSquare();
Circle* pCircle = ≻
pCircle->push();
Square* pSquare = &ss;
pSquare->push();
Special* pSpecial = ≻
pSpecial->push();
pSpecial = &ss;
pSpecial->push();
return 0;
}
``` | Multiple inheritance in C++ leading to difficulty overriding common functionality | [
"",
"c++",
"inheritance",
"class",
""
] |
I'm looking for an AJAX function to dynamically request an HTML page. I already found the following:
```
function ajaxinclude(url)
{
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) // if IE
{
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false) //get page synchronously
page_request.send(null)
return page_request.responseText;
}
```
It works fine in Firefox and Chrome, but it fails in IE on the following line:
```
page_request.open('GET', url, false)
```
Is there a better available function that is guaranteed to be completely cross browser compatible?
**Edit:** Thanks for all the great suggestions... in the end, I decided not to reinvent the wheel here. And one of the things I forgot to mention was that I also need it to update at an interval... though I had already figure that out so I didn't think it made a difference. But then I found the great Ajax.PeriodicUpdater() Method in prototype and vastly changed my mind. I just went from a 50 LOC solution to about 4 lines :) | I would have to agree, don't go reinventing the wheel, or in this case, AJAX.
JQuery and Prototype do an excellent job of letting you NOT have to deal with cross-browser support, and greatly simplifying Javascript type programming. I fell into JQuery first so I'm biased towards it, and from what I've seen the library is a little smaller (read: faster in the browser), but Prototype I believe has been around longer and has TONS of plugins and examples out there. Ruby on Rails also by default uses Prototype. Funny enough, the code in both looks very similar and takes little rewriting to change libraries.
[JQuery Tutorials](http://docs.jquery.com/Tutorials) <-- Just head on down to the AJAX section | Or you can try this if you don't need an entire framework: <http://www.hunlock.com/blogs/The_Ultimate_Ajax_Object> | Cross browser AJAX function to dynamically load HTML | [
"",
"javascript",
"ajax",
""
] |
For a project I have a specification with formulas, I have to implement. In these formulas a cumulative standard normal distribution function exists, that takes a float and outputs a probability. The function is symbolized by a Φ. Exists a Java-library, that computes this function? | A co-worker suggested [colt](http://acs.lbl.gov/~hoschek/colt/), as he used it before. This [function](http://acs.lbl.gov/~hoschek/colt/api/cern/jet/random/Normal.html#cdf(double)) has exactly the result as the example in the reference document. | [Apache Commons - Math](http://commons.apache.org/math/) has what you are looking for.
More specifically, check out the [`NormalDistribution`](http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/distribution/NormalDistribution.html) class. | Which java-library computes the cumulative standard normal distribution function? | [
"",
"java",
"statistics",
"probability",
"computation",
""
] |
Bjarne Stroustrup writes in his [C++ Style and Technique FAQ](http://www.research.att.com/~bs/bs_faq2.html#finally), emphasis mine:
> Because C++ supports an alternative that is ***almost always better***: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource. For example:
>
> ```
> class File_handle {
> FILE* p;
> public:
> File_handle(const char* n, const char* a)
> { p = fopen(n,a); if (p==0) throw Open_error(errno); }
> File_handle(FILE* pp)
> { p = pp; if (p==0) throw Open_error(errno); }
>
> ~File_handle() { fclose(p); }
>
> operator FILE*() { return p; }
>
> // ...
> };
>
> void f(const char* fn)
> {
> File_handle f(fn,"rw"); // open fn for reading and writing
> // use file through f
> }
> ```
>
> In a system, we need a "resource handle" class for each resource. However, we don't have to have an "finally" clause for each acquisition of a resource. In realistic systems, there are far more resource acquisitions than kinds of resources, so the "resource acquisition is initialization" technique leads to less code than use of a "finally" construct.
Note that Bjarne writes "almost always better" and not "always better". Now for my question: What situation would a `finally` construct be better than using the alternative construct (RAII) in C++? | The only reason I can think of that a finally block would be "better" is when it takes less code to accomplish the same thing. For example, if you have a resource that, for some reason doesn't use RAII, you would either need to write a class to wrap the resource and free it in the destructor, or use a finally block (if it existed).
Compare:
```
class RAII_Wrapper
{
Resource *resource;
public:
RAII_Wrapper() : resource(aquire_resource()) {}
~RAII_Wrapper() {
free_resource(resource);
delete resource;
}
Resource *getResource() const {
return resource;
}
};
void Process()
{
RAII_Resource wrapper;
do_something(wrapper.resource);
}
```
versus:
```
void Process()
{
try {
Resource *resource = aquire_resource();
do_something(resource);
}
finally {
free_resource(resource);
delete resource;
}
}
```
Most people (including me) would still argue that the first version is better, because it doesn't force you to use the try...finally block. You also only need to write the class once, not duplicate the code in every function that uses the resource.
**Edit:** Like litb mentioned, you should use an auto\_ptr instead of deleting the pointers manually, which would simplify both cases. | The difference between them is that destructors emphasise reuse of the cleanup solution by associating it with the type being used, whereas try/finally emphasises one-off cleanup routines. So try/finally is more immediately convenient when you have a unique one-off cleanup requirement associated with the point of use, rather than a reusable cleanup solution that can be associated with a type you're using.
I haven't tried this (haven't downloaded a recent gcc for months), but it should be true: with the addition of lambdas to the language, C++ can now have the effective equivalent of `finally`, just by writing a function called `try_finally`. Obvious usage:
```
try_finally([]
{
// attempt to do things in here, perhaps throwing...
},
[]
{
// this always runs, even if the above block throws...
}
```
Of course, you have to write try\_`finally`, but only once and then you're good to go. Lambdas enable new control structures.
Something like:
```
template <class TTry, class TFinally>
void try_finally(const TTry &tr, const TFinally &fi)
{
try
{
tr();
}
catch (...)
{
fi();
throw;
}
fi();
}
```
And there is no link at all between the presence of a GC and a preference for try/finally instead of destructors. C++/CLI has destructors and GC. They're orthogonal choices. Try/finally and destructors are slightly different solutions to the same problem, both deterministic, needed for non-fungible resources.
C++ function objects emphasise reusability but make one-off anonymous functions painful. By adding lambdas, anonymous code blocks are now easy to make, and this avoids C++'s traditional emphasis on "forced reusability" expressed through named types. | Are there cases where a "finally" construct would be useful in C++? | [
"",
"c++",
"raii",
"finally",
""
] |
Do you consider this a code smell?
```
foreach((array)$foo as $bar)
{
$bar->doStuff();
}
```
Should i use that instead?
```
if (isset($foo) && is_array($foo))
{
foreach($foo as $bar)
{
$bar->doStuff();
}
}
```
Any other good practices to cover not set variables and assert an array? | They're both code smells. The second one is just evading all the error messages, kind of like turning off the fire alarm before you set your kitchen on fire. Both of those tell you that you have no idea what's in the variable `$foo` or if it's even been defined in the code above. You need to go back up through the code and find out exactly what's going on with `$foo`.
If it was my code, $foo would probably be always defined either as an array, or else false to indicate the array isn't needed:
```
if(do_we_need_an_array())
$foo = function_returning_an_array();
else
$foo = false;
[...snip...]
if($foo)
foreach($foo as $f) { ... }
``` | If you are testing if variables are set, you can initialize them:
```
if (! $foo or !is_array($foo))
$foo = array();
foreach($foo as $bar)
{
$bar->doStuff();
}
``` | Do you consider foreach((array)$foo as $bar) a code smell? | [
"",
"php",
""
] |
When clicking on the text box part of an `<input type="file" />` in FireFox3, a file browsing window opens.
This doesn't happen in IE7. You have to click the "browse" button to open the file browsing window.
How can I prevent the file browsing window from opening in FireFox when a user clicks on the textbox area? I'd like it so it only opens when the button is pressed. | > How can I prevent the file browsing window from opening in FireFox when a user clicks on the textbox area?
Obscure it with another element.
```
<div style="position: relative">
<input type="file" />
<div style="position: absolute; top: 0; left: 0; width: 11em; height: 2em;"> </div>
</div>
```
But don't do this. It's awfully brittle and will break in many circumstances.
> I'd like it so it only opens when the button is pressed.
I doubt your users would like it, though. It removes expected functionality from the browser, and doesn't replace it with anything better. Or indeed anything at all. | Why can't you leave expected behavior alone? Most people who use FireFox will expect it to happen. Unless there is an actual "design" reason that you did not state for making this happen please don't try and change it. | <input type="file" /> opens file browse window in FireFox3 when clicking the form field part? | [
"",
"javascript",
"css",
"file",
"input",
""
] |
I'm a MySQL guy working on a SQL Server project, trying to get a datetime field to show the current time. In MySQL I'd use NOW() but it isn't accepting that.
```
INSERT INTO timelog (datetime_filed) VALUES (NOW())
``` | `getdate()` or `getutcdate()`. | ```
getdate()
```
is the direct equivalent, *but you should always use UTC datetimes*
```
getutcdate()
```
whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions | SQL Server equivalent of MySQL's NOW()? | [
"",
"sql",
"sql-server",
""
] |
Hi I need some help with the following scenario in php. I have a db with users every user has an ID, have\_card and want\_card. I know how to make a direct match (one user trades with another user). But if there is no direct match but there is a circular swap like:
User #1 has card A wants card B
User #2 has card B wants card C
User #3 has card C wants card A
In this scenario there is no direct match between two users. But if:
User #1 gives his card to User #3
User #3 gives his card to User #2
User #2 gives his card to User #1
Every ones happy.
All the info I have to start with is User #1 how do I find User #2 and User #3?
Thanks to everyone for your answers. | This is a challenging scenario. I had to build this for a book swapping application a while back and using a white board I was able to more easily visual and solve the problem.
What I did was use the same table inside the query multiple times, just using a different name.
In my scenario, the books that were needed were in a separate table from the books the users had. Hopefully you'll be able to see the logic in this query:
```
$query = "SELECT
A.Owner_ID as Owner_1, C.Owner_ID as Owner_2, E.Owner_ID as Owner_3
FROM
E_User_Books_Have as A, E_User_Books_Have as C, E_User_Books_Have as E,
E_User_Books_Needed as B, E_User_Books_Needed as D,E_User_Books_Needed as F
WHERE
A.Book_ID=D.Book_ID AND
C.Book_ID=F.Book_ID AND
E.Book_ID=B.Book_ID AND
A.Owner_ID='$ME' AND B.Owner_ID='$ME' AND A.ID='$ID'AND
C.Owner_ID=D.Owner_ID AND
E.Owner_ID=F.Owner_ID AND
C.Owner_ID!='$ME' AND
E.Owner_ID!='$ME'";
``` | Interestingly, I came across a similar thing to this with the [BoardGameGeek Maths Trade](http://www.boardgamegeek.com/thread/93555). Basically, everyone specifies that they either want a game or have a game and the algorithm maximises trades including circular dependencies.
This is exactly what you want.
Here is an [explanation of how TradeMaximizer works](http://www.boardgamegeek.com/wiki/page/TradeMaximizer). It uses [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) and [skew heaps](http://en.wikipedia.org/wiki/Skew_heap) to find minimal matching solutions (ie a smaller circle is preferable to a larger circle).
Granted this is created in Java but algorithms are universal and you can recreate it as required, particularly once you understand what it's doing and why. | Circular matching. PHP / MySql | [
"",
"php",
"mysql",
""
] |
So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?
---
Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages' | I'd suggest using `virtualenv`'s [bootstrapping](http://pypi.python.org/pypi/virtualenv#creating-your-own-bootstrap-scripts) support. This allows you to execute arbitrary Python after the virtualenv is created, such as installing new packages. | I know where you're coming from with the no-sites-option. I want to use pip freeze to generate requirements lists and don't want a lot of extra cruft in site-packages. I also need to use multiple versions of django as I have legacy projects I haven't upgraded (some old svn checkouts (pre1.0), some 1.0, and some new svn checkouts). Installing Django in the global site-packages isn't really an option.
Instead I have a django folder with releases and a couple of different svn versions and just symlink to the appropriate version in the local site-packages. For ease of use I link to the local site-packages at the same level as the environment and then link in the appropriate django directory and any other "system" style packages I need (usually just PIL). So:
```
$ virtualenv pyenv
$ ln -s ./pyenv/lib/python2.5/site-packages ./installed
$ ln -s /usr/lib/python2.5/site-packages/PIL ./installed
$ ln -s /opt/django/django1.0svn/trunk/django ./installed
```
Now the following works:
```
$ source pyenv/bin/activate
$ python
> import django
> import PIL
``` | Installing certain packages using virtualenv | [
"",
"python",
"virtualenv",
"buildout",
""
] |
I was having a look at [this](http://java.sun.com/docs/books/tutorial/essential/io/cl.html) tutorial at Sun on command line I/O. It stated that:
> You might expect the Standard Streams
> to be character streams, but, for
> historical reasons, they are byte
> streams. System.out and System.err are
> defined as PrintStream objects.
> Although it is technically a byte
> stream, PrintStream utilizes an
> internal character stream object to
> emulate many of the features of
> character streams.
Does any one know what "the historical reasons" are? | The "historical reasons" are that character streams did not exist in Java 1.0. Apparently Sun realized that the character translation model was insufficient and the Character oriented Reader/Writer class hierarchy was added in Java 1.1.
But it was too late for System.out and friends. | I would guess that the reason is to be backwards-compatible with POSIX C/C++ standard I/O, in which stdin, stdout, and stderr (the C/C++ equivalent of System.in, System.out, and System.err respectively) are byte streams. In Windows, those streams perform CRLF translation, but in POSIX systems, no such conversions occur, and you can freely read and write non-character binary data. Lots of Unix utilities do this, such as GNU's `gzip` and `tar`. | Why are System.out/err implemented as Byte Streams in Java? | [
"",
"java",
"iostream",
""
] |
I have the same expression in Javascript but it won't work in PHP for server side validation. Here's the code
```
if (ereg('/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+/',$_POST['email-address']))
echo "valid email";
else
echo "invalid email";
``` | use preg\_match, not ereg. ereg regex strings do not use an enclosing slash character.
Also the double-backslash may not be necessary in a single-quoted string in PHP (not sure about that, though) | filter which comes with PHP:
```
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "E-mail is not valid";
} else {
echo "E-mail is valid";
}
``` | Why doesn't my email regex for PHP work? | [
"",
"php",
"regex",
""
] |
How can I convert an `str` to a `float`?
```
"545.2222" -> 545.2222
```
Or an `str` to a `int`?
```
"31" -> 31
```
---
For the reverse, see [Convert integer to string in Python](https://stackoverflow.com/questions/961632) and [Converting a float to a string without rounding it](https://stackoverflow.com/questions/1317558).
Please instead use [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427) to close duplicate questions where OP received a string *from user input* and immediately wants to convert it, or was hoping for `input` (in 3.x) to convert the type automatically. | ```
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
``` | ## Python2 method to check if a string is a float:
```
def is_float(value):
if value is None:
return False
try:
float(value)
return True
except:
return False
```
For the Python3 version of is\_float see: [Checking if a string can be converted to float in Python](https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python/20929881#20929881)
A longer and more accurate name for this function could be: `is_convertible_to_float(value)`
## What is, and is not a float in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) may surprise you:
The below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: `(float("1_3.4") == float(13.4))` is True
```
val is_float(val) Note
-------------------- ---------- --------------------------------
"" False Blank string
"127" True Passed string
True True Pure sweet Truth
"True" False Vile contemptible lie
False True So false it becomes true
"123.456" True Decimal
" -127 " True Spaces trimmed
"\t\n12\r\n" True whitespace ignored
"NaN" True Not a number
"NaNanananaBATMAN" False I am Batman
"-iNF" True Negative infinity
"123.E4" True Exponential notation
".1" True mantissa only
"1_2_3.4" False Underscores not allowed
"12 34" False Spaces not allowed on interior
"1,234" False Commas gtfo
u'\x30' True Unicode is fine.
"NULL" False Null is not special
0x3fade True Hexadecimal
"6e7777777777777" True Shrunk to infinity
"1.797693e+308" True This is max value
"infinity" True Same as inf
"infinityandBEYOND" False Extra characters wreck it
"12.34.56" False Only one dot allowed
u'四' False Japanese '4' is not a float.
"#56" False Pound sign
"56%" False Percent of what?
"0E0" True Exponential, move dot 0 places
0**0 True 0___0 Exponentiation
"-5e-5" True Raise to a negative number
"+1e1" True Plus is OK with exponent
"+1e1^5" False Fancy exponent not interpreted
"+1e1.3" False No decimals in exponent
"-+1" False Make up your mind
"(1)" False Parenthesis is bad
```
You think you know what numbers are? You are not so good as you think! Not big surprise.
## Don't use this code on life-critical software!
Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The `float(...)` line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems. | How do I parse a string to a float or int? | [
"",
"python",
"parsing",
"floating-point",
"type-conversion",
"integer",
""
] |
I understand that the question is rather hard to understand, I didn't know how to ask it better, so I'll use this code example to make things more clear:
If I have the following files:
test.php:
```
<?php
include('include.php');
echo myClass::myStaticFunction();
?>
```
include.php
```
<?php
__autoload($classname){
include_once("class/".$classname.".php"); //normally checking of included file would happen
}
?>
```
class/myClass.php
```
<?php
class myClass{
public static function myStaticFunction(){
//I want this to return test.php, or whatever the filename is of the file that is using this class
return SOMETHING;
}
?>
```
the magic FILE constant is not the correct one, it returns path/to/myClass.php | in case you need to get "test.php" see `$_SERVER['SCRIPT_NAME']` | I ended up using:
```
$file = basename(strtolower($_SERVER['SCRIPT_NAME']));
``` | Howto get filename from which class was included in PHP | [
"",
"php",
"include",
"filenames",
""
] |
I'm checking if two strings `a` and `b` are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:
```
sorted(a) == sorted(b)
```
and
```
all(a.count(char) == b.count(char) for char in a)
```
but the first one is slower when (for example) the first char of `a` is nowhere in `b`, and the second is slower when they are actually permutations.
Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common? | heuristically you're probably better to split them off based on string size.
Pseudocode:
```
returnvalue = false
if len(a) == len(b)
if len(a) < threshold
returnvalue = (sorted(a) == sorted(b))
else
returnvalue = naminsmethod(a, b)
return returnvalue
```
If performance is critical, and string size can be large or small then this is what I'd do.
It's pretty common to split things like this based on input size or type. Algorithms have different strengths or weaknesses and it would be foolish to use one where another would be better... In this case Namin's method is O(n), but has a larger constant factor than the O(n log n) sorted method. | Here is a way which is O(n), asymptotically better than the two ways you suggest.
```
import collections
def same_permutation(a, b):
d = collections.defaultdict(int)
for x in a:
d[x] += 1
for x in b:
d[x] -= 1
return not any(d.itervalues())
## same_permutation([1,2,3],[2,3,1])
#. True
## same_permutation([1,2,3],[2,3,1,1])
#. False
``` | Checking if two strings are permutations of each other in Python | [
"",
"algorithm",
"python",
""
] |
Is it possible to determine which submit button was used? I have a confirmation form with 2 submit buttons. The first would confirm the order, do some DB tasks, then redirect. The second, which is a Cancel button, will just redirect to the same page, without doing any DB tasks.
Is it possible in the servlet, preferably via the request object, to determine which submit button was used? I'd prefer not to be dependent on Javascript, as that is pretty simple, but will resort to it if the only possibility.
Thanks. | ```
<button name="someName" value="someValue" type="submit">Submit</button>
<button name="otherName" value="otherValue" type="submit">Cancel</button>
```
You'll have `someName=someValue` or `otherName=otherValue` in your request data | Sure, just give each of your `submit` buttons a `name` attribute, and whichever one was clicked will appear in the submitted variables:
```
<input type="submit" name="doConfirm" value="Confirm" />
<input type="submit" name="doCancel" value="Cancel" />
``` | Determining which submit button was used? | [
"",
"java",
"html",
"http",
"forms",
"servlets",
""
] |
I'm working on a project that uses an MDI application with a navigation panel on the side. Currently it is a ListView. However, I would like to redesign it to be similar to the toolbox in visual studio 2008.
If this is something that would require overriding the default paint method, it would also help if you could provide some good references on how to work with the paint method as I do not currently have any experience using it.
Thanks in advance. | You want to be using a ToolBox control. A few freely available ones are available the most friendly that i've used being by Gordon Robinson at: <http://gordondrobinson.com/post/Toolbox-control-written-in-C.aspx> | Have a look at the Nevron User Interface: <http://www.nevron.com/Products.UserInterfaceFor.NET.Overview.aspx> | Looking for a Visual Studio toolbox style navigation for desktop applications | [
"",
"c#",
".net-2.0",
"navigation",
"mdi",
""
] |
I know the question title isn't the best. Let me explain.
I do a TON of text processing which converts natural language to xml. These text files get uploaded fairly fast and thrown into a queue. From there they are pulled one-by-one into a background worker that calls our parser (using boost spirit) to transform the text into xml and load relevant portions into our db.
The parser can do about 100 of these at a time. I have rate-limiters on the background worker to only poll our queue every so often right now so it doesn't perform as fast. I can't throw up more than one background worker right now because my http requests start to drop -- the background worker and the webserver exist on the same machine and I *believe* it is because of cpu usage hitting 80-95%, although we could use more ram on it as well.
I need to scale this better. How would you go about doing it?
In answers to several questions:
* we use amazon web services so buying cheap extra hardware is a bit different from spawning a new amazon instance -- maybe somebody has done some code that autospawns instances on amount of load?
* we do have a http server that just stuffs our files into a queue so the only reason it would be affected is because the cpu is busy dealing with tons of parsing related stuff
* I already rate-limit our background workers, although we don't utilize that in the parser itself
* I haven't tried nice yet but I've used it in the past -- I need to write down some benchmarks on that
* the parser is completely seperate from the web server -- we have nginx/merb as our web/application server and a rake task calling c++ as our background worker -- yet they do exist on the same machine | I would buy a couple of cheap computers and do the text processing on those. As Jeff says in his [latest post](http://www.codinghorror.com/blog/archives/001198.html), "Always try to **spend your way out of a performance problem first** by throwing faster hardware at it." | Perhaps just placing the background worker at a lower scheduling priority (e.g. using [nice](http://en.wikipedia.org/wiki/Nice_(Unix))) would help. This means that your server can handle requests when it needs to, but when it's not busy you can go full blast with the text processing.
Methinks it will give you much more benefit than staggering the background worker arbitrarily. | How do I do lots of processing without gobbling cpu? | [
"",
"c++",
"ruby",
"memory",
"cpu",
"scaling",
""
] |
I'm trying to recreate the iPhone flick / scroll event in a window using JavaScript.
Starting with JQuery, I'm measuring the mouse's acceleration and offset during click - drag - release events using a timer:
```
var MouseY = {
init: function(context) {
var self = this;
self._context = context || window
self._down = false;
self._now = 0;
self._last = 0;
self._offset = 0;
self._timer = 0;
self._acceleration = 0;
$(self._context).mousedown(function() {self._down = true;});
$(self._context).mouseup(function() {self._down = false;});
$(self._context).mousemove(function(e) {self.move(e);});
},
move: function(e) {
var self = this;
self._timer++;
self._last = self._now;
self._now = e.clientY + window.document.body.scrollTop;
self._offset = self._now - self._last;
self._acceleration = self._offset / self._timer;
},
reset: function() {
this._offset = 0;
this._acceleration = 0;
this._timer = 0;
}
};
$(function() {
MouseY.init();
setInterval(function() {
$('#info').html(
'_acceleration:' + MouseY._acceleration + '<br />' +
'_now:' + MouseY._now + '<br />' +
'_offset:' + MouseY._offset + '<br />' +
'_timer:' + MouseY._timer + '<br />'
);
MouseY.reset();
}, 10);
});
```
Now the problem is translating that acceleration into screen movement - are there any algorithms (easing?) or animation libraries that could help me out on this? (I've looked into JQuery's .animate() but I'm unsure of how to apply it continuously during the drag events!
**Update - final solution here:**
<http://johnboxall.github.com/iphone.html> | Hit up this link for the full explanation of one approach that seems to be what you're looking for.
<http://www.faqts.com/knowledge_base/view.phtml/aid/14742/fid/53>
Here's an excerpt:
> This handler then sets up event
> capture for mouse movement and stores
> mouse cursor positions in variables
> mouseX and mouseY. It then starts the
> timer monitorMouse() which measures
> mouse cursor speed by sampling the
> values in these variables at regular
> intervals. The variables mouseLeft
> and mouseTop hold each samplings mouse
> positions and the sampling rate is
> set to 100 milliseconds in the
> variable monitor.timerDelay.
And some of the author's code:
```
nn4 = (document.layers)? true:false;
mouseLeft = mouseTop = mouseX = mouseY = 0;
monitor = {
timerDelay:100,
moveLimit:2,
sampleLimit:10
};
function startMonitor(thisText) {
if (!tip) return;
toolTipText = thisText;
writeTooltip(toolTipText);
document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = function (evt) {
mouseX = evt.pageX;
mouseY = evt.pageY;
return true;
}
monitorMouse();
}
function stopMonitor() {
if (!tip) return;
hideTooltip();
if (monitor.timer) {
clearTimeout(monitor.timer);
monitor.timer = null;
}
document.releaseEvents(Event.MOUSEMOVE);
document.onmousemove = null;
monitor.slowSamples = 0;
}
function monitorMouse() {
if (Math.abs(mouseX - mouseLeft) > monitor.moveLimit
|| Math.abs(mouseY - mouseTop) > monitor.moveLimit)
{
monitor.slowSamples = 0;
}
else if (++monitor.slowSamples > monitor.sampleLimit) {
showTooltip();
return;
}
mouseLeft = mouseX;
mouseTop = mouseY;
monitor.timer = setTimeout("monitorMouse()",monitor.timerDelay);
}
``` | Here's what I found when looking for kinetic/momentum scrolling libraries:
* [iScroll](http://cubiq.org/iscroll)
* [Zynga Scroller](https://github.com/zynga/scroller)
* [Overscroll](http://www.azoffdesign.com/plugins/js/overscroll)
* [TouchScroll](http://uxebu.com/blog/2010/09/15/touchscroll-0-2-first-alpha-available/)
* [jScrollTouch](http://plugins.jquery.com/project/jScrollTouch) | Javascript iPhone Scroll Effect in an iFrame / Javascript Mouse Acceleration | [
"",
"javascript",
"jquery",
"iphone",
"iframe",
"acceleration",
""
] |
I have the following code, which splits up a Vector into a string vector (to use as a key) and an integer at the end (to use as value).
```
payoffs.put(new Vector<String>(keyAndOutput.subList(0, keyAndOutput.size() - 1)), Integer.parseInt(keyAndOutput.lastElement()));
```
The TreeMap in question is constructed using a Comparator with the following method, which imposes a lexicographic, case independent ordering that also takes length into account (longer vectors are always "greater" than shorter ones).
```
public int compare(Vector<String> arg0, Vector<String> arg1) {
int sgn = 0;
if (arg0.size() > arg1.size()) {
return 1;
} else if (arg0.size() < arg1.size()) {
return -1;
}
for (int i = 0; i < arg0.size(); i++) {
if (arg0.elementAt(i).compareToIgnoreCase(arg1.elementAt(i)) == 1) {
sgn = 1;
break;
} else if (arg0.elementAt(i).compareToIgnoreCase(arg1.elementAt(i)) == -1) {
sgn = -1;
break;
} else {
continue;
}
}
return sgn;
}
```
Now, for the problem...despite having 8 entries in the text file this is being read from, the map only ever gets up to 2 entries. Once one entry (key) is entered, it STAYS, but the VALUE changes with every iteration of the scanning process (every time it reads in a new vector from a line in the file). It throws out all the other keys except for the two.
Is this a problem with my comparator? Or is the TreeMap doing something I don't understand with put()? | Answering Not answering the question, with but a couple minor points besides about your code:
1. You should not do the compareTo twice; compare once and assign the result to sgn; then break if !=0
2. Your else continue is redundant.
3. You should not compare for -1 or 1, but <0 or >0; many compareTo methods return based on (x1-x2), which can give any negative or positive number.
EDIT: Doh! And, of course, the return for String.compareToIgnoreCase() is one of those (3) comparators. As the other answer posted at the same time as mine pointed out, that will likely be the cause of your error.
EDIT2: Corrected opening statement to reflect question was actually answered. | I don't know if this is the cause of your problem, but compare functions in Java usually return negative or positive or 0, not necessarily 1 or -1.
I am willing to bet that you are somehow getting a nonzero value from compareToIgnoreCase, but because it's not 1 or -1 you fall through, and end up returning 0 even though the arrays are identical in length and not content. Try checking against >0 and <0
Also, you can organize this code better. For example, do one comparison, save the results, then switch on the results. This way you may be doing two expensive compares for nothing. | Strange behavior of Java's TreeMap put() method | [
"",
"java",
"collections",
"vector",
"treemap",
""
] |
I'm writing a component and would like to insert images from the template folder.
How do you get the correct path to the template folder? | IIRC, the $mainframe global object is eventually going away. Here is a way to do it through the framework:
```
$app = JFactory::getApplication();
$templateDir = JURI::base() . 'templates/' . $app->getTemplate();
``` | What kind of path...
On filesystem:
```
$templateDir = JPATH_THEMES.DS.JFactory::getApplication()->getTemplate().DS;
``` | How to get the path to the current template in Joomla 1.5? | [
"",
"php",
"joomla",
"joomla1.5",
""
] |
I'm currently searching for a Java networking library. What I want to do is sending XML, JSON or other serialized messages from a client to another client and/or client to server.
My first attempt was to create an POJO for each message, plus a MessageWriter for sending and a MessageReader for receiving it. Plus socket and error handling. Which is quite a lot of error prone work.
What I'm looking for is a a higher level library which abstracts from sockets. Furthermore it should supports something like code generation for the messages.
Google's Protocol Buffers (<http://code.google.com/apis/protocolbuffers/>) looks promising. But are there alternatives? The emphasis is not on speed or security (at the moment), it is just supposed to work reliable and with a low amount of implementation time. | Ah... gotcha.
But rather than using code gen. to marshall and unmarshall, if you have Java on both ends, could you use simple object serialization ? If performance and/or message size is a concern, you could make your Message class externalizable.
I had not looked at Protobuf before. Looks pretty decent. Using that, you would then just need a transmission method. | You have several options depending on how abstracted from raw sockets you want to get. Once you depart from socket level programming, you're pretty much into *remoting* territory,
* Standard Remoting Options for Java: RMI or JMS
* Implement JMX Mbeans in each client and the servers and use JMX remoting to invoke message passing operations.
* If you think you might want to use multicast, I would definitely check [JGroups](http://www.jgroups.org/javagroupsnew/docs/index.html).
* If you're looking to create your own protocol but want to use some existing building blocks, check out [Jakarta Commons Net](http://commons.apache.org/proper/commons-net/). The **HttpClient** referenced in Answer #1 has been incorporated into this package.
* There are also some interesting proprietary messaging systems that have the added virtue of supporting multiple platforms/languages such as [Spread](http://www.spread.org) and [DBus](http://www.freedesktop.org/wiki/Software/dbus).
* Can't enumerate remoting options without mentioning WebServices.... but.... **blech!**
I am not completely sure what you mean by *code generation for the messages*. Can you elaborate ? | Is there a good Java networking library? | [
"",
"java",
"networking",
"serialization",
""
] |
As I understand the standard, a trivial destructor is one which is implicitly declared and whose class has only base and non-static members with trivial destructors.
Given the recursivity of this definition, it seems to me that the only "recursion-stopping" condition is to find a base or non-static member with a non-implicitly declared destructor (i.e. user declared).
If that's right, that should mean that a trivial destructor is one which "doesn't have to do anything" and hence it will be declared (implicitly) but not defined.
Saying it in another way: is it correct to say that an implicitly *defined* destructor (that is "it does something") cannot be trivial as per the standard definition?
Sorry for the kind of silly question, but I'd like to clarify things a bit in my head... | No. An implicitly defined, trivial destructor is by definition trivial :) The difference between the declare and define thingy is that in order for the compiler to even *see* that a destructor is available, there must always a declaration. So if you don't provide one, it will implicitly provide one.
But now, it will also define one, if that is needed (if an object of that class type is destroyed). In any case, it has to do something: It needs to call the destructors of all its members and base classes. A simple example which illustrates the effect of implicitly defining a destructor:
```
struct a {
private:
~a();
};
struct bug {
// note: can't be destructed
a a_;
};
```
As soon as you try to create a local object of bug, the compiler will signal an error, because it yields a definition of a destructor for bug, which tries to call the not accessible destructor of a.
Now, i think triviality of destructors/constructors are mostly used to put constraints on your program. Objects having non-trivial versions of them can't be put in unions, for example. On the other side, you can delete an object having incomplete type, provided it has a trivial destructor. Note that if your program can't decide whether or not a trivial destructor was actually defined, the compiler is allowed to omit defining it. That's the so-called `as-if` rule. The compiler has to behave as-if it's Standard compliant - optimizations do not matter as long as they don't change the meaning of a program. | Your wording is a bit unfortunate. E.g. the recursion of course also ends when you run out of members and base classes. Those wording problems also seem to get you more confused.
Anyway, all implicitly-declared destructors, whether they are trivial or not, are defined if and only if they are used. *Used* is a specific term here. A destructor of type T is *used* whenever the lifetime of a T object ends.
Trivial destructors exist because C programmers put structs in unions. This code should remian legal in C++, so the notion of a trivial destructor was invented for C++. All C structs have trivial destructors, when compiled as C++. | destructors: triviality vs implicit definition | [
"",
"c++",
"destructor",
""
] |
I have been noticing `__construct` a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP.
I was wondering if someone could give me a general idea of what it is, and then a simple example of how it is used with PHP? | `__construct` was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor).
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.
An example could go like this:
```
class Database {
protected $userName;
protected $password;
protected $dbName;
public function __construct ( $UserName, $Password, $DbName ) {
$this->userName = $UserName;
$this->password = $Password;
$this->dbName = $DbName;
}
}
// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );
```
Everything else is explained in the PHP manual: [click here](http://php.net/manual/en/language.oop5.decon.php) | `__construct()` is the method name for the [constructor](https://www.php.net/manual/en/language.oop5.decon.php). The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc.
```
class Person {
public function __construct() {
// Code called for each new Person we create
}
}
$person = new Person();
```
A constructor can accept parameters in the normal manner, which are passed when the object is created, e.g.
```
class Person {
public $name = '';
public function __construct( $name ) {
$this->name = $name;
}
}
$person = new Person( "Joe" );
echo $person->name;
```
Unlike some other languages (e.g. Java), PHP doesn't support overloading the constructor (that is, having multiple constructors which accept different parameters). You can achieve this effect using static methods.
**Note**: I retrieved this from the log of the (at time of this writing) accepted answer. | What is the function __construct used for? | [
"",
"php",
"constructor",
""
] |
If I use null as a representation of everything in a database table is that bad practice ?
i.e.
I have the tables: myTable(ID) and myRelatedTable(ID,myTableID)
myRelatedTable.myTableID is a FK of myTable.ID
What I want to accomplish is: if myRelatedTable.myTableID is null then my business logic will interpret that as being linked to all myTable rows.
The reason I want to do this is because I have an uknown amount of rows that could be inserted into myTable after the myRelatedTable row is created and some rows in the myRelatedTable need to reference all existing rows in myTable. | I don't think NULL is the best way to do it but you might use a separate tinyInt column to indicate that the row in MyRelatedTable is related to everything in MyTable, e.g. MyRelatedTable.RelatedAll. That would make it more explicit for other that have to maintain it. Then you could do some sort of Union query e.g.
```
SELECT M.ID, R.ID AS RelatedTableID,....
FROM MyTable M INNER JOIN MyRelated Table R ON R.myTableId = M.Id
UNION
SELECT M.ID, R.ID AS RelatedTableID,....
FROM MyTable M, MyRelatedTable R
WHERE R.RelatedAll = 1
``` | I think you might agree that it would be bad to use the number **3** to represent a value other an **3**.
By the same reasoning it is therefore a bad idea to use NULL to represent anything other than the absence of a value.
If you disagree and twist NULL to some other purpose, the maintenance programmers that come after you will not be grateful. | Is using Null to represent a Value Bad Practice? | [
"",
"sql",
"database-design",
""
] |
I wish to create a very simple web app that simply displays an Image(s) from a database based upon either a date (from a calendar click event) or from a keyword search, getting the image(s) is no problem but I don't know how to display the resulting image. Preferably I would like to display the image in a table or grid or whatever, adjacent to the Calendar and TextBox on the same page that I used to get the search critera
So how to I stream an image to a page from a codebehind bitmap variable ?
Edit:
The database is a cloud database, so databinding is out. | Take a look at the DynamicImageHandler for ASP.NET up on the CodePlex ASP.NET Futures site:
<http://www.hanselman.com/blog/ASPNETFuturesGeneratingDynamicImagesWithHttpHandlersGetsEasier.aspx> | If you don't have the physical file on hand, try using:
`Response.OutputStream.Write(bitmapbuffer, bitmapbuffer.Length)`
I've done this in the past to dynamically serve pdfs and tifs, and it works quite nicely. You'll need to set your img's src attribute to contain the information you need. This web site has an example close to what you are looking for:
<http://www.jigar.net/articles/viewhtmlcontent3.aspx> | displaying an image from a bitmap variable using codebehind | [
"",
"c#",
"asp.net",
"image",
"code-behind",
""
] |
I find it funny that Java (or the java.util library) does not have a built-in function to calculate difference in dates. I want to subtract one date from another to get the elapsed time between them. What is the best way to do this?
I know the simple way is to take the difference of the time in milliseconds and then convert that into days. However, I wanted to know if this works in all cases (with daylight saving, etc.). | > I know the simple way is to take the
> difference of the time in milliseconds
> and then convert that into days.
> However, i wanted to know if this
> works in all cases (with daylight
> saving, etc.).
If your times are derived from UTC dates, or they are just the difference between two calls to System.getCurrentTimeMillis() measured on the same system, you will get a valid number of milliseconds as the difference, independent of any timezone issues. (which is why everything should be using UTC as a storage format -- it's much easier to go from UTC->local time; if you try to go the other way then you need to store the local timezone along with the local time -- or attempt to infer it, gack!)
As for turning this into a number of days, you should just be able to divide by 86400000... with the caveat that there is an occasional [leap second](http://en.wikipedia.org/wiki/Leap_second) every other year or so. | Java's not missing much, if you look at open source: try [Joda-Time](http://www.joda.org/joda-time/). | Calculating difference in dates in Java | [
"",
"java",
"date",
"datetime",
"date-arithmetic",
""
] |
I've got a small app that searches for and stores the names of a large number of files at start-up. I'm splitting this search into several Thread objects that each search one directory, and push results back to the main thread.
When the app loads, I go through each thread and load it:
```
foreach(Thread t in m_threads)
{
t.Start();
while(!t.IsAlive){}
}
```
When I begin this app in the debugger, it loads and the threads quickly find all the files. However if I start outside the debugger it freezes. Attaching the debugger to the process I can see that IsAlive never returns true.
I'm new to C# threading so does anyone have any idea what's going wrong, or how I can more easily debug what's happening? | It may not be exactly related to why things are freezing, but your implementation is quite questionable. You enumerate over a collection of threads, start each one, but then block until the thread is finished? I think what you may have meant to do is start all threads, then block until all threads have finished. (Note: This is assuming you meant to write: "*while(t.IsAlive) {}*", since waiting for the thread to start makes even less sense.)
As for the freezing, we may need to see the rest of the code. Since you said you are new to C# threading, and looking at what you did above, I am assuming you are also new to threading, which means there could be many places that a problem can rise. | The thread may have finished processing before your check against IsAlive.
WHy are you waiting by checking the IsAlive flag anyway?
Why not, instead, fire up all the threads, then in another loop, call [Join()](http://msdn.microsoft.com/en-us/library/system.threading.thread.join.aspx) to wait for the threads to finish? No need to check "IsAlive".
Even better, why not use the ThreadPool instead of firing up a stack of threads yourself? | c# thread starts from debugger, but won't start stand-alone | [
"",
"c#",
"multithreading",
""
] |
The current class library I am working on will have a base class (Field) with over 50 specific "field" types which will inherit from "Field" and nested for maintain readability. For example...
```
abstract class Field
{
public int Length { get; set; }
public class FieldA : Field
{
public static void DoSomething()
{
Console.WriteLine("Did something.");
}
}
}
```
So far everything looks good and I can use the code as shown:
```
class Program
{
static void Main(string[] args)
{
Field.FieldA.DoSomething();
}
}
```
However, why does this work as well? What is going on here that allows the compiler / IDE intellisense to continue to chain these "FieldA"'s?
```
class Program
{
static void Main(string[] args)
{
Field.FieldA.FieldA.FieldA.FieldA.FieldA.FieldA.FieldA.DoSomething();
}
}
```
It's not application breaking by any means, but thought it was peculiar. Does the same thing in Boo (which is the actual language being used for the library). | Sounds like you wanted something like:
```
abstract class Field
{
public int Length { get; set; }
}
public class FieldA : Field
{
public static void DoSomething()
{
Console.WriteLine("Did something.");
}
}
```
Otherwise you're defining a base class with an inner class in it, which inheritorrs will also get. So when you inherit from the outer class to make the inner class, you're starting a loop. | 1. `Field` has a *public* nested-class named `FieldA`
2. `FieldA` inherits from `Field`
3. thus you can always access `FieldA` from `FieldA`.
The reference isn't creating infinite chains, it is simply pointing to the same class. ([some test code](http://pastebin.com/f6d5f0e5f))
When you access `FieldA.FieldA`, the latter `FieldA` is accessible due to the fact that the former `FieldA` is an instance of `Field` so the latter `FieldA` actually access `Field.FieldA` | .NET Nested Classes | [
"",
"c#",
".net",
"boo",
"nested-class",
"class-structure",
""
] |
I have some AJAX work that brings across an additional form element that I don't need in the DOM. I don't have the ability to remove it server side, so I'm looking for some jQuery or classic JavaScript that will allow me to capture all the child elements of the form, remove the form I don't need and finally re-append the child elements back to the DOM.
Any help would be much appreciated
EDIT: Thanks for the quick answers, the below is what I actually used and it works perfect
```
// Captures the children
var children = $("form:eq(1)").children();
// Removes the form
$("form:eq(1)").remove();
// append the child elements back into the DOM
$("#fillDiv").append(children);
``` | Rather than using the `.html()` method (which will cause you to lose any events associated with form elements) you should move the child nodes:
```
// grab the child nodes
var children = $('#badForm').children();
// or var children = $('#badForm > *');
// move them to the body
$(body).append(children);
// remove the form
$('#badForm').remove();
``` | If you have ajax code like this:
```
$.ajax({
type: "get",
url: "url",
data: ,
cache: false,
success: function(data){
}
});
```
You can add on `success` function this:
```
$(data).find('#whatYouNeed').appendTo('#whereYouNeed')
```
In this way you can extract anything you want from that page :) | Using jQuery to remove a second form element without losing the child elements | [
"",
"javascript",
"jquery",
""
] |
What's difference between **shadowing** and **overriding** a method in C#? | Well inheritance...
suppose you have this classes:
```
class A {
public int Foo(){ return 5;}
public virtual int Bar(){return 5;}
}
class B : A{
public new int Foo() { return 1;} //shadow
public override int Bar() {return 1;} //override
}
```
then when you call this:
```
A clA = new A();
B clB = new B();
Console.WriteLine(clA.Foo()); // output 5
Console.WriteLine(clA.Bar()); // output 5
Console.WriteLine(clB.Foo()); // output 1
Console.WriteLine(clB.Bar()); // output 1
//now let's cast B to an A class
Console.WriteLine(((A)clB).Foo()); // output 5 <<<-- shadow
Console.WriteLine(((A)clB).Bar()); // output 1
```
Suppose you have a base class and you use the base class in all your code instead of the inherited classes, and you use shadow, it will return the values the base class returns instead of following the inheritance tree of the real type of the object.
[Run code here](https://dotnetfiddle.net/ApUlvE)
Hope I'm making sense :) | Shadowing is actually VB parlance for what we would refer to as hiding in C#.
Often hiding (shadowing in VB) and overriding are shown as in answer by [Stormenet](https://stackoverflow.com/users/2090/stormenet).
A virtual method is shown to be overridden by a sub-class and calls to that method even on the super-class type or from inside code of the super-class will call the replacement implementation from the sub-class.
Then a concrete method is shown (one not marked as virtual or abstract) being hidden by using the `new` keyword when defining a method with an identical signature on the sub-class. In this case when the method is called on the super-class type the original implementation is used, the new implementation is only available on the sub-class.
However what is often missed is that it is also possible to hide a virtual method.
```
class A
{
public virtual void DoStuff() { // original implementation }
}
class B : A
{
public new void DoStuff() { //new implementation }
}
B b = new B();
A a = b;
b.DoStuff(); //calls new implementation
a.DoStuff(); //calls original implementation.
```
Note in the above example DoStuff becomes concrete and can not be overriden. However it is also possible to use both the `virtual` and `new` keywords together.
```
class A
{
public virtual void DoStuff() { // original implementation }
}
class B : A
{
public new virtual void DoStuff() { //new implementation }
}
class C : B
{
public override void DoStuff() { //replacement implementation }
}
C c = new C();
B b = c;
A a = b;
c.DoStuff(); //calls replacement implementation
b.DoStuff(); //calls replacement implementation
a.DoStuff(); //calls original implementation.
```
Note that despite all the methods involved being virtual, the override on C does not affect the virtual method on A because of the use of `new` in B hides the A implementation.
**Edit:** Its been noted in the comments to this answer that the above may be dangerous or at least not particularly useful. I would say yes it can be dangerous and would be out there if it were at all useful.
In particular you could get into all sorts of trouble if you also change the accessability modifiers. For example:-
```
public class Foo
{
internal Foo() { }
protected virtual string Thing() { return "foo"; }
}
public class Bar : Foo
{
internal new string Thing() { return "bar"; }
}
```
To an external inheritor of `Bar`, `Foo`'s implementation of Thing() remains accesible and overridable. All legal and explainable according to .NET type rules neverless quite unintuative.
I've posted this answer to deepen an understanding of how things work not as a suggestion of techniques that can be used freely. | Difference between shadowing and overriding in C#? | [
"",
"c#",
""
] |
I have been testing out the `yield return` statement with some of the code I have been writing. I have two methods:
```
public static IEnumerable<String> MyYieldCollection {
get
{
wrapper.RunCommand("Fetch First From Water_Mains");
for (int row = 0; row < tabinfo.GetNumberOfRows() ; row++) //GetNumberOfRows
//will return 1000+ most of the time.
{
yield return wrapper.Evaluate("Water_Mains.col1");
wrapper.RunCommand("Fetch Next From Water_Mains");
}
}
}
```
and
```
public static List<String> MyListCollection
{
get
{
List<String> innerlist = new List<String>();
wrapper.RunCommand("Fetch First From Water_Mains");
for (int row = 0; row < tabinfo.GetNumberOfRows(); row++)
{
innerlist.Add(wrapper.Evaluate("Water_Mains.col1"));
wrapper.RunCommand("Fetch Next From Water_Mains");
}
return innerlist;
}
}
```
then I use a `foreach` loop over each collection:
```
foreach (var item in MyYieldCollection) //Same thing for MyListCollection.
{
Console.WriteLine(item);
}
```
The funny thing is for some reason I seem to be able to loop over and print out the full `MyListCollection` faster then the MyYieldCollection.
Results:
* MyYieldCollection -> 2062
* MyListCollection -> 1847
I can't really see a reason for this, am I missing something or is this normal? | How have you done your timings? Are you in the debugger? In debug mode? It looks like you are using `DataTable`, so I used your code as the template for a test rig (creating 1000 rows each time), and used the harness as below, in release mode **at the command line**; the results were as follows (the number in brackets is a check to see they both did the same work):
```
Yield: 2000 (5000000)
List: 2100 (5000000)
```
Test harness:
```
static void Main()
{
GC.Collect(GC.MaxGeneration,GCCollectionMode.Forced);
int count1 = 0;
var watch1 = Stopwatch.StartNew();
for(int i = 0 ; i < 5000 ; i++) {
foreach (var row in MyYieldCollection)
{
count1++;
}
}
watch1.Stop();
GC.Collect(GC.MaxGeneration,GCCollectionMode.Forced);
int count2 = 0;
var watch2 = Stopwatch.StartNew();
for (int i = 0; i < 5000; i++)
{
foreach (var row in MyListCollection)
{
count2++;
}
}
watch1.Stop();
Console.WriteLine("Yield: {0} ({1})", watch1.ElapsedMilliseconds, count1);
Console.WriteLine("List: {0} ({1})", watch2.ElapsedMilliseconds, count2);
}
```
(note you shouldn't normally use `GC.Collect`, but it has uses for levelling the field for performance tests)
The only other change I made was to the `for` loop, to avoid repetition:
```
int rows = tabinfo.Rows.Count;
for (int row = 0; row < rows; row++) {...}
```
So I don't reproduce your numbers... | What happens if one iteration of your loop is expensive and you only need to iterate over a few items in your collection?
With yield you only need to pay for what you get ;)
```
public IEnumerable<int> YieldInts()
{
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(1000) // or do some other work
yield return i;
}
}
public void Main()
{
foreach(int i in YieldInts())
{
Console.WriteLine(i);
if(i == 42)
{
break;
}
}
}
``` | Why is my IEnumerable<String> using yield return slower to iterate then List<String> | [
"",
"c#",
"ienumerable",
""
] |
For web development what are some standard/good java tools. That apply to all aspects of development.
For example, The IDE (Eclipse, RAD, Intellij) is important, but what else is there.
Ant is a good one.
Cygwin, Linux OS possibly. | Another good IDE for Java web development I use is [Netbeans](http://www.netbeans.org/). Has many useful features version control, debugger, profiler, api access etc ...
You can edit, build, test, and run all inside of the IDE. | Before trying to write a piece of code check if it is implemented in some library. Great source of common programming task solutions can be found in [Apache Commons libraries](http://commons.apache.org). | What are some good Java web development tools (across the board) | [
"",
"java",
""
] |
Consider this code (Java, specifically):
```
public int doSomething()
{
doA();
try {
doB();
} catch (MyException e) {
return ERROR;
}
doC();
return SUCCESS;
}
```
Where `doB()` is defined as:
```
private void doB() throws MyException
```
Basically, `MyException` exists only in case `doB()` meets some condition (which is not catastrophic, but does need to somehow raise this condition) so that `doSomething()` will know to exit with an error.
Do you find the use of an exception, in this case to control flow, acceptable? Or is this a code smell? If so, how would you refactor this? | It entirely depends on what that error condition is, and what the method's job is. If returning `ERROR` is a valid way of handling that error for the calling function, why would it be bad?
Often, however, it *is* a smell. Consider this:
```
bool isDouble(string someString) {
try {
double d = Convert.ParseInt32(someString);
} catch(FormatException e) {
return false;
}
return true;
}
```
That is a very big code smell, because you don't expect a double value. You just want to know whether a string contains a double.
Sometimes, the framework you use doesn't have other ways of doing what you want. For the above, there is a better way:
```
bool isDouble(string someString) {
bool success;
Convert.TryParseInt32(someString, ref success);
return success;
}
```
Those kinds of exceptions have a special name, coined by someone whose blog I read recently, but sadly, I forgot its name. Please comment if you know it. Last but not least, the above is pseudocode. I'm not a C# developer so the above doesn't compile, I'm sure, but `TryParseInt32` / `ParseInt32` demonstrates that well I think, so I'm going with C#.
Now, to your code. Let's inspect two functions. One smells, and the other doesn't:
### 1. Smell
```
public int setupSystem() {
doA();
try { doB(); }
catch (MyException e)
{ return ERROR; }
doC();
return SUCCESS;
}
```
That's a *code smell*, because when you want to setup a system, you don't want it to fail. Failing to setup a system means you can't continue without handling that error.
### 2. OK
```
public int pingWorkstation() {
doA();
try { doB(); }
catch (MyException e)
{ return ERROR; }
doC();
return SUCCESS;
}
```
That is OK, because the purpose of that method is to test whether the workstation is still reachable. If it's not, then that is part of the result of that method, and not an exceptional case that needs an alternative return path. | Is it really important for doC() to be executed when doB() fails? If not, why not simply let the Exception propagate up the stack to where it can be handled effectively. Personally, I consider using error codes a code smell.
**Edit:** In your comment, you have described exactly the scenarion where you should simply declare
```
public void doSomething() throws MyException
``` | Throwing exceptions to control flow - code smell? | [
"",
"java",
"exception",
""
] |
I'm aware of the risks of rolling your own user authentication scripts, but I'm also wary of using packages that don't seem to be actively maintained: the [current version of PEAR LiveUser](http://pear.php.net/package/LiveUser/download/) is almost a year old.
Please recommend (and argue the case for) an actively-maintained user-authentication library which can be integrated into an existing web project. It should ideally support various roles - anonymous users, registered users and administrators at various levels. | It looks to me like PEAR hasn't changed much because it's stable. I wouldn't be afraid of using it. | It sounds like what you want is a user control library, rather than an authentication library.
For example, in the [Zend Framework](http://framework.zend.com) there are two classes: [`Zend_Auth`](http://framework.zend.com/manual/en/zend.auth.html) (which handles user authentication: logins (e.g. [simple database tables](http://framework.zend.com/manual/en/zend.auth.adapter.dbtable.html) to [OpenID](http://framework.zend.com/manual/en/zend.auth.adapter.openid.html))) and [`Zend_Acl`](http://framework.zend.com/manual/en/zend.acl.html) (which handles the user access side of things).
I quite like the ZF classes - I haven't tried using them outside of a ZF project but most of their classes can so give it a try. Even if you decide to build your own they'd be useful for reference. | Actively maintained PHP libraries for user authentication? | [
"",
"php",
"security",
"authentication",
""
] |
I am working on my first project using ExtJS.
I have a Data Grid sitting inside a Tab that is inside a Window.
I want to add a link or button to the each element of the grid (I am using extended elements at the moment with HTML content through the RowExpander) that will make an AJAX call and open another tab. | I actually worked this out in the end. Pretty convoluted, and let's just say I will not be involving myself with ExtJS again if I can help it.
I am using the Grid.RowExpander to place HTML inside the Grid using XTemplate.
My links are therefore fairly straight forward:
```
<a href="#" class="add_cart_btn" id="{product_id}" onclick="return false;">Add to Cart</a>
```
Where {product\_id} is from JSON data loaded from an Ajax query. This is important, as you will see below.
Finding these events is much more difficult ... the Grid can tell you the row, but I actually needed to grab elements from a table inside the grid row. Long story, but I inherited some of this code.
Then in my parent component I have attached an event to the Grid itself.
```
this.on({
click :{scope: this, fn:this.actionGridClick}
});
```
To find the actual link, I search for the link in the target that has the correct class. In this case "add\_cart\_btn"
```
actionGridClick:function(e) {
// Looking for a click on a cart button
var addCartEl = Ext.get(e.getTarget('.add_cart_btn'));
if(addCartEl) {
productID = addCartEl.id;
// Once we have the ID, we can grab data from the data store
// We then call to the server to complete the "add to cart" functionality
}
}
```
Mpst of this is not very helpful except in my case, but it's here for posterity if anyone needs something similar in the future. | If you are looking to add the link to the grid itself, you can specify another column in your ColumnModel and apply a renderer to the column. The function of the renderer is to return formatted content to be applied to that cell, which can be tailored according to the value of the dataIndex of the column (you should have a dataIndex, even if it is a duplicate of another column), and the record of that row.
```
function myRenderer(value,meta,record,rowIndex,colIndex,store){
// Do something here
}
```
Your link might have a click event to call a method, opening another tab
```
function myClickEvent(value1, value2){
var myTabs = Ext.getCmp('myTabPanel');
myTabs.add(// code for new tab);
}
```
If you're adding the links to your expanded area, within the RowExpander, then you'll have to write the rendering into the Template you're using for your expanded content area. | ExtJS: AJAX Links in Grid in Tab in Window | [
"",
"javascript",
"extjs",
""
] |
I rewrite URLs to include the title of user generated travelblogs.
I do this for both readability of URLs and SEO purposes.
```
http://www.example.com/gallery/280-Gorges_du_Todra/
```
The first integer is the id, the rest is for us humans (but is irrelevant for requesting the resource).
Now people can write titles containing any UTF-8 character, but most are not allowed in the URL.
My audience is generally English speaking, but since they travel, they like to include names like
```
Aït Ben Haddou
```
What is the proper way to translate this for displaying in an URL using PHP on linux.
So far I've seen several solutions:
1. just strip all non allowed characters, replace spaces
this has strange results:
`'Aït Ben Haddou' → /gallery/280-At_Ben_Haddou/`
Not really helpfull.
2. just strip all non allowed characters, replace spaces, leave charcode (stackoverflow.com) most likely because of the 'regex-hammer' used
this gives strange results:
`'tést tést' → /questions/0000/t233st-t233st`
3. translate to 'nearest equivalent'
`'Aït Ben Haddou' → /gallery/280-Ait_Ben_Haddou/`
But this goes wrong for german; for example 'ü' should be transliterated 'ue'.
For me, as a Dutch person, the 3rd result 'looks' the best.
I'm quite sure however that (1) many people will have a different opinion and (2) it is just plain wrong in the german example.
Another problem with the 3rd option is: how to find all possible characters that can be converted to a 7bit equivalent?
So the question is:
1. what, in your opinion, is the most desirable result. (within tech-limits)
2. How to technically solve it. (reach the desired result) with PHP. | Ultimately, you're going to have to give up on the idea of "correct", for this problem. Translating the string, no matter how you do it, destroys accuracy in the name of compatibility and readability. All three options are equally compatible, but #1 and #2 suffer in terms of readability. So just run with it and go for whatever looks best — option #3.
Yes, the translations are wrong for German, but unless you start requiring your users to specify what language their titles are in (and restricting them to only one), you're not going to solve that problem without far more effort than it's worth. (For example, running each word in the title through dictionaries for each known language and translating that word's diacritics according to the rules of its language would *work*, but it's excessive.)
Alternatively, if German is a higher concern than other languages, make your translation *always* use the German version when one exists: `ä`→`ae`, `ë`→`e`, `ï`→`i`, `ö`→`oe`, `ü`→`ue`.
**Edit:**
Oh, and as for the actual method, I'd translate the special cases, if any, via `str_replace`, then use `iconv` for the rest:
```
$text = str_replace(array("ä", "ö", "ü", "ß"), array("ae", "oe", "ue", "ss"), $text);
$text = iconv('UTF-8', 'US-ASCII//TRANSLIT', $text);
``` | To me the third is most readable.
You could use a little dictionary e.g. `ï -> i` and `ü -> ue` to specify how you'd like various charcaters to be translated. | How to handle diacritics (accents) when rewriting 'pretty URLs' | [
"",
"php",
"url-rewriting",
"diacritics",
""
] |
I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv. What's the quickest way to get something up? If it affects your suggestion, I will likely be adding more functionality to this, down the road. | Have a look at [werkzeug](http://werkzeug.pocoo.org/). Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.
It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod\_wsgi or with a plain simple python server for debugging). | [web.py](http://webpy.org/) is probably the simplest web framework out there. "Bare" CGI is simpler, but you're completely on your own when it comes to making a service that actually does something.
"Hello, World!" according to web.py isn't much longer than an bare CGI version, but it adds URL mapping, HTTP command distinction, and query parameter parsing *for free*:
```
import web
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name:
name = 'world'
return 'Hello, ' + name + '!'
if __name__ == "__main__":
app.run()
``` | Best way to create a simple python web service | [
"",
"python",
"web-services",
""
] |
I understand that const\_cast to remove constness of objects is bad,
I have the following use case,
```
//note I cannot remove constness in the foo function
foo(const std::vector<Object> & objectVec) {
...
int size = (int) objectVec.size();
std::vector<Object> tempObjectVec;
//Indexing here is to just show a part of the vector being
//modified
for (int i=0; i < (int) size-5; ++i) {
Object &a = const_cast<Object&> objectVec[i];
tempObjectVec.push_back(a);
}
foo1(tempObjectVec);
}
```
If i change tempObjectVec objects in foo1, will the original objects in ObjectVec change, I say yes since I am passing references, further is this efficient. Can you suggest alternatives. | Well, that depends on Object. But the Objects *are* being copied, when you pass them to push\_back. You can check this by adding some debug code to the copy constructor. So if Object is well-behaved and keeps distinct copies separate, then foo1 can change the vector it gets all it likes.
A more efficient way to do this would be to have foo1 accept a start and end iterators:
```
void foo1(std::vector<Object>::const_iterator start,
std::vector<Object>::const_iterator end);
...
foo1(objectVec.begin(), objectVec.end() - 5);
```
If you don't use const\_cast, then the type system will ensure that foo1 does not change any elements, as these are const\_iterators. | Your `tempObjectVec` can't be a vector of references, so I presume it should be declared as something like:
```
std::vector<Object> tempObjectVec;
```
When you execute the `tempObjectVec.push_back(a)`, a copy of the object will be made to push it into the `tempObjectVec` vector. Since this is making a copy, you shouldn't even need to use the `const_cast` to remove the constness, I'm not clear on why you needed to do that. | const_cast for vector with object | [
"",
"c++",
""
] |
Is it possible to call a [VBScript](http://en.wikipedia.org/wiki/VBScript) function from a [JavaScript](http://en.wikipedia.org/wiki/JavaScript) call, or alternately call JavaScript from a VBScript call? | Yes, if your main script is a [Windows Script File](http://msdn.microsoft.com/en-us/library/15x4407c.aspx) (WSF).
WSF files can include other script files and execute code from multiple engines. | **Calling a VBScript function from Javascript**
Your VBScript:
```
Function myVBFunction()
' here comes your vbscript code
End Function
```
Your Javascript:
```
function myJavascriptFunction(){
myVBFunction(); // calls the vbs function
}
window.onload = myJavascriptFunction;
```
**Calling a Javascript function from VBScript**
```
Function myVBFunction()
myJavascriptFunction()
End Function
``` | Calling VBScript from JavaScript or vice versa? | [
"",
"javascript",
"asp-classic",
"vbscript",
""
] |
in terms of both parsing (serializing, deserializing) and sending packets over the network is there any good estimation of performance differences between binary and xml serialization? | Nope.
It depends highly on what sort of data is inside the XML document itself. If you have a lot of structured data, the overhead for XML will be large. For example, if your data looks like:
```
<person>
<name>Dave</dave>
<ssn>000-00-0000</ssn>
<email1>xxxxxx/email1>
</person>
...
```
You'll have a lot more overhead than if you have an XML document that looks like:
```
<book name="bible">
In the beginning God created the heavens and the earth.
Now the earth was formless and empty ...
And if any man shall take away from the words of the book of this prophecy, God shall take away his part out of the book of life, and out of the holy city, and from the things which are written in this book. He which testifieth these things saith, Surely I come quickly. Amen. Even so, come, Lord Jesus.
</book>
```
So it's not really a fair question. It depends highly on the data YOU intend to send, and how/if you're compressing it. | The biggest difference between `BinaryFormatter` and xml serialization is portability; BinaryFormatter is hard to guarantee between versions, so is only really suitable for shortterm storage or transfer.
However, you can get the best of both, *and* have it smaller *and* have it quicker, by using bespoke binary serialization - and you don't even have to do it yourself ;-p
[protobuf-net](http://code.google.com/p/protobuf-net/) is a .NET implementation of Google's protocol buffers binary serialization spec; it is smaller than either `XmlSerializer` or `BinaryFormatter`, *fully* portable (not just between versions - you can load a pb stream in, for example, java, etc), extensible, and fast. It is also pretty comprehensively tested, with a fair number of users.
A full breakdown of size and speed, covering `XmlSerializer`, `BinaryFormatter`, `DataContractSerializer` and protobuf-net is [here](http://code.google.com/p/protobuf-net/wiki/Performance). | Is there any perfomormance differences between binary and XML serialization? | [
"",
"c#",
"xml",
"binary-data",
""
] |
I often use an `ArrayList` instead of a 'normal' `array[]`.
I feel as if I am cheating (or being lazy) when I use an `ArrayList`, when is it okay to use an `ArrayList` over an array? | Arrays are strongly typed, and work well as parameters. If you know the length of your collection and it is fixed, you should use an array.
ArrayLists are not strongly typed, every Insertion or Retrial will need a cast to get back to your original type. If you need a method to take a list of a specific type, ArrayLists fall short because you could pass in an ArrayList containing any type. ArrayLists use a dynamically expanding array internally, so there is also a hit to expand the size of the internal array when it hits its capacity.
What you really want to use is a generic list like `List<T>`. This has all the advantages of Array and ArrayLists. It is strongly typed and it supports a variable length of items. | In addition to Bob's and Frederick's response, I would like to point it out that while arrays have covariance, generic lists do not. For example, an array of type `MyChildClass[]` can be easily casted to `MyParentClass[]`, while `List<MyChildClass>` cannot be casted to `List<MyParentClass>`, at least not directly.
If you need covariance, either use arrays, use LINQ's Cast() method or some other means to cast each item individually ~~or wait for C# 4~~. | When to use ArrayList over array[] in c#? | [
"",
"c#",
"arrays",
"arraylist",
""
] |
Years ago I learned the hard way about precision problems with floats so I quit using them. However, I still run into code using floats and it make me cringe because I know some of the calculations will be inaccurate.
So, when is it appropriate to use a float?
**EDIT:**
As info, I don't think that I've come across a program where the accuracy of a number isn't important. But I would be interested in hearing examples. | Short answer: You only have to use a **float** when you know exactly what you're doing and why.
Long answer: **floats** (as opposed to **doubles**) aren't really used anymore outside 3D APIs as far as I know. Floats and doubles have the same performance characteristics on modern CPUs, doubles are somewhat bigger and that's all. If in doubt, just use double.
Oh yes, and use **decimal** for financial calculations, of course. | All floating point calculations are inaccurature in a general case, floats just more so than doubles. If you want more information have a read of
[What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html)
As for when to use floats - they are often used when precision is less important than saving memory. For example simple particle simulations in video games. | When to use a Float | [
"",
"c#",
"types",
"floating-point",
""
] |
Are there any good tools available to track memory usage In a tomcat java webapp? I'm looking for something that can give a breakdown by class or package.
Thanks, J | I use the Netbeans IDE and it is able to profile any type of Java project including webapps. Once you have the project setup in Netbeans you just click Profile and answer a few easy questions.
It is very easy to create a new project and import your existing code into it.
You can see screenshots of this here: <http://profiler.netbeans.org/>
You can download Netbeans from here: <http://www.netbeans.org/>
VisualVM may also work for you. There are also a number of plugins available for it. VisualVM has been shipping with the JDK since JDK 6 update 7. You can check it out here: <https://visualvm.dev.java.net/> | [jconsole](http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html#memory) can give you summary statistics. I've used it in the past while load testing to infer the size of loaded classes (by noting the before and after usage when loading LOTS of objects.) Note that the usage keeps going UP until a garbage collection is triggered, so you will need to account for transient objects in your calculations. | Tracking memory usage in a tomcat webapp | [
"",
"java",
"memory",
""
] |
How can I achieve the following with a format string: Do 01.01.2009 ?
It has to work in all languages (the example would be for Germany). So there should only be the short weekday and then the short date.
I tried 'ddd d' (without the '). However, this leads to 'Do 01'.
Is there maybe a character I can put before the 'd' so that it is tread on its own or something like that? | ```
DateTime.Now.ToString("ddd dd/MM/yyyy")
``` | You should be using the [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) standard if you are targeting audiences with varied spoken languages.
```
DateTime.Now.ToString("ddd yyyy-MM-dd");
```
Alternatively, you can target the current culture with a short date:
```
DateTime.Now.ToString("d", Thread.CurrentThread.CurrentCulture);
```
or a long date:
```
DateTime.Now.ToString("D", Thread.CurrentThread.CurrentCulture);
``` | How to format a Date without using code - Format String Question | [
"",
"c#",
"datetime",
"formatting",
""
] |
I have a C#/.Net job that imports data from Excel and then processes it. Our client drops off the files and we process them. I don't have any control over the original file.
I use the OleDb library to fill up a dataset. The file contains some numbers like 30829300, 30071500, etc... The data type for those columns is "Text".
Those numbers are converted to scientific notation when I import the data. Is there anyway to prevent this from happening? | The OleDb library **will**, more often than not, mess up your data in an Excel spreadsheet. This is largely because it forces everything into a fixed-type column layout, *guessing* at the type of each column from the values in the first 8 cells in each column. If it guesses wrong, you end up with digit strings converted to scientific-notation. Blech!
To avoid this you're better off skipping the OleDb and reading the sheet directly yourself. You can do this using the COM interface of Excel (also blech!), or a third-party .NET Excel-compatible reader. [SpreadsheetGear](http://www.spreadsheetgear.com/) is one such library that works reasonably well, and has an interface that's very similar to Excel's COM interface. | One workaround to this issue is to change your select statement, instead of SELECT \* do this:
```
"SELECT Format([F1], 'General Number') From [Sheet1$]"
-or-
"SELECT Format([F1], \"#####\") From [Sheet1$]"
```
However, doing so will blow up if your cells contain more than 255 characters with the following error:
"Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."
Fortunately my customer didn't care about erroring out in this scenario.
This page has a bunch of good things to try as well:
<http://www.dicks-blog.com/archives/2004/06/03/external-data-mixed-data-types/> | Scientific notation when importing from Excel in .Net | [
"",
"c#",
".net",
"excel",
"oledb",
""
] |
I am trying to read CSS selectors in my stylesheets with the `document.styleSheets` array. It works fine with `<link>` and `<style>` tags, but when I use `@import` inside a `<style>` it doesn't show up in the array - only as a cssRule (style is "Undefined" in Safari 3 and FF 3).
So: How can I parse the css in an @imported file? | Assuming that our document contains an @import-rule as first rule in the first stylesheet, here's the code for standards compliant browsers
```
document.styleSheets[0].cssRules[0].styleSheet.cssRules;
```
and the special case for our all-beloved IE
```
document.styleSheets[0].imports[0].rules;
```
You could have easily figured this out yourself if you had read [the page at quirksmode.org](http://www.quirksmode.org/dom/w3c_css.html#access) to which I had already linked and then walked the properties of the `@import`-rule with a `for..in` loop - that's what I did...
**PS:** I can't comment on other answers yet, but if I could, I would have ridiculed you properly ;) | > Check this page - which further links to this one on quirksmode.org.
Thanks, but I have tried that... the Quirksmode examples never parse stylesheets embedded with @import.
If I have this HTML/CSS:
```
<link rel="stylesheet" type="text/css" href="css/test1.css" />
<style type="text/css">
@import url('css/test2.css');
div {
color: blue;
}
</style>
```
... then document.styleSheets.length is 2 (the link tag and the style tag). The CSS file that is linked through @import will be available as
```
document.styleSheets[1].cssRules[0].
```
In other words, a CSS rule. This can also be seen at the [Quirksmode](http://www.quirksmode.org/dom/changess.html) page that you mentioned, Christoph. I can get its cssText ("@import url('css/test2.css');") but I can't figure out how to parse the CSS inside the file (test2.css)...
If I have totally missed something obvious here, feel free to ridicule me... :) | How do I parse @import stylesheets with Javascript | [
"",
"javascript",
"css",
""
] |
I am writing an application to manage user access to files. The short version of a very long story is that I have to use directory and file priveleges to do it. No document management system for our cheap CEO...
Anyway... I have everything working except the case where the user can view which files are in the directory but not actually see the contents of the file. (There may be sensitive HR data in the files.)
I tried FileSystemRights.ListDirectory, but that seems to (dispite MS documentation) set ReadData to true as well. I turn off ReadData (the ability to read the files) and I suddenly have no access to the directory again. The two appear linked.
Any ideas for which permission(s) to set to achieve this?
My current code is:
```
SetSecurity(pth, usr, FileSystemRights.ListDirectory, AccessControlType.Allow);
...
public void SetSecurity(string dirName, string account,
FileSystemRights rights, AccessControlType controlType)
{
// Get a FileSecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = Directory.GetAccessControl(dirName);
dSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
// Set the new access settings.
Directory.SetAccessControl(dirName, dSecurity);
}
```
Thanks.
--Jerry | The FileSystemRights enum maps both ReadData and ListDirectory to the value 1, so the two are 100% equivalent as far as .NET is concerned.
Have you tried Traverse as opposed to ListDirectory?
Edit: Based on [this](http://support.microsoft.com/kb/308419) KB article it appears that Windows XP considers them to be the same too, just one applies only to files, and one applies only to directories.
Edit 2: As long as you set the ReadData/ListDirectory access rule to NOT be inherited by child objects, you should be able to apply it to the directory without applying it to the files in the directory. The FileSystemAccessRule class does support changing inheritance flags. | The files are probably inheriting the security properties from parent.
You may try calling [DirectorySecurity.SetAccessRuleProtection(true, false)](http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.objectsecurity.setaccessruleprotection.aspx) to prevent the files from inheriting, before calling Directory.SetAccessControl(); | C# File/Directory Permissions | [
"",
"c#",
""
] |
For domain entities, should property names be prefaced with the entity name? I.E. my class Warehouse has a property WarehouseNumber. Should that property be named WarehouseNumber or simply Number?
Thoughts? | I prefer not using the prefix, I find it easier to type, and more readable, the context of what the entity is almost always apparent. | Think of the concepts you are representing, the context in which they appear, and their relative frequency.
In this case, the pieces of data are `Warehouse` and `Number`. In the context of a `Warehouse`, `Number` is properly qualified. Outside of a `Warehouse`, `WarehouseNumber` would be properly qualified, i.e. `Order.WarehouseNumber`.
`Warehouse.WarehouseNumber`, then, would be redundant. | Domain Entity Property Names | [
"",
"c#",
"class",
"dns",
""
] |
I am writing code to migrate data from our live Access database to a new Sql Server database which has a different schema with a reorganized structure. This Sql Server database will be used with a new version of our application in development.
I've been writing migrating code in C# that calls Sql Server and Access and transforms the data as required. I migrated for the first time a table which has entries related to new entries of another table that I have not updated recently, and that caused an error because the record in the corresponding table in SQL Server could not be found
So, my SqlServer productions table has data only up to 1/14/09, and I'm continuing to migrate more tables from Access. So I want to write an update method that can figure out what the new stuff is in Access that hasn't been reflected in Sql Server.
My current idea is to write a query on the SQL side which does SELECT Max(RunDate) FROM ProductionRuns, to give me the latest date in that field in the table. On the Access side, I would write a query that does SELECT \* FROM ProductionRuns WHERE RunDate > ?, where the parameter is that max date found in SQL Server, and perform my translation step in code, and then insert the new data in Sql Server.
What I'm wondering is, do I have the syntax right for getting the latest date in that Sql Server table? And is there a better way to do this kind of migration of a live database?
Edit: What I've done is make a copy of the current live database. Which I can then migrate without worrying about changes, then use that to test during development, and then I can migrate the latest data whenever the new database and application go live. | I personally would divide the process into two steps.
1. I would create an exact copy of Access DB in SQLServer and copy all the data
2. Copy the data from this temporary SQLServer DB to your destination database
In that way you can write set of SQL code to accomplish second step task
Alternatively use [SSIS](http://msdn.microsoft.com/en-us/library/ms141026.aspx) | Generally when you convert data to a new database that will take it's place in porduction, you shut out all users of the database for a period of time, run the migration and turn on the new database. This ensures no changes to the data are made while doing the conversion. Of course I never would have done this using c# either. Data migration is a database task and should have been done in SSIS (or DTS if you have an older version of SQL Server).
If the databse you are converting to is just in development, I would create a backup of the Access database and load the data from there to test the data loading process and to get the data in so you can do the application development. Then when it is time to do the real load, you just close down the real database to users and use it to load from. If you are trying to keep both in synch wile you develop, well I wouldn't do that but if you must, make a nightly backup of the file and load first thing in the morning using your process. | Queries for migrating data in live database? | [
"",
"sql",
"sql-server",
"ms-access",
"migration",
""
] |
I need to create a structure or series of strings that are fixed lenght for a project I am working on. Currently it is written in COBOL and is a communication application. It sends a fixed length record via the web and recieves a fixed length record back. I would like to write it as a structure for simplicity, but so far the best thing I have found is a method that uses string.padright to put the string terminator in the correct place.
I could write a class that encapsulates this and returns a fixed length string, but I'm hoping to find a simple way to fill a structure and use it as a fixed length record.
edit--
The fixed length record is used as a parameter in a URL, so its http:\somewebsite.com\parseme?record="firstname lastname address city state zip". I'm pretty sure I won't have to worry about ascii to unicode conversions since it's in a url. It's a little larger than that and more information is passed than address, about 30 or 35 fields. | As an answer, you should be able to use char arrays of the correct size, without having to marshal.
Also, the difference between a class and a struct in .net is minimal. A struct cannot be null while a class can. Otherwise their use and capabilities are pretty much identical.
Finally, it sounds like you should be mindful of the size of the characters that are being sent. I'm assuming (I know, I know) that COBOL uses 8bit ASCII characters, while .net strings are going to use a UTF-16 encoded character set. This means that a 10 character string in COBOL is 10 bytes, but in .net, the same string is 20 bytes. | Add the MarshalAs tag to your structure. Here is an example:
```
<StructLayout (LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Public Structure OSVERSIONINFO
Public dwOSVersionInfoSize As Integer
Public dwMajorVersion As Integer
Public dwMinorVersion As Integer
Public dwBuildNumber As Integer
Public dwPlatformId As Integer
<MarshalAs (UnmanagedType.ByValTStr, SizeConst:=128)> _
Public szCSDVersion As String
End Structure
```
<http://bytes.com/groups/net-vb/369711-defined-fixed-length-string-structure> | Fixed length strings or structures in C# | [
"",
"c#",
".net",
"vb.net",
""
] |
Can anyone point me to a site, or give me some wisdom on how you go about choosing names for interfaces, classes and perhaps even methods and properties relating to what that object or method does?
This is specifically for Microsoft development, so Java-esque "doGet" and so on isn't really used, however some general rules that cross language barriers must (I would've thought) exist.
An example might help: I have 4 choices of names for an interface:
```
IGroupedItem
IGroupableItem
IDataEntity
IGroupedEntity
```
They all contain an adjective and the noun, or just a noun. Looking at the .NET framework it seems like there must be some kind of ruleset for this, for consistency? Aside from the obvious verbs for methods.
**Edit:** Though the example is an interface, I'm not limiting this to just interfaces. The general guideline is classes are nouns, methods verbs, properties nouns. I suppose what I mean is choice of the synonym. Is throwing "Entity" everywhere wrong | Look at the [MSDN articles](http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx) for naming guidelines. In short:
* Use nouns for class names and property names (it's obvious)
* For interface names, start with I and use nouns and/or adjectives to describe behavior
* Use verbs for method names to describe action
For your example - IGroupableItem. | Interfaces are things a class is capable of doing. Not what it **is**, but what it can **do**.
```
IGroupableItem
```
Other names describe what things are or are too vague to be useful.
Specifically, "IDataEntity" is largely meaningless. After all, everything's a data entity. | Naming conventions: Guidelines for verbs/nouns and english grammar usage | [
"",
"c#",
".net",
"naming-conventions",
""
] |
I am C# developer. I really love the curly brace because I came from C, C++ and Java background. However, I also like the other programming languages of the .NET Family such as VB.NET. Switching back and forth between C# and VB.NET is not really that big of deal if you have been programming for a while in .NET. That is very common approach in the company where I work. As C# guy, I really like the XML literal and `with` keywords provided by the VB.NET compiler. I wish Microsoft had included those features in C# also.
I am just curious , what other developer has to say about it! | I wouldn't be suprised if "With" or a similar feature is added to C# eventually along with other heretofore popular exclusively VB features. There was a lot of talk in the C# 4.0 preview presentations recently at PDC and elsewhere of the increased "focus on language parity" starting with C# 4.0 and VB 10. | Personally I don't like WITH when it's used after construction - if you need to do several things with an object after it's initialized, usually that behaviour should be encapsulated in the type itself. If you really want to do something like WITH, it's only a matter of declaring a short variable and optionally introducing a new scope.
However, it *is* useful to be able to compactly initialize an object with several properties - which is precisely why C# 3 allows you to write:
```
MyObject x = new MyObject { Name="Fred", Age=20, Salary=15000 };
```
There are limitations to this (which the optional and named parameters in C# 4 will help to overcome) but it's better than it was without leading to potential messes/ambiguities.
(On the XML literal front, I'm again with the C# team - XML is a very specific technology to put into a language. If they could come up with a *generalised* form which happened to create XML but could be used to create other trees too, that would be nice - just as query expressions aren't directly tied to IEnumerable or IQueryable.) | Why is the with() construct not included in C#, when it is really cool in VB.NET? | [
"",
"c#",
"vb.net",
"with-statement",
""
] |
How do you manage your php codes? Do you prefer functioning within one php file or including larger blocks of "raw code"?
Edit: In fact, my code is pretty nasty, as I don't use any namespaces and classes - only functions and including. I shall look the classes up ^^. | If you are using php classes, this will sort itself out. If you are not, then it's really hard to give an acceptable answer, except that you should learn to. All php code I've seen done either way without classes seems to become quickly messy. | Use them as you need them.
I use include for chunks of big code doing processing, and functions for "utility" functions. Sometines i use includes within function also... it really depends on how clean you like your code.
Think that many includes means more fopen() from the PHP module, and those can slow doewn the whole script execution..so dont try and put too many includes though. | Do you prefer functioning or including within one php file? | [
"",
"php",
"function",
"include",
""
] |
I am looking to find a librray that emulates part of the capabilities of Ruby's ERB library. ie substitute text for variables between <% and %>. I dont need the code execution part that ERB provides but if you know of something that has this I would be super appreciative. | Have a look at [TemplateMachine](http://www.stefansarstedt.com/templatemaschine.html), I haven't tested it, but it seems to be a bit ERB-like. | I modified a class I used to test some things a while ago. It's not even nearly as good as ERB but it gets the job done substituting text. It only works with properties though, so you might want to fix that.
**Usage:**
```
Substitutioner sub = new Substitutioner(
"Hello world <%=Wow%>! My name is <%=Name%>");
MyClass myClass = new MyClass();
myClass.Wow = 42;
myClass.Name = "Patrik";
string result = sub.GetResults(myClass);
```
**Code:**
```
public class Substitutioner
{
private string Template { get; set; }
public Substitutioner(string template)
{
this.Template = template;
}
public string GetResults(object obj)
{
// Create the value map and the match list.
Dictionary<string, object> valueMap = new Dictionary<string, object>();
List<string> matches = new List<string>();
// Get all matches.
matches = this.GetMatches(this.Template);
// Iterate through all the matches.
foreach (string match in matches)
{
if (valueMap.ContainsKey(match))
continue;
// Get the tag's value (i.e. Test for <%=Test%>.
string value = this.GetTagValue(match);
// Get the corresponding property in the provided object.
PropertyInfo property = obj.GetType().GetProperty(value);
if (property == null)
continue;
// Get the property value.
object propertyValue = property.GetValue(obj, null);
// Add the match and the property value to the value map.
valueMap.Add(match, propertyValue);
}
// Iterate through all values in the value map.
string result = this.Template;
foreach (KeyValuePair<string, object> pair in valueMap)
{
// Replace the tag with the corresponding value.
result = result.Replace(pair.Key, pair.Value.ToString());
}
return result;
}
private List<string> GetMatches(string subjectString)
{
try
{
List<string> matches = new List<string>();
Regex regexObj = new Regex("<%=(.*?)%>");
Match match = regexObj.Match(subjectString);
while (match.Success)
{
if (!matches.Contains(match.Value))
matches.Add(match.Value);
match = match.NextMatch();
}
return matches;
}
catch (ArgumentException)
{
return new List<string>();
}
}
public string GetTagValue(string tag)
{
string result = tag.Replace("<%=", string.Empty);
result = result.Replace("%>", string.Empty);
return result;
}
}
``` | ERB like library for C# | [
"",
"c#",
"ruby",
"templates",
"erb",
""
] |
How do I set Java's min and max heap size through environment variables?
I know that the heap sizes can be set when launching java, but I would like to have this adjusted through environment variables on my server. | You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)
Some products like Ant or Tomcat might come with a batch script that looks for the JAVA\_OPTS environment variable, but it's not part of the Java runtime. If you are using one of those products, you may be able to set the variable like:
```
set JAVA_OPTS="-Xms128m -Xmx256m"
```
You can also take this approach with your own command line like:
```
set JAVA_OPTS="-Xms128m -Xmx256m"
java ${JAVA_OPTS} MyClass
``` | If you want any `java` process, not just ant or Tomcat, to pick up options like `-Xmx` use the environment variable `_JAVA_OPTIONS`.
In bash: `export _JAVA_OPTIONS="-Xmx1g"` | How do I set Java's min and max heap size through environment variables? | [
"",
"java",
"environment-variables",
"heap-memory",
""
] |
I have a Visual Studio solution that comprises of several projects and are separated into different directories.
In my C# or VB.NET code, I want to determine the base directory (or the directory that the solution is in).
A dirty solution would be to call the directory `parent.parent.parent` until I find a file \*.sln, but I also have several solutions in other directories that I don't want to be returned.
I am just wondering if there is a cleaner method, maybe part of `System.Diagnostics.Debugger` or similar?
I look forward to your reply, thanks. | As the sln file does not need to be deployed on the target machine - why are you trying to find it at all?
If you still want to use the sln- try at [EnvDTE Namespace](http://msdn.microsoft.com/en-us/library/envdte._solution_members(VS.80).aspx)
> EnvDTE.DTE dte = (EnvDTE.DTE) System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
>
> string folder = System.IO.Path.GetDirectoryName(dte.ActiveDocument.FullName); | Even though you have solutions in other directories, presumably those aren't directories within your original solution, are they? What situation do you envisage where the "recurse up until you find a .sln file" would fail (other than running from the wrong directory)?
One alternative would be to pass the solution directory as a command line argument.
What do you need this for, out of interest? | How to return the Visual Studio currently open soution directory | [
"",
"c#",
".net",
"vb.net",
"visual-studio",
"ide",
""
] |
For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can gather PIL had better documentation (does ruby-gd even have a homepage?) and more features. Just wanted to hear a few opinions to help me decide.
Thanks.
Vince | ImageMagic is a huge library and will do everything under the sun, but many report memory issues with the RMagick variant and I have personally found it to be an overkill for my needs.
As you say ruby-gd is a little thin on the ground when it comes to English documentation.... but GD is a doddle to install on post platforms and there is a little wrapper with some helpful examples called [gruby](http://gruby.sourceforge.jp/index.en.html) thats worth a look. (If you're after alpha transparency make sure you install the latest GD lib)
For overall community blogy help, PIL's the way. | PIL is a good library, use it. ImageMagic (what RMagick wraps) is a very heavy library that should be avoided if possible. Its good for doing local processing of images, say, a batch photo editor, but way too processor inefficient for common image manipulation tasks for web.
**EDIT:** In response to the question, PIL supports drawing vector shapes. It can draw polygons, curves, lines, fills and text. I've used it in a project to produce rounded alpha corners to PNG images on the fly over the web. It essentially has most of the drawing features of GDI+ (in Windows) or GTK (in Gnome on Linux). | PIL vs RMagick/ruby-gd | [
"",
"python",
"ruby",
"python-imaging-library",
"rmagick",
""
] |
How to script a constraint on a field in a table, for an acceptable range of values is between 0 and 100? | ```
ALTER TABLE Table
ADD CONSTRAINT CK_Table_Column_Range CHECK (
Column >= 0 AND Column <= 100 --Inclusive
)
``` | Try:
```
ALTER TABLE myTableName
ADD CONSTRAINT myTableName_myColumnName_valZeroToOneHundred
CHECK (myColumnName BETWEEN 0 AND 100)
```
This check would be inclusive - here is some info about BETWEEN from MSDN:
[BETWEEN (Transact SQL)](http://msdn.microsoft.com/en-us/library/ms187922(SQL.90).aspx) | Script SQL constraint for a number to fall within a Range? | [
"",
"sql",
"sql-server",
"constraints",
""
] |
I am conducting some throughput testing. My application has to
1. read from JMS
2. do some processing
3. write to JMS
My goal here is to simulate #2, 'some processing'. That is, introduce a delay and occupy the CPU for a given time (e.g. 500ms) before forwarding the event.
The naive approach would be to `Thread.sleep(500)`. This would introduce the right delay in execution, but would not exercise the CPU.
Calculating Fibonacci numbers is one option.
**Has anyone used any interesting techniques just to keep CPU(s) busy for a given time?**
Ideal characteristics would be:
* Performs a variety of instructions, rather than (for example) just spinning on a loop
* Not something the HotSpot VM is going to optimise away to nothing
* Has an easy way to adjust the processing period up or down (time to complete will clearly vary given the hardware) | Encrypt a string (in a loop) by calling Cipher.update(). Encryption algorithms are by definition very difficult to optimize. The only problem is that there is some non-trivial setup you need to perform. I'm marking this answer as community wiki, so that somebody who's written it recently can fill it in. | You could try something simple like
```
private static void spin(int milliseconds) {
long sleepTime = milliseconds*1000000L; // convert to nanoseconds
long startTime = System.nanoTime();
while ((System.nanoTime() - startTime) < sleepTime) {}
}
```
Test:
```
public static void main(String[] args) {
final int NUM_TESTS = 1000;
long start = System.nanoTime();
for (int i = 0; i < NUM_TESTS; i++) {
spin(500);
}
System.out.println("Took " + (System.nanoTime()-start)/1000000 +
"ms (expected " + (NUM_TESTS*500) + ")");
}
```
My output:
```
$ java SpinTest
Took 500023ms (expected 500000)
```
So the loop didn't get optimized away (and yeah, I spiked my CPU to 100% for eight minutes just to test this :)). | generate CPU load in Java | [
"",
"java",
"encryption",
"load",
"cpu",
""
] |
I'm working on a program that uses PHP's internal array pointers to iterate along a multidimensional array. I need to get an element from the current row, and I've been doing it like so:
```
$arr[key($arr)]['item']
```
However, I'd much prefer to use something like:
```
current($arr)['item'] // invalid syntax
```
I'm hoping there's a function out there that I've missed in my scan of the documentation that would enable me to access the element like so:
```
getvalue(current($arr), 'item')
```
or
```
current($arr)->getvalue('item')
```
Any suggestions? | I very much doubt there is such a function, but it's trivial to write
```
function getvalue($array, $key)
{
return $array[$key];
}
```
Edit: As of PHP 5.4, you can index array elements directly from function expressions, `current($arr)['item']`. | Have you tried using one of the [iterator classes](http://php.net/manual/en/spl.iterators.php) yet? There might be something in there that does exactly what you want. If not, you can likely get what you want by extending the ArrayObject class. | Access PHP array element with a function? | [
"",
"php",
"arrays",
""
] |
I have an ASP.NET web application that calls a .NET DLL, that in turn calls a web service. The web service call is throwing an exception:
> Unable to generate a temporary class
> (result=1). error CS0001: Internal
> compiler error (0xc00000fd) error
> CS0003: Out of memory
>
> Stack Trace: at
> System.Xml.Serialization.Compiler.Compile(Assembly
> parent, String ns,
> XmlSerializerCompilerParameters
> xmlParameters, Evidence evidence)
> at
> System.Xml.Serialization.TempAssembly.GenerateAssembly(XmlMapping[]
> xmlMappings, Type[] types, String
> defaultNamespace, Evidence evidence,
> XmlSerializerCompilerParameters
> parameters, Assembly assembly,
> Hashtable assemblies) at
> System.Xml.Serialization.TempAssembly..ctor(XmlMapping[]
> xmlMappings, Type[] types, String
> defaultNamespace, String location,
> Evidence evidence) at
> System.Xml.Serialization.XmlSerializer.GetSerializersFromCache(XmlMapping[]
> mappings, Type type) at
> System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[]
> mappings, Type type) at
> System.Web.Services.Protocols.SoapClientType..ctor(Type
> type) at
> System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()
I should mention that this is the first time I have executed this particular bit of code on this PC (I recently did a Windows reformat/reinstall) -- which makes me think it is a problem with the environment (the same application runs fine on our test and production servers). But I'm stumped as to the cause.
---
Some additional details to answer follow-up questions:
* This is a real PC (not a VM).
* I'm running .NET 3.5 on IIS 7. Our production servers are IIS 6, but it has worked correctly on IIS 7 before.
* The PC has 2 GB of RAM with plenty of that free.
* I haven't changed any of the machine.config settings, nor any of the web.config settings related to process model, compilation, memory usage, etc.
* The local IIS\_IUSRS group has read/write permissions for the "Temporary ASP.NET Files" folder.
* I checked the application pool settings: both private memory and virtual memory are set to 0 (no limit).
Memory usage of the worker process:
* I recycled the worker process to get a clean slate and then hit an ASP.NET page in the application...Task Manager shows 22 MB used.
* I then hit the event that makes the web service call and the memory usage shoots up to about 150 MB, levels off, then I get the exception. | Well, I'm not sure exactly **why** this worked (which is frustrating), but I did come up with something...
My previous install of Windows was 32-bit, but when I rebuilt my PC recently, I went with the 64-bit version. So, I changed the "Enable 32-Bit Applications" setting on my application pool in IIS to "True", and everything seems to work fine now.
The DLL and the web site itself are configured to compile as "Any CPU", so they shouldn't have caused any problems on Win64. And the "out of memory" error is still a bit perplexing (and unhelpful). If anyone has any ideas, you get the "accepted" points. | Thanks for adding more detail.
Have a look at this link: <http://support.microsoft.com/?kbid=908158>
It's similiar to the problem you're having.
It recommends the following:
To resolve this issue, grant the user account the List Folder Contents and Read permissions on the %windir%\Temp folder.
This one:
<http://club.workflowgen.com/scripts/club/publigen/content/templates/show.asp?P=53&L=EN>
recommends:
To avoid this problem, give read/write priviledges for the Temp folder to the ASPNET account. When ASP.NET Web Services process WebMethods, the identity that is used most frequently to gain access to the system Temp folder is the local ASPNET account, which is the default account under which ASP.NET applications run.
However, if you have configured your application to use impersonation in its Web.config file, the thread can also use the identity of any caller. If this is the case, all potential calling identities must have read/write priviledges to the Temp folder. A likely calling identity is the Internet Information Services (IIS) application's anonymous account (typically the ISUR\_xxx account). The thread may also use the IWAM\_xxx account or NETWORK SERVICE. | "Out of memory" exception on call to web service | [
"",
"c#",
"asp.net",
"web-services",
""
] |
Hopefully the title is self explanatory, what is the advantage of using the .call() method in Javascript compared with just writing functionName(); ? | [`functionName.call()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/call) takes an object instance as its first parameter. It then runs `functionName` within the context of that object instance (ie "this" is the specified instance) | If you don't pass anything into `call()`, it will be the same; the function will be run with the same scope that the call to `call()` is made:
```
function test() {
alert(this);
}
test(); // alerts the window object
test.call(); // alerts the window object
```
But if you pass an object into `call()`, that object will be used as the scope:
```
test.call("hi"); // alerts "hi"
``` | difference between functionName() and functionName.call() in javascript | [
"",
"javascript",
""
] |
So I'm refactoring a legacy codebase I've inherited, and in the process I found a static class that encapsulates the logic for launching 3rd party applications. It essentially looks like this (shortened for brevity to only show one application):
```
using System.IO;
using System.Configuration;
public static class ExternalApplications
{
public string App1Path
{
get
{
if(null == thisApp1Path)
thisApp1Path = Configuration.AppSettings.Get("App1Path");
return thisApp1Path;
}
}
private string thisApp1Path = null;
public bool App1Exists()
{
if(string.IsNullOrEmpty(App1Path))
throw new ConfigurationException("App1Path not specified.");
return File.Exists(App1Path);
}
public void ExecuteApp1(string args)
{
// Code to launch the application.
}
}
```
It's a nice attempt to separate the external applications from the rest of the code, but it occurs to me that this could have been refactored further. What I have in mind is something like this:
```
using System.IO;
public abstract class ExternalApplicationBase
{
protected ExternalApplicationBase()
{
InitializeFromConfiguration();
}
public string Path { get; protected set; }
public bool Exists()
{
if(string.IsNullOrEmpty(this.Path))
throw new ConfigurationException("Path not specified.");
return File.Exists(this.Path);
}
public virtual void Execute(string args)
{
// Implementation to launch the application
}
protected abstract InitializeFromConfiguration();
}
public class App1 : ExternalApplicationBase
{
protected virtual void InitializeFromConfiguration()
{
// Implementation to initialize this application from
// the application's configuration file.
}
}
public class App2 : ExternalApplicationBase
{
protected virtual void InitializeFromConfiguration()
{
// Implementation to initialize this application from
// the application's configuration file.
}
}
```
My concerns are as follows:
1. A class, interface, or other construct may already exist that does this, and I just haven't stumbled across it.
2. It may be overkill for what I want to do. Note, however, that the application uses at least three separate 3rd party applications that I have identified so far (and more are almost certain to pop up).
3. I'm not entirely comfortable with the name of the base class. It seems fuzzy, and not very informative (but I couldn't think of much better, given that Application is already well defined, reserved by the Framework, and would create a gross level of confusion were I to use it).
4. The idea is that I want to be able to keep the application configuration data (it's path and executable name) in the App.Config file, and check for its existence when my application starts up; when my software needs to launch the software, I want to do it through a single method call, and not have the code building command lines and trying to launch the software manually (as it currently does).
So I'm sending out a request for help, guidance, and suggestions. Anything you can profer is greatly appreciated.
P.S. I'm asking this here because I work, as I frequently do, as a sole developer at my firm; I don't have anyone else to bounce these ideas off of. You guys have tons of experience with this stuff, and it would be foolish of me not to ask for your advice, so I hope you'll all bear with me. Thanks in advance! | Here is another way of refactoring this:
```
using System.IO;
public class ExternalApplication
{
public ExternalApplication(string path)
{
this.Path = path;
}
public string Path { get; protected set; }
public bool Exists()
{
if(string.IsNullOrEmpty(this.Path))
throw new ConfigurationException("Path not specified.");
return File.Exists(this.Path);
}
public void Execute(string args)
{
// Implementation to launch the application
}
}
public class AppFactory
{
public ExternalApplication App1()
{
// Implementation to initialize this application from
// the application's configuration file.
}
public ExternalApplication App2()
{
// Implementation to initialize this application from
// the application's configuration file.
}
public ExternalApplication AppFromKey(string key)
{
// get from somewhere
}
}
```
In this case, you have a single type `ExternalApplication` and a factory that has methods the return a properly configured application for you. | Seems reasonable to me.
I did something similar in the past, but I didn't have an abstract base class. Instead I passed in the application path in the constructor. | .NET Class Refactoring Dilemma | [
"",
"c#",
".net",
"oop",
"refactoring",
""
] |
I am building an application that queries a web service. The data in the database varies and changes over time. How do I build a unit test for this type of application?
The web service sends back xml or a no search results html page. I cannot really change the web service. My application basically queries the web service using HTTPURLConnection and gets the response as a String.
Hope that helps with more detail. | Abstract out the web service using a proxy that you can mock out. Have your mock web service return various values representing normal data and corner cases. Also simulate getting exceptions from the web service. Make sure you code works under these conditions and you can be reasonably certain that it will work with any values the web service supplies.
Look at [jMock](http://www.jmock.org/) for Java mocking. | Strictly speaking of unit-testing, you can only test units that have a **deterministic behavior**.
A test that connects to an external web server is an **integration test**.
The solution is to mock the HTTPURLConnection - that is, create a class in your unit tests that derives from HTTPURLConnection class and that returns an hardcoded, or a parameterizable value. **EDIT**: notice this can be done maunally, without any mocking framework.
The class that queries the web server shall not instanciate the HTTPURLConnection, but receive it via a parameter. In the unit tests, you create the HTTPURLConnectionMock, and passes it to the class that interrogates the web server which will use it as it is using a real HTTPURLConnection. In the production code, you create a real HTTPURLConnection and pass it to the class.
You can also make your HTTPURLConnectionMock able to throw an IOException, to **test error conditions**. Just have a method to tell it not to return the result but an exception at next request. | How do you make a unit test when the results vary? | [
"",
"java",
"unit-testing",
"integration-testing",
""
] |
i need help with disk\_total\_space function..
i have this on my code
```
<?php
$sql="select * from users order by id";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
?>
Name : <?php echo $row['name']; ?>
Email : <?php echo $row['email']; ?>
Diskspace Available : <?php
$dir = "C:/xampp/htdocs/freehosting/".$row['name'];
disk_total_space($dir);
} ?>
```
However this return me same disk space for every users ..
Anyone can shed me some light?
thanks :) | I think what you want is something like this:
```
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
foreach($files as $t) {
if (is_dir(rtrim($path, '/') . '/' . $t)) {
if ($t<>"." && $t<>"..") {
$size = foldersize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
}
} else {
$size = filesize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
}
}
return $total_size;
}
function format_size($size) {
$mod = 1024;
$units = explode(' ','B KB MB GB TB PB');
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
return round($size, 2) . ' ' . $units[$i];
}
$SIZE_LIMIT = 5368709120; // 5 GB
$sql="select * from users order by id";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$disk_used = foldersize("C:/xampp/htdocs/freehosting/".$row['name']);
$disk_remaining = $SIZE_LIMIT - $disk_used;
print 'Name: ' . $row['name'] . '<br>';
print 'diskspace used: ' . format_size($disk_used) . '<br>';
print 'diskspace left: ' . format_size($disk_remaining) . '<br><hr>';
}
```
**edit**: the recursive function had a bug in it originally. Now it should also read folders inside the original folders, and folders inside those folders, and so on. | <https://www.php.net/disk_total_space> says,
> "Given a string containing a directory, this function will return the total number of bytes on the **corresponding filesystem** or **disk partition**."
You're likely seeing the total\_space of C:
[Alternative solutions do exist for both Windows and Linux](http://forums.devshed.com/showpost.php?p=1527717&postcount=4). | php disk_total_space | [
"",
"php",
"directory",
""
] |
I have coordinates from some source and want to tag my jpg files with them. What is the best python library for writing geotags into exif data? | [pexif](https://github.com/bennoleslie/pexif) was written with geotags as a goal (my emphasis):
> pexif is a Python library for parsing and more importantly editing EXIF data in JPEG files.
>
> This grew out of **a need to add GPS tagged data to my images**, Unfortunately the other libraries out there couldn't do updates and didn't seem easily architectured to be able to add such a thing. Ain't reusable software grand!
>
> My main reason for writing this was to provide an easy way for geo-tagging my photos, and the library now seems mature enough to do that. | Here is an example how to set GPS position using pyexiv2 library. I've tested this script by uploading geotagged image to Panoramio
```
#!/usr/bin/env python
import pyexiv2
import fractions
from PIL import Image
from PIL.ExifTags import TAGS
import sys
def to_deg(value, loc):
if value < 0:
loc_value = loc[0]
elif value > 0:
loc_value = loc[1]
else:
loc_value = ""
abs_value = abs(value)
deg = int(abs_value)
t1 = (abs_value-deg)*60
min = int(t1)
sec = round((t1 - min)* 60, 5)
return (deg, min, sec, loc_value)
def set_gps_location(file_name, lat, lng):
"""Adds GPS position as EXIF metadata
Keyword arguments:
file_name -- image file
lat -- latitude (as float)
lng -- longitude (as float)
"""
lat_deg = to_deg(lat, ["S", "N"])
lng_deg = to_deg(lng, ["W", "E"])
print lat_deg
print lng_deg
# convert decimal coordinates into degrees, munutes and seconds
exiv_lat = (pyexiv2.Rational(lat_deg[0]*60+lat_deg[1],60),pyexiv2.Rational(lat_deg[2]*100,6000), pyexiv2.Rational(0, 1))
exiv_lng = (pyexiv2.Rational(lng_deg[0]*60+lng_deg[1],60),pyexiv2.Rational(lng_deg[2]*100,6000), pyexiv2.Rational(0, 1))
exiv_image = pyexiv2.Image(file_name)
exiv_image.readMetadata()
exif_keys = exiv_image.exifKeys()
exiv_image["Exif.GPSInfo.GPSLatitude"] = exiv_lat
exiv_image["Exif.GPSInfo.GPSLatitudeRef"] = lat_deg[3]
exiv_image["Exif.GPSInfo.GPSLongitude"] = exiv_lng
exiv_image["Exif.GPSInfo.GPSLongitudeRef"] = lng_deg[3]
exiv_image["Exif.Image.GPSTag"] = 654
exiv_image["Exif.GPSInfo.GPSMapDatum"] = "WGS-84"
exiv_image["Exif.GPSInfo.GPSVersionID"] = '2 0 0 0'
exiv_image.writeMetadata()
set_gps_location(sys.argv[1], float(sys.argv[2]), float(sys.argv[3]))
``` | What is the best way to geotag jpeg-images with python? | [
"",
"python",
"jpeg",
"exif",
"geotagging",
""
] |
I've done quite a bit of research into this but it seems that the methods used are inconsistent and varied.
Here are some methods I have used in the past:
```
/* 1: */ typeof myFunc === 'function'
/* 2: */ myFunc.constructor === Function
/* 3: */ myFunc instanceof Function
```
As part of my research I had a look at how some well-known libraries accomplished this:
```
/* jQuery 1.2.6: */ !!fn && typeof fn != "string" && !fn.nodeName && fn.constructor != Array && /^[\s[]?function/.test( fn + "" )
/* jQuery 1.3b1: */ toString.call(obj) === "[object Function]"
/* Prototype 1.6: */ typeof object == "function"
/* YUI 2.6: */ typeof o === 'function'
```
I'm amazed there are so many different methods beings used, surely a single acceptable test has been agreed upon? And I'm completely clueless as to what the intentions were with jQuery 1.2.6's rendition, looks a bit OTT...
So, my quesiton remains, what is the best\* way of testing for a function?
I would also appreciate some insight into some of the above methods, especially jQuery 1.2.6's. (I can see what they're doing, it just seems odd)
[\*] By 'best', I mean the most widely accepted cross-browser compatible method.
---
EDIT: Yes, I know it's been discussed before but I'd still like some discussion on the most effective method. Why are there so many different used methods?
The discussions on SO thus far have only mentioned the typeof operator (mostly) but nobody has hinted at the effectiveness of alternate methods. | The best way to test if an object is a function is `typeof myFunc === 'function'`. If you are using a library, use that library's function test: `jQuery.isFunction(myFunc)`.
Things *can* be misreported as functions when using `typeof`. This is very rare but a library is there to remove these inconsistencies. jQuery working around these issues:
* Firefox reports function with `typeof document.createElement("object")`
* Safari reports function with `typeof document.body.childNodes`
* Older versions of Firefox reported regular expressions as functions (this not the case in 3.0).
* Some IE built in global functions (`alert`) and some node methods (`getAttribute`) are reported to be of type "object".
Using `instanceof` rather than `typeof` circumvents some of these. For example, `document.createElement("object") instanceof Function` is `false` in Firefox.
You can view the birth of the first method in the comments for [the original ticket (#3618)](http://dev.jquery.com/ticket/2968). The new method is from [changeset 5947](http://dev.jquery.com/changeset/5947) and seems to have been invented by Resig to solve [IE memory leaks](http://dev.jquery.com/ticket/3618). It's probably slower, but smaller, and cleaner.
There isn't much difference between == and === here in terms of how things work but the strict evaluation is ever so slightly faster and thus preferred. | John Resig the developer of jQuery does seem to have made some bizarre choices in the internals of jQuery.
```
toString.call(obj) === "[object Function]"
```
looks quite neat but I can't think of any situation where the above would be true where the simple `typeof` approach would fail but perhaps he knows something the rest of use don't.
```
typeof o === "function"
```
I would go with the latter since it has greater clarity, unless you've got strong evidence that it won't work. | Best method of testing for a function in JavaScript? | [
"",
"javascript",
"function",
""
] |
I have 3 byte arrays in C# that I need to combine into one. What would be the most efficient method to complete this task? | For primitive types (including bytes), use [`System.Buffer.BlockCopy`](https://learn.microsoft.com/en-us/dotnet/api/system.buffer.blockcopy) instead of [`System.Array.Copy`](https://learn.microsoft.com/en-us/dotnet/api/system.array.copy). It's faster.
I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:
1. New Byte Array using `System.Array.Copy` - 0.2187556 seconds
2. New Byte Array using `System.Buffer.BlockCopy` - 0.1406286 seconds
3. IEnumerable<byte> using C# yield operator - 0.0781270 seconds
4. IEnumerable<byte> using LINQ's Concat<> - 0.0781270 seconds
I increased the size of each array to 100 elements and re-ran the test:
1. New Byte Array using `System.Array.Copy` - 0.2812554 seconds
2. New Byte Array using `System.Buffer.BlockCopy` - 0.2500048 seconds
3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds
I increased the size of each array to 1000 elements and re-ran the test:
1. New Byte Array using `System.Array.Copy` - 1.0781457 seconds
2. New Byte Array using `System.Buffer.BlockCopy` - 1.0156445 seconds
3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds
Finally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop **only** 4000 times:
1. New Byte Array using `System.Array.Copy` - 13.4533833 seconds
2. New Byte Array using `System.Buffer.BlockCopy` - 13.1096267 seconds
3. IEnumerable<byte> using C# yield operator - 0 seconds
4. IEnumerable<byte> using LINQ's Concat<> - 0 seconds
So, if you need a new byte array, use
```
byte[] rv = new byte[a1.Length + a2.Length + a3.Length];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);
```
But, if you can use an `IEnumerable<byte>`, ***DEFINITELY*** prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.
```
IEnumerable<byte> rv = a1.Concat(a2).Concat(a3);
```
If you have an arbitrary number of arrays and are using .NET 3.5, you can make the `System.Buffer.BlockCopy` solution more generic like this:
```
private byte[] Combine(params byte[][] arrays)
{
byte[] rv = new byte[arrays.Sum(a => a.Length)];
int offset = 0;
foreach (byte[] array in arrays) {
System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
offset += array.Length;
}
return rv;
}
```
\*Note: The above block requires you adding the following namespace at the the top for it to work.
```
using System.Linq;
```
To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:
1. New Byte Array using `System.Array.Copy` - 78.20550510 seconds
2. New Byte Array using `System.Buffer.BlockCopy` - 77.89261900 seconds
3. IEnumerable<byte> using C# yield operator - 551.7150161 seconds
4. IEnumerable<byte> using LINQ's Concat<> - 448.1804799 seconds
The point is, it is ***VERY*** important to understand the efficiency of both the creation *and the usage* of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon. | Many of the answers seem to me to be ignoring the stated requirements:
* The result should be a byte array
* It should be as efficient as possible
These two together rule out a LINQ sequence of bytes - anything with `yield` is going to make it impossible to get the final size without iterating through the whole sequence.
If those aren't the *real* requirements of course, LINQ could be a perfectly good solution (or the `IList<T>` implementation). However, I'll assume that Superdumbell knows what he wants.
(EDIT: I've just had another thought. There's a big semantic difference between making a copy of the arrays and reading them lazily. Consider what happens if you change the data in one of the "source" arrays after calling the `Combine` (or whatever) method but before using the result - with lazy evaluation, that change will be visible. With an immediate copy, it won't. Different situations will call for different behaviour - just something to be aware of.)
Here are my proposed methods - which are very similar to those contained in some of the other answers, certainly :)
```
public static byte[] Combine(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
public static byte[] Combine(byte[] first, byte[] second, byte[] third)
{
byte[] ret = new byte[first.Length + second.Length + third.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
third.Length);
return ret;
}
public static byte[] Combine(params byte[][] arrays)
{
byte[] ret = new byte[arrays.Sum(x => x.Length)];
int offset = 0;
foreach (byte[] data in arrays)
{
Buffer.BlockCopy(data, 0, ret, offset, data.Length);
offset += data.Length;
}
return ret;
}
```
Of course the "params" version requires creating an array of the byte arrays first, which introduces extra inefficiency. | Best way to combine two or more byte arrays in C# | [
"",
"c#",
"arrays",
""
] |
My experience with MySQL is very basic. The simple stuff is easy enough, but I ran into something that is going to require a little more knowledge. I have a need for a table that stores a small list of words. The number of words stored could be anywhere between 1 to 15. Later, I plan on searching through the table by these words. I have thought about a few different methods:
A.) I could create the database with 15 fields, and just fill the fields with null values whenever the data is smaller than 15. I don't really like this. It seems really inefficient.
B.) Another option is to use just a single field, and store the data as a comma separated list. Whenever I come back to search, I would just run a regular expression on the field. Again, this seems really inefficient.
I would hope there is a good alternative to those two options. Any advice would be very appreciated.
-Thanks | C) use a [normal form](http://en.wikipedia.org/wiki/Database_normalization); use multiple rows with appropriate keys. an example:
```
mysql> SELECT * FROM blah;
+----+-----+-----------+
| K | grp | name |
+----+-----+-----------+
| 1 | 1 | foo |
| 2 | 1 | bar |
| 3 | 2 | hydrogen |
| 4 | 4 | dasher |
| 5 | 2 | helium |
| 6 | 2 | lithium |
| 7 | 4 | dancer |
| 8 | 3 | winken |
| 9 | 4 | prancer |
| 10 | 2 | beryllium |
| 11 | 1 | baz |
| 12 | 3 | blinken |
| 13 | 4 | vixen |
| 14 | 1 | quux |
| 15 | 4 | comet |
| 16 | 2 | boron |
| 17 | 4 | cupid |
| 18 | 4 | donner |
| 19 | 4 | blitzen |
| 20 | 3 | nod |
| 21 | 4 | rudolph |
+----+-----+-----------+
21 rows in set (0.00 sec)
```
This is the table I posted in this other question about [`group_concat`](https://stackoverflow.com/questions/397708/is-it-possible-to-concatenate-strings-from-multiple-rows-and-tables-into-one-resu#397733). You'll note that there is a unique key `K` for every row. There is another key `grp` which represents each category. The remaining field represents a category member, and there can be variable numbers of these per category. | What other data is associated with these words?
One typical way to handle this kind of problem is best described by example. Let's assume your table captures certain words found in certain documents. One typical way is to assign each document an identifier. Let's pretend, for the moment, that each document is a web URL, so you'd have a table something like this:
```
CREATE TABLE WebPage (
ID INTEGER NOT NULL,
URL VARCHAR(...) NOT NULL
)
```
Your Words table might look something like this:
```
CREATE TABLE Words (
Word VARCHAR(...) NOT NULL,
DocumentID INTEGER NOT NULL
)
```
Then, for each word, you create a new row in the table. To find all words in a particular document, select by the document's ID:
```
SELECT Words.Word FROM Words, WebPage
WHERE Words.DocumentID = WebPage.DocumentID
AND WebPage.URL = 'http://whatever/web/page/'
```
To find all documents with a particular word, select by word:
```
SELECT WebPage.URL FROM WebPage, Words
WHERE Words.Word = 'hello' AND Words.DocumentID = WebPage.DocumentID
```
Or some such. | MySQL design with dynamic number of fields | [
"",
"php",
"mysql",
"database",
""
] |
Is it possible to have a switch in C# which checks if the value is null or empty not "" but `String.Empty`? I know i can do this:
```
switch (text)
{
case null:
case "":
break;
}
```
Is there something better, because I don't want to have a large list of IF statements?
I'mm trying to replace:
```
if (String.IsNullOrEmpty(text))
blah;
else if (text = "hi")
blah
``` | You can use pattern matching to test for string length (or other things). This code was tested in .NET 6 and .NET 7.
```
// Program.cs
Console.WriteLine(PatternMatch(null));
Console.WriteLine(PatternMatch(""));
Console.WriteLine(PatternMatch("Hello world!"));
Console.WriteLine(PatternMatch("Blah!"));
Console.WriteLine(PatternMatch("99 bottles of beer on the wall"));
string PatternMatch(string str)
{
switch (str)
{
case null: return "String is null";
case "": return "String is empty";
case var blah when str.StartsWith("Blah"): return "Blerg";
case var match when Regex.IsMatch(match, @"\d\d.*"): return "Starts with 2 digits";
case { Length: > 0 }: return str;
default: return "We should never get here";
};
}
```
The output should be:
```
String is null
String is empty
Hello world!
Blerg
Starts with 2 digits
```
You can do the same thing using switch expressions too.
```
string PatternMatch2(string str) => str switch
{
null => "String is null",
"" => "String is empty",
var blah when str.StartsWith("Blah") => "Blerg",
var match when Regex.IsMatch(match, @"\d\d.*") => "Starts with 2 digits",
{ Length: > 0 } => str,
_ => "We should never get here"
};
``` | I would suggest something like the following:
```
switch(text ?? String.Empty)
{
case "":
break;
case "hi":
break;
}
```
Is that what you are looking for? | C# Switch with String.IsNullOrEmpty | [
"",
"c#",
"string",
"switch-statement",
"semantics",
""
] |
Take the following class as an example:
```
class Sometype
{
int someValue;
public Sometype(int someValue)
{
this.someValue = someValue;
}
}
```
I then want to create an instance of this type using reflection:
```
Type t = typeof(Sometype);
object o = Activator.CreateInstance(t);
```
Normally this will work, however because `SomeType` has not defined a parameterless constructor, the call to `Activator.CreateInstance` will throw an exception of type `MissingMethodException` with the message "*No parameterless constructor defined for this object.*" Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes. | I originally posted this answer [here](https://stackoverflow.com/questions/178645/how-does-wcf-deserialization-instantiate-objects-without-calling-a-constructor#179486), but here is a reprint since this isn't the exact same question but has the same answer:
`FormatterServices.GetUninitializedObject()` will create an instance without calling a constructor. I found this class by using [Reflector](http://www.red-gate.com/products/reflector/index.htm) and digging through some of the core .Net serialization classes.
I tested it using the sample code below and it looks like it works great:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;
namespace NoConstructorThingy
{
class Program
{
static void Main(string[] args)
{
MyClass myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); //does not call ctor
myClass.One = 1;
Console.WriteLine(myClass.One); //write "1"
Console.ReadKey();
}
}
public class MyClass
{
public MyClass()
{
Console.WriteLine("MyClass ctor called.");
}
public int One
{
get;
set;
}
}
}
```
### With .NET 8 right around the corner and the [obsoletion of the FormatterService](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatterservices?view=net-8.0)
You can use [`RuntimeHelpers.GetUninitializedObject`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimehelpers.getuninitializedobject?view=net-7.0), which is the same method that `FormatterService.GetUninitializedObject` was calling under the hood in the first place. | Use this overload of the CreateInstance method:
```
public static Object CreateInstance(
Type type,
params Object[] args
)
```
> Creates an instance of the specified
> type using the constructor that best
> matches the specified parameters.
See: <http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx> | Creating instance of type without default constructor in C# using reflection | [
"",
"c#",
"reflection",
"instantiation",
"default-constructor",
""
] |
Curious if anyone has opinions on which method would be better suited for asp.net caching. Option one, have fewer items in the cache which are more complex, or many items which are less complex.
For sake of discussion lets imagine my site has SalesPerson and Customer objects. These are pretty simple classes but I don’t want to be chatty with the database so I want to lazy load them into cache and invalidate them out of the cache when I make a change – simple enough.
Option 1
Create Dictionary and cache the entire dictionary. When I need to load an instance of a SalesPerson from the cache I get out the Dictionary and perform a normal key lookup against the Dictionary.
Option 2
Prefix the key of each item and store it directly in the asp.net cache. For example every SalesPerson instance in the cache would use a composite of the prefix plus the key for that object so it may look like sp\_[guid] and is stored in the asp.net cache and also in the cache are the Customer objects with a key like cust\_[guid].
One of my fears with option two is that the numbers of entries will grow very large, between SalesPerson, Customer and a dozen or so other categories I might have 25K items in cache and highly repetitive lookups for something like a string resource that I am using in several places might pay a penalty while the code looks through the cache’s key collection to find it amongst the other 25K.
I am sure at some point there is a diminishing return here on storing too many items in the cache but I am curious as to opinions on these matters. | You are best off to create many, smaller items in the cache than to create fewer, larger items. Here is the reasoning:
1) If your data is small, then the number of items in the cache will be relatively small and it won't make any difference. Fetching single entities from the cache is easier than fetching a dictionary and then fetching an item from that dictionary, too.
2) Once your data grows large, the cache may be used to manage the data in an intelligent fashion. The HttpRuntime.Cache object makes use of a Least Recently Used (LRU) algorithm to determine which items in the cache to expire. If you have only a small number of highly used items in the cache, this algorithm will be useless. However, if you have many smaller items in the cache, but 90% of them are not in use at any given moment (very common usage heuristic), then the LRU algorithm can ensure that those items that are seeing active use remain in the cache while evicting less-used items to ensure sufficient room remains for the used ones.
As your application grows, the importance of being able to manage what is in the cache will be most important. Also, I've yet to see any performance degradation from having millions of keys in the cache -- hashtables are extremely fast and if you find issues there it's likely easily solved by altering your naming conventions for your cache keys to optimize them for use as hashtable keys. | We have built an application that uses Caching for storing all resources. The application is multi-language, so for each label in the application we have at least three translations. We load a (Label,Culture) combination when first needed and then expire it from cache only if it was changed by and admin in the database. This scenario worked perfectly well even when the cache contained 100000 items in it. We only took care to configure the cache and the expiry policies such that we really benefit of the Cache. We use no-expiration, so the items are cached until the worker process is reset or until the item is intentionally expired. We also took care to define a domain for the values of the keys in such a way to uniquely identify a label in a specific culture with the least amount of characters. | Efficiency of persistence methods for large asp.net cache store | [
"",
"c#",
"asp.net",
"caching",
""
] |
Say I'm working with Sharepoint (this applies to other object models as well) and in the middle of my statement, I call a method, in this case "OpenWeb()", which creates an IDisposable SPWeb object. Now, I cannot call Dispose() on the SPWeb object because I don't have the reference to it. **So do I need to be concerned about this leaking memory?**
```
SPUser spUser = SPControl.GetContextSite(HttpContext.Current).OpenWeb().SiteUsers[@"foo\bar"];
```
I know that I could have broken up the statement into multiple lines and get the SPWeb reference to call Dispose:
```
SPWeb spWeb = SPControl.GetContextSite(HttpContext.Current).OpenWeb();
SPUser spUser = spWeb.SiteUsers[@"foo\bar"];
spWeb.Dispose();
```
Please keep in mind that my question is not about aesthetics, but more about what happens to the IDisposable object that I cannot explicitly call Dispose() on, since I don't have the reference.
Sorry about not being clear enough when I first asked the question. I've since rephrased it. Thanks for all the responses so far. | "what happens to the IDisposable object that I cannot explicitly call Dispose() on?"
In general you can call Dispose (either implicitly with a using statement or explicitly) on all disposable objects, however in the hypothetical scenario where you **can not**, it **depends** on the way the object was implemented.
In general, the .Net objects will follow pattern along [these lines](http://www.koders.com/csharp/fid88562D7F1F6AB4C639B301D7C90A8B1E2924C1A4.aspx). The pattern is to define a finalizer that cleans stuff up in case dispose is not called and then have dispose suppress the finalizer. Which reduces memory load and gives the GC less work to do.
Amongst the many problems with calling Dispose from the finalizer, is that you are turning a single threaded problem into a multithreaded problem, the finalizer will run on a **different** thread which can expose some very subtle and hard to catch bugs. Also, it means you will be holding on to unmanaged resources for longer than expected (Eg. you open a file, forget to call close or dispose and next time you go to open it its locked)
Bottom line is, it is a **best practice** to dispose all disposable objects, otherwise you can introduce weird and complex bugs. With the caveat that some frameworks, like sharepoint, return shared instances of objects that should not be disposed according to the documentation.
I usually find the code much more readable when I dispose my objects with the "using" pattern. The problem with calling Dispose explicitly (object.Dispose()) is that it can be hard to trace where the object was allocated and it is very easy to forget. You can not forget to close the curly bracket of the using statement, the compiler will complain :)
**EDIT / GOTCHA**
According to [MS documentation](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.aspx) You should not call dispose on references to share point shared objects which are returned by GetContextSite. So, you should be extra careful here.
See [this answer](https://stackoverflow.com/questions/415313/what-happens-to-an-idisposable-object-created-in-the-middle-of-a-statement-that-i#456313) for a safe sharepoint pattern you should use.
> However, if you have a reference to a
> shared resource, such as when the
> object is provided by the
> GetContextSite method in a Web Part,
> do not use either method to close the
> object. Using either method on a
> shared resource causes an Access
> Violation error to occur. In scenarios
> where you have a reference to a shared
> resource, instead let Windows
> SharePoint Services or your portal
> application manage the object. | The following is more idiomatic and reads better as well:
```
using (SPWeb spWeb = SPControl.GetContextSite(HttpContext.Current).OpenWeb())
{
SPUser spUser = spWeb.SiteUsers[@"foo\bar"];
}
``` | What happens to an IDisposable object created in the middle of a statement that I cannot explicity call Dispose() on? | [
"",
"c#",
"sharepoint",
"garbage-collection",
"dispose",
""
] |
Is it possible to pass parts of a linq Query into a function?
I want create a common interface for my DAL that always uses the same query interface. For example,
```
List<T> Get(Join j, Where w, Select s){
return currentDataContext<T>.Join(j).Where(w).Select(s).ToList();
}
```
Is this sort of thing possible? I'm thinking it would be done with expression trees, but I haven't been able to find examples of it. | Well, the "join" is tricky, because it is very hard to express a join - but things like where / select / orderby are pretty easy...
Really, it is just a case of combining the various LINQ methods on `IQueryable<T>`, which generally accept `Expression<Func<...>>` for some combination. So a basic select with an optional predicate would be:
```
public IQueryable<T> Get<T>(
Expression<Func<T,bool>> predicate
) where T : class
{
IQueryable<T> query = (IQueryable<T>)GetTable(typeof(T));
if (predicate != null) query = query.Where(predicate);
return query;
}
```
I would tend to return `IQueryable<T>` too, since that is fully composable. If the caller wants a list, they can always use `ToList()` on it... or (for example):
```
using(var ctx = new MyDataContext(CONN))
{
ctx.Log = Console.Out;
int frCount = ctx.Get<Customer>(c => c.Country == "France").Count();
}
```
which (using Northwind) does the query:
```
SELECT COUNT(*) AS [value]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[Country] = @p0
```
The problem with including the "select" (projection) in the query is that you would end up with multiple generic types. Since you often want the projection the be an anonymous type, it would then be pretty impossible to specify the projection type (anonymous) **and** the table-type, and it would not be callable.
In reality, I wonder if there is much benefit writing such a method at all. I might just stick with a base method:
```
public IQueryable<T> Get<T>() where T : class
{
return (IQueryable<T>)GetTable(typeof(T));
}
```
And let the caller compose it in their preferred way - perhaps with query syntax:
```
var list = (from cust in ctx.Get<Customer>()
where cust.Country == "France"
select cust.CompanyName).Take(10).ToList();
```
Which uses:
```
SELECT TOP (10) [t0].[CompanyName]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[Country] = @p0
```
---
Alternatively, if you really do want to include the order by and projection, then an extension method is the most practical approach; then you don't need to specify the original (source) T (which is what makes it uncallable when mixed with anon-types):
```
public static class QueryExtension
{
public static IQueryable<TProjection>
Get<TSource, TProjection, TOrderKey>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> where, // optional
Expression<Func<TSource, TProjection>> select,
Expression<Func<TProjection, TOrderKey>> orderBy)
{
if (where != null) source = source.Where(where);
return source.Select(select).OrderBy(orderBy);
}
}
```
Then consider a DAL method such as:
```
public List<string> Countries()
{
return Customers.Get(
x=>x.CompanyName != "",
x=>x.Country,
x=>x).Distinct().ToList();
}
```
Which uses (again, with Northwind):
```
SELECT DISTINCT [t0].[Country]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CompanyName] <> @p0
``` | Check this generic class: [TableView.cs](http://blogs.msdn.com/kfarmer/archive/2007/11/13/encapsulation-and-linq-to-sql.aspx).
It basically uses a Func<TEntity, bool> delegate to apply the Where predicate:
```
//...
public TableView(DataContext dataContext, Expression<Func<TEntity, bool>> predicate)
{
this.table = dataContext.GetTable<TEntity>();
this.baseQuery = table.Where(predicate);
this.predicate = predicate.Compile();
}
//...
``` | In LINQ to SQL, how do you pass parts of a LINQ query into a function | [
"",
"c#",
"linq",
"linq-to-sql",
"expression-trees",
""
] |
The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory). It's too slow. Profiling says all the time is spent in `operator new`.
Notes: The application already uses a custom memory allocator that does pooling. The compiler is VC++ 6.0 and the code uses the old RogueWave collections rather than the STL.
The only idea I have right now is to introduce Object Pooling. I'd maintain large collections of pre-allocated objects for each type and re-use them. But this will be a lot of work in this old code, and I'm not yet sure there's enough re-use that it would even help. I was hoping someone smarter than me has an idea. | The only way is to reduce the number of memory allocations. Have you used a profiler that will tell you exactly what is doing the allocation? Are you possibly doing some string manipulation?
If all the time is spent allocating the objects the factory is creating, you may need to go to a pool. | Have you tried using a custom allocator for objects of known size? This is a good technique for speeding up allocations. | How to improve performance of an Abstract Factory when all the time appears to be spent in memory allocation | [
"",
"c++",
"optimization",
""
] |
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.
Which one is closer to LISP: Python or Ruby?
I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?
PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back. | I'd go with Ruby. It's got all kinds of metaprogramming and duck punching hacks that make it really easy to extend. Features like blocks may not seem like much at first, but they make for some really clean syntax if you use them right. Open classes can be debugging hell if you screw them up, but if you're a responsible programmer, you can do things like `2.days.from_now` (example from Rails) really easily (Python can do this too, I think, but with a bit more pain)
PS: Check out ["Why Ruby is an acceptable LISP"](http://www.randomhacks.net/articles/2005/12/03/why-ruby-is-an-acceptable-lisp). | [Peter Norvig](http://norvig.com), [a famous and great lisper](http://norvig.com/paip.html), converted to Python. He wrote the article [Python for Lisp Programmers](http://norvig.com/python-lisp.html), which you might find interesting with its detailed comparison of features.
Python looks like executable pseudo-code. It's easy to pick up, and often using your intuition will just work. Python allows you to easily put your ideas into code.
Now, for web development, Python might seem like a more scattered option than Ruby, with the plethora of Python web frameworks available. Still, in general, Python is a very nice and useful language to know. As Ruby and Python's niches overlap, I agree with Kiv that it is partly a matter of personal taste which one you pick. | Please advise on Ruby vs Python, for someone who likes LISP a lot | [
"",
"python",
"ruby",
"lisp",
""
] |
In ANSI C++, how can I assign the cout stream to a variable name? What I want to do is, if the user has specified an output file name, I send output there, otherwise, send it to the screen. So something like:
```
ofstream outFile;
if (outFileRequested)
outFile.open("foo.txt", ios::out);
else
outFile = cout; // Will not compile because outFile does not have an
// assignment operator
outFile << "whatever" << endl;
```
I tried doing this as a Macro function as well:
```
#define OUTPUT outFileRequested?outFile:cout
OUTPUT << "whatever" << endl;
```
But that gave me a compiler error as well.
I supposed I could either use an IF-THEN block for every output, but I'd like to avoid that if I could. Any ideas? | Use a reference. Note that the reference must be of type `std::ostream`, not `std::ofstream`, since `std::cout` is an `std::ostream`, so you must use the least common denominator.
```
std::ofstream realOutFile;
if(outFileRequested)
realOutFile.open("foo.txt", std::ios::out);
std::ostream & outFile = (outFileRequested ? realOutFile : std::cout);
``` | I assume your program behaves like standard unix tools, that when not given a file will write to standard output, and when given a file will write into that file. You can redirect `cout` to write into another stream buffer. As long as your redirection is alive, everything written to cout is transparently written to the destination you designated. Once the redirection object goes out of scope, the original stream is put and output will write to the screen again:
```
struct CoutRedirect {
std::streambuf * old;
CoutRedirect():old(0) {
// empty
}
~CoutRedirect() {
if(old != 0) {
std::cout.rdbuf(old);
}
}
void redirect(std::streambuf * to) {
old = std::cout.rdbuf(to);
}
}
int main() {
std::filebuf file;
CoutRedirect pipe;
if(outFileRequested) {
file.open("foo.txt", std::ios_base::out);
pipe.redirect(&file);
}
}
```
Now, cout is redirected to the file as long as the pipe is alive in main. You can make it more "production ready" by making it non-copyable, because it's not ready to be copied: If the copy goes out of scope, it would restore the original stream already. | Assigning cout to a variable name | [
"",
"c++",
"cout",
"ofstream",
""
] |
What is the difference between storing a datatable in Session vs Cache? What are the advantages and disadvantages?
So, if it is a simple search page which returns result in a datatable and binds it to a gridview. If user 'a' searches and user 'b' searches, is it better to store it in Session since each user would most likely have different results or can I still store each of their searches in Cache or does that not make sense since there is only one cache. I guess basically what I am trying to say is that would the Cache be overwritten. | One important difference is, that items in the cache can expire (will be removed from cache) after a specified amount of time. Items put into a session will stay there, until the session ends.
ASP.NET can also remove items from cache when the amount of available memory gets small.
Another difference: the session state can be kept external (state server, SQL server) and shared between several instances of your web app (for load balancing). This is not the case with the cache.
Besides of these differences (as others have noted): session is per user/session while cache is per application. | AFAIK, The key difference is session is per user, while cache will be for application scoped items.
As noted in the other answers you can store per user info in the cache, providing you provide a key (either by session or cookie). Then you'd have more control to expire items in the cache and also set dependencies on them. So if the DataTable in question is going to change on a regular basis, then caching is probably an appropriate option. Otherwise, if it is static session might be more appropriate. [Steven Smith has an excellent video on caching at dnrtv](http://dnrtv.com/default.aspx?showID=85) that is worth checking out.
It really depends on what you're trying to achieve, how much time you've got. There are some other alternatives to consider with respect to how you store state in an application.
Depending on how large the table is, you could consider storing the state in a cookie (encrypted if it is sensitive information). Alternatively, if it's application scoped data you cold use a static field on a page or class. There is the Application object as well.
**Update**: I think the key question you have to ask yourself, is who should see this data.
```
Are they going to access the data frequently?
```
(No, don't bother).
```
Is it going to change?
```
(No, use a static field or Application).
```
Is it acceptable for user a and user b to see the same results?
```
(No, use the cache with a key comprising of the username and the search term.).
(Yes, use the cache using a key of the search term).
Honestly though, if you're not far along in your development, I would consider parking the caching/state issue to a later date - you might not even need it.
The first three rules of performance tuning are:
1. Measure, 2. Measure some more. 3. Measure again... | Advantages of Cache vs Session | [
"",
"c#",
"asp.net",
"session",
"caching",
"viewstate",
""
] |
what will happen with the overlapping portion of boost once C++0x becomes mainstream?
Will boost still contain everything it used to, or will they adapt the library to update it with the new std:: stuff?
Will boost have both a normal c++ version and a c++0x version that they will maintain? | One would *hope* that Boost continues to support existing classes, for a couple of reasons.
First, there is a body of code that uses the overlapping features in Boost that needs to be supported, for some time.
Second, overlapping implementations allow me to select which one I'd prefer to use. There might be some difference between std::Frob and Boost::Frob that is important to my project, and having a choice is good.
In the long term, though, I would expect a migration toward the standard from both the application writers and the tools providers. That makes it a less risky choice to go with std::. | I am not affiliated with Boost and have no they idea what they will do but it seems like Boost will be left untouched.
There already has been released TR1 (VS 2008 feature pack) and Boost was left untouched. Since many users have not adopted Boost or TR1 yet, my prediction is that for at least next five years boost and c++0x libraries will exist in different namespaces and availaible for C++0x users as well as C++ users. | what will happen with the overlapping portion of boost once C++0x becomes mainstream? | [
"",
"c++",
"boost",
"c++11",
""
] |
How can I change the Text for a CheckBox without a postback?
```
<asp:CheckBox ID="CheckBox1" runat="server" Text="Open" />
```
I would like to toggle the Text to read "Open" or "Closed" when the CheckBox is clicked on the client. | ```
function changeCheckboxText(checkbox)
{
if (checkbox.checked)
checkbox.nextSibling.innerHTML = 'on text';
else
checkbox.nextSibling.innerHTML = 'off text';
}
```
called as:
```
<asp:CheckBox runat="server" ID="chkTest" onclick="changeCheckboxText(this);" />
```
Just FYI, it's usually bad practice to change the text of the checkbox label because it tends to confuse the user. | If you're interested to use a framework javascript like jQuery, i propose a solution ilke this:
```
$("input[id$=CheckBox1]").click(function() {
if ($(this).attr("checked")) {
$(this).next("label:first").text("Open");
}
else {
$(this).next("label:first").text("Close");
}
});
``` | Change the Text of an asp:CheckBox when clicked | [
"",
"asp.net",
"javascript",
"checkbox",
""
] |
In several questions I've seen recommendations for the [Spirit](http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/index.html) parser-generator framework from [boost.org](http://www.boost.org/), but then in the comments there is grumbling from people using Spirit who are not happy. Will those people please stand forth and explain to the rest of us what are the drawbacks or downsides to using Spirit? | It is a quite cool idea, and I liked it; it was especially useful to really learn how to use C++ templates.
But their documentation recommends the usage of spirit for small to medium-size parsers. A parser for a full language would take ages to compile.
I will list three reasons.
* Scannerless parsing. While it's quite simpler, when backtracking is required it may slow down the parser. It's optional though - a lexer might be integrated, see the C preprocessor built with Spirit. A grammar of ~300 lines (including both .h and .cpp files) compiles (unoptimized) to a file of 6M with GCC. Inlining and maximum optimizations gets that down to ~1,7M.
* Slow parsing - there is no static checking of the grammar, neither to hint about excessive lookahead required, nor to verify basic errors, such as for instance usage of left recursion (which leads to infinite recursion in recursive-descent parsers LL grammars). Left recursion is not a really hard bug to track down, though, but excessive lookahead might cause exponential parsing times.
* Heavy template usage - while this has certain advantages, this impacts compilation times and code size. Additionally, the grammar definition must normally be visible to all other users, impacting even more compilation times.
I've been able to move grammars to .cpp files by adding explicit template instantiations with the right parameters, but it was not easy.
UPDATE: my response is limited to my experience with Spirit classic, not Spirit V2. I would still expect Spirit to be heavily template-based, but now I'm just guessing. | In boost 1.41 a new version of Spirit is being released, and it beats of pants off of spirit::classic:
> After a long time in beta (more than 2
> years with Spirit 2.0), Spirit 2.1
> will finally be released with the
> upcoming Boost 1.41 release. The code
> is very stable now and is ready for
> production code. We are working hard
> on finishing the documentation in time
> for Boost 1.41. You can peek at the
> current state of the documentation
> here. Currently, you can find the code
> and documentation in the Boost SVN
> trunk. If you have a new project
> involving Spirit, we highly recommend
> starting with Spirit 2.1 now. Allow me
> to quote OvermindDL's post from the
> Spirit mailing list:
>
> > > I may start to sound like a bot with
> > > how often I say this, but
> > > Spirit.Classic is ancient, you should
> > > switch to Spirit2.1, it can do
> > > everything you did above a GREAT deal
> > > easier, a lot less code, and it
> > > executes faster. For example,
> > > Spirit2.1 can build your entire AST
> > > inline, no weird overriding, no need
> > > to build things up afterwards, etc...,
> > > all as one nice and fast step. You
> > > really need to update. See the other
> > > posts from the past day for links to
> > > docs and such for Spirit2.1. Spirit2.1
> > > is currently in Boost Trunk, but will
> > > be formally released with Boost 1.41,
> > > but is otherwise complete. | What are the disadvantages of the Spirit parser-generator framework from boost.org? | [
"",
"c++",
"parsing",
"boost",
"boost-spirit",
"parser-generator",
""
] |
I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this:
```
<a class="article" href="#5">
```
I then use jQuery to find the a.article elements and attach the appropriate event handler. *(don't get too hung up on the usability or semantics here, it's just an example)*
Anyway, this method works, but it [smells](https://stackoverflow.com/questions/114342/what-are-code-smells-what-is-the-best-way-to-correct-them) a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?)
The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of).
```
<a articleid="5" href="link/for/non-js-users.html">
```
In [my recent question](https://stackoverflow.com/questions/427262/) I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the `class` attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution.
Another method I'd used in the past was to actually generate some JS and insert it into the page in a `<script>` tag, creating a struct which would associate with the object.
```
var myData = {
link0 : {
articleId : 5,
target : '#showMessage'
// etc...
},
link1 : {
articleId : 13
}
};
<a href="..." id="link0">
```
But this can be a real pain in butt to maintain and is generally just very messy.
So, to get to the question, **how do you store arbitrary pieces of information for HTML tags**? | Which version of HTML are you using?
In HTML 5, it is totally valid to have [custom attributes prefixed with data-](https://www.w3schools.com/tags/att_global_data.asp), e.g.
```
<div data-internalid="1337"></div>
```
In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.
If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain. | If you are using jQuery already then you should leverage the "data" method which is the recommended method for storing arbitrary data on a dom element with jQuery.
To store something:
```
$('#myElId').data('nameYourData', { foo: 'bar' });
```
To retrieve data:
```
var myData = $('#myElId').data('nameYourData');
```
That is all that there is to it but take a look at the [jQuery documentation](http://docs.jquery.com/Core/data) for more info/examples. | How to store arbitrary data for some HTML tags | [
"",
"javascript",
"html",
""
] |
How do I split a number by the decimal point in php?
I've got $num = 15/4; which turns $num into 3.75. I would like to split out the 3 and the 75 parts, so $int = 3 and $dec = 75. My non-working code is:
```
$num = 15/4; // or $num = 3.75;
list($int, $dec) = split('.', $num);
```
but that results in empty $int and $dec.
Thanks in advance. | If you `explode` the decimal representation of the number, you lose precision. If you don't mind, so be it (that's ok for textual representation). Take the locale into account! We Belgians use a comma (at least the non-programming ones :).
If you *do* mind (for computations e.g.), you can use the `floor` function:
```
$num = 15/4
if ($num > 0) {
$intpart = floor( $num ); // results in 3
$fraction = $num - $intpart; // results in 0.75
} else {
$intpart = ceil( $num ); // results in -3
$fraction = $num - $intpart; // results in -0.75
}
``` | ```
$num = 15/4; // or $num = 3.75;
list($int, $dec) = explode('.', $num);
``` | Split a number by decimal point in php | [
"",
"php",
"split",
""
] |
I am using the singleton pattern in all my PHP class files.
Would it by any chance cause a user's action on the site to conflict with other user's action?
For instance, when the application goes live and we have several users on the site at the same time, doing similar things hereby calling the same PHP classes (behind the scene), since singleton prevents multiple instance of a class and returns just a single instance.
e.g. I have a class called Search.php and it is a singleton class. This class handles all search queries from the website. If several users are performing a search on the site at the same time, will their actions conflict with each other since its just a single instance of the Search class that can be created.
Thanks very much for your time. | The short answer is no.
Each page request is handled as a unique instance and the only thing that tie them together for each user is the session cookie. Try to think of PHP as an application which starts when you call a script and dies when the script finishes. It does not maintain any state and is not inherently aware of any other PHP instances.
The singleton pattern is simply a way for you to design a class, where you can call it anywhere in your code (like a global) without having to care about whether it already has been instantiated or not and you want it to persist in memory. | Each request is self contained and does not share data with other requests (unless you use specific extensions for that, like memcache). So having singletons in your application would not affect separate requests from separate users.
What should be of concern to you is your overuse of the singleton pattern. A singleton is an OO version of a global, and can cause some weird bugs if you are not careful. It is better to use scoped operations that do not rely on global settings, and use singletons sparingly. | Are PHP singleton classes somehow shared between requests? | [
"",
"php",
"class",
"singleton",
""
] |
What is used instead of [Maven](http://en.wikipedia.org/wiki/Apache_Maven) for C# Windows Forms projects?
We have developers all over the world and are trying to come up with some dependency management system that is clean simple and fast. | There is [Byldan](http://byldan.codeplex.com/), but the project seems quite young.
(See also Stack Overflow question *[Is there a Maven alternative or port for the .NET world?](https://stackoverflow.com/questions/652583/is-there-a-maven-alternative-or-port-for-the-net-world)*.) | I wrote a tutorial on the subject, *[Using Maven to manage .NET projects](https://web.archive.org/web/20110830022107/http://docs.codehaus.org/display/MAVENUSER/Using+Maven+to+manage+.NET+projects)*. | Is there an alternative to Maven for .NET/Windows Forms projects? | [
"",
"c#",
"dependencies",
""
] |
I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views?
regards
chriss | Personally, I'd use one view to handle each form's POST.
On the other hand, you could use a hidden input element that indicate which form was used
```
<form action="/blog/" method="POST">
{{ blog_form.as_p }}
<input type="hidden" name="form-type" value"blog-form" /> <!-- set type -->
<input type="submit" value="Submit" />
</form>
...
<form action="/blog/" method="POST">
{{ micro_form.as_p }}
<input type="hidden" name="form-type" value"micro-form" /> <!-- set type -->
<input type="submit" value="Submit" />
</form>
```
With a view like:
```
def blog(request):
if request.method == 'POST':
if request.POST['form-type'] == u"blog-form": # test the form type
form = BlogForm(request.POST)
...
else:
form = MicroForm(request.POST)
...
return render_to_response('blog.html', {
'blog_form': BlogForm(),
'micro_form': MicroForm(),
})
```
... but once again, I think one view per form (even if the view only accepts POSTs) is simpler than trying to do the above. | like ayaz said, you should give unique name to form submit button
```
<form action="." method="post">
......
<input type="submit" name="form1">
</form>
<form action="." method="post">
......
<input type="submit" name="form2">
</form>
#view
if "form1" in request.POST:
...
if "form2" in request.POST:
...
``` | How to process two forms in one view? | [
"",
"python",
"django",
"django-forms",
"django-templates",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.