Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I want to show the results of this code in my TextBox:
```
string txtout1 = txtOrgText.Text.Replace(parm, txtTo.Text).ToString();
txtout = txtout1;
```
I have a textbox, `txtOrgtext`, into which the user inputs text. I want to put some text into txtout now.
I have set txtout to ReadOnly and MultiLine.
When I try running my program, I get the following error:
```
Error 1 Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox' C:\Users\xxx\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs 45 25 WindowsFormsApplication1
```
I tried `txtout1.ToString()`, but nothing changes.
I also tried `txtout.Text = txtout1` and get this error :
```
Cross-thread operation not valid:
Control 'txtout' accessed from a thread other than the thread it was created on.
```
I got an error because I used Threading, without Threading it works fine. | What you need to do is:
```
txtout.Text = txtout1;
```
This is because `txtout1` is just a string of characters, while `txtout` is a full TextBox, with all the drawing and colouring and stuff like that.
I see that you were on the right lines with your first line of code - txtOrgText.Text - the `.Text` is used both ways - for reading and writing. (Or "looking" and "changing" is another way of putting it.)
You do this with a lot of other controls - a ComboBox, a Form (to set the caption), a DomainUpDown (the thing with the arrows on the right) to name a few.
The reason that "ToString()" doesn't work is that ToString() is making your string of text into a string of text! It doesn't turn it into a TextBox for you. | txtOut.Text = txtout1; | C# Put string into TextBox | [
"",
"c#",
""
] |
I'm doing an exercise where I store coordinates into a .txt file called mydata, and then read it back from that file. However, I"m having trouble reading it back.
code:
```
#include "std_lib_facilities.h"
// Classes----------------------------------------------------------------------
struct Point{
Point(int a, int b):x(a), y(b) {};
Point(){};
int x;
int y;
};
// Main-------------------------------------------------------------------------
int main()
{
vector<Point> original_points;
vector<Point> processed_points;
cout << "Please enter 7 coordinate pairs.\n";
int x, y;
while(cin >> x >> y){
if(x == -1 || y == -1) break;
original_points.push_back(Point(x, y));}
cout << "Please enter file to send points to.\n";
string name;
cin >> name;
ofstream ost(name.c_str());
if(!ost)error("can't open output file", name);
for(int i = 0; i < original_points.size(); ++i)
ost << original_points[i].x << ',' << original_points[i].y << endl;
ost.close();
cout << "Please enter file to read points from.\n";
string iname;
cin >> iname;
ifstream ist(iname.c_str());
if(!ist)error("can't write from input file", name);
while(ist >> x >> y) processed_points.push_back(Point(x, y));
for(int i = 0; i < processed_points.size(); ++i)
cout << processed_points[i].x << ',' << processed_points[i].y << endl;
keep_window_open();
}
```
To test to see if the data is being read from the file I am pushing it back into a processed points vector, but when I run the program and enter points, it doesn't output any points from the processed\_points vector. I think the problem is in the...
```
while(ist >> x >> y)
```
and this isn't the correct way to read from a file. Any help would be appreciated, thanks. | The `,` you're emitting in the line
```
ost << original_points[i].x << ',' << original_points[i].y << endl;
```
is what stands in your way, since you're NOT reading it back! Either use a space instead of that comma, or, DO read it back... | If you don't need to force reading new line:
```
while( (ist >> x) && ist.ignore(1024,',') && (ist >> y))
processed_points.push_back(Point(x, y));
```
The best way is to read whole line first, and then use stringstream to parse the point.
```
string temp;
while( std::getline(ist,temp) )
{
std::stringstream line(temp);
if( (line >> x) && line.ignore(1024,',') && ( line >> y ) )
processed_points.push_back(Point(x, y));
}
``` | Reading data from a file | [
"",
"c++",
""
] |
I'm trying to group data from the following three tables to create a new table. the `account_no` fields in `bmf` and `acct_map` are actually drawn from `cmf`.
Fields:
```
bmf: account_no, trans_date
cmf: account_no, balance_due
acct_map: account_no, external_id
```
The fields I want in my new table are :
```
external_id, account_no, balance_due
```
When I use query 1, without the `external_id` column, it works fine and populates the data correctly. But when I try query 2, it creates a blank table. Why is this happening?
Query 1:
```
create table paid as
select bmf.account_no, sum(cmf.balance_due) postpaid_balance
from bmf, cmf
where to_char(bmf.trans_date, 'YYYY MM DD') = '1996 08 14' and
bmf.account_no = cmf.account_no
group by bmf.account_no
```
Query 2:
```
create table paid as
select bmf.account_no, sum(cmf.balance_due) postpaid_balance, acct_map.external_id
from bmf, cmf, acct_map
where to_char(bmf.trans_date, 'YYYY MM DD') = '1996 08 14' and
bmf.account_no = cmf.account_no and
acct_map.account_no = bmf.account_no
group by bmf.account_no, acct_map.external_id
``` | Have you tried running your select query only first? I am guessing there is no account\_no in table acct\_map which is matching with account\_no in bmf or cmf. Please check as your query seems to be fine so looks like a data issue. | This is an `inner join`, so I'm guessing that there are no records from Query 1 that share an `account_no` with `acct_map`.
You can quickly test this with the following query:
```
select count(*)
from
acct_map
where
account_no in (select bmf.account_no
from bmf, cmf
where to_char(bmf.trans_date, 'YYYY MM DD') = '1996 08 14' and
bmf.account_no = cmf.account_no)
``` | Creating tables with fields from 3 different tables | [
"",
"sql",
"oracle10g",
""
] |
I would like to add an element to a list that preserve the order of the list.
Let's assume the list of object is *[a, b, c, d]* I have a function *cmp* that compares two elements of the list. if I add f object which is the bigger I would like it to be at the last position.
maybe it's better to sort the complete list... | `bisect.insort` is a little bit faster, where applicable, than append-then-sort (unless you have a few elements to add before you need the list to be sorted again) -- measuring as usual on my laptop (a speedier machine will of course be faster across the board, but the ratio should remain roughly constant):
```
$ python -mtimeit -s'import random, bisect; x=range(20)' 'y=list(x); bisect.insort(y, 22*random.random())'
1000000 loops, best of 3: 1.99 usec per loop
```
vs
```
$ python -mtimeit -s'import random, bisect; x=range(20)' 'y=list(x); y.append(22*random.random()); y.sort()'
100000 loops, best of 3: 2.78 usec per loop
```
How much you care about this difference, of course, depend on how critical a bottleneck this operation is for your application -- there are of course situation where even this fraction of a microsecond makes all the difference, though they are the exception, not the rule.
The `bisect` module is not as flexible and configurable -- you can easily pass your own custom comparator to sort (although if you can possibly put it in the form of a key= argument you're *strongly* advised to do that; in Python 3, only key= remains, cmp= is gone, because the performance just couldn't be made good), while bisect rigidly uses built-in comparisons (so you'd have to wrap your objects into wrappers implementing `__cmp__` or `__le__` to your liking, which also has important performance implications).
In your shoes, I'd start with the append-then-sort approach, and switch to the less-handy bisect approach only if profiling showed that the performance hit was material. Remember [Knuth's](http://en.wikipedia.org/wiki/Optimization_(computer_science)#When_to_optimize) (and Hoare's) famous quote, and [Kent Beck's](http://www.c2.com/cgi/wiki?MakeItWorkMakeItRightMakeItFast) almost-as-famous one too!-) | Yes, this is what [bisect.insort](http://effbot.org/librarybook/bisect.htm) is for, however it doesn't take a comparison function. If the objects are custom objects, you can override one or more of the [rich comparison methods](http://docs.python.org/reference/datamodel.html#object.__lt__) to establish your desired sort order. Or you could store a 2-tuple with the sort key as the first item, and sort that instead. | is it possible to add an element to a list and preserve the order | [
"",
"python",
""
] |
This my chat mixed with threads to run server and chat at same time. The problem is when I send a message to the chat lets say "Hello" as the first message,
and "bye" as the second
Output will go:
Hello
Byelo And some extra characters that I do not want there
how to remove my chat's extra characters and letters? C++
I tried cout<<"Message: "<
## But it did not seem to work
```
#include <windows.h>
#include <winsock2.h>
#include <stdio.h>
#include <iostream>
#include <cpl.h>
#include <string>
using namespace std;
DWORD WINAPI Thread(LPVOID);
HANDLE Thread_Handle = NULL;
DWORD Thread_ID = 0;
DWORD WINAPI Thread(LPVOID data)
{
while(1){
WSADATA t_wsa; // WSADATA structure
WORD wVers; // version number
int iError; // error number
wVers = MAKEWORD(2, 2); // Set the version number to 2.2
iError = WSAStartup(wVers, &t_wsa); // Start the WSADATA
if(iError != NO_ERROR || iError == 1){
// MessageBox(NULL, (LPCTSTR)"Error at WSAStartup()", (LPCTSTR)"Server::Error", MB_OK|MB_ICONERROR);
WSACleanup();
}
if(LOBYTE(t_wsa.wVersion) != 2 || HIBYTE(t_wsa.wVersion) != 2){
// MessageBox(NULL, (LPCTSTR)"Error at WSAStartup()", (LPCTSTR)"Server::Error", MB_OK|MB_ICONERROR);
WSACleanup();
}
SOCKET sServer;
sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sServer == INVALID_SOCKET || iError == 1){
// MessageBox(NULL, (LPCTSTR)"Invalid Socket!", (LPCTSTR)"Server::Error", MB_OK|MB_ICONERROR);
WSACleanup();
}
SOCKADDR_IN sinServer;
memset(&sinServer, 0, sizeof(sinServer));
sinServer.sin_family = AF_INET;
sinServer.sin_addr.s_addr = INADDR_ANY; // Where to start server?
sinServer.sin_port = htons( 1002); // Port
if(bind(sServer, (LPSOCKADDR)&sinServer, sizeof(sinServer)) == SOCKET_ERROR){
/* failed at starting server */
// MessageBox(NULL, (LPCTSTR)"Could not bind the server!", (LPCTSTR)"Server::Error", MB_OK|MB_ICONERROR);
WSACleanup();
}
while(listen(sServer, 20) == SOCKET_ERROR){
Sleep(10);
}
SOCKET sClient;
int szlength;
szlength = sizeof(sinServer);
sClient = accept(sServer, (LPSOCKADDR)&sinServer, &szlength);
if (sClient == INVALID_SOCKET){
// MessageBox(NULL, (LPCTSTR)"Could not accept this client!", (LPCTSTR)"Server::Error", MB_OK|MB_ICONERROR);
closesocket(sServer);
WSACleanup();
} else {
// MessageBox(NULL, (LPCTSTR)"Accepted a Client!", (LPCTSTR)"Server::Success", MB_OK);
}
// Now we can send/recv data!
int iRet;
char buffer[200];
// strcpy(buffer, "Welcome to our Server!\0");
iRet = send(sClient, buffer, strlen(buffer), 0);
if(iRet == SOCKET_ERROR){
//MessageBox(NULL, (LPCTSTR)"Could not send data!", (LPCTSTR)"Server::Error", MB_OK|MB_ICONERROR);
closesocket(sClient);
closesocket(sServer);
WSACleanup();
}
char autoresponse[80];
int bytes;
// strcpy(autoresponse, "Message Received!");
autoresponse[strlen(autoresponse)-1] = 0;
//MessageBox(NULL, (LPCTSTR)"Server is ready for messages and is hiding!", (LPCTSTR)"Server::Success", MB_OK);
char *cClientMessage;
cClientMessage = new char[600];
cClientMessage[599] = 0;
while(bytes = recv(sClient, cClientMessage, 599, 0)){
if(bytes < 1){
continue;
}
char cRead[99];///////////////////////////////////////////////////////////////////
cout<<"Message: "<<cClientMessage<<" \n";
/////////////////////////////////////////////////////////////////////////////
iRet = send(sClient, autoresponse, strlen(autoresponse), 0);
if(iRet == SOCKET_ERROR){
// MessageBox(NULL, (LPCTSTR)"Could not send response!", (LPCTSTR)"Server::Error", MB_OK|MB_ICONERROR);
}}
delete [] cClientMessage;
// Cleanup
closesocket(sClient);
closesocket(sServer);
// Shutdown Winsock
WSACleanup();
Sleep(10);
}
return (0);
}
int main()
{
Thread_Handle = CreateThread(NULL,0,Thread,(LPVOID)0,0,&Thread_ID);
while(1){
char IP[100];
char message[255];
cout<<"IP: \n";
cin>>IP;
char buffer[150];
WSADATA t_wsa; // WSADATA structure
WORD wVers; // version number
int iError; // error number
wVers = MAKEWORD(2, 2); // Set the version number to 2.2
iError = WSAStartup(wVers, &t_wsa); // Start the WSADATA
if(iError != NO_ERROR || iError == 1){
MessageBox(NULL, (LPCTSTR)"Error at WSAStartup()", (LPCTSTR)"Client::Error", MB_OK|MB_ICONERROR);
WSACleanup();
return 0;
}
/* Correct version? */
if(LOBYTE(t_wsa.wVersion) != 2 || HIBYTE(t_wsa.wVersion) != 2){
MessageBox(NULL, (LPCTSTR)"Error at WSAStartup()", (LPCTSTR)"Client::Error", MB_OK|MB_ICONERROR);
WSACleanup();
return 0;
}
SOCKET sClient;
sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sClient == INVALID_SOCKET || iError == 1){
MessageBox(NULL, (LPCTSTR)"Invalid Socket!", (LPCTSTR)"Client::Error", MB_OK|MB_ICONERROR);
WSACleanup();
return 0;
}
SOCKADDR_IN sinClient;
memset(&sinClient, 0, sizeof(sinClient));
char cIP[50];
sinClient.sin_family = AF_INET;
sinClient.sin_addr.s_addr = inet_addr(IP); // Where to start server?
sinClient.sin_port = htons(1003); // Port
if(connect(sClient, (LPSOCKADDR)&sinClient, sizeof(sinClient)) == SOCKET_ERROR){
/* failed at starting server */
MessageBox(NULL, (LPCTSTR)"Could not connect to the server!", (LPCTSTR)"Client::Error", MB_OK|MB_ICONERROR);
WSACleanup();
return 0;
}
while(1){
cout<<"Message: \n";
cin.getline(message,255);
string input2 = message;
// Now we can send/recv data!
int iRet;
char cBuffer[600];
char buffer2[260];
// MessageBox(NULL, (LPCTSTR)"Connected!", (LPCTSTR)"Client::Server", MB_OK|MB_ICONEXCLAMATION);
strcpy(buffer, message );
iRet = send(sClient, buffer, strlen(buffer), 0); //send data
if(iRet == SOCKET_ERROR){
MessageBox(NULL, (LPCTSTR)"Could not send data!", (LPCTSTR)"Client::Error", MB_OK|MB_ICONERROR);
WSACleanup();
return 0;
}
}
int bytes;
bytes = SOCKET_ERROR;
char *cServerMessage;
cServerMessage = new char[600];
while(bytes = recv(sClient, cServerMessage, 599, 0)){
if(bytes == SOCKET_ERROR){
char cError[500];
sprintf(cError, "Connection failed, WINSOCK error code: %d", WSAGetLastError());
MessageBox(NULL, (LPCTSTR)cError, (LPCTSTR)"Client::Error", MB_OK|MB_ICONERROR);
closesocket(sClient);
// Shutdown Winsock
WSACleanup();
return 0;
}
if (bytes == 0 || bytes == WSAECONNRESET) {
MessageBox(NULL, (LPCTSTR)"Connection Disconnected!", (LPCTSTR)"Client::Error", MB_OK|MB_ICONERROR);
closesocket(sClient);
// Shutdown Winsock
WSACleanup();
return 0;
}
if(bytes < 1){
Sleep(300);
continue;
}
delete [] cServerMessage;
// Cleanup
closesocket(sClient);
// Shutdown Winsock
WSACleanup();
return 0;
}
Sleep(10);
// This is how to terminate a thread // TerminateThread(Thread_Handle,0);
}
return 0;
}
``` | `recv()` doesn't append a `'\0'` to the end of the bytes written. You need to use the return value of `recv()` and add the `'\0'` yourself. | If you don't care about the extra byte of bandwidth, the quickest fix is probably just to send strlen(buffer)+1 bytes insead of strlen(buffer) bytes in your call to send(). | how to remove my chat's extra characters? C++ | [
"",
"c++",
"sockets",
""
] |
I have an image in my project stored at Resources/myimage.jpg. How can I dynamically load this image into Bitmap object? | The best thing is to add them as Image Resources in the Resources settings in the Project. Then you can get the image directly by doing Resources.myimage. This will get the image via a generated C# property.
If you just set the image as Embedded Resource you can get it with:
```
string name = "Resources.myimage.jpg"
string namespaceName = "MyCompany.MyNamespace";
string resource = namespaceName + "." + name;
Type type = typeof(MyCompany.MyNamespace.MyTypeFromSameAssemblyAsResource);
Bitmap image = new Bitmap(type.Assembly.GetManifestResourceStream(resource));
```
Where MyTypeFromSameAssemblyAsResource is any type that you have in your assembly. | Are you using Windows Forms? If you've added the image using the Properties/Resources UI, you get access to the image from generated code, so you can simply do this:
```
var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
``` | Load image from resources area of project in C# | [
"",
"c#",
"image",
"winforms",
"load",
""
] |
I understand how a transaction might be useful for co-ordinating a pair of updates. What I don't understand is wrapping single statements in transactions, which is 90% of what I've ever seen. In fact, in real life code it is more common in my experience to find a series of logically related transactions each wrapped in their own transaction, but the whole is not wrapped in a transaction.
**In MS-SQL, is there any benefit from wrapping single selects, single updates, single inserts or single deletes in a transaction?**
I suspect this is superstitious programming. | It does nothing. All individual SQL Statements, (with rare exceptions like Bulk Inserts with No Log, or Truncate Table) are automaticaly "In a Transaction" whether you explicitly say so or not.. (even if they insert, update, or delete millions of rows).
EDIT: based on @Phillip's comment below... In current versions of SQL Server, Even Bulk Inserts and Truncate Table do write *some* data to the transaction log, although not as much as other operations do. The critical distinction from a transactional perspective, is that in these other types of operations, the data in your database tables being modified is not in the log in a state that allows it to be rolled back.
All this means is that the changes the statement makes to data in the database are logged to the transaction log so that they can be undone if the operation fails.
The only function that the "Begin Transaction", "Commit Transaction" and "RollBack Transaction" commands provide is to allow you to put two or more individual SQL statements into the same transaction.
EDIT: (to reinforce marks comment...) YES, this could be attributed to "superstitious" programming, or it could be an indication of a fundamental misunderstanding of the nature of database transactions. A more charitable interpretation is that it is simply the result of an over-application of consistency which is inappropriate and yet another example of Emersons euphemism that:
*A foolish consistency is the hobgoblin of little minds,
adored by little statesmen and philosophers and divines* | As Charles Bretana said, "it does nothing" -- nothing in addition to what is already done.
Ever hear of the "ACID" requirements of a relational database? That "A" stands for Atomic, meaning that either the statement works in its entirety, or it doesn't--and while the statement is being performed, **no** other queries can be done *on the data affected by that query.* BEGIN TRANSACTION / COMMIT "extends" this locking functionality to the work done by multiple statements, but it adds nothing to single statements.
**However,** the database transaction log is **always** written to when a database is modified (insert, update, delete). This is not an option, a fact that tends to irritate people. Yes, there's wierdness with bulk inserts and recovery modes, but it still gets written to.
I'll name-drop isolation levels here too. Fussing with this will impact individual commands, but doing so will still not make a declared-transaction-wrapped query perform any differently than a "stand-alone" query. (Note that they can be very powerful and very dangeroug with multi-statement declared transactions.) Note also that "nolock" does *not* apply to inserts/updates/deletes -- those actions always required locks. | What does a transaction around a single statement do? | [
"",
"sql",
"sql-server",
"transactions",
""
] |
I'm new to C#. I'm building an application that persists an XML file with a list of elements. The structure of my XML file is as follows:
```
<Elements>
<Element>
<Name>Value</Name>
<Type>Value</Type>
<Color>Value</Color>
</Element>
<Element>
<Name>Value</Name>
<Type>Value</Type>
<Color>Value</Color>
</Element>
<Element>
<Name>Value</Name>
<Type>Value</Type>
<Color>Value</Color>
</Element>
</Elements>
```
I have < 100 of those items, and it's a single list (so I'm considering a DB solution to be overkill, even SQLite). When my application loads, I want to read this list of elements to memory. At present, after browsing the web a bit, I'm using XmlTextReader.
However, and maybe I'm using it in the wrong way, I read the data tag-by-tag, and thus expect the tags to be in a certain order (otherwise the code will be messy). What I would like to do is read complete "Element" structures and extract tags from them by name. I'm sure it's possible, but how?
To clarify, the main difference is that the way I'm using XmlTextReader today, it's not tolerant to scenarios such as wrong order of tags (e.g. Type comes before Name in a certain Element).
What's the best practice for loading such structures to memory in C#? | Any particular reason you're not using XmlDocument?
```
XmlDocument myDoc = new XmlDocument()
myDoc.Load(fileName);
foreach(XmlElement elem in myDoc.SelectNodes("Elements/Element"))
{
XmlNode nodeName = elem.SelectSingleNode("Name/text()");
XmlNode nodeType = elem.SelectSingleNode("Type/text()");
XmlNode nodeColor = elem.SelectSingleNode("Color/text()");
string name = nodeName!=null ? nodeName.Value : String.Empty;
string type = nodeType!=null ? nodeType.Value : String.Empty;
string color = nodeColor!=null ? nodeColor.Value : String.Empty;
// Here you use the values for something...
}
``` | It's *really* easy to do in LINQ to XML. Are you using .NET 3.5? Here's a sample:
```
using System;
using System.Xml.Linq;
using System.Linq;
class Test
{
[STAThread]
static void Main()
{
XDocument document = XDocument.Load("test.xml");
var items = document.Root
.Elements("Element")
.Select(element => new {
Name = (string)element.Element("Name"),
Type = (string)element.Element("Type"),
Color = (string)element.Element("Color")})
.ToList();
foreach (var x in items)
{
Console.WriteLine(x);
}
}
}
```
You probably want to create your own data structure to hold each element, but you just need to change the "Select" call to use that. | C# newbie: reading repetitive XML to memory | [
"",
"c#",
"xml",
""
] |
I have a complex data type, including a number of functions, as well as the usual get and get methods. My life would be considerably easier if I could use WCF so my client can also use this data type.
Do I
1. Ignore all the operations, putting `[DataMemeber]` only where needed.
2. Put the class in question in a shared library assembly for both client and server to access.
Thanks,
Roberto
PS. I realise that the question is probably not as well worded as it could be. | Ok, it turns out to be a combination of all the above answers.
1. Stick the data classes into a shared assembly, referenced from both the client and server projects.
2. Make sure you have the "Reuse Types in Referenced Assemblies" item checked in the "Configure Service Reference" dialog.
3. At the begining of each of your data contracts put a [KnownType] attribute.
The code looks like so:
```
[DataContract]
[KnownType(typeof(WHS2SmugmugShared.Photo))]
[KnownType(typeof(WHS2SmugmugShared.PhotoInfo))]
public class Photo
{
//code here
}
```
In the above case, I use PhotoInfo in the Photo class. PhotoInfo does NOT have a KnownType attribute associated with it in the class file. And it does not appear to be required.
This allows you to serialize complex types but still keep their operations. | All that's transferred across the WCF boundary is what is serialized - which amounts to the class's state. The methods won't be. So if you need them to be available both sides, then you'll need a shared library as you suggest.
When you add a service reference, you have the option to reuse the data type, in which case WCF will deserialize into the shared class, complete with methods. But it's only the field values that have actually been transferred across the boundary. | Can I add a WCF DataContract to a complex type? | [
"",
"c#",
".net",
"wcf",
"visual-studio",
"datacontract",
""
] |
the template code is like this:
```
template <class type1>
struct DefaultInstanceCreator {
type1 * operator ()() {
return new type1;
}
};
template < class type1
, class InstanceCreator = DefaultInstanceCreator<type1> >
class objectCache
{
public:
objectCache (InstanceCreator & instCreator)
:instCreator_ (instCreator) {}
type1* Get() {
type1 * temp = instCreator_ ();
}
private:
InstanceCreator instCreator_;
};
```
this code work well with object class like this:
```
class A{
public:
A(int num){
number = num;
}
int number;
struct CreateInstance {
CreateInstance (int value) : value_ (value) {}
A * operator ()() const{
return new A(value_);
}
int value_;
};
};
objectCache< A, A::CreateInstance > intcache(A::CreateInstance(2));
A* temp = intcache.Get();
cout << temp->number <<endl;
```
when I tried this template with type like int, string...
```
objectCache< int > intcache();
int* temp = intcache.Get();
*temp = 3;
cout <<temp <<endl;
```
I get E left of "'.Get' must have class/struct/union",
I can't find out where is the problem
when I change to
```
objectCache< int > intcache;
```
I get "'objectCache' : no appropriate default constructor available"
use
```
objectCache< int > intcache(DefaultInstanceCreator<int>());
```
I get left of "'.Get' must have class/struct/union" too. | In here, you aren't passing in the parameter to the `intcache` constructor:
```
objectCache< int > intcache();
int* temp = intcache.Get();
```
This causes the first line to revert to the well known ["most vexing parse"](http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/5650981735) of C++, in short, you are declaring `intcache` as a function which takes no parameters and returns `objectCache<int>`.
Maybe you mean this:
```
objectCache< int > intcache;
```
But probably you wanted to pass a factory:
```
objectCache< int > intcache((DefaultInstanceCreator<int>()));
``` | You're declaring a function, instead of a variable. Try this:
```
objectCache< int > intcache;
``` | How to make this template code work? | [
"",
"c++",
"templates",
""
] |
I generally include 1 functions file into the hader of my site, now this site is pretty high traffic and I just like to make every little thing the best that I can, so my question here is,
Is it better to include multiple smaller function type files with just the code that's needed for that page or does it really make no difference to just load it all as 1 big file, my current functions file has all the functions for my whole site, it's about 4,000 lines long and is loaded on every single page load sitewide, is that bad? | It's difficult to say. 4,000 lines isn't that large in the realms of file parsing. In terms of code management, that's starting to get on the unwieldy side, but you're not likely to see much of a measurable performance difference by breaking it up into 2, 5 or 10 files, and having pages include only the few they need (it's better coding practice, but that's a separate issue). Your differential in number-of-lines read vs. number-of-files that the parser needs to open doesn't seem large enough to warrant anything significant. My initial reaction is that this is probably not an issue you need to worry about.
On the opposite side of the coin, I worked on an enterprise-level project where some operations had an `include()` tree that often extended into the hundreds of files. Profiling these operations indicated that the time taken by the `include()` calls alone made up 2-3 seconds of a 10 second load operation (this was PHP4). | If you can install extensions on your server, you should take a look at [APC](http://pecl.php.net/package/APC) ([see also](http://www.php.net/apc)).
*It is free, by the way ;-) ; but you must be admin of your server to install it ; so it's generally not provided on shared hosting...*
It is what is called an "opcode cache".
Basically, when a PHP script is called, two things happen :
* the script is "compiled" into opcodes
* the opcodes are executed
APC keeps the opcodes in RAM ; so the file doesn't have to be re-compiled each time it is called -- and that's a great thing for both CPU-load and performances.
To answer the question a bit more :
* 4,000 lines is not that much, speaking of performances ; Open a couple of files of any big application / Framework, and you'll rapidly get to a couple thousand of lines
* a **really important** thing to take into account is maintenability : what will be easier to work with for you and your team ?
* loading many small files might imply many system calls, which are slow ; but those would probably be cached by the OS... So probably not **that** relevant
* If you are doing even 1 database query, this one *(including network round-trip between PHP server and DB server)* will probably take more time than the parsing of a couple thousand lines ;-) | Which is better performance in PHP? | [
"",
"php",
"performance",
"include",
""
] |
I have a small project that I'm making, and I'm trying to figure out if it's possible to get an instance of every class that inherits from a particular interface.
Here's a simplified example of what I'm trying to accomplish:
```
public interface IExample
{
string Foo();
}
public class Example1 : IExample
{
public string Foo()
{
return "I came from Example1 !";
}
}
public class Example2 : IExample
{
public string Foo()
{
return "I came from Example2 !";
}
}
//Many more ExampleN's go here
public class ExampleProgram
{
public static void Main(string[] args)
{
var examples = GetExamples();
foreach (var example in examples)
{
Console.WriteLine(example.Foo());
}
}
public static List<IExample> GetExamples()
{
//What goes here?
}
}
```
Is there any way (short of hard-coding it) for the GetExamples method to return a list containing an instance of each class inheriting from the interface IExample? Any insight you can give would be much appreciated. | See: [Check if a class is derived from a generic class](https://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class)
Also: [Implementations of interface through Reflection](https://stackoverflow.com/questions/80247/implementations-of-interface-through-reflection) (**this may be exactly what you want**)
You will basically just need to enumerate through every type in the target assembly and test to see if it implements the interface. | Building upon Matt's solution, I would implement it something like this:
```
public static List<IExample> GetExamples()
{
return GetInstances<IExample>().ToList();
}
private static IEnumerable<T> GetInstances<T>()
{
return Assembly.GetExecutingAssembly().GetTypes()
.Where(type => type.IsClass &&
!type.IsAbstract &&
type.GetConstructor(Type.EmptyTypes) != null &&
typeof (T).IsAssignableFrom(type))
.Select(type => (T) Activator.CreateInstance(type));
}
```
This solution skips types that cannot be instantiated such as abstract classes, derived interfaces and classes without default (parameterless) public constructors. | Is it possible to get an instance of every class that inherits from an interface? | [
"",
"c#",
"inheritance",
"instance",
""
] |
I want to delete many rows with the same set of field values in some (6) tables. I could do this by deleting the result of one subquery in every table (Solution 1), which would be redundant, because the subquery would be the same every time; so I want to store the result of the subquery in a temporary table and delete the value of each row (of the temp table) in the tables (Solution 2). Which solution is the better one?
First solution:
```
DELETE FROM dbo.SubProtocols
WHERE ProtocolID IN (
SELECT ProtocolID
FROM dbo.Protocols
WHERE WorkplaceID = @WorkplaceID
)
DELETE FROM dbo.ProtocolHeaders
WHERE ProtocolID IN (
SELECT ProtocolID
FROM dbo.Protocols
WHERE WorkplaceID = @WorkplaceID
)
// ...
DELETE FROM dbo.Protocols
WHERE WorkplaceID = @WorkplaceID
```
Second Solution:
```
DECLARE @Protocols table(ProtocolID int NOT NULL)
INSERT INTO @Protocols
SELECT ProtocolID
FROM dbo.Protocols
WHERE WorkplaceID = @WorkplaceID
DELETE FROM dbo.SubProtocols
WHERE ProtocolID IN (
SELECT ProtocolID
FROM @Protocols
)
DELETE FROM dbo.ProtocolHeaders
WHERE ProtocolID IN (
SELECT ProtocolID
FROM @Protocols
)
// ...
DELETE FROM dbo.Protocols
WHERE WorkplaceID = @WorkplaceID
```
Is it possible to do solution 2 without the subquery? Say doing `WHERE ProtocolID IN @Protocols` (but syntactically correct)?
I am using Microsoft SQL Server 2005. | While you can avoid the subquery in SQL Server with a join, like so:
```
delete from sp
from subprotocols sp
inner join protocols p on
sp.protocolid = p.protocolid
and p.workspaceid = @workspaceid
```
You'll find that this doesn't gain you really any performance over either of your approaches. Generally, with your subquery, SQL Server 2005 optimizes that `in` into an `inner join`, since it doesn't rely on each row. Also, SQL Server will probably cache the subquery in your case, so shoving it into a temp table is most likely unnecessary.
The first way, though, would be susceptible to changes in `Protocols` during the transactions, where the second one wouldn't. Just something to think about. | Can try this
```
DELETE FROM dbo.ProtocolHeaders
FROM dbo.ProtocolHeaders INNER JOIN
dbo.Protocols ON ProtocolHeaders.ProtocolID = Protocols.ProtocolID
WHERE Protocols.WorkplaceID = @WorkplaceID
``` | Using temporary table in where clause | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I know it is possible to create a TestCase or TestSuite with the wizard within JUnit, but how does one sync the code after the class under the test has been modified, such as method signature modification or newly added methods. I would like my TestCases to be able to sync up (remove or add) those changed methods/parameters/method signatures within my TestCases.
I tried searching on Google to no avail, maybe there is an eclipse plugin for that? | Tests which have a 1-1 relationship with the structure of the production code are a test smell. It's much better for the tests to be written as a specification of the system's behaviour (~one test per behaviour), instead of having tests generated based on the production code (~one test per method).
Quoted from <http://blog.daveastels.com/files/BDD_Intro.pdf>
> When you realize that it's all about specifying behaviour and not writing tests, your point of
> view shifts. Suddenly the idea of having a Test class for each of your production classes is ridiculously
> limiting. And the thought of testing each of your methods with its own test method (in a
> 1-1 relationship) will be laughable. | As has been mentioned before, refactorings such as renames or moves will be automatically reflected in the test cases as long as you refactor using the Eclipse tooling and not by manually renaming for example.
As for new methods, it's impossible to generate tests automatically. Of course there are some exceptions for auto-generated code where you control the generation and where you could generate test cases as well but for "normal" manual code the best you could do was to provide stubs (empty methods), and what's the use in that?
A better approach is to track [code coverage](http://en.wikipedia.org/wiki/Code_coverage) using a tool such as [Cobertura](http://cobertura.sourceforge.net/) or [Emma](http://emma.sourceforge.net/), which happens to have a [nice Eclipse plugin](http://www.eclemma.org/) that allows you to see, inside your source code, what code is being covered by tests and which isn't. This then is your report of where you need more testing. | Is it possible to synchronize JUnit test cases with the classes under tests within Eclipe? | [
"",
"java",
"eclipse",
"synchronization",
"junit",
"junit4",
""
] |
first of all thank you all for reading this.
i want to populate my database (derby) every time i run the test class to be able to perform test like delete or update or deletebyid stuffs.
I use
```
<property name="hibernate.hbm2ddl.auto">create</property>
```
in my hibernate.cfg.xml file so i'm expecting the database to be first drop and created each time i run the test.
i used the class constructor or setup methods but soon realized that they are called the number of time there is a test method in the class (i assume the beforetest and the rest behave the same).
So my question is how do i setup the initial data to work with?
thanks for reading. | Assuming JUnit 4: There are two groups of annotations, which can be used to trigger the execution of code before and after running the actual test case method(s):
**Before**
> Methods annotated with this marker are
> executed by the JUnit framework before
> it calls the next test case method.
**After**
> Methods annotated with this marker are executed by JUnit after the
> actual test case method has been run.
**BeforeClass**
> Methods marked with this annotation will be executed only once (before
> JUnit runs the first test case). If I read your post correctly, this
> is the option you actually want.
**AfterClass**
> Methods tagged with this annotation will be executed only once (after JUnit has run the
> last test case).
```
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class SomeTest {
@Test
public void test1() {
System.out.println("test1");
}
@Test
public void test2() {
System.out.println("test2");
}
@Before
public void setUp() {
// Here goes the code, which makes sure, all tests
// see the same context
System.out.println("setUp");
}
@BeforeClass
public static void setUpGlobals() {
// Expensive hibernate set-up will go here. It is
// called only once
System.out.println("setUpGlobals");
}
}
```
will produce the output
* setUpGlobals
* setUp
* test1
* setUp
* test2 | Take a look at [DbUnit](http://www.dbunit.org/), it's a JUnit extension aimed to ease db based application testing. One of its features is to have a pre-defined datasets, which populate the database on the beginning of the test. See more here - <http://www.dbunit.org/components.html#dataset> | create initial data for hibernate driven testing | [
"",
"java",
"unit-testing",
"hibernate",
""
] |
though I haven't worked with sockets professionally, I find them interesting. I read some part of Unix Network Programming by Richard Stevens (considered to be the Bible I suppose as it is referred by everyone I ask) but the problem is the examples require a universal header unp.h which is a PIA to use.
Can some of you suggest a good reading for socket programming in Unix/Linux? Considering I am relatively experienced C/C++ coder. | The canonical reference is *UNIX Network Programming* by W. Richard Stevens. upn.h is really just a helper header, to make the book examples clearer - it doesn't do anything particularly magic.
To get up and running very quickly, it's hard to go past [Beej's Guide To Network Programming using Internet Sockets](http://beej.us/guide/bgnet/). | I used [Beej's Guide to Network Programming](http://beej.us/guide/bgnet/)
There's plenty of examples of client and server code with explanations at each step of the way. | Good Readings on Unix/Linux Socket Programming? | [
"",
"c++",
"linux",
"sockets",
""
] |
I have a dll file in the workspace of the project which is under maintenance. Is there any method to keep a watch on the dll and see which executable is loading it?
EDIT: I just need to find out which executable loads the dll? Can it be found using Process Explorer. I tried using FileMon by watching the events matching the file name. It didn't work. | You can use [ProcessExplorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to see who is **currently** using or locking a dll.
I'm not aware of any tool that can tell you which executable references your dll *without* the exe actually running. Unless you can know that it is one of a limited number of applications - in which case you could examine each one with [Reflector](http://www.red-gate.com/products/reflector/).
Or you could delete the dll and wait until an executable complains?
This is why the critical (missing) information in your question is whether you are looking to find out who is currently locking your dll, or whether you want to know who will be affected if you change it. | You can use [Filemon](http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx) to monitor any file access to any file you want. | Find out which executable references a .NET dll? | [
"",
"c#",
""
] |
Imagine the following schema and sample data (SQL Server 2008):
```
OriginatingObject
----------------------------------------------
ID
1
2
3
ValueSet
----------------------------------------------
ID OriginatingObjectID DateStamp
1 1 2009-05-21 10:41:43
2 1 2009-05-22 12:11:51
3 1 2009-05-22 12:13:25
4 2 2009-05-21 10:42:40
5 2 2009-05-20 02:21:34
6 1 2009-05-21 23:41:43
7 3 2009-05-26 14:56:01
Value
----------------------------------------------
ID ValueSetID Value
1 1 28
etc (a set of rows for each related ValueSet)
```
I need to obtain the ID of the most recent ValueSet record for each OriginatingObject. Do not assume that the higher the ID of a record, the more recent it is.
I am not sure how to use GROUP BY properly in order to make sure the set of results grouped together to form each aggregate row includes the ID of the row with the highest DateStamp value for that grouping. Do I need to use a subquery or is there a better way? | You can do it with a correlated subquery or using IN with multiple columns and a GROUP-BY.
Please note, simple GROUP-BY can only bring you to the list of OriginatingIDs and Timestamps. In order to pull the relevant ValueSet IDs, the cleanest solution is use a subquery.
Multiple-column IN with GROUP-BY (probably faster):
```
SELECT O.ID, V.ID
FROM Originating AS O, ValueSet AS V
WHERE O.ID = V.OriginatingID
AND
(V.OriginatingID, V.DateStamp) IN
(
SELECT OriginatingID, Max(DateStamp)
FROM ValueSet
GROUP BY OriginatingID
)
```
Correlated Subquery:
```
SELECT O.ID, V.ID
FROM Originating AS O, ValueSet AS V
WHERE O.ID = V.OriginatingID
AND
V.DateStamp =
(
SELECT Max(DateStamp)
FROM ValueSet V2
WHERE V2.OriginatingID = O.ID
)
``` | ```
SELECT OriginatingObjectID, id
FROM (
SELECT id, OriginatingObjectID, RANK() OVER(PARTITION BY OriginatingObjectID
ORDER BY DateStamp DESC) as ranking
FROM ValueSet)
WHERE ranking = 1;
``` | Variant use of the GROUP BY clause in TSQL | [
"",
"sql",
"t-sql",
"group-by",
""
] |
I'm looking for some simple tasks like listing all the running process of a user, or kill a particular process by pid etc. Basic unix process management from Java. Is there a library out there that is relatively mature and documented? I could run a external command from the JVM and then parse the standard output/error but that seems like a lot of work and not robust at all. Any suggestions? | You will need to roll your own solution I think. Killing an external process created using the `Process` APIs can be done using `Process.destroy()`. (But note that `destroy()` as implemented on Linux / Unix does a "soft" kill, not a `SIGKILL`, so the external process may be able to avoid being killed.)
Anything beyond that is non-portable.
* Listing processes (on a Linux machine) can be done by reading the `/proc` file system.
* Other things can be done by calling a native command using `Process`. It depends on whether your management functionality requires use of syscalls that are not available to a "pure" Java program.
* It is possible (in theory) to use JNI and native code to dig around in the JVM's native data structures to find the OS-level PID for the process and send it a signal.
If you go down the JNI + native library route, beware that native pointer problems and native threading issues can kill your JVM. You may also need to deal with building and distributing the native library for multiple architectures, etc. Also beware that the internal data structures are liable to be different for different JVM platforms, releases, etc, and that they are liable to change without notice. | I recommend [JavaSysMon](https://github.com/jezhumble/javasysmon): You can list processes (pid, ppid, name and so on), kill processes (inclusive child processes) and monitor your computer. If you want to use it in a Maven project:
```
<dependency>
<groupId>javasysmon</groupId>
<artifactId>javasysmon</artifactId>
<version>0.3.3</version>
</dependency>
<repository>
<id>javasysmon-repo</id>
<url>http://openr66.free.fr/maven2/</url>
</repository>
``` | What is the best way to manage unix process from java? | [
"",
"java",
"unix",
"posix",
""
] |
The code below is outdated in Python 3.0 by being replaced by `subprocess.getstatusoutput()`.
```
import commands
(ret, out) = commands.getstatusoutput('some command')
print ret
print out
```
The real question is what's the multiplatform alternative to this command from Python because the above code does fail ugly under Windows because getstatusoutput is supported only under Unix and Python does not tell you this, instead you get something like:
```
>test.py
1
'{' is not recognized as an internal or external command,
operable program or batch file.
``` | This would be the multiplatform implementation for getstatusoutput():
```
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
"""This new implementation should work on all platforms."""
import subprocess
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = "".join(pipe.stdout.readlines())
sts = pipe.returncode
if sts is None: sts = 0
return sts, output
``` | I wouldn't really consider this *multiplatform*, but you can use `subprocess.Popen`:
```
import subprocess
pipe = subprocess.Popen('dir', stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = pipe.stdout.readlines()
sts = pipe.wait()
print sts
print output
```
---
Here's a drop-in replacement for `getstatusoutput`:
```
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
"""This new implementation should work on all platforms."""
import subprocess
pipe = subprocess.Popen(cmd, shell=True, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = str.join("", pipe.stdout.readlines())
sts = pipe.wait()
if sts is None:
sts = 0
return sts, output
```
This snippet was proposed by the original poster. I made some changes since `getstatusoutput` duplicates `stderr` onto `stdout`.
---
The problem is that `dir` isn't really a multiplatform call but [`subprocess.Popen`](http://docs.python.org/3.1/library/subprocess.html#subprocess.Popen) allows you to execute shell commands on any platform. I would steer clear of using shell commands unless you absolutely need to. Investigate the contents of the [`os`](http://docs.python.org/3.1/library/os.html), [`os.path`](http://docs.python.org/3.1/library/os.path.html), and [`shutil`](http://docs.python.org/3.1/library/shutil.html) packages instead.
```
import os
import os.path
for rel_name in os.listdir(os.curdir):
abs_name = os.path.join(os.curdir, rel_name)
if os.path.isdir(abs_name):
print('DIR: ' + rel_name)
elif os.path.isfile(abs_name):
print('FILE: ' + rel_name)
else:
print('UNK? ' + rel_name)
``` | What is the multiplatform alternative to subprocess.getstatusoutput (older commands.setstatusoutput() from Python? | [
"",
"python",
"redirect",
"process",
""
] |
I'm writing an IRC bot in Python, due to the alpha nature of it, it will likely get unexpected errors and exit.
What's the techniques that I can use to make the program run again? | You can use `sys.exit()` to tell that the program exited abnormally (generally, 1 is returned in case of error).
Your Python script could look something like this:
```
import sys
def main():
# ...
if __name__ == '__main__':
try:
main()
except Exception as e:
print >> sys.stderr, e
sys.exit(1)
else:
sys.exit()
```
You could call again `main()` in case of error, but the program might not be in a state where it can work correctly again.
It may be safer to launch the program in a new process instead.
So you could write a script which invokes the Python script, gets its return value when it finishes, and relaunches it if the return value is different from 0 (which is what `sys.exit()` uses as return value by default).
This may look something like this:
```
import subprocess
command = 'thescript'
args = ['arg1', 'arg2']
while True:
ret_code = subprocess.call([command] + args)
if ret_code == 0:
break
``` | You can create wrapper using subprocess(<http://docs.python.org/library/subprocess.html>) which will spawn your application as a child process and track it's execution. | How to make the program run again after unexpected exit in Python? | [
"",
"python",
"irc",
""
] |
Suppose I have developed one web portal in PHP/MySQL. I want to make it work in mobile also. What is the easiest way to do this?
Can we use PHP with any mobile based mark up languages like WML or XHTML i.e. as we can use PHP with HTML in web applications used to view in normal web browsers? | PHP has nothing to do directly with the platform you want to display your app on. PHP is just the tool to deliver the kind of markup you need for your page to be displayed on whatever platform you want. It's up to your own knowledge and creativity to render markup which suits your needs. So in other words, yes of course you can send WML, XML, XHTML, you name it to the client!
The client doesn't know anything about PHP anyways (PHP 'exists' only on the server side), the client doesn't understand PHP and doesn't need to. It understands XHTML or any other markup and that's what you have to deliver! What tool you use to do that is completely up to you. PHP is one option.
So all you need to know is for what platform/client you want to render your content and what kind of markup this platform understands and then deliver the right markup to the right platform/client including the respective CSS, js, etc.
What your app does:
1. detect what client is requesting your site
2. see if you're able to send the appropriate markup
3. send this markup or if not available some default or similar markup | PHP is just a tool which generates some markup language (or anything else, actually, which might not be markup-oriented at all) that is understood by the client -- the browser.
Your PHP code will have to be able to generate two kind of different outputs :
* a "full ouput" (likely HTML), which you already have, for computer web browsers
* a "light ouput" (maye VML, maybe HTML too but without some heavy stuff), for mobile-based browsers.
The task you'll have to deal with is to differenciate between mobile and non-mobile users ; this might be done by user-agent sniffing, for instance, or detecting what the client requested.
A nice thing to do could be to use a special domain-name for users of mobile platforms ; something like mobile.example.com ; for instance, so they can bookmark it and directly access the "mobile-version" of your site -- can be useful if your detection doesn't work well ^^
If you are targetting advanced-mobile-machines (like iPhone) which have a not too bad browser, you might want to send them "rich" HTML pages ; just test your pages to verify they fit on the small screen of theses machines ; and, maybe you'll want to send less data (like not display some sidebars, or have a smaller menu, ... )
BTW, what kind of platform do you mean by "mobile" ? Those old phones with small screens, or more power-users-oriented phones, like iPhone / Android / stuff like that ?
This could make quite a difference, actually, as the more recent ones have nice functionnalities that the oldest didn't have ^^
In any case, one important thing to remember :
* you will spend some time making the site work on these devices
* you will have to spend more time maintaining it !
Which means : do something simple, and, as much as possible, use the same PHP code for both mobile and non-mobile version of the site : the less code you duplicate, the less code you'll have to maintain !
Hope these few ideas (not really well sorted, I admit) will help...
Have fun ! | What is the easiest way to convert existing PHP web application to mobile application? | [
"",
"php",
"mysql",
"xhtml",
"mobile",
"portal",
""
] |
Forgive me if this screams newbie but what does `=>` mean in C#? I was at a presentation last week and this operator (I think) was used in the context of ORM. I wasn't really paying attention to the specifics of syntax until I went back to my notes. | In C# the [lambda operator](http://msdn.microsoft.com/en-us/library/bb397687.aspx) is written "=>" (usually pronounced "**goes to**" when read aloud). It means that the arguments on the left are passed into the code block (lambda function / anonymous delegate) on the right.
So if you have a Func or Action (or any of their cousins with more type parameters) then you can assign a lambda expression to them rather than needing to instantiate a delegate or have a separate method for the deferred processing:
```
//creates a Func that can be called later
Func<int,bool> f = i => i <= 10;
//calls the function with 12 substituted as the parameter
bool ret = f(12);
``` | Since nobody mentioned it yet, in VB.NET you'd use the function keyword instead of =>, like so:
```
dim func = function() true
'or
dim func1 = function(x, y) x + y
dim result = func() ' result is True
dim result1 = func1(5, 2) ' result is 7
``` | What does "=>" mean? | [
"",
"c#",
".net",
".net-3.5",
"lambda",
""
] |
I am making a screen capturing application and everything is going fine. All I need to do is capture the active window and take a screenshot of this active window. Does anyone know how I can do this? | ```
ScreenCapture sc = new ScreenCapture();
// capture entire screen, and save it to a file
Image img = sc.CaptureScreen();
// display image in a Picture control named imageDisplay
this.imageDisplay.Image = img;
// capture this window, and save it
sc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif);
```
<http://www.developerfusion.com/code/4630/capture-a-screen-shot/> | ```
Rectangle bounds = Screen.GetBounds(Point.Empty);
using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using(Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save("test.jpg", ImageFormat.Jpeg);
}
```
for capturing current window use
```
Rectangle bounds = this.Bounds;
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(bounds.Left,bounds.Top), Point.Empty, bounds.Size);
}
bitmap.Save("C://test.jpg", ImageFormat.Jpeg);
}
``` | Capture screenshot of active window? | [
"",
"c#",
"screenshot",
"active-window",
""
] |
I have a slew of normal inline `<a>` links that I want to open up small "floating" objects on click. These objects would be simple HTML `div`s (with some CSS) that would load on top of the page and below the link. I don't want to use relative positioning which would push the page around and I can't think of a way to use absolute positioning to get the `div`s underneath the inline links. I currently envision toggling the display value of the objects from none to whatever and back. I'm open to ideas.
Thanks!
Mike | You may use absolute positioning with the parent set to relative. e.g.
```
<div id="container">
<a href=...>hover me for floating!</a>
<div class="floating">
...
</div>
</div>
```
In CSS,
```
#container { position: relative; ... }
.floating { position: absolute; top: 20px; left: 20px; }
```
In the above example, the .floating div is absolute positioned, which means it is taken away from the normal flow (ie, no placeholding it). But it also relative reference to it's parent, which is the div#container in this case, so that, if you set the top and left position, it is actually calculated from the top-left corner of div#container rather than to the document body. | you can use "fixed" position:
```
<div style="position: fixed; left:100px; top:100px; background-color: white; height: 200px; width: 200px;"> ... </div>
```
**"fixed position"** --> Generates an absolutely positioned element, positioned relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties | How can I produce a "floating" object below an inline element in HTML? | [
"",
"javascript",
"html",
"css",
""
] |
How can I make a post request to a different php page within a php script? I have one front end computer as the html page server, but when the user clicks a button, I want a backend server to do the processing and then send the information back to the front end server to show the user. I was saying that I can have a php page on the back end computer and it will send the information back to the front end. So once again, how can I do a POST request to another php page, from a php page? | Possibly the easiest way to make PHP perform a POST request is to use [cURL](http://curl.haxx.se/), either as an [extension](http://php.net/curl) or simply shelling out to another process. Here's a post sample:
```
// where are we posting to?
$url = 'http://foo.com/script.php';
// what post fields?
$fields = array(
'field1' => $field1,
'field2' => $field2,
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// execute post
$result = curl_exec($ch);
// close connection
curl_close($ch);
```
Also check out [Zend\_Http](http://framework.zend.com/manual/en/zend.http.html) set of classes in the Zend framework, which provides a pretty capable HTTP client written directly in PHP (no extensions required).
**2014 EDIT** - well, it's been a while since I wrote that. These days it's worth checking [Guzzle](http://guzzle.readthedocs.org/en/latest/) which again can work with or without the curl extension. | Assuming your php install has the CURL extension, it is probably the easiest way (and most complete, if you wish).
Sample snippet:
```
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
'lname'=>urlencode($last_name),
'fname'=>urlencode($first_name),
'email'=>urlencode($email)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
```
Credits go to [http://php.dzone.com](http://php.dzone.com/news/execute-http-post-using-php-cu).
Also, don't forget to visit the appropriate [page(s)](http://www.php.net/manual/en/ref.curl.php) in the PHP Manual | Post to another page within a PHP script | [
"",
"php",
"post",
"request",
""
] |
I have searched hi and low for a solution for this, basicly I would like a panel with a plus sign next to it and when the user clicks the plus the blank version of form 1 is replicated in a new panel that gets revealed after clicking the + sign:
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
| Form 1 |
| |
| | (+)
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
| Form 2 |
| |
| | (+)(-)
Also it would be handy to have the minus sign to remove the panel again.
Does anybody know of such and thing or can someone point me in the right direction.
Thanks for looking. | Lets assume you've got
```
<div id="wrap">
<div class="duplicate">
something
<span class="plus">+</span>
</div>
</div>
```
What you could do is:
```
$('span.plus').click(function() {
new = $(this).parent().clone().appendTo('#wrap');
$('<span class="minus">-</span>').insertAfter(new.children('span'))
.click(function() {
$(this).parent().remove();
});
});
```
Not tested of course... ;)
Edit: Damn... I assumed you're using jQuery... But it should work in a similar way with any other Javascript framework. | ```
function cloneForm() {
var form1 = document.getElementById( 'form1' );
var form2 = form1.cloneNode( true );
document.insertBefore( form2, form1.nextSibling );
}
```
This one clones the form. But if you want to clone the div the form is on, replace 'form's with 'div'.
Edit: fixed the typo | Dynamically reveal hidden divs | [
"",
"javascript",
"ajax",
""
] |
I have a binary log file with streaming data from a sensor (Int16).
Every 6 seconds, 6000 samples of type Int16 are added, until the sensor is disconnected.
I need to poll this file on regular intervals, continuing from last position read.
Is it better to
a) keep a filestream and binary reader open and instantiated between readings
b) instantiate filestream and binary reader each time I need to read (and keep an external variable to track the last position read)
c) something better?
EDIT: Some great suggestions so far, need to add that the "server" app is supplied by an outside source vendor and cannot be modified. | If it's always adding the same amount of data, it may make sense to reopen it. You might want to find out the length before you open it, and then round down to the whole number of "sample sets" available, just in case you catch it while it's still writing the data. That may mean you read less than you *could* read (if the write finishes between you checking the length and starting the read) but you'll catch up next time.
You'll need to make sure you use appropriate sharing options so that the writer can still write while you're reading though. (The writer will probably have to have been written with this in mind too.) | Can you use [MemoryMappedFiles](http://msdn.microsoft.com/en-us/library/ms810613.aspx)?
If you can, mapping the file in memory and sharing it between processes you will be able to read the data by simply incrementing the offset for your pointer each time.
If you combine it with an event you can signal your reader when he can go in an read the information. There will be no need to block anything as the reader will always read "old" data which has already been written. | c# - reading from binary log file that is updated every 6 seconds with 12k of data | [
"",
"c#",
"filestream",
"binaryreader",
""
] |
I have an object with two arrays of strings. The object is data bound to a listbox. One list is bound as the list's ItemsSource. The other, which is the thing causing me trouble, needs to be bound to a combobox that's part of a DataTemplate that is set to the list's ItemTemplate. Basically each item on the listbox has the corresponding element of the first list and a combo box that contains the second list. In other words, every item in the list has the same combobox of choices.
The problem comes from the fact that it winds up that the DataTemplate is data bound the first list. I was expecting the DataTemplate to be databound to the object that contains both lists. Now, with that happening, I can't figure out what kind of binding syntax I need to get at the "parent" of the DataContext, if that's even possible.
Can someone point me in the right direction?
Thanks! | If I'm understanding you correctly, you can set the DataContext of your ListBox to an instance of a class (in my example I do it in code by: list.DataContext = myclass;) and you want to set the ItemSource of your listbox to a list in the class (ie Items) and the itemssource of your combobox to another list in the class (ie Values). Here's my xaml that seems to work:
```
<ListBox Name="list" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding}"/>
<ComboBox ItemsSource=
"{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListBox}},
Path=DataContext.Values}"
/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
and heres the class that I'm binding to:
```
public class AClass
{
protected List<string> _Items;
public List<string> Items
{
get
{
if (_Items == null)
{
_Items = new List<string>();
}
return _Items;
}
}
protected List<string> _Values;
public List<string> Values
{
get
{
if (_Values == null)
{
_Values = new List<string>();
}
return _Values;
}
}
}
```
In code I created an instance of AClass, added Items and Values, and set the instance to the DataContext of the listbox. | I don't think you want to do what you are trying to do. You are asking for the pain.
What you'd likely want to do instead is reference a static collection inside each item in your collection that contains the subcollection for your ComboBox. So:
```
//Pseudocode
TopLevelEntity
{
SubLevelEntity[] SubItemsForComboBox;
}
```
This way for each "TopLevelEntity" you'd be prepared with your collection of items for the combo box.
```
<ListView ItemsSource="{StaticResource MyCollectionOfTopLevelEntities}">
<ItemTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding SubItemsForComboBox} />
</DataTemplate>
</ItemTemplate>
</ListView>
```
As is my way, I've not verified this code and it's possible it doesn't even compile, but the theory should be sound.
Let us know what you decide to do. | Getting at the "parent" of a databound object? | [
"",
"c#",
"wpf",
"data-binding",
"datatemplate",
""
] |
With three numbers, `$x`, `$y`, and `$z`, I use the following code to find the greatest and place it in `$c`. Is there a more efficient way to do this?
```
$a = $x;
$b = $y;
$c = $z;
if ($x > $z && $y <= $x) {
$c = $x;
$a = $z;
} elseif ($y > $z) {
$c = $y;
$b = $z;
}
``` | Probably the easiest way is `$c = max($x, $y, $z)`. See the documentation on [`max`*Docs*](http://php.net/max) for more information, it compares by the integer value of each parameter but will return the original parameter value. | You can also use an array with max.
```
max(array($a, $b, $c));
```
if you need to | Find greatest of three values in PHP | [
"",
"php",
""
] |
I was thinking about how to secure the Data Layer in a C# Application, the layer could in this case be either a LINQ to SQL Model Diagram stored with the Application itself containg the connection string to the SQL Server Database.
Or it could be connectivity between the application and webservices.
Either you need to impement some sort of security, for instance, the Connection String in a Application can easily be reverse engineered and Webservices can easily be tracked and used for other reasons than the applications original purpose.
So my question is in a shorter way: **How do you solve the security issues when handling Webservices and/or direct connection to a SQL Server From a Windows Forms Application?** | In your case there are two main attack possibilities:
* Steal the connection string and then access the database directly
* Call methods in your C# code directly without using the UI
For the connection string you need to store it in an encrypted form in a config file. Problem is that there need to be enough information in the winforms app so that it can decrypt and use it.
For accessing the code directly you can use code access security and obfuscation.
In your case I would not give the windows app direct access to the database. Let the windows app call a WCF service, the the WCF service would access the database.
The user's user account is allowed to call the WCF service, the WCF service is running under an account that is allowed to access the database, the user's user account has no rights to the database.
Windows App with 3 Layers:
* UI
* Business (Security check what UI should be shown to the user)
* Proxy
WCF Service with 2 Layers:
* Facade / Business Layer (Security check is user allowed to call this method with this data)
* Entity Framework datamodel
Common dll's to both Layers
* Contracts / WCF Interfaces
* Data Transfer Objects
For info on proxy, contracts and DTO's see this video:
<http://www.dnrtv.com/default.aspx?showNum=103> | Shiraz Bhaiji came close, but I think they missed the key step.
Yes, you want access to the database to be mediated by a middle tier, exposed through WCF, which imposes whatever business logic you require, including full access control. This service does have the connection string that you want to keep secret, but it's not accessible to the WinForm clients.
The key step is that the client uses the user's authentication to gain appropriate levels of access, and never has any ability to contact the database or even get full control of the middle tier. The middle tier grants access to methods based on the groups that the client user is a member of. This means that a user with low security can call any method they like, but they'll get access denied exceptions, or data filtering, or whatever other failure mode is appropriate. The user account, on its own, has no access to the database, so the middle tier can do whatever it likes.
The obvious way to bypass this would be for the client to use the account of someone with full access. Of course, if they could do that, they'd already have what they wanted.
Hopefully, this approach would be useful in solving your problem.
*edit*
This solution does not allow LINQ-to-SQL in the client, just the middle tier. If that's a dealbreaker, then this isn't for you. Then again, the moment the client can access the database directly, a gigantic security door is opened up, and it's hard to close. There's a huge amount of extra work involved in securing the database itself so that it provides the sort of user-based, row-level security that comes naturally from a three-tier solution. I would generally recommend against it, although I do recognize that there are times when it is entirely appropriate. | Securing your Data Layer in a C# Application | [
"",
"c#",
"security",
"architecture",
""
] |
I have this code.
```
byte dup = 0;
Encoding.ASCII.GetString(new byte[] { (0x80 | dup) });
```
When I try to compile I get:
> Cannot implicitly convert type 'int'
> to 'byte'. An explicit conversion
> exists (are you missing a cast?)
Why does this happen? Shouldn't | two bytes give a byte? Both of the following work, assuring that each item is a byte.
```
Encoding.ASCII.GetString(new byte[] { (dup) });
Encoding.ASCII.GetString(new byte[] { (0x80) });
``` | It's that way by design in C#, and, in fact, dates back all the way to C/C++ - the latter also promotes operands to `int`, you just usually don't notice because `int -> char` conversion there is implicit, while it's not in C#. This doesn't just apply to `|` either, but to all arithmetic and bitwise operands - e.g. adding two `byte`s will give you an `int` as well. I'll quote the relevant part of the spec here:
> Binary numeric promotion occurs for
> the operands of the predefined +, –,
> \*, /, %, &, |, ^, ==, !=, >, <, >=, and <= binary operators. Binary
> numeric promotion implicitly converts
> both operands to a common type which,
> in case of the non-relational
> operators, also becomes the result
> type of the operation. Binary numeric
> promotion consists of applying the
> following rules, in the order they
> appear here:
>
> * If either operand is of
> type decimal, the other operand is
> converted to type decimal, or a
> compile-time error occurs if the other
> operand is of type float or double.
> * Otherwise, if either operand is of
> type double, the other operand is
> converted to type double.
> * Otherwise,
> if either operand is of type float,
> the other operand is converted to type
> float.
> * Otherwise, if either operand
> is of type ulong, the other operand is
> converted to type ulong, or a
> compile-time error occurs if the other
> operand is of type sbyte, short, int,
> or long.
> * Otherwise, if either
> operand is of type long, the other
> operand is converted to type long.
> * Otherwise, if either operand is of
> type uint and the other operand is of
> type sbyte, short, or int, both
> operands are converted to type long.
> * Otherwise, if either operand is of
> type uint, the other operand is
> converted to type uint.
> * Otherwise,
> both operands are converted to type
> int.
I don't know the exact rationale for this, but I can think about one. For arithmetic operators especially, it might be a bit surprising for people to get `(byte)200 + (byte)100` suddenly equal to `44`, even if it makes some sense when one carefully considers the types involved. On the other hand, `int` is generally considered a type that's "good enough" for arithmetic on most typical numbers, so by promoting both arguments to `int`, you get a kind of "just works" behavior for most common cases.
As to why this logic was also applied to bitwise operators - I imagine this is so mostly for consistency. It results in a single simple rule that is common for *all* non-boolean binary types.
But this is all mostly guessing. Eric Lippert would probably be the one to ask about the real motives behind this decision for C# at least (though it would be a bit boring if the answer is simply "it's how it's done in C/C++ and Java, and it's a good enough rule as it is, so we saw no reason to change it"). | The literal 0x80 has the type "int", so you are not oring bytes.
That you can pass it to the byte[] only works because 0x80 (as a literal) it is within the range of byte.
**Edit**: Even if 0x80 is cast to a byte, the code would still not compile, since oring bytes will still give int. To have it compile, the result of the or must be cast: `(byte)(0x80|dup)` | OR-ing bytes in C# gives int | [
"",
"c#",
"types",
"logic",
"bit-manipulation",
"byte",
""
] |
I want to know how can I build UIs like skype using standard .Net/C#. Is it possible at all?
Thanks | You can use [Windows Presentation Foundation](http://msdn.microsoft.com/en-us/library/ms754130.aspx) to build more stylish GUIs than Windows Forms. It's pretty difficult to move from Forms to WPF. You usually need a good design tool, like [Expression Blend](http://www.microsoft.com/expression/products/Blend_Overview.aspx). | AFAIK skype was built using Qt4, it's rather easy to build custom gui widgets, check
[C++ GUI Programming with Qt4, 2nd Edition](https://rads.stackoverflow.com/amzn/click/com/0132354160) and this [tutorial](http://zetcode.com/tutorials/qt4tutorial/customwidget/).
P.S. check [this](http://blog.shadowgears.com/2008/10/making-qt4-dance-with-msvc-2008.html) to see how to build qt4 on windows using MSVC 2008. | How to build UIs like skype | [
"",
"c#",
".net",
"user-interface",
""
] |
Is there any open source C# code or library to present a graphical waveform given a byte array? | This is as open source as it gets:
```
public static void DrawNormalizedAudio(ref float[] data, PictureBox pb,
Color color)
{
Bitmap bmp;
if (pb.Image == null)
{
bmp = new Bitmap(pb.Width, pb.Height);
}
else
{
bmp = (Bitmap)pb.Image;
}
int BORDER_WIDTH = 5;
int width = bmp.Width - (2 * BORDER_WIDTH);
int height = bmp.Height - (2 * BORDER_WIDTH);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.Black);
Pen pen = new Pen(color);
int size = data.Length;
for (int iPixel = 0; iPixel < width; iPixel++)
{
// determine start and end points within WAV
int start = (int)((float)iPixel * ((float)size / (float)width));
int end = (int)((float)(iPixel + 1) * ((float)size / (float)width));
float min = float.MaxValue;
float max = float.MinValue;
for (int i = start; i < end; i++)
{
float val = data[i];
min = val < min ? val : min;
max = val > max ? val : max;
}
int yMax = BORDER_WIDTH + height - (int)((max + 1) * .5 * height);
int yMin = BORDER_WIDTH + height - (int)((min + 1) * .5 * height);
g.DrawLine(pen, iPixel + BORDER_WIDTH, yMax,
iPixel + BORDER_WIDTH, yMin);
}
}
pb.Image = bmp;
}
```
This function will produce something like this:

This takes an array of samples in floating-point format (where all sample values range from -1 to +1). If your original data is actually in the form of a byte[] array, you'll have to do a little bit of work to convert it to float[]. Let me know if you need that, too.
**Update**: since the question technically asked for something to render a byte array, here are a couple of helper methods:
```
public float[] FloatArrayFromStream(System.IO.MemoryStream stream)
{
return FloatArrayFromByteArray(stream.GetBuffer());
}
public float[] FloatArrayFromByteArray(byte[] input)
{
float[] output = new float[input.Length / 4];
for (int i = 0; i < output.Length; i++)
{
output[i] = BitConverter.ToSingle(input, i * 4);
}
return output;
}
```
**Update 2**: I forgot there's a better way to do this:
```
public float[] FloatArrayFromByteArray(byte[] input)
{
float[] output = new float[input.Length / 4];
Buffer.BlockCopy(input, 0, output, 0, input.Length);
return output;
}
```
I'm just so in love with `for` loops, I guess. | I modified MusiGenesis's solution a little bit.
This gave me a much better result, especially with house music :)
```
public static Bitmap DrawNormalizedAudio(List<float> data, Color foreColor, Color backColor, Size imageSize)
{
Bitmap bmp = new Bitmap(imageSize.Width, imageSize.Height);
int BORDER_WIDTH = 0;
float width = bmp.Width - (2 * BORDER_WIDTH);
float height = bmp.Height - (2 * BORDER_WIDTH);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(backColor);
Pen pen = new Pen(foreColor);
float size = data.Count;
for (float iPixel = 0; iPixel < width; iPixel += 1)
{
// determine start and end points within WAV
int start = (int)(iPixel * (size / width));
int end = (int)((iPixel + 1) * (size / width));
if (end > data.Count)
end = data.Count;
float posAvg, negAvg;
averages(data, start, end, out posAvg, out negAvg);
float yMax = BORDER_WIDTH + height - ((posAvg + 1) * .5f * height);
float yMin = BORDER_WIDTH + height - ((negAvg + 1) * .5f * height);
g.DrawLine(pen, iPixel + BORDER_WIDTH, yMax, iPixel + BORDER_WIDTH, yMin);
}
}
return bmp;
}
private static void averages(List<float> data, int startIndex, int endIndex, out float posAvg, out float negAvg)
{
posAvg = 0.0f;
negAvg = 0.0f;
int posCount = 0, negCount = 0;
for (int i = startIndex; i < endIndex; i++)
{
if (data[i] > 0)
{
posCount++;
posAvg += data[i];
}
else
{
negCount++;
negAvg += data[i];
}
}
posAvg /= posCount;
negAvg /= negCount;
}
``` | Open source C# code to present wave form? | [
"",
"c#",
"audio",
""
] |
I've got a WinForms app, where if there is already an instance running & the user tries to spin up another one, I stop it by checking against a Mutex before calling Application.Run(). That part works just fine. What I would like to do is pass a message from the new instance of the app (along with a piece of data in string form) to the existing instance before killing the new process.
I've tried calling PostMessage, and I do receive the message on the running app, but the string I pass along in the lparam is failing (yes, I have checked to make sure I'm passing in a good string to begin with). How can I best do this?
```
static class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool PostMessage(int hhwnd, uint msg, IntPtr wparam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
private const int HWND_BROADCAST = 0xffff;
static uint _wmJLPC = unchecked((uint)-1);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
_wmJLPC = RegisterWindowMessage("JumpListProjectClicked");
if (_wmJLPC == 0)
{
throw new Exception(string.Format("Error registering window message: \"{0}\"", Marshal.GetLastWin32Error().ToString()));
}
bool onlyInstance = false;
Mutex mutex = new Mutex(true, "b73fd756-ac15-49c4-8a9a-45e1c2488599_ProjectTracker", out onlyInstance);
if (!onlyInstance) {
ProcessArguments();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
GC.KeepAlive(mutex);
}
internal static void ProcessArguments()
{
if (Environment.GetCommandLineArgs().Length > 1)
{
IntPtr param = Marshal.StringToHGlobalAuto(Environment.GetCommandLineArgs()[1]);
PostMessage(HWND_BROADCAST, _wmJLPC, IntPtr.Zero, param);
}
}
}
```
Elsewhere, in my Form...
```
protected override void WndProc(ref Message m)
{
try
{
if (m.Msg == _wmJLPC)
{
// always returns an empty string
string param = Marshal.PtrToStringAnsi(m.LParam);
// UI code omitted
}
}
catch (Exception ex)
{
HandleException(ex);
}
base.WndProc(ref m);
}
``` | Greg,
The unmanaged pointer created by StringToHGlobalAuto is only valid in the process space that created it. The memory it references can't be accessed from the other process.
To pass data from one app to another, use SendMessage() with the WM\_COPYDATA message.
Scott | Check your code again. You're using StringToHGlobalAuto to create the string (likely ending up with Unicode). Then, you're calling PtrToStringAnsi, which is not using unicode.
If you can't get this solution working, there are several options. You can read about them by looking for IPC (InterProcess Communication.)
One method I've used, since it was quick and easy, is to create a well-known file with the needed content. You lock use of that file with named events, and tell the "owner" app that the file has changed by setting another named event. The "owner" checkes the event occasionally, or launches a worker thread to watch for it.
Again, IPC has many flavors, if these ideas don't work, keep looking. | How to send a message from one instance of a managed app to another? | [
"",
"c#",
"interop",
"ipc",
"postmessage",
""
] |
I wanted to know how linker resolves the printf symbol in the following assembly code.
```
#include<stdio.h>
void main()
{
printf("Hello ");
}
.file "test.c"
.def ___main; .scl 2; .type 32; .endef
.section .rdata,"dr"
LC0:
.ascii "Hello \0"
.text
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
movl $0, %eax
addl $15, %eax
addl $15, %eax
shrl $4, %eax
sall $4, %eax
movl %eax, -4(%ebp)
movl -4(%ebp), %eax
call __alloca
call ___main
movl $LC0, (%esp)
**call _printf**
leave
ret
.def **_printf**; .scl 3; .type 32; .endef
```
Bit of Low Level Explanation will be highly appreciated.
Thanks in advance. | Assuming ELF file format, the assembler will generate an undefined symbol reference in the object file. This'll look like this:
```
Symbol table '.symtab' contains 11 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS test.c
2: 00000000 0 SECTION LOCAL DEFAULT 1
3: 00000000 0 SECTION LOCAL DEFAULT 3
4: 00000000 0 SECTION LOCAL DEFAULT 4
5: 00000000 0 SECTION LOCAL DEFAULT 5
6: 00000000 0 SECTION LOCAL DEFAULT 6
7: 00000000 0 SECTION LOCAL DEFAULT 7
8: 00000000 52 FUNC GLOBAL DEFAULT 1 main
9: 00000000 0 NOTYPE GLOBAL DEFAULT UND printf
10: 00000000 0 NOTYPE GLOBAL DEFAULT UND exit
```
It'll also create a relocation entry to point to the part of the code image that needs to be updated by the linker with the correct address. It'll look like this:
```
$ readelf -r test.o
Relocation section '.rel.text' at offset 0x358 contains 3 entries:
Offset Info Type Sym.Value Sym. Name
0000001f 00000501 R_386_32 00000000 .rodata
00000024 00000902 R_386_PC32 00000000 printf
00000030 00000a02 R_386_PC32 00000000 exit
```
The linker's job is then to walk through the relocation table fixing up the code image with the final symbol addresses.
There's an excellent book, but I can't find the details right now (and it's out of print). However, this looks like it may be useful: <http://www.linuxjournal.com/article/6463> | For a great book on the linking process, see Linkers & Loaders by John Levine. You can get the manuscript chapters in HTML format [here](http://www.freebookzone.com/goto.php?bkcls=pl_cpp&bkidx=59&lkidx=1). | How linker resolves the symbol in assembly code | [
"",
"c++",
"c",
"assembly",
"linker",
""
] |
I'm trying to cross compile an in house language(ihl) to Python.
One of the ihl features is pointers and references that behave like you would expect from C or C++.
For instance you can do this:
```
a = [1,2]; // a has an array
b = &a; // b points to a
*b = 2; // derefernce b to store 2 in a
print(a); // outputs 2
print(*b); // outputs 2
```
Is there a way to duplicate this functionality in Python.
**I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above**
My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(
I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable. | This can be done explicitly.
```
class ref:
def __init__(self, obj): self.obj = obj
def get(self): return self.obj
def set(self, obj): self.obj = obj
a = ref([1, 2])
b = a
print(a.get()) # => [1, 2]
print(b.get()) # => [1, 2]
b.set(2)
print(a.get()) # => 2
print(b.get()) # => 2
``` | You may want to read [*Semantics of Python variable names from a C++ perspective*](http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/). The bottom line: **All variables are references**.
More to the point, don't think in terms of variables, but in terms of objects which can be *named*. | Simulating Pointers in Python | [
"",
"python",
"pointers",
""
] |
\*\*\*\*UPDATED\*\*\*\*
I have a custom **ContentActionInvoker** that has some crazy logic in it.
I'd like in some case to invoke a different action in a diffrent controller and with some different parameters.
How can this be done?
```
class ContentActionInvoker : ControllerActionInvoker
{
protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
{
....
}
}
``` | Why do you need to redirect the user's experience back through the webserver (forcing the browser to make a round-trip) to access another class that is operating in the same AppDomain as the code that received the request from the MvcHandler?
If you want process data in another method, with different parameters, just instantiate that other class (or controller, which is just another class...) and either return the ActionResult generated by THOSE methods, or reformat your own ActionResult for the View requested. | Don't you want to use `RedirectToAction("MyAction")`? | ASP.NET MVC routing & InvokeActionMethod | [
"",
"c#",
"asp.net-mvc",
""
] |
I have two getter members:
```
Node* prev() { return prev_; }
int value() { return value_ }
```
Please note the lack of const identifiers (I forgot them, but now I want to know why this won't work). I am trying to get this to compile:
```
Node(Node const& other) : prev_(other.prev()), value_(other.value()) { }
```
The compiler rejects this. I thought that C++ allows non-const to const conversion in function parameters, such as:
```
{
Foo(int bar);
}
Foo(const int bar)
{
//lala
}
```
Why won't it let me do the same thing with a copy constructor? The const identifier means I promise not to change anything, so why would it matter if I get my value from a const or non-const source? | You're not trying to do a non-const to const conversion. You're attempting to call two methods which are not const an a const reference (calls to prev and value). This type of operation is strictly forbidden by const semantics.
What you could do instead is use the fields prev\_ and value\_ directly. Because it's a member of the same type you can access privates which will be available on the const object. | > I thought that C++ allows non-const to const conversion in function parameters, such as:
You are trying to do the exact opposite: Const to non-const. Calling a non-const member function, the compiler will bind the expression (which is a `Node const` to a `Node&` for binding the `this` pointer). It thus will drop const - not allowed because it would call a non-const function on a const object.
```
/* class Foo */ {
Foo(int bar);
}
/* Foo:: */ Foo(const int bar)
{
//lala
}
```
Well that code is a whole other thing. It declares a function (constructor) two times, with the only difference being that one time the parameter is const, and another time it isn't. The type of the function is the same both times, and so they don't conflict (the `const` parameter will only have an impact within the function body locally - it won't make any difference to the caller). In addition, this code doesn't contain any call (assuming that the first block is within some function).
If you wonder: If the above two versions are identical - why isn't the below? Then this is because the below contains one other level of indirection: Below, the reference itself (the *top level*) is not const (you can't put `const` on a reference itself directly), but the type referenced is const. At this time, const is *not* ignored in determining the type of the function.
```
/* class Foo */ {
Foo(int &bar);
}
// different thing, won't work!
/* Foo:: */ Foo(const int &bar)
{
//lala
}
``` | Why won't C++ allow non-const to const conversion in copy ctor? | [
"",
"c++",
"constants",
"copy-constructor",
""
] |
How can I send emails with attachments with a PHP script? | I recommend using [PHPMailer](http://sourceforge.net/projects/phpmailer/). | Use [SwiftMailer](http://swiftmailer.org/).
```
$message = new Swift_Message("My subject");
$message->attach(new Swift_Message_Part("Attached txt file"));
$message->attach(new Swift_Message_Attachment(new Swift_File("filename.txt"), "filename.txt", "text/txt"));
$swift->send($message, "email@host", "myemail@host");
``` | Send email with attachments in PHP? | [
"",
"php",
"email",
""
] |
From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way?
Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process. | Have you tried [SIGAR - System Information Gatherer And Reporter](http://support.hyperic.com/display/SIGAR/Home)?
After install
```
import os, sigar
sg = sigar.open()
mem = sg.mem()
sg.close()
print mem.total() / 1024, mem.free() / 1024
```
Hope this helps | [psutil](http://code.google.com/p/psutil/) would be another good choice. It also needs a library installed however.
```
>>> import psutil
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=2081050624L, percent=75.1,
used=8074080256L, free=300068864L, active=3294920704,
inactive=1361616896, buffers=529895424L, cached=1251086336)
``` | Getting total/free RAM from within Python | [
"",
"python",
"wxpython",
""
] |
So, this may be a really stupid question, but I'm obviously missing something here.
Consider the following code:
```
var selectedItems = [];
selectedItems.push("0ce49e98-a8aa-46ad-bc25-3a49d475e9d3");
//fyi, selectedItems[selectedItems.length] = "0ce49e98-a8aa-46ad-bc25-3a49d475e9d3"; produced the same result.
```
At the end `selectedItems` content looks like this:
```
Name Value Type
------------- -------------------------------------- ------
selectedItems {...} Object
- [0] "0ce49e98-a8aa-46ad-bc25-3a49d475e9d3" String
- length 1 Long
```
But if I just try to call split() on the same string, like this:
```
selectedItems = "0ce49e98-a8aa-46ad-bc25-3a49d475e9d3".split(",")
```
Now the content of my supposed array looks like this (missing length):
```
Name Value Type
------------- -------------------------------------- ------
selectedItems {...} Object
- [0] "0ce49e98-a8aa-46ad-bc25-3a49d475e9d3" String
```
Any idea what the difference is? What's actually happening here?
Thanks in advance.
**UPDATED**:
I have a feeling there's actually something structurally different about the two resulting values, because (atlas) ajax chokes on the one with the length property when I try to pass it to a server-side WebMethod (no actual error message, but I know the call fails). I'm not sure.
**UPDATE #2**
I noticed that setting the targetLocationIdList this way, results in no 'length' property being displayed in Quick Watch window:
```
var params =
{
jobId : args.get_JobId(),
targetLocationIdList : retVal.split(',')
};
```
But this results contain 'length' property displayed in Quick Watch window:
```
var retValArr = [];
retValArr = retVal.split(',');
var params =
{
jobId : args.get_JobId(),
targetLocationIdList : retValArr
};
``` | There isn't a difference at all programmatically. If you run your example in both chrome developers window and firebug it looks like the 2nd
```
Name Value
Type
------------- -------------------------------------- ------
selectedItems {...} Object
- [0] "0ce49e98-a8aa-46ad-bc25-3a49d475e9d3" String
```
Length is an implied property
**EDIT**
```
var retVal = 'test';
var params =
{
jobId : 1,
targetLocationIdList : retVal.split(',')
};
console.log(params.targetLocationIdList.length) // prints 1
```
The code above prints 1 in IE8,Firefox,Chrome (in their dev tools or firebug) so think that this must be an issue with Visual Studio or with Atlas in the way that it shows the object. | Might this be a bug in the debugger? (Or is this causing problems in the browser?) | Puzzling javascript array behavior | [
"",
"asp.net",
"javascript",
"visual-studio",
"ajax",
"arrays",
""
] |
Is it possible to get the name of the top level class from an extended class, without setting it from the top level class. See example below, I would like to get 'Foo' from Base. I know I could set a variable from Foo, but hoping to skip the extra step.
Thanks.
```
class Base {
function __construct() {
echo '<p>get_class: '.get_class().'</p>';
echo '<p>__CLASS__: '.__CLASS__.'</p>';
}
}
class Foo extends Base {
}
$test = new Foo();
```
(PHP 5.2.4+) | Use:
```
get_class($this);
``` | [`get_called_class()`](http://php.net/manual/en/function.get-called-class.php) for static classes or [`get_class($this)`](http://php.net/manual/en/function.get-class.php) for instantiated.
`get_called_class()`, as Jason said, was introduced in PHP 5.3 | Get class name from extended class | [
"",
"php",
"oop",
""
] |
Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like [SQLAlchemy](http://www.sqlalchemy.org/)? | The Django people are sensible people with a philosophy of decoupling things. So yes, in theory you should be perfectly able to use Django's ORM in a standalone application.
Here's one guide I found: [Django ORM as a standalone component](http://jystewart.net/process/2008/02/using-the-django-orm-as-a-standalone-component/). | I would suggest using SQLAlchemy and a declarative layer on top of it such as [Elixir](http://elixir.ematia.de/trac/wiki "Elixir") if you prefer a Django-like syntax. | Django ORM for desktop application | [
"",
"python",
"django",
"orm",
""
] |
My goal is to maximise performance. The basics of the scenario are:
* I read some data from SQL Server 2005 into a DataTable (1000 records x 10 columns)
* I do some processing in .NET of the data, all records have at least 1 field changed in the DataTable, but potentially all 10 fields could be changed
* I also add some new records in to the DataTable
* I do a SqlDataAdapter.Update(myDataTable.GetChanges()) to persist the updates (an inserts) back to the db using a InsertCommand and UpdateCommand I defined at the start
* Assume table being updated contains 10s of millions of records
This is fine. However, if a row has changed in the DataTable then ALL columns for that record are updated in the database even if only 1 out of 9 columns has actually changed value. This means unnecessary work, particularly if indexes are involved. I don't believe SQL Server optimises this scenario?
I think, if I was able to only update the columns that had actually changed for any given record, that I should see a noticeable performance improvement (esp. as cumulatively I will be dealing with millions of rows).
I found this article: <http://netcode.ru/dotnet/?lang=&katID=30&skatID=253&artID=6635>
But don't like the idea of doing multiple UPDATEs within the sproc.
Short of creating individual UPDATE statements for each changed DataRow and then firing them in somehow in a batch, I'm looking for other people's experiences/suggestions.
(Please assume I can't use triggers)
Thanks in advance
**Edit:** Any way to get SqlDataAdapter to send UPDATE statements specific to each changed DataRow (only to update the actual changed columns in that row) rather than giving a general .UpdateCommand that updates all columns? | Isn't it possible to implement your own IDataAdapter where you implement this functionality ?
Offcourse, the DataAdapter only fires the correct SqlCommand, which is determined by the RowState of each DataRow.
So, this means that you would have to generate the SQL command that has to be executed for each situation ...
But, I wonder if it is worth the effort. How much performance will you gain ?
I think that - if it is really necessary - I would disable all my indexes and constraints, do the update using the regular SqlDataAdapter, and afterwards enable the indexes and constraints. | you might try is do create an XML of your changed dataset, pass it as a parameter ot a sproc and the do a single update by using sql nodes() function to translate the xml into a tabular form.
you should never try to update a clustered index. if you do it's time to rethink your db schema. | Minimise database updates from changes in DataTable/SqlDataAdapter | [
"",
"c#",
".net",
"sql-server-2005",
"performance",
"optimization",
""
] |
I have a Treeview on my main page. This makes the control a member of main page class.
How can I access this control from another PHP script?
A "require\_once" with the main page file doesn't work, that re-creates the main page when the other script is called because of the commands at the bottom of each VCL-page's source. | Unfortunately, I couldn't find a solution to this, so a major restructuring of the software could prevent the situation. | Separate your tree class and the main page.
```
require_once("tree.class.php");
``` | How to access a VCL-Control from another PHP script? | [
"",
"php",
"delphi4php",
""
] |
I wrote some PHP code that will allow me to create an html dropdown box, and then choose what should be the selected value. The code is:
```
$role_drop = "<select name='role'>";
$role_drop .= "\r\n<option value='Resident Assistant'>Resident Assistant</option>";
$role_drop .= "\r\n<option value='Community Assistant'>Community Assistant</option>";
$role_drop .= "\r\n<option value='Head RA'>Head RA</option>";
$role_drop .= "\r\n</select>";
$result = mysql_query("SELECT role FROM users");
if (@mysql_num_rows($result)) {
while ($r=@mysql_fetch_assoc($result)) {
$role = $r["role"];
$role_drop = str_replace(">$role</option>", "selected=\"\" >$role</option>",$role_drop);
echo $role_drop;
}
}
```
In reality, this code has a bunch of HTML mixed in, but here is all of the PHP. When I run it, it seems to work. However, let's say the query returned 4 dropdown boxes with roles (from 4 users), and I were to Edit, or select, a new role for the 2nd dropdown box returned (with an UPDATE query), then when the page refreshes, all of the roles including and AFTER the dropdown box I updated will display their selected values as the new one I selected in the 2nd dropdown box.
And it's not that the values in the actual database are wrong, they are just displaying the wrong selected value. Here is the source code for the 3rd dropdown box after I select a new value for the second one:
```
<select name="role">
<option selected="" value="Resident Assistant">Resident Assistant</option>
<option value="Community Assistant">Community Assistant</option>
<option selected="" value="Head RA">Head RA</option>
</select>
```
So, it seems its selecting the correct value (Resident Assistant), however its ALSO selecting "Head RA", which is what I changed the prior dropdown box to.
It's very strange, and I have NO idea why this is happening. Any ideas?
Thanks! | It's because you're updating `$role_drop` each time, so all the previous changes are going to show up in subsequent dropdowns. I'd change the loop to something like this:
```
if (@mysql_num_rows($result)) {
while ($r=@mysql_fetch_assoc($result)) {
$role = $r["role"];
$temp_role_drop = str_replace(">$role</option>", "selected=\"\">$role</option>", $role_drop);
echo $temp_role_drop;
}
}
```
That way you're not overwriting your original dropdown markup. | Nuts - forgot to escape my code. I meant, "It's just `<OPTION VALUE="foo" SELECTED>`". | Problem With PHP/HTML Dropdown Box Code (selected value) | [
"",
"php",
"html",
"drop-down-menu",
""
] |
I'm using the following piece of code and under some mysterious circumstances the result of the addition is not as it's supposed to be:
```
double _west = 9.482935905456543;
double _off = 0.00000093248155508263153;
double _lon = _west + _off;
// check for the expected result
Debug.Assert(_lon == 9.4829368379380981);
// sometimes i get 9.48293685913086 for _lon (which is wrong)
```
I'm using some native DLLs within my application and i suspect that some DLL is responsible for this 'miscalculation', but i need to figure out which one.
Can anyone give me a hint how to figure out the root of my problem? | double is not completely accurate, try using decimal instead
The advanteage of using double and float over decimal is performance | At first I thought this was a rounding error but actually it is your assertion that is wrong. Try adding the *entire* result of your calculation without any arbitrary rounding on your part.
Try this:
```
using System;
class Program
{
static void Main()
{
double _west = 9.482935905456543;
double _off = 0.00000093248155508263153;
double _lon = _west + _off;
// check for the expected result
Console.WriteLine(_lon == 9.48293683793809808263153);
}
}
```
In the future though it is best to use `System.Decimal` in cases where you need to avoid rounding errors that are usually associated with the `System.Single` and `System.Double` types.
That being said, however, this is not the case here. By arbitrarily rounding the number at a given point you are assuming that the type will also round at that same point which is not how it works. Floating point numbers are stored to their maximum representational capacity and only once that threshold has been reached does rounding take place. | add two double given wrong result | [
"",
"c#",
".net",
"floating-point",
"double",
"addition",
""
] |
I have two JSON objects here, generated through the Google Search API. The URL's of these objects can be found below.
<http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=hello%20world&rsz=large>
<http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=hello%20world&rsz=large&start=8>
As you can see the first URL returns the first eight results, whilst the second one returns the next eight. Instead of checking these results separately I'd like to *programmatically* merge them into one JSON object and pass them through as the first sixteen results.
I've attempted this with a couple of extremely simple JSON objects, but what Google returns is still a bit above my head, so I'm hoping for a bit of help with doing such a thing.
As far as I've been told it is not against Google's Terms of Service to merge two objects into one, only that these always go through as two results (which they will). Some friends have pointed me in the direction of automated tools that are capable of doing such things, but I'm yet to find such a tool.
I'm currently working within ASP.NET so C# or VB.NET code is great, but I'm somewhat language independent so any help in any language will be very much appreciated.
Can anyone provide any help and/or advice on doing such a thing?
**EDIT:** These results will eventually be saved to a database, so any server-side methods would be fantastic, even if it means putting them straight into a table for dealing with later. | ```
function MergeJSON (o, ob) {
for (var z in ob) {
o[z] = ob[z];
}
return o;
}
```
This looks a lot like the code from Elliot, but is a bit safer in some conditions. It is not adding a function to the object, which could lead to some syntax problems, when used in with a framework like Extjs or jQuery. I had the problem that it gave me problems in the syntax when used in an event listener. But credits go to Elliot, he did the job.
Use this as following:
```
a = {a : 1}
b = {b : 2}
c = {c : 3}
x = MergeJSON ( a, b);
x = MergeJSON ( x, c);
result : x == {a : 1, b : 2, c : 3}
```
Thank you Elliot | ```
Object.prototype.merge = (function (ob) {
var o = this;
var i = 0;
for (var z in ob) {
if (ob.hasOwnProperty(z)) {
o[z] = ob[z];
}
}
return o;
})
var a = {a:1}
var b = {b:2}
var c = a.merge(b); // === {a:1,b:2}
``` | Merge two JSON objects programmatically | [
"",
"c#",
"asp.net",
"json",
"string-concatenation",
""
] |
I am a new to professional development. I mean I have only 5 months of professional development experience. Before that I have studied it by myself or at university. So I was looking over questions and found here a question about code quality. And I got a question related to it myself. How do I increase my code understanding/reading skills? Also will it improve the code quality I will write? Is there better code notation than Hungarian one? And is there any really good books for C++ design patterns(or the language doesn't matter?)?
Thank you in advance answering these questions and helping me improving :)
P.S. - Also I have forgot to tell you that I am developing with C++ and C# languages. | There is only way I've found to get better at reading other peoples code and that is read other peoples code, when you find a method or language construct you don't understand look it up and play with it until you understand what is going on.
Hungarian notation is terrible, very few people use it today, it's more of an in-joke among programmers.
In fact the name hungarian notation is a joke itself as:
> "The term Hungarian notation is
> memorable for many people because the
> strings of unpronounceable consonants
> vaguely resemble the consonant-rich
> orthography of some Eastern European
> languages."
From [How To Write Unmaintainable Code](http://www.stateslab.org/HowToWriteUnmaintainableCode-Green00.html)
> "Hungarian Notation is the tactical
> nuclear weapon of source code
> obfuscation techniques; use it! Due to
> the sheer volume of source code
> contaminated by this idiom nothing can
> kill a maintenance engineer faster
> than a well planned Hungarian Notation
> attack."
And the ever popular linus has a few words to say on the matter.
> "Encoding the type of a function into
> the name (so-called Hungarian
> notation) is brain damaged—the
> compiler knows the types anyway and
> can check those, and it only confuses
> the programmer."
>
> - [Linus Torvalds](http://lxr.linux.no/linux/Documentation/CodingStyle)
**EDIT:**
Taken from a comment by Tobias Langner.
"For the differences between Apss Hungarian and Systems Hungarian see [Joel on Software](http://www.joelonsoftware.com/articles/Wrong.html)".
Joel on Software has tips on how to read other people code called [Reading Code is Like Reading the Talmud](http://www.joelonsoftware.com/articles/fog0000000053.html). | > How do I increase my code
> understanding/reading skills?
Read read read. Learn from your mistakes. Review answers on SO and elsewhere. When you can think back on a piece of code you wrote and go "aha! I should've done xyz instead!" then you're learning. Read a good book for your language of choice, get beyond the basics and understand more advanced concepts.
Then, apart from reading: write write write! Coding is like math: you won't fully grock it without actually solving problems. Glancing at a math problem's solution is different than getting out a blank piece of paper and solving it yourself.
If you can, do some pair programming too to see how others code and bounce ideas around.
> Also will it improve the code quality
> I will write?
See above. As you progress you should get more efficient. It won't happen by reading a book on design patterns. It will happen by solving real world problems and understanding why what you read works.
> Is there better code notation than
> Hungarian one?
It depends. Generally I avoid them and use descriptive names. The one exception where I might use Hungarian type of notations is for UI elements such as Windows Forms or ASP.NET controls, for example: using *btn* as a prefix for a Submit button (*btnSubmit*), *txt* for a TextBox (*txtFirstName*), and so on but it differs from project to project depending on approach and patterns utilized.
With regards to UI elements, some people like to keep things alphabetical and may append the control type at the end, so the previous examples become submitButton and firstNameTextBox, respectively. In Windows Forms many people name forms as frmMain, which is Hungarian, while others prefer naming it based on the application name or form purpose, such as MainForm, ReportForm, etc.
**EDIT:** be sure to check out the difference between [Apps Hungarian and Systems Hungarian](http://www.joelonsoftware.com/articles/Wrong.html) as mentioned by @Tobias Langner in a comment to an earlier response.
Pascal Case is generally used for method names, classes, and properties, where the first letter of each word is capitalized. For local variables Camel Case is typically used, where the first letter of the first word is lowercase and subsequent words have their first letters capitalized.
You can check out the naming conventions and more from the .NET Framework Design Guidelines. There is [a book](https://rads.stackoverflow.com/amzn/click/com/0321545613) and some of it is [on MSDN](http://msdn.microsoft.com/en-us/library/ms229002.aspx).
> And is there any really good books for
> C++ design patterns(or the language
> doesn't matter?)?
Design patterns should be applicable to any language. Once you understand the concept and the reasoning behind that pattern's usefulness you should be able to apply it in your language of choice. Of course, don't approach everything with a "written in stone" attitude; the pattern is the goal, the implementation might differ slightly between languages depending on language features available to you. Take the [Decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern) for example, and [see how C# extension methods allow it to be implemented differently than without it](http://andrewtroelsen.blogspot.com/2009/04/decorator-pattern-extension-methods.html).
Design Pattern books:
[Head First Design Patterns](https://rads.stackoverflow.com/amzn/click/com/0596007124) - good beginner intro using Java but code is available for C++ and C# as a download (see "book code and downloads" section on [the book's site](http://headfirstlabs.com/books/hfdp/))
[Design Patterns: Elements of Reusable Object-Oriented Software](https://rads.stackoverflow.com/amzn/click/com/0201633612) - classic gang of four (GOF)
[Patterns of Enterprise Application Architecture](https://rads.stackoverflow.com/amzn/click/com/0321127420) - Martin Fowler
If you're looking for best practices for quality coding in C++ and C# then look for the "[Effective C++](https://rads.stackoverflow.com/amzn/click/com/0321334876)" and "[More Effective C++](https://rads.stackoverflow.com/amzn/click/com/020163371X)" books (by Scott Meyers) and "[Effective C#](https://rads.stackoverflow.com/amzn/click/com/0321245660)" and "[More Effective C#](https://rads.stackoverflow.com/amzn/click/com/0321485890)" books (by Bill Wagner). They won't hold your hand along the way though, so you should have an understanding of the language in general. There are other books in the "Effective" series so make sure you see what's available for your languages.
I'm sure you can do a search here for other recommended reading so I'll stop here.
**EDIT:** added more details under the Hungarian Notation question. | How to read code without any struggle | [
"",
"c++",
"design-patterns",
""
] |
I have a rather complicated setup which I have boiled down to the code below. I have an outer **FormPanel**, where I am trying to include a component that is a sub-class **FormPanel**. In FF it is causing a "this.body is null" error.
Is this happening to anyone else? Is it possible to get this to work? I very much do not want to have to touch the subclass if I don't have to.
```
var test = new Ext.Window({
title: 'test',
items: [{
xtype: 'form',
items: [{
// this is where the subclass of FormPanel goes
xtype: 'form',
items: [{
xtype: 'textfield',
fieldLabel: 'Testing'
}]
}]
}]
});
test.show();
``` | I'm not sure if this is your exact issue, but I do know you are never supposed to embed an xtype: 'form' into an xtype: 'form'. If you need its layout functionality then instead of xtype: 'form', use xtype: 'panel' with layout: 'form'. | You are essentially trying to embed a FormPanel inside another FormPanel. This will not work. I think what you want is this:
```
var test = new Ext.Window({
title: 'test',
items: [{
xtype: 'form',
items: [{
xtype: 'textfield',
fieldLabel: 'Testing'
}]
}]
});
test.show();
``` | ExtJS FormPanel in a FormPanel fails with "this.body is null" | [
"",
"javascript",
"extjs",
""
] |
I am trying to create a Firefox extension that can run multiple XMLHttpRequests per page. The code is below (my main function calls the makeRequest on different URLs). My problem is that it always returns (at the "alert('Found ...')" for debugging purposes) the same URL instead of displaying the different responses. I think the issue is that I should somehow pass the http\_request instance to the alertContents() function instead of just using http\_request directly, but not sure how or if this is correct. Thank you.
```
function makeRequest(url,parameters) {
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url + parameters, true);
http_request.send(null);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert('Found: ' + http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
``` | Your problem is you've only got one http\_request identifier which is reused every time the makeRequest function is called. Here is one simple adjustment:-
```
function makeRequest(url,parameters) {
var http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
alertContents(http_request)
};
http_request.open('GET', url + parameters, true);
http_request.send(null);
return http_request;
}
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert('Found: ' + http_request.responseText);
} else {
alert('There was a problem with the request.');
}
http_request.onreadystatechange = fnNull;
}
}
function fnNull() { };
```
The http\_request identifier is local to each makeRequest execution. The correct instance of XHR is then passed to alerrContents each time onreadystatechange is fired by using a capture.
BTW, why separate url from parameters? Since the caller has to ensure the parameters argument is correctly url encoded it doesn't seem like a very useful abstraction. In addition the caller can simply pass a URL containing a querystring anyway. | this function can be further improved with cross browser functionality:
```
function makeRequest(method, url, parameters) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
http_request.overrideMimeType('text/xml');
//http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
alertContents(http_request);
}
url += (method=="GET")?parameters:"";
http_request.open(method, url, true);
if (method == "POST") {
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
}
http_request.send((method=="GET")?null:parameters);
}
``` | Firefox Extension - Multiple XMLHttpRequest calls per page | [
"",
"javascript",
"ajax",
"firefox-addon",
""
] |
While cleaning up some old php scripts I've noticed some weird behavior with require/include statements when I try to use variables.
On the live server, the following code works fine..
```
<?php
$test = "http://localhost/elearning/trunk/mypage.php";
require "$test";
?>
```
..but on my XAMPP installation ((basic package) version 1.6.7) I receive the following error:
Warning: require() [function.require]: URL file-access is disabled in the server configuration in C:\Documents and Settings\username\Desktop\xampp-win32-1.6.7\xampp\htdocs\elearning\trunk\test.php on line 22
Warning: require(<http://localhost/elearning/trunk/mypage.php>) [function.require]: failed to open stream: no suitable wrapper could be found in C:\Documents and Settings\username\Desktop\xampp-win32-1.6.7\xampp\htdocs\elearning\trunk\test.php on line 22
Fatal error: require() [function.require]: Failed opening required '<http://localhost/elearning/trunk/mypage.php>' (include\_path='.;C:\Documents and Settings\username\Desktop\xampp-win32-1.6.7\xampp\php\pear\') in C:\Documents and Settings\username\Desktop\xampp-win32-1.6.7\xampp\htdocs\elearning\trunk\test.php on line 22
If I copy+paste <http://localhost/elearning/trunk/mypage.php> (directly from the error) into my browser, mypage.php loads. Is this an error in my configuration, or my approach? | You can't use paths that start with http:// on some servers because of security. What you want to use instead is a directory path.
You can get your current directory path by doing something like
`echo $_SERVER['DOCUMENT_ROOT'];`
that will give you your directory path from the root folder of the server. That is the path you want to use to include/require stuff.
---
*If you didn't quite understand that, try this.*
There are two types of paths:
**World Wide Web Paths:**
<http://example.com/directory/file.php>
**Server Directory Paths:**
/home/usr/www/site/html/
The Server directory path is where your files are located on the server's hard drive. Much like your computer's hard drive, it is never changes unless you move the files. On the other hand, The World Wide Web Path (the one everyone uses to access your website) can change based on what domain you are using, where your Document Root is pointing, Mod Rewrites, and more.
*Note: The Document Root is the top most directory that your server serves files from. So, if you had index.php in your document root, it would show up like this on the web:
<http://example.com/index.php>.*
When PHP looks for a file, it uses the Server Directory Path, because it is running on the server. When Javascript, which runs from the user computer, wants to look for a file, it uses the World Wide Web path to access it, because it isn't accessing it from the server.
I really hope that somewhere in there, something made sense. | try require "./mypage.php"
not the whole exact directory | Why am I unable to use a variable in my require or include statement on XAMPP? | [
"",
"php",
"include",
"xampp",
"require",
""
] |
I need a way to import the entire Python standard library into my program.
While this may seems like a bad idea, I want to do this is so py2exe will package the entire standard library with my program, so my users could import from it in the shell that I give them.
Is there an easy way to do this?
Bonus points: I would prefer that this action will NOT import the packages I have installed in site-packages and which did not come with Python. However, this is not critical. | Hey, I just thought of something: I only need a list of all the modules in stdlib, and then I'll automatically generate a Python script that imports each of them "manually", like this:
```
import re
import math
import time
# ...
```
And then include that with my program.
So all I need now is an easily formatted list of all the modules/packages in stdlib. Now how do I get that?
**UPDATE:**
I got the list like this: I installed Python 2.6 on a virtual machine, then ran in IDLE:
```
import pkgutil
stuff = [thing[1] for thing in pkgutil.iter_modules()]
stuff.sort() # To make it easy to look through
print(stuff)
```
Then copy pasted the output into my IDE, and made a little script to write:
```
if False:
import re
import email
import time
# ...
```
Into a Python module which I import in my program.
It works! py2exe packs the entire stdlib.
**UPDATE:**
I created a package that does this. I would upload it here but since I don't see any upload button, you can get it off my project folder:
<http://github.com/cool-RR/PythonTurtle/tree/master>
It's in the folder `src`, the package is called `almostimportstdlib` and it's documented. | I created a zip file from all the Python standard library and then added it to `sys.path` when the program started.
You can have a look at the sources [here](http://svn.berlios.de/svnroot/repos/sconsexe/trunk/) (abandoned project) | Importing the entire Python standard library | [
"",
"python",
"import",
"packaging",
"py2exe",
""
] |
I have a PHP script that creates a thumbnail and lists an image gallery. The problem I'm having is that it lists it by timestamp on the server but I want it to list 'naturally'.
```
<?php
# SETTINGS
$max_width = 100;
$max_height = 100;
$per_page = 24;
$page = $_GET['page'];
$has_previous = false;
$has_next = false;
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if ( $handle = opendir(".") ) {
$lightbox = rand();
echo '<ul id="pictures">';
$count = 0;
$skip = $page * $per_page;
if ( $skip != 0 )
$has_previous = true;
while ( $count < $skip && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' )
$count++;
}
$count = 0;
while ( $count < $per_page && ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
if ( ! is_dir('thumbs') ) {
mkdir('thumbs');
}
if ( ! file_exists('thumbs/'.$file) ) {
makeThumb( $file, $type );
}
echo '<li><a href="'.$file.'" class="zoom" rel="group">';
echo '<img src="thumbs/'.$file.'" alt="" />';
echo '</a></li>';
$count++;
}
}
echo '</ul>';
while ( ($file = readdir($handle)) !== false ) {
if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) {
$has_next = true;
break;
}
}
}
}
function getPictureType($file) {
$split = explode('.', $file);
$ext = $split[count($split) - 1];
if ( preg_match('/jpg|jpeg/i', $ext) ) {
return 'jpg';
} else if ( preg_match('/png/i', $ext) ) {
return 'png';
} else if ( preg_match('/gif/i', $ext) ) {
return 'gif';
} else {
return '';
}
}
function makeThumb( $file, $type ) {
global $max_width, $max_height;
if ( $type == 'jpg' ) {
$src = imagecreatefromjpeg($file);
} else if ( $type == 'png' ) {
$src = imagecreatefrompng($file);
} else if ( $type == 'gif' ) {
$src = imagecreatefromgif($file);
}
if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) {
$newW = $oldW * ($max_width / $oldH);
$newH = $max_height;
} else {
$newW = $max_width;
$newH = $oldH * ($max_height / $oldW);
}
$new = imagecreatetruecolor($newW, $newH);
imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
if ( $type == 'jpg' ) {
imagejpeg($new, 'thumbs/'.$file);
} else if ( $type == 'png' ) {
imagepng($new, 'thumbs/'.$file);
} else if ( $type == 'gif' ) {
imagegif($new, 'thumbs/'.$file);
}
imagedestroy($new);
imagedestroy($src);
}
?>
``` | The trick was to put everything inside an array... I took the liberty of rewriting your `getPictures()` function... This one implements the sorting.
```
function getPictures() {
global $page, $per_page, $has_previous, $has_next;
if (!is_dir('thumbs')) {
mkdir('thumbs');
}
if ($handle = opendir(".")) {
$lightbox = rand();
$files = array();
while (($file = readdir($handle)) !== false) {
if (!is_dir($file) && ($type = getPictureType($file)) != '') {
$files[] = $file;
}
}
natsort($files);
$has_previous = $skip != 0;
$has_next = (count($files) - $skip - $per_page) > 0;
$spliceLength = min($per_page, count($files) - $skip);
$files = array_slice($files, $skip, $spliceLength);
echo '<ul id="pictures">';
foreach($files as $file) {
if (!file_exists('thumbs/' . $file)) {
$type = getPictureType($file);
makeThumb($file, $type);
}
echo '<li><a href="' . $file . '" class="zoom" rel="group">';
echo '<img src="thumbs/' . $file . '" alt="" />';
echo '</a></li>';
}
echo '</ul>';
}
}
``` | You're not even using an array.
Instead of echo'ing your li's as you encounter them you need to put them into an array, indexed by filename.
```
$output[$file] = '<li>etc</li>';
```
Then once your loop has completed, you'll need to use a custom function to do a natural key sort, since PHP's natsort() only works on values.
```
function natksort($array) {
$keys = array_keys($array);
natsort($keys);
$ret = array();
foreach ($keys as $k) {
$ret[$k] = $array[$k];
}
return $ret;
}
$output = natksort($output);
echo '<ul>';
foreach ($output as $out) {
echo $out;
}
echo '</ul>';
```
**Edit**
Wow, I found this little gem to do the sorting:
```
uksort($array, 'strnatcasecmp');
```
Credit: <http://www.chipstips.com/?p=269> | PHP: Sorting array with natsort | [
"",
"php",
"arrays",
"sorting",
""
] |
What's the difference between using oracle's plus notation `(+)` over the ansi standard `join` notation?
Is there a difference in performance?
Is the plus notation deprecated? | AFAIK, the `(+)` notation is only present for backwards compatibility because Oracle debuted it before the ANSI standard for joins was put in place. It's specific to Oracle and you should avoid using it in new code when there's an equivalent standards-compliant version available.
**It seems there are differences between the two, and the `(+)` notation has restrictions that the ANSI join syntax does not have. Oracle themselves recommend that you not use the `(+)` notation.
Full description here in the [Oracle® Database SQL Language Reference
11g Release 1 (11.1)](http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/queries006.htm):**
> Oracle recommends that you use the `FROM` clause `OUTER JOIN` syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator `(+)` are subject to the following rules and restrictions, which do not apply to the `FROM` clause `OUTER JOIN` syntax:
>
> * You cannot specify the `(+)` operator in a query block that also contains `FROM` clause join syntax.
> * The `(+)` operator can appear only in the `WHERE` clause or, in the context of left-correlation (when specifying the `TABLE` clause) in the `FROM` clause, and can be applied only to a column of a table or view.
> * If A and B are joined by multiple join conditions, then you must use the `(+)` operator in all of these conditions. If you do not, then Oracle Database will return only the rows resulting from a simple join, but without a warning or error to advise you that you do not have the results of an outer join.
> * The `(+)` operator does not produce an outer join if you specify one table in the outer query and the other table in an inner query.
> * You cannot use the `(+)` operator to outer-join a table to itself, although self joins are valid.
>
> For example, the following statement is not valid:
>
> ```
> SELECT employee_id, manager_id
> FROM employees
> WHERE employees.manager_id(+) = employees.employee_id;
> ```
>
> However, the following self join is valid:
>
> ```
> SELECT e1.employee_id, e1.manager_id, e2.employee_id
> FROM employees e1, employees e2
> WHERE e1.manager_id(+) = e2.employee_id;
> ```
>
> * The `(+)` operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary expression can contain one or more columns marked with the `(+)` operator.
> * A `WHERE` condition containing the `(+)` operator cannot be combined with another condition using the `OR` logical operator.
> * A `WHERE` condition cannot use the `IN` comparison condition to compare a column marked with the `(+)` operator with an expression.
>
> If the `WHERE` clause contains a condition that compares a column from table B with a constant, then the `(+)` operator must be applied to the column so that Oracle returns the rows from table A for which it has generated nulls for this column. Otherwise Oracle returns only the results of a simple join.
>
> In a query that performs outer joins of more than two pairs of tables, a single table can be the null-generated table for only one other table. For this reason, you cannot apply the `(+)` operator to columns of B in the join condition for A and B and the join condition for B and C. Refer to `SELECT` for the syntax for an outer join. | The most comprehensive answer obviously is the one by [nagul](https://stackoverflow.com/a/1193722/1845976).
An addition for those who are looking for quick translation/mapping to the ANSI syntax:
```
--
-- INNER JOIN
--
SELECT *
FROM EMP e
INNER JOIN DEPT d ON d.DEPTNO = e.DEPTNO;
-- Synonym in deprecated oracle (+) syntax
SELECT *
FROM EMP e,
DEPT d
WHERE d.DEPTNO = e.DEPTNO;
--
-- LEFT OUTER JOIN
--
SELECT *
FROM EMP e
LEFT JOIN DEPT d ON d.DEPTNO = e.DEPTNO;
-- Synonym in deprecated oracle (+) syntax
SELECT *
FROM EMP e,
DEPT d
WHERE d.DEPTNO (+) = e.DEPTNO;
--
-- RIGHT OUTER JOIN
--
SELECT *
FROM EMP e
RIGHT JOIN DEPT d ON d.DEPTNO = e.DEPTNO;
-- Synonym in deprecated oracle (+) syntax
SELECT *
FROM EMP e,
DEPT d
WHERE d.DEPTNO = e.DEPTNO(+);
--
-- CROSS JOIN
--
SELECT *
FROM EMP e
CROSS JOIN DEPT d;
-- Synonym in deprecated oracle (+) syntax
SELECT *
FROM EMP e,
DEPT d;
--
-- FULL JOIN
--
SELECT *
FROM EMP e
FULL JOIN DEPT d ON d.DEPTNO = e.DEPTNO;
-- Synonym in deprecated oracle (+) syntax !NOT WORKING!
SELECT *
FROM EMP e,
DEPT d
WHERE d.DEPTNO (+) = e.DEPTNO(+);
``` | Difference between Oracle's plus (+) notation and ansi JOIN notation? | [
"",
"sql",
"performance",
"oracle",
"join",
""
] |
I'm trying to work out the best way to setup our multi-module Apache Maven project in a way that allows for disparate release cycles of modules, and doesn't introduce dependency issues when debugging the project.
We currently have a setup along the lines of:
* bigsystem@1.2
+ parent-1.1-SNAPSHOT
+ module a@1.4-SNAPSHOT
- parented by parent@1.1-SNAPSHOT
+ module b@1.3-SNAPSHOT
- parented by parent@1.1-SNAPSHOT
- depends on a@1.1
+ module c@1.1-SNAPSHOT
- parented by parent@1.1-SNAPSHOT
- depends on a@1.2
- depends on b@1.1
The dependencies declared in modules b and c contain the minimum version required to compile the module, which isn't necessarily the current version of the module, or the version of the module being deployed.
From a build perspective this works well, each module can be released/updated as needed, however when trying to debug the deployed application under IntelliJ IDEA (versions 8 and 9 EAPs) having opened the top level pom, IDEA decides that since we declared a dependency on a@1.2, that anytime we step into one of a's classes, it should open it from a-1.2-sources.jar rather than the current a@1.4 sources in the project. This is further confused by the fact that stepping into any of b's classes takes us to b@1.1 rather than b@1.3.
My initial attempt to work around this was to declare the version numbers in the parent pom's dependencyManagement section and just have the sub-modules inherit the version. This worked to the degree of solving the IDEA debug issue as the dependencyManagement section can point everyone to the current -SNAPSHOT versions.
This unfortunately causes a problem when doing a maven release due to having to release the parent pom before releasing the module, but as the parent may refer to multiple in-development -SNAPSHOTS it can't be released and we end up adding version references back to the modules pom to satisfy the release.
It would seem that using maven's dependencyManagement section would only really work well if we were releasing ALL bundles at the same time, regardless of if they changed, but as we're wanting to manage releases of each sub module only when needed this model doesn't seem to fit.
I have a suspicion I'm missing something, and that a combination of dependencyManagement and version ranges might satisfy out requirements although I've yet to see version ranges work properly.
Is there a better way? A proper way? | The final/working solution we ended up using was fairly similar to what we started with. The actual project structure remains the same:
* bigsystem@1.2
+ parent-1.1-SNAPSHOT
+ module a@1.4-SNAPSHOT
o parented by parent@1.1-SNAPSHOT
+ module b@1.3-SNAPSHOT
o parented by parent@1.1-SNAPSHOT
o depends on a@1.1
+ module c@1.1-SNAPSHOT
o parented by parent@1.1-SNAPSHOT
o depends on a@1.2
o depends on b@1.1
+ distribution a@1.2-SNAPSHOP
However the main differences are that:
* parent module does not include any versions of *project artifacts*
* individual modules fully declare their project dependencies and specify a version range, i.e. [1.0.0,1.1.0)
* all modules start there version number cycles from .1, i.e 1.0.1-SNAPSHOT, this allows the version range to satisfied by initial snapshots (1.0.0-SNAPSHOT is earlier than 1.0.0 final, so not included).
* distribution pom (not initially shown in question) identifies the *exact* version to be deployed/included in a specific release.
* delete all project -SNAPSHOTS from local maven repository when releasing so that ranges pickup releases only ( or use -Dmaven.repo.local=/tmp/sometemprepo for a fresh local repo)
This makes each module more standalone and gives us the freedom to release and deploy new versions of our project artifacts with minimal fuss. | I would recommend not making them modules, but make their POMs independent. That way you do not have to worry about trying to satisfy parent POM dependencies. Since they are released independently, they really should have independent project object models. Think of Apache Commons as a template. | How do I properly setup a multi-module Maven project with sliding release cycles | [
"",
"java",
"maven-2",
"intellij-idea",
""
] |
Suppose I have a C++ macro CATCH to replace the catch statement and that macro receive as parameter a variable-declaration regular expression, like `<type_name> [*] <var_name>` or something like that. Is there a way to recognize those "fields" and use them in the macro definition?
For instance:
```
#define CATCH(var_declaration) <var_type> <var_name> = (<var_type>) exception_object;
```
Would work just like:
```
#define CATCH(var_type, var_name) var_type var_name = (var_type) exception_object;
```
---
As questioned, I'm using g++. | You can't do it with just macros, but you can be clever with some helper code.
```
template<typename ExceptionObjectType>
struct ExceptionObjectWrapper {
ExceptionObjectType& m_unwrapped;
ExceptionObjectWrapper(ExceptionObjectType& unwrapped)
: m_unwrapped(unwrapped) {}
template<typename CastType>
operator CastType() { return (CastType)m_wrapped; }
};
template<typename T>
ExceptionObjectWrapper<T> make_execption_obj_wrapper(T& eobj) {
return ExceptionObjectWrapper<T>(eobj);
}
#define CATCH(var_decl) var_decl = make_exception_obj_wrapper(exception_object);
```
With these definitions,
CATCH(Foo ex);
*should* work. I will admit to laziness in not testing this (in my defence, I don't have your exception object test with). If exception\_object can only be one type, you can get rid of the ExceptionObjectType template parameter. Further more, if you can define the cast operators on the exception\_object itself you can remove the wrappers altogether. I'm guessing exception\_object is actually a void\* or something though and your casting pointers. | What compiler are you using? I've never seen this done in the gcc preprocessor, but I can't say for sure that no preprocessor out there can implement this functionality.
What you could do however is run your script through something like sed to do your prepreprocessing so to speak before the preprocessor kicks in. | Is it possible to treat macro's arguments as regular expressions? | [
"",
"c++",
"regex",
"macros",
""
] |
Hey guys, I have a regular expression that is pretty long, and is hard to look at.
i was wondering if you could help shorten it up, so it's more manageable.
I admit, I'm not a regexp guru, and I just hack away to get by. If you come up with something better (it doesn't even have to be shorter), please explain your reasoning, so I might have a better understanding of the techniques you use.
**Regex:**
```
^([a-zA-Z0-9# ]+)-([a-zA-Z ]*)([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z0-9_ ]+)-([a-zA-Z ~]+)([a-zA-Z0-9_ ]+)\.rpt$
```
**Tests:**
```
TESTFIX - ABCD 10118 - E008 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ 91.rpt
TESTFIX - EFGD 10118 - E008 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ 92.rpt
TESTFIX - 10118_14041 M - E008 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ 93.rpt
TESTFIX - ABCD 10118 - E008 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ 93.rpt
TESTFIX - EFGD 10118 - E008 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ 93.rpt
TESTFIX - EFGD 10118 - E008 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ 93.rpt
TESTFIX - ABCD 10118 - E008 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ 93.rpt
#1REALLYLONGNAME - 10244 - E011 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - DX ~ ALPHALTR.rpt
#1 LIVEREP - 10045 - E011 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ SING.rpt
#2 LIVEREP - 10045 M - E011 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ MUL.rpt
WELLREP - WELL10000 - E011 - E009 - IXX - IXX - IXX - IXX - IXX - IXX - SX ~ CLT.rpt
```
each section is split up by the ' - ' sequence of characters.
All sections can contain spaces, and any valid file name character
There has to be group capturing for each section
If it matters, I'll be using this regexp in C# | First of all, get a good regular expression development tool. My favorite is [Expresso](http://www.ultrapico.com/Expresso.htm).
Here is a cleaned up version:
```
^[\w# ]+ - [a-zA-Z ]*(?:[\w_ ]+ - ){9}[a-zA-Z]+ ~[\w_ ]+\.rpt$
```
Changes include:
* Removed the capture groupings "()" -
I'll assume that you're only
validating the text since you didn't
mention any capturing. If you need
them, they're easy enough to add back
* Use of alphanumeric character class - "\w" which is equivalent to "[a-zA-Z0-9]"
* Replaced the repeated portion in the middle with "(?:[\w\_ ]+ - ){9}" This matches ([alphanumeric underscore space]+ - ) nine times. It doesn't capture because of the "?:" I put after the first parenthesis.
EDIT:
Here it is with the capture groups back:
```
^([\w# ]+) - ([a-zA-Z ]*)(?:([\w_ ]+) - ){9}([a-zA-Z]+) ~ ([\w_ ]+)\.rpt$
```
Note that when you go through the numbered capture groups, the third one will have 9 captures in it. | When you are talking about "simplifying" Regular Expressions, you really need to also know what you **don't** want to match, as that can really help simplify your tests with special characters, sequence repetition, etc.
That said, here is a cleaned up version that is produces *exactly* the same result as your original expression:
```
^([a-zA-Z0-9# ]+)-([a-zA-Z ]*)(?:([\w ]+)-){9}([a-zA-Z ~]+)([\w ]+)\.rpt$
```
Some notes on why this differs from the other posted answer:
* According to my reference for Perl-compatible regular expressions, \w actually also includes underscore. (**Edit:** this is apparently different from C# which is explained in the link to MSDN. This difference may be useful to note.)
* My expression assumes you had the spaces in the character classes on purpose. If, in fact, you can have multiple spaces between dashes, leave it this way, otherwise, go with the other answer. | Long Regex - How would you do it? | [
"",
"c#",
"regex",
""
] |
Does anyone have a good and efficient extension method for finding if a sequence of items has any duplicates?
Guess I could put `return subjects.Distinct().Count() == subjects.Count()` into an extension method, but kind of feels that there should be a better way. That method would have to count elements twice and sort out all the distict elements. A better implementation should return true on the first duplicate it finds. Any good suggestions?
I imagine the outline could be something like this:
```
public static bool HasDuplicates<T>(this IEnumerable<T> subjects)
{
return subjects.HasDuplicates(EqualityComparer<T>.Default);
}
public static bool HasDuplicates<T>(this IEnumerable<T> subjects, IEqualityComparer<T> comparer)
{
...
}
```
But not quite sure how a smart implementation of it would be... | ```
public static bool HasDuplicates<T>(this IEnumerable<T> subjects)
{
return HasDuplicates(subjects, EqualityComparer<T>.Default);
}
public static bool HasDuplicates<T>(this IEnumerable<T> subjects, IEqualityComparer<T> comparer)
{
HashSet<T> set = new HashSet<T>(comparer);
foreach (T item in subjects)
{
if (!set.Add(item))
return true;
}
return false;
}
``` | This is in production code. Works great:
```
public static bool HasDuplicates<T>(this IEnumerable<T> sequence, IEqualityComparer<T> comparer = null) {
var set = new HashSet<T>(comparer);
return !sequence.All(item => set.Add(item));
}
``` | C#: A good and efficient implementation of IEnumerable<T>.HasDuplicates | [
"",
"c#",
"ienumerable",
"implementation",
"duplicates",
""
] |
I'm making an MSN client in PHP. I have this code, which connects to a server and logs in to MSN:
```
$server2 = explode(":", $xfr[3]);
$socket2 = pfsockopen($server2[0], (int)$server2[1]);
$_SESSION["socket"] = $socket;
echo '<b>Connected to 2nd server.</b><br />';
//Send MSNP version
fputs($socket2, "VER 0 MSNP10 CVR0\r\n");
echo fread($socket2, 5000) . '<br />';
//Send user-agent
fputs($socket2, "CVR 1 0x0409 php ".phpversion()." i386 MSNMSGR 7.0.0000 MSMSGS ".$_POST["username"]."\r\n");
echo fread($socket2, 5000) . '<br />';
//Send username
fputs($socket2, "USR 2 TWN I ".$_POST["username"]."\r\n");
//Read USR
$usr = fread($socket2, 5000);
echo $usr . '<br />';
$usr = explode(" ", $usr);//This is for later usage.
```
Now I need to use this socket in another page (`AJAX/status.php`). php.net says that the connection stays available. However, this is status.php (just ignore $\_SESSION["cid"]), which is called via AJAX:
```
<?php
session_start();
fputs($_SESSION["socket"], "CHG 12 " . $_GET["s"] . " " . $_SESSION["cid"], 5000);
echo fread($_SESSION["socket"]);
```
Which should change the status. I get this error:
```
<br />
<b>Warning</b>: fputs(): supplied argument is not a valid stream resource in <b>C:\wamp\apps\msnphp\AJAX\status.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: Wrong parameter count for fread() in <b>C:\wamp\apps\msnphp\AJAX\status.php</b> on line <b>4</b><br />
```
My socket is persistent, and it's id is saved in session variable $\_SESSION["socket"]. I do not understand why it does not work.
I use Windows XP Professional SP2 as server, with WAMP (Apache, MySQL and PHP) server.
Can anyone help me? Thanks! | pfsockopen() returns a resource. You cannot store resources in the Session as they are just handles to external resources which may not be there later.
If you request the same page again you might get to reuse the connection by calling pfsockopen() again with the same parameters, but I don't think you have any guarantee of this, and it probably won't be practical as for this you probably want one connection per user session.
You could start background PHP processes which connect to the remote server, and read/write events into a queue (maybe a database or memcached). You'd have to make sure these processes are terminated properly otherwise you could quickly have a lot sitting there. Your front-end PHP script can then just read/write from/to the queue.
The problem you have is really based on HTTP being stateless, but the service you are connecting to being stateful. So you have to somehow maintain state (for the external resource) on your webserver, which is not something that is very easy to do with PHP. | Change this:
```
$socket2 = pfsockopen($server2[0], (int)$server2[1]);
$_SESSION["socket"] = $socket;
```
for this!
```
$socket2 = pfsockopen($server2[0], (int)$server2[1]);
$_SESSION["socket"] = $socket2 /* WITH "2" */;
```
;) | PHP pfsockopen in a session | [
"",
"php",
"session",
"sockets",
"msn",
""
] |
In C++ (MSVC) how can I test whether an exception is currently "in flight". Ie, code which is being called as part of a class destructor may be getting invoked because an exception is unwinding the stack.. How can I detect this case as opposed to the normal case of a destructor being called due to a normal return? | Actually it's possible to do this, call uncaught\_exception() in <exception> header.
One reason you might want to do this is before throwing an exception in a destructor, which would lead to program termination if this destructor was called as part of stack unwinding.
See <http://msdn.microsoft.com/en-us/library/k1atwat8%28VS.71%29.aspx> | Before you go too far down the uncaught\_exception() path, look at <http://www.gotw.ca/gotw/047.htm> | How to detect when an exception is in flight? | [
"",
"c++",
"exception",
"visual-c++",
""
] |
The StreamWriter.Close() says it also closes the underlying stream of the StreamWriter. What about StreamWriter.Dispose ? Does Dispose also dispose and/or close the underlying stream | `StreamWriter.Close()` just calls `StreamWriter.Dispose()` under the bonnet, so they do exactly the same thing.
`StreamWriter.Dispose()` does close the underlying stream.
[Reflector](http://www.red-gate.com/products/reflector/) is your friend for questions like this :) | Some people will say, just dont dispose the stream, this is a really bad idea, because once the streamwriter goes out of scope GarbageCollection can pick it up anytime and dipose it, thus closing the Handle to the stream, but creating a descendant class which overrides this behaviour of StreamWriter is easy, heres the code:
```
/// <summary>
/// Encapsulates a stream writer which does not close the underlying stream.
/// </summary>
public class NoCloseStreamWriter : StreamWriter
{
/// <summary>
/// Creates a new stream writer object.
/// </summary>
/// <param name="stream">The underlying stream to write to.</param>
/// <param name="encoding">The encoding for the stream.</param>
public NoCloseStreamWriter(Stream stream, Encoding encoding)
: base(stream, encoding)
{
}
/// <summary>
/// Creates a new stream writer object using default encoding.
/// </summary>
/// <param name="stream">The underlying stream to write to.</param>
/// <param name="encoding">The encoding for the stream.</param>
public NoCloseStreamWriter(Stream stream)
: base(stream)
{
}
/// <summary>
/// Disposes of the stream writer.
/// </summary>
/// <param name="disposing">True to dispose managed objects.</param>
protected override void Dispose(bool disposeManaged)
{
// Dispose the stream writer but pass false to the dispose
// method to stop it from closing the underlying stream
base.Dispose(false);
}
}
```
If you look in Reflector / ILSpy you will find that the closing of the base stream is actually done in Dispose(true), and when close is called it just calls Dispose which calls Dispose(True), from the code there should be no other side effects, so the class above works nicely.
You might want to add all the constructors though, i have just added 2 here for simplicity. | Does .Disposing a StreamWriter close the underlying stream? | [
"",
"c#",
".net",
""
] |
Suppose you have some method that could be made static, inside a non-static class.
For example:
```
private double power(double a, double b)
{
return (Math.Pow(a, b));
}
```
Do you see any benefit from changing the method signature into static? In the example above:
```
private static double power(double a, double b)
{
return (Math.Pow(a, b));
}
```
Even if there is some performance or memory gain, wouldn't the compiler do it as a simple optimization in compile time?
---
**Edit:** What I am looking for are the benefits by declaring the method as static. I *know* that this is the common practice. I would like to understand the logic behind it.
And of course, this method is just an example to clarify my intention. | Note that it is highly unlikely the compiler is even allowed to make that change on your behalf since it changes the signature of the method. As a result, some carefully crafted reflection (if you were using any) could stop working, and the compiler really cannot tell if this is the case. | As defined, `power` is stateless and has no side effects on any enclosing class so it should be declared `static`.
This [article](http://msdn.microsoft.com/en-us/library/ms973852.aspx) from MSDN goes into some of the performance differences of non-static versus static. The call is about four times faster than instantiating and calling, but it really only matters in a tight loop that is a performance bottleneck. | Static vs. non-static method | [
"",
"c#",
"performance",
""
] |
I've gone back and forth on this problem and can't seem to figure out the best way to do this.
Here's the situation:
* Access database (3rd party product) with data I need in it, from a good number of tables (18 tables)
* Ideally, need to try to get records into strongly-typed objects somehow so I can query around with LINQ
* LINQ to SQL classes don't support ODBC provider (this would have gotten me home free)
* I do NOT need to insert/update/delete. Only select/read.
I've toyed around with the idea of just exporting the tables to XML (it's not that much) but then I'm still faced with the problem of building the schema and generating the classes. Since it's an ODBC source there should be a way to ORM this, right?
How would you solve this? | You can do this using nHibernate, since it supports MS Access as a backend. Here are the [details of using nHibernate with MS Access](http://www.hibernate.org/361.html#A4). It uses NHibernate.JetDriver.dll to access the Jet data engine (MS Access).
Just realize that MS Access isn't going to give you the same performance/support/etc as most other DB backends with an ORM. | The dll for using NHibernate to Acccess seems to be on sourceForge (just googling, not checking)
<http://sourceforge.net/project/shownotes.php?release_id=460590>
If you are just querying access, it might be worth defining views in a relationnal database
This way you will have a solution for using a form of cache/snapshot later on(for example by converting your views into table that you refresh each hour/ 5min. etc depending on your expectations)
if the performance degrade too much. | Best way to do ORM with Access DB as datasource | [
"",
"c#",
".net",
"linq",
"orm",
"odbc",
""
] |
is there a way to find if the value parsed and returned by [java.io.StreamTokenizer](http://java.sun.com/javase/6/docs/api/java/io/StreamTokenizer.html).**nval** (e.g. `200`) was an integer or a floating number ?
Thanks
**Edited**:
I want to be able to know if the input was '200' or '200.0'. | I don't think it is possible with StringTokenizer, it's too old. You can use Scanner to do the job:
```
Scanner fi = new Scanner("string 200 200.0");
fi.useLocale(Locale.US);
while (fi.hasNext()) {
if (fi.hasNextInt()) {
System.out.println("Integer: " + fi.nextInt());
} else if (fi.hasNextDouble()) {
System.out.println("Double: " + fi.nextDouble());
} else {
System.out.println("String: " + fi.next());
}
}
```
Documentation for the class is [here](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html) | I would use the modulus operator:
```
if (yourNval % 1 > 0)
{
// nval is floating point.
}
else
{
// nval is an integer.
}
```
This works because modulus [works with floating point numbers](http://www.cafeaulait.org/course/week2/15.html) in Java as well as integers.
UPDATE: Since you specify a need to distinguish integers from doubles with zero-value decimal portions, I think you'll have to do something like the following:
```
Double(yourNval).toString().indexOf('.');
```
So a more-complete function will look like:
```
if (yourNval % 1 > 0)
{
// nval is floating point.
}
else
{
// nval is an integer.
// Find number of trailing zeroes.
String doubleStr = Double(yourNval).toString();
int decimalLoc = doubleStr.indexOf('.');
int numTrailingZeroes = 0;
if (decimalLoc > 0)
{
numTrailingZeroes = doubleStr.length() - decimalLoc - 1;
}
}
``` | java.io.StreamTokenizer.TT_NUMBER: Floating or Integer? | [
"",
"java",
"parsing",
""
] |
I have an animation in WPF that is jerky, my WPF form is layed out as follows:
a 1280x800 Window contains a 2400x7\*\* grid, seperated into 3 columns.
* Column 1 is \* width
* Column 2 is 148 width
* Column 3 is \* width
This allows me to, using an animation, chage the grid's margin to ~-1000 on the left side to bring the left column off screen, move the middle column to the far right, and then pan the right most column on screen (think of it like a 2 page panning design.)
This is all great, but my screen components animate at different speeds when i slide them left/right, is there a way to essentially double buffer my entire drawing space and pan it all together? or is this against the spirit of WPF. | Simple buffering wouldn't help with this problem, because it seems that lags are not in graphics, but rather in logic behind updating properties of different elements during animation. Following should help though:
* On button click, render whole grid to RenderTargetBitmap.
* Paint resulting image (RenderTargetBitmap inherits from BitmapSource) on some rectangle over the grid.
* Hide the actual grid.
* Animate bitmap, move hidden grid to the new position
* Show grid
* Hide bitmap
As for spirit of WPF, it can be called necessary evil. You can notice how text rendering in WPF itself changes during scrolling, for example - using RenderTargetBitmap is no worse.
Disclaimer: I didn't try to reproduce problem nor read the XAML, but the method above naturally avoids all problems with vector graphics or hosted elements. | I've checked your code and can verify the funny transition. However, the animation lags only when going to the right.
When I replaced your WebBrowser with a colored Border, the lag was gone.
So the conclusion would be that the issue here is the slow rendering of an outside hosted visual. The WebBrowser is an interop ui element, inheriting from [HwndHost](http://msdn.microsoft.com/en-us/library/system.windows.interop.hwndhost.aspx).
So it's definetly nothing to do with XAML, I think you're stuck with the performance as it is. | Jerky Animations in WPF | [
"",
"c#",
".net",
"wpf",
"animation",
""
] |
Here's my situation. I have a user table and a password\_reset table which references the user table.
I want to run a single query that will return some fields from a password\_reset row that references their user row. However, I want to return just the user's email if they DO NOT have a row in password\_reset. Here is what I have so far, which works in the event that they DO have a password\_reset row, but not if they don't (in that case, it returns no rows at all).
```
SELECT u.email, p.code, p.expires
FROM users u, password_resets p
WHERE u.username = :username
AND u.id = p.user_id
```
How would I go about writing this? Can I even do it with just one query? | ```
SELECT u.email, p.code, p.expires
FROM users AS u
LEFT JOIN password_resets AS p USING (u.id = p.user_id)
WHERE u.username = :username
``` | ```
SELECT Users.email
FROM Users
LEFT JOIN Password_resets ON Users.PrimaryKey = Password_resets.ForeignKey
WHERE Password_resets.ForeignKey IS NULL
``` | Is there a way to write this as one query? | [
"",
"sql",
""
] |
I need to replicate a sequence/counter across an eight node cluster. This means that each http request receives the next value in the sequence by calling something like getNextIntAndIncrement(), where the sequence state is synchronized across all servers. To clarify, this must exist at application/global scope, not session. I know it sounds like an awful idea and will undoubtably lead to bottlenecking but this is the requirement.
My question is what is the best solution? I've looked at stateful session beans, but they appear to be designed for only one client. I considered a database sequence. I've also looked at Terracotta clustering; they have a sequence demo <http://www.terracotta.org/web/display/orgsite/Recipe?recipe=sequencer> However I'd like to avoid third party solutions if a J2EE solution exists. I'm using Weblogic 8.1. | Some Java EE vendors have distrubted cache solutions (eg. WebSphere's Object Grid) asnd you've already identifed 3rd party offerings but I don't believe a portable standard exists.
What's wrong with the DB solution? It's clear that locking is going to be needed, so why not leave to the DB. My guess is that if you really need true incremental values, no values missed etc. then transactional relationships with other database values will be important, so use the DB.
If you can relax the need for absolute sequenetial values (ie. allow gaps) then you can parcel out sets of numbers and thereby greatly reduce contention. If you truly need sequential values, no gaps, then you are buying into the need for some degree of locking between the instances - you can't allow a second "thread" to get a new sequence number until you "commit" the use of the current one. If you can afford to lose the odd sequence number then you do much better. Or if you can independent numbering schemes between instances you are in a much better positions. For example name you servers a, b, c ... have ids a001, a002, b001, c001, c002 etc. | I think a database sequence would likely give you the most deterministic result, especially if you use highly-serialized transactions to request it.
However, I would seriously question the validity of doing something like this, but that is just my 2 cents. | clustering/replicating counter state with application level scope | [
"",
"java",
"jakarta-ee",
"weblogic",
"cluster-computing",
""
] |
I'm using a solution for assembling image files to a zip and streaming it to browser/Flex application. (ZipStream by Paul Duncan, <http://pablotron.org/software/zipstream-php/>).
Just loading the image files and compressing them works fine. Here's the core for compressing a file:
```
// Reading the file and converting to string data
$stringdata = file_get_contents($imagefile);
// Compressing the string data
$zdata = gzdeflate($stringdata );
```
My problem is that I want to process the image using GD before compressing it. Therefore I need a solution for converting the image data (imagecreatefrompng) to string data format:
```
// Reading the file as GD image data
$imagedata = imagecreatefrompng($imagefile);
// Do some GD processing: Adding watermarks etc. No problem here...
// HOW TO DO THIS???
// convert the $imagedata to $stringdata - PROBLEM!
// Compressing the string data
$zdata = gzdeflate($stringdata );
```
Any clues? | One way is to tell GD to output the image, then use PHP buffering to capture it to a string:
```
$imagedata = imagecreatefrompng($imagefile);
ob_start();
imagepng($imagedata);
$stringdata = ob_get_contents(); // read from buffer
ob_end_clean(); // delete buffer
$zdata = gzdeflate($stringdata);
``` | ```
// ob_clean(); // optional
ob_start();
imagepng($imagedata);
$image = ob_get_clean();
``` | PHP GD: How to get imagedata as binary string? | [
"",
"php",
"zip",
"gd",
""
] |
I am having some trouble with jQuery.
I am making a simple CMS and in the interface I have a list of pages, in each list item is an edit link. I made jQuery listen for clicks with that edit id. It will then look at the parent LI to see what id it has so the user can save the changes to the right pageId in the database.
My List
```
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a href="#" id="edit">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a href="#" id="edit">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
```
And the javascript
```
<script type="text/javascript">
$(document).ready(function() {
$('a#edit').click(function(){
alert($(this).parent("li").attr("id"));
})
});
```
But only the first edit link works. All the others just get ignored.
You can see the problem working here, <http://info.radio-onair.ath.cx/active/scms/admin/pages/test.html>
Thanks in advance. | In HTML, `id` refers to a **unique identifier**. In other words, it is against standards to have 2 elements with the same `id`. jQuery here behaves correctly.
Use a `class` instead of an `id` to identify your tags as such:
**HTML:**
```
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a class="edit" href="#">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a class="edit" href="#">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
```
**JavaScript:**
```
$(document).ready(function() {
$('a.edit').click(function(){
alert($(this).parent("li").attr("id"));
})
});
```
---
Alternatively, since the parent tag already seems to have a unique class, you could simply use it to target wanted tags. This would reduce what I call "class noise" (the defining of useless class to target element which could be targeted by their parent's unique attributes).
**HTML:**
```
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a href="#">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a href="#">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
```
**JavaScript:**
```
$(document).ready(function() {
$("li.sortable a:contains('edit')").click(function(){
alert($(this).parent("li").attr("id"));
})
});
``` | I think this is because use use the same **id** for each element. Try using a class instead.
```
<a href="#" class="edit">edit</a>
```
And then
```
$('a.edit').click(...)
``` | jQuery click function only works on first element | [
"",
"javascript",
"jquery",
""
] |
When storing latitude or longitude data in an ANSI SQL compliant database, what datatype would be most appropriate? Should `float` be used, or `decimal`, or ...?
I'm aware that Oracle, MySql, and SQL Server have added some special datatypes specifically for handling geo data, but I'm interested in how you would store the information in a "plain vanilla" SQL database. | For latitudes use: `Decimal(8,6)`, and longitudes use: `Decimal(9,6)`
If you're not used to precision and scale parameters, here's a format string visual:
Latitude and Longitude
`##.######` and `###.######`
To 6 decimal places should get you to around ~10cm of accuracy on a coordinate. | EDIT (14+ years later): Don't use float for precision-based numeric values. dotjoe's answer to use Decimal(9,6) is perfect.
Leaving my old answer here for laughs:
> We use float, but any flavor of numeric with 6 decimal places should
> also work. **- me, 2009** | What datatype to use when storing latitude and longitude data in SQL databases? | [
"",
"sql",
"database",
"geocoding",
"latitude-longitude",
""
] |
I have a string which contains the text of an article. This is sprinkled with BBCodes (between square brackets). I need to be able to grab the first say, 200 characters of an article without cutting it off in the middle of a bbcode. So I need an index where it is safe to cut it off. This will give me the article summary.
* The summary must be minimum 200 characters but can be longer to 'escape' out of a bbcode. (this length value will actually be a parameter to a function).
* It must not give me a point inside a stand alone bbcode (see the pipe) like so: [lis|t].
* It must not give me a point between a start and end bbcode like so: [url="http://www.google.com"]Go To Goo|gle[/url].
* It must not give me a point inside either the start or end bbcode or in-between them, in the above example.
It should give me the "safe" index which is after 200 and is not cutting off any BBCodes.
Hope this makes sense. I have been struggling with this for a while. My regex skills are only moderate. Thanks for any help! | First off, I would suggest considering what you will do with a post that is entirely wrapped in BBcodes, as is often true in the case of a font tag. In other words, a solution to the problem as stated will easily lead to 'summaries' containing the entire article. It may be more valuable to identify which tags are still open and append the necessary BBcodes to close them. Of course in cases of a link, it will require additional work to ensure you don't break it. | Well, the obvious *easy* answer is to present your "summary" without any bbcode-driven markup at all (regex below taken from [here](http://twelvestone.com/forum_thread/view/28916))
```
$summary = substr( preg_replace( '|[[\/\!]*?[^\[\]]*?]|si', '', $article ), 0, 200 );
```
However, do do the job you explicitly describe is going to require more than just a regex. A lexer/parser would do the trick, but that's a moderately complicated topic. I'll see if I can come up w/something.
## EDIT
Here's a pretty ghetto version of a lexer, but for this example it works. This converts an input string into bbcode tokens.
```
<?php
class SimpleBBCodeLexer
{
protected
$tokens = array()
, $patterns = array(
self::TOKEN_OPEN_TAG => "/\\[[a-z].*?\\]/"
, self::TOKEN_CLOSE_TAG => "/\\[\\/[a-z].*?\\]/"
);
const TOKEN_TEXT = 'TEXT';
const TOKEN_OPEN_TAG = 'OPEN_TAG';
const TOKEN_CLOSE_TAG = 'CLOSE_TAG';
public function __construct( $input )
{
for ( $i = 0, $l = strlen( $input ); $i < $l; $i++ )
{
$this->processChar( $input{$i} );
}
$this->processChar();
}
protected function processChar( $char=null )
{
static $tokenFragment = '';
$tokenFragment = $this->processTokenFragment( $tokenFragment );
if ( is_null( $char ) )
{
$this->addToken( $tokenFragment );
} else {
$tokenFragment .= $char;
}
}
protected function processTokenFragment( $tokenFragment )
{
foreach ( $this->patterns as $type => $pattern )
{
if ( preg_match( $pattern, $tokenFragment, $matches ) )
{
if ( $matches[0] != $tokenFragment )
{
$this->addToken( substr( $tokenFragment, 0, -( strlen( $matches[0] ) ) ) );
}
$this->addToken( $matches[0], $type );
return '';
}
}
return $tokenFragment;
}
protected function addToken( $token, $type=self::TOKEN_TEXT )
{
$this->tokens[] = array( $type => $token );
}
public function getTokens()
{
return $this->tokens;
}
}
$l = new SimpleBBCodeLexer( 'some [b]sample[/b] bbcode that [i] should [url="http://www.google.com"]support[/url] what [/i] you need.' );
echo '<pre>';
print_r( $l->getTokens() );
echo '</pre>';
```
The next step would be to create a parser that loops over these tokens and takes action as it encounters each type. Maybe I'll have time to make it later... | Finding a point in a string that is not inside BBCodes | [
"",
"php",
"regex",
"string",
"bbcode",
""
] |
I'm puzzled by minidom parser handling of empty element, as shown in following code section.
```
import xml.dom.minidom
doc = xml.dom.minidom.parseString('<value></value>')
print doc.firstChild.nodeValue.__repr__()
# Out: None
print doc.firstChild.toxml()
# Out: <value/>
doc = xml.dom.minidom.Document()
v = doc.appendChild(doc.createElement('value'))
v.appendChild(doc.createTextNode(''))
print v.firstChild.nodeValue.__repr__()
# Out: ''
print doc.firstChild.toxml()
# Out: <value></value>
```
How can I get consistent behavior? I'd like to receive *empty string* as value of *empty element* (which *IS* what I put in XML structure in the first place). | Cracking open xml.dom.minidom and searching for "/>", we find this:
```
# Method of the Element(Node) class.
def writexml(self, writer, indent="", addindent="", newl=""):
# [snip]
if self.childNodes:
writer.write(">%s"%(newl))
for node in self.childNodes:
node.writexml(writer,indent+addindent,addindent,newl)
writer.write("%s</%s>%s" % (indent,self.tagName,newl))
else:
writer.write("/>%s"%(newl))
```
We can deduce from this that the short-end-tag form only occurs when childNodes is an empty list. Indeed, this seems to be true:
```
>>> doc = Document()
>>> v = doc.appendChild(doc.createElement('v'))
>>> v.toxml()
'<v/>'
>>> v.childNodes
[]
>>> v.appendChild(doc.createTextNode(''))
<DOM Text node "''">
>>> v.childNodes
[<DOM Text node "''">]
>>> v.toxml()
'<v></v>'
```
As pointed out by Lloyd, the XML spec makes no distinction between the two. If your code *does* make the distinction, that means you need to rethink how you want to serialize your data.
xml.dom.minidom simply displays something differently because it's easier to code. You can, however, get consistent output. Simply inherit the `Element` class and override the `toxml` method such that it will print out the short-end-tag form when there are no child nodes with non-empty text content. Then monkeypatch the module to use your new Element class. | ```
value = thing.firstChild.nodeValue or ''
``` | Empty XML element handling in Python | [
"",
"python",
"xml",
"string",
""
] |
I've implemented a class that looks like this interface:
```
[ImmutableObject(true)]
public interface ICustomEvent
{
void Invoke(object sender, EventArgs e);
ICustomEvent Combine(EventHandler handler);
ICustomEvent Remove(EventHandler handler);
ICustomEvent Combine(ICustomEvent other);
ICustomEvent Remove(ICustomEvent other);
}
```
This CustomEvent class works much like a MulticastDelegate. It can invoked. It can be combined with another CustomEvent. And a CustomEvent can be removed from another CustomEvent.
Now, I want to declare a class like this:
```
class EventProvider
{
public event CustomEvent MyEvent;
private void OnMyEvent()
{
var myEvent = this.MyEvent;
if (myEvent != null) myEvent.Invoke(this, EventArgs.Empty);
}
}
```
Unfortunately, this code does not compile. A Compiler Error CS0066 appears:
*'EventProvider.MyEvent': event must be of a delegate type*
Basically, what I need is a property that has **add** and **remove** accessors instead of **get** and **set**. I think the only way to have that is using the **event** keyword. I know that one obvious alternative is to declare two methods that would do the adding and removing, but I want to avoid that too.
Does anybody knows if there is a nice solution this problem? I wonder if there is any way to cheat the compiler to accept a non-delegate type as an event. A custom attribute, perhaps.
By the way, someone asked a similar question in experts-exchange.com. Since that site is not free, I can't see the responses. Here is the topic: <http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_21697455.html> | If you want to be able to add and remove `CustomEvent` objects from the event (instead of regular delegates), there are two options:
Make an implicit cast from ICustomEvent to EventHandler (or some other delegate) that returns an instance method of ICustomEvent (probably Invoke), then use the Target property of the delegate to get the original ICustomEvent in the `add` and `remove` accessors.
**EDIT**: Like this:
```
CustomEvent myEvent;
public event EventHandler MyEvent {
add {
if (value == null) throw new ArgumentNullException("value");
var customHandler = value.Target as ICustomEvent;
if (customHandler != null)
myEvent = myEvent.Combine(customHandler);
else
myEvent = myEvent.Combine(value); //An ordinary delegate
}
remove {
//Similar code
}
}
```
Note that you'll still need to figure out how to add the first handler if it's a delegate (if the `myEvent` field is `null`)
---
Make a writable property of type CustomEvent, then overload the `+` and `-` operators to allow `+=` and `-=` on the property.
**EDIT**: To prevent your callers from overwriting the event, you could expose the previous value in CustomEvent (I'm assuming it works like an [immutable stack](http://blogs.msdn.com/ericlippert/archive/2007/12/04/immutability-in-c-part-two-a-simple-immutable-stack.aspx)) and, in the setter, add
```
if (myEvent.Previous != value && value.Previous != myEvent)
throw new ArgumentException("You cannot reset a CustomEvent", "value");
```
Note that when the last handler is removed, both `value` and `myEvent.Previous` will be `null`. | Try this:
```
CustomEvent myEvent
public event EventHandler MyEvent {
add { myEvent = myEvent.Combine(value); }
remove {myEvent = myEvent.Remove(value); }
}
```
You can add and remove normal EventHandler delegates to it, and it will execute the `add` and `remove` accessors.
---
**EDIT**: You can find a weak event implementation [here](http://www.codeproject.com/KB/cs/WeakEvents.aspx).
**2nd EDIT**: Or [here](http://msdn.microsoft.com/en-us/library/aa970850.aspx). | Events of a non-delegate type | [
"",
"c#",
".net",
"events",
"delegates",
""
] |
I have been wracking my brain trying to figure this out. For the first time I used jEdit the other day and I was pleasantly surprised that it auto indented my code (meaning that I'd put in the following code:
```
int method () {
_ //<-- and it put me here automatically
```
I've tried to get the same thing working with eclipse but with no success. I got into the code formatter but I don't see how to make that happen.
Is it possible to do this? Also while I'm here, is there a such thing as a eclipse plugin that will allow you to search the methods and classes of the standard java library?
Thanks | My clean eclipse install does this by default.
Have you changed any options? Make sure the file you are editing has the `.java` file extension. The preference options that control the typing automations are under `Java -> Editor -> Typing` in the `Window -> Preferences` menu.
Also, I find that the auto-indenting, and most of the other auto-complete functions of eclipse do not function well if the file I am editing has errors in it which prevent compilation. Make sure that your curly-braces are matched correctly, this is the main one that I've noticed blocks auto-indent.
Regarding searching through the standard Java libraries, use the `Search -> Java..` menu option, and check the JRE libraries checkbox, then search away. You can also use the Hierarchy view to see how the classes relate. Also, in the Package and Project views you can expand the JRE System Library, and then expand `rt.jar` which holds pretty much all the standard Java pacakges. | Personally all I use for this is the format options Window->preferences under Java->Code Style ->Formatter.
I once took the time to tweek how I like my code to look like when I work and exported the whole thing. After that I just code without too much bother on what it looks like. When I find the code looks messy by pressing the combination ctrl+shift+f and the whole class becomes pretty again, comments and all.
After a while it pretty much became a reflex...
code code code
ctrl-s, ctrl-b (cause I disable auto build sometimes), ctrl-shift-f
code some more etc...
Once I got used to this I never really cared how it presented the code as i was typing because I knew it would look all pretty as soon as the loop/if/switch/method etc is finished | AutoIndent in Eclipse possible? | [
"",
"java",
"eclipse",
"formatting",
"coding-style",
"indentation",
""
] |
> **Possible Duplicate:**
> [Best Practice: Initialize class fields in constructor or at declaration?](https://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration)
I am working with C# but this probably applies to Java (or any other language that allows this behavior as well)...
Which way is preferable/best practice? Assume I will ALWAYS need \_memberVar
1.
```
class MyClass
{
private Dictionary<int, string> _memberVar = new Dictionary<int, string>();
public MyClass() {}
}
```
**- OR -**
2.
```
class MyClass
{
private Dictionary<int, string> _memberVar = null
public MyClass()
{
_memberVar = new Dictionary<int, string>();
}
}
```
Now lets say that `MyClass` has upwards of 10 constructors... So I don't want to have `_memberVar = new Dictionary<int, string>();` in all of those constructors lol. Is there anything wrong with the 1st way? Thanks
**Edit:**
I realize I can chain the constructors, but this is a rather complex class... some constructors call the base, some call other constructors already etc etc. | You do not have to initialise member variables, but it does not hurt if you do. Member variables acquire their default values automatically, usually a `null` for objects and the default value for primitive types (such as `0` for an `int`).
As for having different constructors, you do not have to repeat the member initialisation in each version since you can call an overloaded constructor from any other just as you would with an overloaded method.
Regarding best practice, **personally** I initialise member variables in the constructor as this is where I want to "construct" my object into a stable state. In other words, even if I would have initialised member variables where I declare them, when the constructor is called, it would be as if I was wiping the slate clean. | With respect to \_memberVar being initialized in 10 constructors: I think you need to rethink your class. That sounds excessive. If you're doing the same work in each constructor, then you're violating DRY. Instead, try to adopt this structure:
```
public class MyClass {
Foo _foo;
Bar _bar;
Baz _baz;
public MyClass(Foo foo, Bar bar, Baz baz) {
_foo = foo; _bar = bar; _baz = baz;
}
public MyClass(Foo foo, Bar bar) : this(foo, bar, new Baz()) { }
public MyClass(Foo foo) : this(foo, new Bar()) { }
public MyClass() : this(new Foo()) { }
}
```
Note, that I intentionally did *not* call into the broadest constructor in each of the rest, but instead cascaded so as to inherit behavior in case the sense of defaults changed for each.
As to member initialization at declaration, if the member is not constructed using one of the arguments to a constructor, I prefer to initialize at declaration. | Best practice for initializing member variables? | [
"",
"c#",
""
] |
When I try:
```
LinkedList<String> stringList = new LinkedList<String>();
```
I get the following compilation error:
```
type LinkedList does not take parameters
```
What am I missing? Can't you do this? | Check to make sure you don't have a compiled class named `LinkedList` in the same directory. (Especially since "linked list" is a common term, and it is something that people often try to implement as beginners.) This is important if you import your classes using something like `import java.util.*;`, because the `*` imports on-demand, so if there is a class with the same name in the package already, then that class is used and the `java.util.LinkedList` is not imported. | Are you possibly compiling against a JDK 1.4 or earlier? Or do you have your language setting in your build or IDE set to pre-5.0 (so no generics support)?
By the way, the best way to do that is
```
List<String> stringList = new LinkedList<String>();
```
Use the interface rather than the implementation wherever possible.
That being said, assuming you're compiling against a JDK 5.0+, have your language settings set to Java 5+ and that is a java.util.LinkedList then your code is perfectly valid. | What's wrong with: LinkedList<String> stringList = new LinkedList<String>(); | [
"",
"java",
""
] |
I recently read that the differences between
```
char
unsigned char
```
and
```
signed char
```
is platform specific.
I can't quite get my head round this? does it mean the the bit sequence can vary from one platform to the next ie platform1 the sign is the first bit, platform2 the sign could be at the end? how would you code against this?
Basically my question comes from seeing this line:
```
typedef unsigned char byte;
```
I dont understand the relevance of the signage? | Let's assume that your platform has eight-bit bytes, and suppose we have the bit pattern `10101010`. To a `signed char`, that value is −86. For `unsigned char`, though, that same bit pattern represents 170. We haven't moved any bits around; it's the same bits, interpreted two different ways.
Now for `char`. The standard doesn't say which of those two interpretations should be correct. A `char` holding the bit pattern `10101010` could be *either* −86 *or* 170. It's going to be one of those two values, but you have to know the compiler and the platform before you can predict which it will be. Some compilers offer a command-line switch to control which one it will be. Some compilers have different defaults depending on what OS they're running on, so they can match the OS convention.
In most code, it really shouldn't matter. They are treated as three distinct types, for the purposes of overloading. Pointers to one of those types aren't compatible with pointers to another type. Try calling `strlen` with a `signed char*` or an `unsigned char*`; it won't work.
Use `signed char` when you want a one-byte signed numeric type, and use `unsigned char` when you want a one-byte unsigned numeric type. Use plain old `char` when you want to hold characters. That's what the programmer was thinking when writing the typedef you're asking about. The name "byte" doesn't have the connotation of holding character data, whereas the name "unsigned char" has the word "char" in its name, and that causes some people to think it's a good type for holding characters, or that it's a good idea to compare it with variables of type `char`.
Since you're unlikely to do general arithmetic on characters, it won't matter whether `char` is signed or unsigned on any of the platforms and compilers you use. | You misunderstood something. signed char is always signed. unsigned char is always unsigned. But whether plain char is signed or unsigned is implementation specific - that means it depends on your compiler. This makes difference from int types, which all are signed (int is the same as signed int, short is the same as signed short). More interesting thing is that char, signed char and unsigned char are treated as three distinct types in terms of function overloading. It means that you can have in the same compilation unit three function overloads:
```
void overload(char);
void overload(signed char);
void overload(unsigned char);
```
For int types is contrary, you can't have
```
void overload(int);
void overload(signed int);
```
because int and signed int is the same. | Can someone explain how the signedness of char is platform specific? | [
"",
"c++",
"signedness",
""
] |
I'm wondering what event/events is/are being used in counting the vowels while your typing the sentence in the textbox.
I'm not quite sure if it's something to do with "`KeyPress`" or "`KeyUp`".
I would appreciate your help.
=====
This is now where I'm stucked:
```
private void btnCount_Click(object sender, EventArgs e)
{
string yourSentence;
yourSentence = textBox1.Text.ToLower().Trim();
char ch1 = 'a';
char ch2 = 'e';
char ch3 = 'i';
char ch4 = 'o';
char ch5 = 'u';
int counta = 0;
int counte = 0;
int counti = 0;
int counto = 0;
int countu = 0;
int j = counta + counte + counti + counto + countu;
foreach (char v in yourSentence)
{
if (v == ch1) { counta++; j++; }
else if (v == ch2) { counte++; j++; }
else if (v == ch3) { counti++; j++; }
else if (v == ch4) { counto++; j++; }
else if (v == ch5) { countu++; j++; }
}
listBox1.Items.Add("There are " + counta.ToString().Trim() + " a's in the sentence");
listBox1.Items.Add("There are " + counte.ToString().Trim() + " e's in the sentence");
listBox1.Items.Add("There are " + counti.ToString().Trim() + " i's in the sentence");
listBox1.Items.Add("There are " + counto.ToString().Trim() + " o's in the sentence");
listBox1.Items.Add("There are " + countu.ToString().Trim() + " u's in the sentence");
listBox1.Items.Add("All in all there are " + j.ToString().Trim() + " vowels in the sentence");
private void textBox1_KeyDown(object sender, EventArgs e)
{
string yourSentence;
yourSentence = textBox1.Text.ToLower().Trim();
//I think I have to add the codings here. But what will happened to the
//btnCount_Click?
}
``` | Well there is a [TextChanged](http://msdn.microsoft.com/fr-fr/library/system.windows.controls.textbox.textchanged%28VS.95%29.aspx) event in the TextBox that triggers whenever a character is typed or deleted. This could be used to count vowels in real-time.
**Edit:**
I combined your code from textBox1\_keyDown and btnCount\_Click and put it in the TextChanged event, and it worked almost perfectly. I only had to add one line:
```
listBox1.Items.Clear();
```
...just before items are added to the listbox. This way, the listbox is emptied before adding the counts.
This is the result:
```
private void textBox1_TextChanged(object sender, EventArgs e)
{
string yourSentence;
yourSentence = textBox1.Text.ToLower().Trim();
char ch1 = 'a';
char ch2 = 'e';
char ch3 = 'i';
char ch4 = 'o';
char ch5 = 'u';
int counta = 0;
int counte = 0;
int counti = 0;
int counto = 0;
int countu = 0;
int j = counta + counte + counti + counto + countu;
foreach (char v in yourSentence)
{
if (v == ch1) { counta++; j++; }
else if (v == ch2) { counte++; j++; }
else if (v == ch3) { counti++; j++; }
else if (v == ch4) { counto++; j++; }
else if (v == ch5) { countu++; j++; }
}
listBox1.Items.Clear();
listBox1.Items.Add("There are " + counta.ToString().Trim() + " a's in the sentence");
listBox1.Items.Add("There are " + counte.ToString().Trim() + " e's in the sentence");
listBox1.Items.Add("There are " + counti.ToString().Trim() + " i's in the sentence");
listBox1.Items.Add("There are " + counto.ToString().Trim() + " o's in the sentence");
listBox1.Items.Add("There are " + countu.ToString().Trim() + " u's in the sentence");
listBox1.Items.Add("All in all there are " + j.ToString().Trim() + " vowels in the sentence");
}
```
I don't need any other code to make this work. | I built a search box that acts something like an AJAX text box - it does the search basd on what has been typed "so far" in the text box. There's no need to type in the text and then click an associated button. It searches as you type. I don't know if there's a name for this UI pattern, there oughta be.
The dynamic search is hooked to the TextChanged event. But the key was, I didn't it want to search while the text was being actively changed, as the user was typing. I wanted to search when the changes were complete, when the typing stopped.
This may be interesting for you too.
The hueristic I used: if 600ms elapses after the last textchange event, then typing has stopped, and *that's* when the search should run. But how do you get code to run 600ms AFTER a TextChange event. It's not possible to [Thread.Sleep](http://msdn.microsoft.com/en-us/library/d00bd51t.aspx) within the event handler. This just causes UI delay.
The solution I came up with was this: use [Threadpool.QueueUserWorkItem](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx) in the TextChange event to queue up a worker method, called *MaybeDoSearch*. In that worker, do a [Thread.Sleep](http://msdn.microsoft.com/en-us/library/d00bd51t.aspx) for the delay interval (600ms). When the Sleep completes, check the elapsed time since the prior TextChanged event. If that time exceeds 600 ms, then actually do the Search.
It looks like this
```
System.DateTime _lastChangeInSearchText;
private const int DELAY_IN_MILLISECONDS = 600;
private void tbSearch_TextChanged(object sender, EventArgs e)
{
_lastChangeInSearchText = System.DateTime.Now;
string textToFind = tbSearch.Text;
if ((textToFind != null) && (textToFind != ""))
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(MaybeDoSearch), textToFind);
else
{
// clear the ListView that contains the search results
this.ListView2.Items.Clear();
}
}
private void MaybeDoSearch(object o)
{
System.Threading.Thread.Sleep(DELAY_IN_MILLISECONDS);
System.DateTime now = System.DateTime.Now;
var _delta = now - _lastChangeInSearchText;
if (_delta >= new System.TimeSpan(0,0,0,0,DELAY_IN_MILLISECONDS))
{
// actually do the search
ShowSearchResults();
}
}
```
Mine is a WinForms app. Because the MaybeDoSearch() runs on a worker thread, not the UI thread, then in the ShowSearchResults(), UI update must be protected with [InvokeRequired](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx).
> During normal typing, a person will type 2 or 3 characters in 600ms. The result is there are 2 or 3 work items queued and running (mostly Sleeping), on separate threadpool threads, at any given moment while typing is actively occurring.
Someone suggested earlier that you will have to re-scan all of the text for vowels with every change. It's redundant work at runtime, which for efficiency purposes you'd normally want to avoid. But the code is so much simpler that way. I had the same issue, and decided to not try to figure out just *how* the text changed with the current TextChange event. It changed, so the code does a full new search. The search completes quicker than the delay interval (600ms). In your case, counting vowels, it will be even faster. | Events in counting vowels | [
"",
"c#",
"counter",
""
] |
I have the following admin setup so that I can add/edit a user and their profile at the same time.
```
class ProfileInline(admin.StackedInline):
"""
Allows profile to be added when creating user
"""
model = Profile
class UserProfileAdmin(admin.ModelAdmin):
"""
Options for the admin interface
"""
inlines = [ProfileInline]
list_display = ['edit_obj', 'name', 'username', 'email', 'is_active',
'last_login', 'delete_obj']
list_display_links = ['username']
list_filter = ['is_active']
fieldsets = (
(None, {
'fields': ('first_name', 'last_name', 'email', 'username',
'is_active', 'is_superuser')}),
)
ordering = ['last_name', 'first_name']
search_fields = ['first_name', 'last_name']
admin.site.register(User, UserProfileAdmin)
```
The problem is I need two of the fields in the Profile inline form to be required when adding the user. The inline form doesn't validate unless input is entered. Is there anyway to make the inline required, so that it can't be left blank? | I took Carl's advice and made a much better implementation then the hack-ish one I mentioned in my comment to his answer. Here is my solution:
From my forms.py:
```
from django.forms.models import BaseInlineFormSet
class RequiredInlineFormSet(BaseInlineFormSet):
"""
Generates an inline formset that is required
"""
def _construct_form(self, i, **kwargs):
"""
Override the method to change the form attribute empty_permitted
"""
form = super(RequiredInlineFormSet, self)._construct_form(i, **kwargs)
form.empty_permitted = False
return form
```
And the admin.py
```
class ProfileInline(admin.StackedInline):
"""
Allows profile to be added when creating user
"""
model = Profile
extra = 1
max_num = 1
formset = RequiredInlineFormSet
class UserProfileAdmin(admin.ModelAdmin):
"""
Options for the admin interface
"""
inlines = [ProfileInline]
list_display = ['edit_obj', 'name', 'username', 'email', 'is_active',
'last_login', 'delete_obj']
list_display_links = ['username']
list_filter = ['is_active']
fieldsets = (
(None, {
'fields': ('first_name', 'last_name', 'email', 'username',
'is_active', 'is_superuser')}),
(('Groups'), {'fields': ('groups', )}),
)
ordering = ['last_name', 'first_name']
search_fields = ['first_name', 'last_name']
admin.site.register(User, UserProfileAdmin)
```
This does exactly what I want, it makes the Profile inline formset validate. So since there are required fields in the profile form it will validate and fail if the required information isn't entered on the inline form. | Now with Django 1.7 you can use parameter `min_num`. You do not need class `RequiredInlineFormSet` anymore.
See <https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.min_num>
```
class ProfileInline(admin.StackedInline):
"""
Allows profile to be added when creating user
"""
model = Profile
extra = 1
max_num = 1
min_num = 1 # new in Django 1.7
class UserProfileAdmin(admin.ModelAdmin):
"""
Options for the admin interface
"""
inlines = [ProfileInline]
...
admin.site.register(User, UserProfileAdmin)
``` | How do I require an inline in the Django Admin? | [
"",
"python",
"python-3.x",
"django",
"django-admin",
"inline",
""
] |
Why is the '/g' required when using string replace in JavaScript?
e.g. `var myString = myString.replace(/%0D%0A/g,"<br />");` | It isn't required, but by default `string.replace` in JavaScript will only replace the first matching value it finds. Adding the `/g` will mean that all of the matching values are replaced. | The "**g**" that you are talking about at the end of your regular expression is called a "modifier".
The "**g**" represents the "**global modifier**". This means that your replace will replace all copies of the matched string with the replacement string you provide.
A list of useful modifiers:
1. **g** - Global replace. Replace all instances of the matched string in the provided text.
2. **i** - Case insensitive replace. Replace all instances of the matched string, ignoring differences in case.
3. **m** - Multi-line replace. The regular expression should be tested for matches over multiple lines.
You can combine modifiers, such as g and i together, to get a global case insensitive search.
Examples:
```
//Replace the first lowercase t we find with X
'This is sparta!'.replace(/t/,'X');
//result: 'This is sparXa!'
//Replace the first letter t (upper or lower) with X
'This is sparta!'.replace(/t/i, 'X');
//result: 'Xhis is sparta!'
//Replace all the Ts in the text (upper or lower) with X
'This is sparta!'.replace(/t/gi, 'X' );
//result: 'Xhis is sparXa!'
```
For more information see the [JavaScript RegExp Object Reference](http://www.w3schools.com/jsref/jsref_obj_regexp.asp "W3C JavaScript RegExp Object Reference") at the w3schools. | Why do i need to add /g when using string replace in Javascript? | [
"",
"javascript",
""
] |
HashMapList keeps its elements inside a HashMap) and when I call add method this error message will be shown in the concole "Exception in thread "main" java.lang.NullPointerException
```
public class HashMapList<K, V extends Product> extends AbstractList<Product> {
public V element;
public int index;
Map<Integer, V> map;
public HashMapList() {
super();
new HashMap<Integer, V>();
}
// Override
public void add(int index, V element) {
map.put(new Integer(index), element);
}
}
```
**thanks,I have solved the first problem** but when I call add method like==>
```
HashMapList<Integer, Book> list = new HashMapList<Integer, Book>();
list.add(0, new Book("physics"));
```
and Book class is==>
```
public class Book extends Product {
public String name = null;
public Book(String name) {
super(name);
}
}
```
and Product class is==>
```
public class Product implements Comparable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name = null;
public Product(String name) {
if (name == null)
throw new NullPointerException();
this.name = name;
}
public String getName() {
return name;
}
// Override
public int compareTo(Object o) {
Product product = (Product) o;
int compare = getName().compareTo(product.name);
return compare;
}
}
```
And when I want to print this list basically with System.out.println(list);
this sentence will be shown in the concole:**[org.bihe.com1112.Book@1fb8ee3, org.bihe.com1112.Book@61de33, org.bihe.com1112.Book@14318bb]** | For your second question, you should really start another thread. It is correctly printing the string representation of your object. Your `Book` class does not provide a custom overridden `toString()` method. So it uses the one inherited from `Object`, which just returns a string made of the full name of the class and the `hashCode` of the object, which is what you are seeing. You should override the `toString()` method if you want to see something different. | You are not assigning anything to map
```
public HashMapList() {
super();
map = new HashMap<Integer, V>();
}
```
whenever you get a null pointer exception look for where you assign a value to the variable to you are using. Here look for anywhere in your code where you say "map = ...". | "Exception in thread "main" java.lang.NullPointerException when adding to a HashMapList | [
"",
"java",
"collections",
""
] |
I've read that (all things equal) PHP is typically faster than MySQL at arithmetic and string manipulation operations. This being the case, where does one draw the line between what one asks the database to do versus what is done by the web server(s)? We use stored procedures exclusively as our data-access layer. My unwritten rule has always been to leave output formatting (including string manipulation and arithmetic) to the web server. So our queries return:
* unformatted dates
* null values
* no calculated values (i.e. return values for columns "foo" and "bar" and let the web server calculate foo\*bar if it needs to display value foobar)
* no substring-reduced fields (except when shortened field is so significantly shorter that we want to do it at database level to reduce result set size)
* two separate columns to let front-end case the output as required
What I'm interested in is feedback about whether this is generally an appropriate approach or whether others know of compelling performance/maintainability considerations that justify pushing these activities to the database.
Note: I'm intentionally tagging this question to be dbms-agnostic, as I believe this is an architectural consideration that comes into play regardless of one's specific dbms. | I would draw the line on how certain layers could rotate out in place for other implementations. It's very likely that you will never use a different RDBMS or have a mobile version of your site, but you never know.
The more orthogonal a data point is, the closer it should be to being released from the database in that form. If on every theoretical version of your site your values A and B are rendered A \* B, that should be returned by your database as A \* B and never calculated client side.
Let's say you have something that's format heavy like a date. Sometimes you have short dates, long dates, English dates... One pure form should be returned from the database and then that should be formatted in PHP.
So the orthogonality point works in reverse as well. The more dynamic a data point is in its representation/display, the more it should be handled client side. If a string A is always taken as a substring of the first six characters, then have that be returned from the database as pre-substring'ed. If the length of the substring depends on some factor, like six for mobile and ten for your web app, then return the larger string from the database and format it at run time using PHP. | Usually, data formatting is better done on client side, especially culture-specific formatting.
Dynamic pivoting (i. e. variable columns) is also an example of what is better done on client side
When it comes to string manipulation and dynamic arrays, `PHP` is far more powerful than any `RDBMS` I'm aware of.
However, data formatting can use additional data which is also kept in the database. Like, the coloring info for each row can be stored in additional table.
You should then correspond the color to each row on database side, but wrap it into the tags on `PHP` side.
The rule of thumb is: retrieve everything you need for formatting in as few database round-trips as possible, then do the formatting itself on the client side. | Database vs. Front-End for Output Formatting | [
"",
"sql",
"mysql",
"sql-server",
"database",
"oracle",
""
] |
When should I be using stored procedures instead of just writing the logic directly in my application? I'd like to reap the benefits of stored procedures, but I'd also like to not have my application logic spread out over the database and the application.
Are there any rules of thumb that you can think of in reference to this? | Wow... I'm going to swim directly against the current here and say, "almost always". There are a laundry list of reasons - some/many of which I'm sure others would argue. But I've developed apps both with and without the use of stored procs as a data access layer, and it has been my experience that well written stored procedures make it so much easier to write your application. Then there's the well-documented performance and security benefits. | This depends entirely on your environment. The answer to the question really isn't a coding problem, or even an analysis issue, but a business decision.
If your database supports just one application, and is reasonably tightly integrated with it, then it's better, for reasons of flexibility, to place your logic inside your application program. Under these circumstances handling the database simply as a plain data repository using common functionality looses you little and gains flexibility - with vendors, implementation, deployment and much else - and many of the purist arguments that the 'databases are for data' crowd make are demonstratively true.
On the other hand if your are handling a corporate database, which can generally be identified by having multiple access paths into it, then it is highly advisable to screw down the security as far as you can. At the very least all appropriate constraints should enabled, and if possible access to the data should be through views and procedures only. Whining programmers should be ignored in these cases as...
1. With a corporate database the asset is valuable and invalid data or actions can have business-threatening consequences. Your primary concern is safeguarding the business, not how convenient access is for your coders.
2. Such databases are by definition accessed by more than one application. You need to use the abstraction that stored procedures offer so the database can be changed when application A is upgraded and you don't have the resource to upgrade application B.
3. Similarly the encapsulation of business logic in SPs rather than in application code allows changes to such logic to be implemented across the business more easily and reliably than if such logic is embedded in application code. For example if a tax calculation changes it's less work, and more robust, if the calculation has to be changed in one SP than multiple applications. The rule of thumb here is that the business rule should be implemented at the closest point to the data where it is unique - so if you have a specialist application then the logic for that app can be implemented in that app, but logic more widely applicable to the business should be implemented in SPs.
Coders who dive into religious wars over the use or not of SPs generally have worked in only one environment or the other so they extrapolate their limited experience into a cast-iron position - which indeed will be perfectly defensible and correct in the context from which they come but misses the big picture. As always, you should make you decision on the needs of the business/customers/users and not on the which type of coding methodology you prefer. | When should I use stored procedures? | [
"",
"sql",
"database",
"stored-procedures",
""
] |
It's always a big problem for web designers to make their page look good in all the commonly used browsers. What are the best ways to deal with this fact? | For CSS:
1. Use a reset (like [Meyer](http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/) or [YUI](http://developer.yahoo.com/yui/reset/)) to "level the playing field" before your style is applied
2. Style for the weirdest browser that you have to support (like IE6), make it look right, then change what you need to for more modern browsers. Trust me, this is much easier than doing it the other way around!
For Javascript, I'd use a framework like [jQuery](http://jquery.com) or [YUI](http://developer.yahoo.com/yui/) since they go a long way in abstracting away most of the browser-specific quirks you're likely to encounter.
Good luck! | Use well supported libraries - don't try and start from scratch. For example, JQuery handles a lot of browser issues for you. | What are the best practices for making the CSS and JS of a web page cross-browser compatible? | [
"",
"javascript",
"html",
"css",
""
] |
When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the `-Wall -Wextra` options) I suddenly got a bunch of errors of the form `warning: type qualifiers ignored on function return type`.
Consider `temp.cpp`:
```
class Something
{
public:
const int getConstThing() const {
return _cMyInt;
}
const int getNonconstThing() const {
return _myInt;
}
const int& getConstReference() const {
return _myInt;
}
int& getNonconstReference() {
return _myInt;
}
void setInt(const int newValue) {
_myInt = newValue;
}
Something() : _cMyInt( 3 ) {
_myInt = 2;
}
private:
const int _cMyInt;
int _myInt;
};
```
Running `g++ temp.cpp -Wextra -c -o blah.o`:
```
temp.cpp:4: warning: type qualifiers ignored on function return type
temp.cpp:7: warning: type qualifiers ignored on function return type
```
Can someone tell me what I am doing wrong that violates the C++ standard? I suppose that when returning by value, the leading `const` is superfluous, but I'm having trouble understanding why it's necessary to generate a warning with it. Are there other places where I should leave off the const? | It doesn't violate the standard. That's why they're *warnings* and not *errors*.
And indeed you're right — the leading `const` is superfluous. The compiler warns you because you've added code that in other circumstances might mean something, but in this circumstance means nothing, and it wants to make sure you won't be disappointed later when your return values turn out to be modifiable after all. | I encountered this warning when compiling some code that uses Boost.ProgramOptions. I use `-Werror` so the warning was killing my build, but because the source of the warning was in the depths of Boost I couldn't get rid of it by modifying my code.
After much digging I found the compiler option that disables the warning:
```
-Wno-ignored-qualifiers
```
Hope this helps. | Pedantic gcc warning: type qualifiers on function return type | [
"",
"c++",
"constants",
"gcc-warning",
""
] |
I'm looking for the implementation of MemoryStream which does not allocate memory as one big block, but rather a collection of chunks. I want to store a few GB of data in memory (64 bit) and avoid limitation of memory fragmentation. | You need to first determine if virtual address fragmentation is the problem.
If you are on a 64 bit machine (which you seem to indicate you are) I seriously doubt it is. Each 64 bit process has almost the the entire 64 bit virtual memory space available and your only worry is virtual address space fragmentation not physical memory fragmentation (which is what the operating system must worry about). The OS memory manager already pages memory under the covers. For the forseeable future you will not run out of virtual address space before you run out of physical memory. This is unlikely change before we both retire.
If you are have a 32 bit address space, then allocating contiguous large blocks of memory in the GB ramge you will encounter a fragmentation problem quite quickly. There is no stock chunk allocating memory stream in the CLR. There is one in the under the covers in ASP.NET (for other reasons) but it is not accessable. If you must travel this path you are probably better off writing one youself anyway because the usage pattern of your application is unlikely to be similar to many others and trying to fit your data into a 32bit address space will likely be your perf bottleneck.
I highly recommend requiring a 64 bit process if you are manipulating GBs of data. It will do a much better job than hand-rolled solutions to 32 bit address space fragmentation regardless of how cleaver you are. | Something like this:
```
class ChunkedMemoryStream : Stream
{
private readonly List<byte[]> _chunks = new List<byte[]>();
private int _positionChunk;
private int _positionOffset;
private long _position;
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush() { }
public override long Length
{
get { return _chunks.Sum(c => c.Length); }
}
public override long Position
{
get
{
return _position;
}
set
{
_position = value;
_positionChunk = 0;
while (_positionOffset != 0)
{
if (_positionChunk >= _chunks.Count)
throw new OverflowException();
if (_positionOffset < _chunks[_positionChunk].Length)
return;
_positionOffset -= _chunks[_positionChunk].Length;
_positionChunk++;
}
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int result = 0;
while ((count != 0) && (_positionChunk != _chunks.Count))
{
int fromChunk = Math.Min(count, _chunks[_positionChunk].Length - _positionOffset);
if (fromChunk != 0)
{
Array.Copy(_chunks[_positionChunk], _positionOffset, buffer, offset, fromChunk);
offset += fromChunk;
count -= fromChunk;
result += fromChunk;
_position += fromChunk;
}
_positionOffset = 0;
_positionChunk++;
}
return result;
}
public override long Seek(long offset, SeekOrigin origin)
{
long newPos = 0;
switch (origin)
{
case SeekOrigin.Begin:
newPos = offset;
break;
case SeekOrigin.Current:
newPos = Position + offset;
break;
case SeekOrigin.End:
newPos = Length - offset;
break;
}
Position = Math.Max(0, Math.Min(newPos, Length));
return newPos;
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
while ((count != 0) && (_positionChunk != _chunks.Count))
{
int toChunk = Math.Min(count, _chunks[_positionChunk].Length - _positionOffset);
if (toChunk != 0)
{
Array.Copy(buffer, offset, _chunks[_positionChunk], _positionOffset, toChunk);
offset += toChunk;
count -= toChunk;
_position += toChunk;
}
_positionOffset = 0;
_positionChunk++;
}
if (count != 0)
{
byte[] chunk = new byte[count];
Array.Copy(buffer, offset, chunk, 0, count);
_chunks.Add(chunk);
_positionChunk = _chunks.Count;
_position += count;
}
}
}
class Program
{
static void Main(string[] args)
{
ChunkedMemoryStream cms = new ChunkedMemoryStream();
Debug.Assert(cms.Length == 0);
Debug.Assert(cms.Position == 0);
cms.Position = 0;
byte[] helloworld = Encoding.UTF8.GetBytes("hello world");
cms.Write(helloworld, 0, 3);
cms.Write(helloworld, 3, 3);
cms.Write(helloworld, 6, 5);
Debug.Assert(cms.Length == 11);
Debug.Assert(cms.Position == 11);
cms.Position = 0;
byte[] b = new byte[20];
cms.Read(b, 3, (int)cms.Length);
Debug.Assert(b.Skip(3).Take(11).SequenceEqual(helloworld));
cms.Position = 0;
cms.Write(Encoding.UTF8.GetBytes("seeya"), 0, 5);
Debug.Assert(cms.Length == 11);
Debug.Assert(cms.Position == 5);
cms.Position = 0;
cms.Read(b, 0, (byte) cms.Length);
Debug.Assert(b.Take(11).SequenceEqual(Encoding.UTF8.GetBytes("seeya world")));
Debug.Assert(cms.Length == 11);
Debug.Assert(cms.Position == 11);
cms.Write(Encoding.UTF8.GetBytes(" again"), 0, 6);
Debug.Assert(cms.Length == 17);
Debug.Assert(cms.Position == 17);
cms.Position = 0;
cms.Read(b, 0, (byte)cms.Length);
Debug.Assert(b.Take(17).SequenceEqual(Encoding.UTF8.GetBytes("seeya world again")));
}
}
``` | "Chunked" MemoryStream | [
"",
"c#",
".net",
""
] |
I've had a hard time figuring out how I can write a **struct** in C# that has constraints on its fields' values. For example, **System.DateTime**
```
DateTime d = new DateTime();
```
puts the value **01/01/0001 12:00:00 AM** in **d**. But I can't write an explicit parameterless constructor, as **struct**s are not allowed to have an explicit parameterless constructor. So, how can I create a **struct** that will be default constructed within the constraints I want?
The only thing I could think of was to design properties such that they return values within the constraints I want. For example, if I store an **int** that I want to be greater than 0 I just add one to the return value and disallow setting to less than 1. Is this the sensible route to take? | See the answer to [this](https://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net) question for additional info. Basically, without parameters, value type fields are always initialized to default values as a performance optimization, since value types are often used in bigger numbers in arrays etc.
You should consider creating a class if you want *true* constraints, but "smart properties" may be the way to go if performance is in question when using your class. As for the DateTime type, yes, it does "smart" properties, storing the date as a number which is converted to specific format upon request (access via properties). The **01/01/0001 12:00:00 AM** is actually the representation of the default internal 0, by design. | I think you`d better suggest using a class in that situation. Put this struct into it, and in parameterless constructor you can explicitly set value you want your struct to contain. | Structs With Constraints | [
"",
"c#",
"constructor",
"struct",
""
] |
I am creating a Distinct extension method where I can pass in the criteria like the following.
```
persons.Distinct(p => p.Name);
```
I got the code from the web but I am having a hard time understanding the purpose of `Func<T, TResult>`. Also, when I say `p => p.Name` am I sending the `String` `Name` or am I sending the complete `Person` object? Here is the new Distinct method:
```
public static class ExtensionMethods
{
public static IEnumerable<T> Distinct<T>(
this IEnumerable<T> list, Func<T,object> checker)
{
return list.Distinct(new GenericComparer<T>(checker));
}
}
public class GenericComparer<T> : IEqualityComparer<T>
{
private Func<T, object> _checker;
public GenericComparer(Func<T,object> checker)
{
_checker = checker;
}
public bool Equals(T x, T y)
{
return _checker(x).Equals(_checker(y));
}
public int GetHashCode(T obj)
{
return _checker(obj).GetHashCode();
}
}
```
And here is the usage:
```
static void Main(string[] args)
{
var persons = new List<Person>()
{
new Person() { Id = 1, Name = "Mary"},
new Person() {Id = 2, Name="John"},
new Person() { Id = 3, Name = "Mary"}
};
var uniquePersons = persons.Distinct(p => p.Name);
foreach(var person in uniquePersons)
{
Console.WriteLine(person.Name);
}
}
``` | When you do this:
```
persons.Distinct(p => p.Name);
```
You're basically creating a function on the fly ([using lambda expressions](http://msdn.microsoft.com/en-us/library/bb397687.aspx)), that looks like this:
```
string theFunction(Person p)
{
return p.Name;
}
```
This is a function that fits the signature of a `Func<Person,String>` delegate. The Distinct method can take a delegate (basically a function pointer) which it uses to determine whether or not an element is distinct - in your case, only unique strings (returned by the function above) will be considered "distinct" elements. This delegate is run on each element of your "persons" enumerable, and the results of those functions are used. It then creates a sequence (`IEnumerable<Person>`) from those elements. | ```
Func<T, TResult>
```
defines a function that accepts one parameter (of type T) and returns an object (of type TResult).
In your case, if you want a function that takes a Person object and returns a string...you'd want
```
Func<Person, string>
```
which is the equivalent of:
```
string Function(Person p)
{
return p.Name;
}
``` | How does Func<T,TResult> Work? | [
"",
"c#",
"lambda",
""
] |
I am building a service using WCF and I need to send over images. I looked around on how this is done and found that Base64 encoding is often used to send binary data as text. Is this a good practice to send over images (~500 kb)? | That's a really big message, but yes, if you must send them, base 64 is the way to go. If you only have .net clients then you could look at binary message encoding to shrink the size down | Base64 is safely encodes binary data, it will be fine. Just keep in mind it makes the transfer size about 30% larger. | Base64 encoding for images | [
"",
"c#",
".net",
"wcf",
"base64",
""
] |
I know I can use different frameworks like prototype or jQuery to attach a function to the `window.onload`, but's not what I'm looking for.
I need something like `.readyState` so that I can do something like this:
```
if(document.isReady){
var id = document.getElem ...
}
```
is there any other way than using what the frameworks do? | i've updated the code of [DOMAssistant library](http://code.google.com/p/domassistant/source/browse/trunk/modules/DOMAssistantLoad.js) it works fine with me
```
var domReady = (function (){
var arrDomReadyCallBacks = [] ;
function excuteDomReadyCallBacks(){
for (var i=0; i < arrDomReadyCallBacks.length; i++) {
arrDomReadyCallBacks[i]();
}
arrDomReadyCallBacks = [] ;
}
return function (callback){
arrDomReadyCallBacks.push(callback);
/* Mozilla, Chrome, Opera */
if (document.addEventListener ) {
document.addEventListener('DOMContentLoaded', excuteDomReadyCallBacks, false);
}
/* Safari, iCab, Konqueror */
if (/KHTML|WebKit|iCab/i.test(navigator.userAgent)) {
browserTypeSet = true ;
var DOMLoadTimer = setInterval(function () {
if (/loaded|complete/i.test(document.readyState)) {
//callback();
excuteDomReadyCallBacks();
clearInterval(DOMLoadTimer);
}
}, 10);
}
/* Other web browsers */
window.onload = excuteDomReadyCallBacks;
}
})()
``` | **Edit:** As the year 2018 comes upon us, I think it's safe to listen for the [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event.
```
function fireOnReady() { /* ... */ }
if (document.readyState === 'complete') {
fireOnReady();
} else {
document.addEventListener("DOMContentLoaded", fireOnReady);
}
```
> Please note, the event will only fire **once** when your page loads! If you have to support really old browsers, then check out the super lightweight script I put together below.
---
---
**For historical reference only:**
---
---
jQuery has an undocumented property called isReady which is used internally to determine whether the DOM ready event has fired:
```
if($.isReady) {
// DOM is ready
} else {
// DOM is not yet ready
}
```
I started at 1.5.2 went back as far as 1.3.2 and the property is there. While undocumented, I would say that you can rely on this property in future versions of jQuery.
**Edit:** And a year later - v1.7.2, they still use `$.isReady` - still undocumented, so please use at your own risk. Be careful when upgrading.
**Edit:** v1.9, they still use `$.isReady` - still undocumented
**Edit:** v2.0, with all of it's "major" changes, still uses `$.isReady` - still undocumented
**Edit:** v3.x still uses `$.isReady` - still undocumented
**Edit:** As several people have pointed out, the above does not really answer the question. So I have just created a [mini DOM ready snippet](https://github.com/DesignByOnyx/mini-domready) which was inspired by Dustin Diaz's [even smaller DOM ready snippet](http://www.dustindiaz.com/smallest-domready-ever). Dustin created a neat way to check the document readyState with something similar to this:
```
if( !/in/.test(document.readyState) ) {
// document is ready
} else {
// document is NOT ready
}
```
The reason this works is because the browser has 3 loading states: "loading", "interactive", and "complete" *(older WebKit also used "loaded", but you don't have to worry about that any more)*. You will notice that both "loading" and "interactive" contain the text "in"... so if the string "in" is found inside of `document.readyState`, then we know we are not ready yet. | Javascript domready? | [
"",
"javascript",
"dom-events",
""
] |
I`m writing binary search tree template for two reasons - learning C++ and learning most common algorithms and data structures.
So, here is the question - as long as I want to implement iterators, it seems to me that there is no strict definition for where tree ends. What are your suggestions? How do I do this? | For trees, there are standards for traversing the tree, i.e. enumerating the nodes: Preorder traversal, inorder traversal, and postorder traversal. Rather than describe all these here, I'll redirect you to [<http://en.wikipedia.org/wiki/Tree_traversal>](http://en.wikipedia.org/wiki/Tree_traversal). The concepts are mostly applied to binary trees, but you can extend the idea to arbitrary trees by adding more cases: Effectively, handle a node then recurse, recurse then handle a node, handle all children then recurse into each...etc. There's no canonical categorization of this approach that I'm aware of. | You have to keep something clear when writing an iterator - an iterator for a data structure provides access to a collection as a linear sequence of items. Certain collections, like arrays, lists, and queues, are naturally compatible with being treated as a linear sequence. Other types of collections - trees, dictionaries, graphs - do not necessarily have a simple interpretation as a linear list. In fact, multiple interpretations are generally valid.
What you really to do when writing an iterator for a collection like a tree is address the following concerns:
1. Where does iteration of the collection begin (root? leaves?)
2. How does iteration progress to the next element (infix? postfix? suffix? breadth?)
3. When does iteration terminate (leaves? root? final node?)
Whatever you choose, you should be very clear in how you name (and document) your iterator to make it obvious how it will visit and emit nodes.
You may need to write multiple iterators for the different kinds of traverals you intend to support. There are some good articles here that dicuss [tree traversal models](http://www.google.com/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FTree_traversal&ei=nMJxSs6CMJKcMaOsubEM&usg=AFQjCNFYiakxxRqG2mq_MLT6vE2oDwyq3g&sig2=9zSF_sM3PpRcMt5IY5mbdQ). | Does it make sense to implement iterators for containers which has no obvious end - e.g. trees? | [
"",
"c++",
"data-structures",
"iterator",
"binary-tree",
""
] |
I have a piece of code that presents an interesting question (in my opinion).
```
/*power.c raises numbers to integer powers*/
#include <stdio.h>
double power(double n, int p);
int main(void)
{
double x, xpow; /*x is the orginal number and xpow is the result*/
int exp;/*exp is the exponent that x is being raised to */
printf("Enter a number and the positive integer power to which\n the first number will be raised.\n enter q to quit\n");
while(scanf("%lf %d", &x, &exp) ==2)
{
xpow = power(x, exp);
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("enter the next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed your power trip -- bye!\n");
return 0;
}
double power(double n, int p)
{
double pow = 1;
int i;
for(i = 1; i <= p; i++)
{
pow *= n;
}
return pow;
}
```
If you'll notice the order of numbers to be entered is the floating point number and then the decimal number (base number and then the exponent). But when I enter the input with an integer base and floating point exponent it produces a strange result.
```
[mike@mike ~/code/powerCode]$ ./power
Enter a number and the positive integer power to which
the first number will be raised.
enter q to quit
1 2.3
1 to the power 2 is 1
enter the next pair of numbers or q to quit.
2 3.4
0.3 to the power 2 is 0.09
enter the next pair of numbers or q to quit.
```
It seems to push the second number of the floating point exponent back onto the next input. I was hoping some one could explain what was going on behind the scenes. I know that this is the work of scanf() not checking its array boundaries but if some one could give me some deeper understanding I'd really appreciate it.
Thanks Stack Overflow.
-M.I.
Edit.
Just wanted to thank everyone for their input. Any other answers are more then welcome.
Thanks again, S.O. | When reading the first "2.3" scanf read up to the "." realizes it is no longer a valid integer and stops. So ".3" is left in the buffer, then you type "2 3.4" so ".3\n2 3.4" is in the buffer. When scanf parses that it gets ".3" and "2" just like your example shows. | This is because when you're using scanf to read "2.3", the scan is stopping at, but not consuming the "." in ".3". Thus, when you make the next call to scanf, it starts by reading in ".3".
To elaborate, scanf calls are not restricted to one line of text. scanf() skips over whitespace, including tabs, spaces and newlines. | scanf() causing strange results | [
"",
"c++",
"c",
"scanf",
""
] |
I am trying to fetch the sum of several counts in one query:
```
SELECT(
SELECT COUNT( * )
FROM comments +
SELECT COUNT( * )
FROM tags +
SELECT COUNT( * )
FROM search
)
```
I am missing something here. I get syntax error. | ```
SELECT ( SELECT COUNT(*) FROM comments )
+ ( SELECT COUNT(*) FROM tags )
+ ( SELECT COUNT(*) FROM search )
``` | One more (not sure if supported with MySQL, though - works in SQL Server):
```
SELECT SUM(Counts) FROM
(SELECT COUNT(*) AS Counts FROM COMMENTS UNION ALL
SELECT COUNT(*) FROM Tags UNION ALL
SELECT COUNT(*) FROM Search) s
``` | Add results from several COUNT queries | [
"",
"sql",
"mysql",
""
] |
I'm using jQuery to create a "dialog" that should pop up on top of the page and in the center of the page (vertically and horizontally). How should I go about making it stay in the center of the page (even when the user resizes or scrolls?) | I would use
```
position: fixed;
top: 50%;
left: 50%;
margin-left: -(dialogwidth/2);
margin-top: -(dialogheight/2);
```
but with this solution and a browsers viewport-size of less than your dialog is, parts of the dialog will be unreachable on top and left sides because they are outside the viewport.
So you have to decide if it's suitable for your dialogs size.
(CSS doesn't know how to calculate, yet. So the little math over there has to be done by you, right now. Therefore your dialog has to be a fixed size which you have to know.)
Edit:
Oh yes, if you want to serve your dialog for the IE6 too, you should do something like this:
```
#dialog { position: absolute; }
#dialog[id] { position: fixed; }
```
Since IE6 is not capable of fixed positions and also not capable of attribute-selectors, the IE6 will be the only one who has the position set to absolute. (This will only affect with scrolling behaviour. absolute stays on its place in page and fixed stays on its place in the browser. The rest is similar.) | Check out [Infinity Web Design's](http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm) piece on this.
```
#mydiv {
background-color:#F3F3F3;
border:1px solid #CCCCCC;
height:18em;
left:50%;
margin-left:-15em;
margin-top:-9em;
position:absolute;
top:50%;
width:30em;
}
```
This is the CSS they use, and I've tested it out in multiple browsers.
You'll note that the left margin is negative half the width and the top margin is negative half the height. This takes care of the centering, more or less, with absolutely positioning it at 50% top and left. | How do I keep a div in the center of the page? | [
"",
"javascript",
"jquery",
""
] |
When declaring an associative array, how do you handle the indentation of the elements of the array? I've seen a number of different styles (PHP syntax, since that's what I've been in lately). This is a pretty picky and trivial thing, so move along if you're interested in more serious pursuits.
1) Indent elements one more level:
```
$array = array(
'Foo' => 'Bar',
'Baz' => 'Qux'
);
```
2) Indent elements two levels:
```
$array = array(
'Foo' => 'Bar',
'Baz' => 'Qux'
);
```
3) Indent elements beyond the array constructor, with closing brace aligned with the start of the constructor:
```
$array = array(
'Foo' => 'Bar',
'Baz' => 'Qux'
);
```
4) Indent elements beyond the array construct, with closing brace aligned with opening brace:
```
$array = array(
'Foo' => 'Bar',
'Baz' => 'Qux'
);
```
Personally, I like #3—the broad indentation makes it clear that we're at a break point in the code (constructing the array), and having the closing brace floating a bit to the left of all of the array's data makes it clear that this declaration is done. | Personally I always go:
```
$array = array(
'1' => '2',
3 => 4,
);
```
The indent is one tab level (typically 4 spaces, sometimes 2). I detest excessive white-space. This works well with nested arrays. | I generally use this kind of indentation for array's declarations :
```
function test()
{
$my_array = array(
'a' => 1,
'bcdef' => 2,
'gh' => array(
'glop',
'test'
),
'ijk' => 20,
);
}
```
Quite similar to #1, but with this difference :
* the final `}` is unindented
I never put many spaces arround the '`=>`' to align the values (like [ennuikiller suggested](https://stackoverflow.com/questions/1149300/formatting-associative-array-declaration/1149318#1149318)) : I find that really hard to read, and often have my eyes jump to the wrong value ^^
Also note that I always put a '`,`' at the end of the last declaration :
* it is perfectly valid
* you don't have to add it when you add one more line to the array
* when you add one line at the end of the array, you modifiy just one line : the one you are addin (and definitly not the one before, to add the ',' as it is already there) ; this helps with diffs and patches : less modified lines, easier to read
One more thing : this is what I do when I work on a project that doesn't specify formating rules ; else, I try to respect those as much as possible (so that formating is coherent between members of the project's team) | Formatting associative array declaration | [
"",
"php",
"arrays",
"formatting",
"coding-style",
"associative-array",
""
] |
Is there a way to remove the "Add" functionality on the Django admin site? For certain entities, I only want the Django admin to be able to view them or change existing ones, but not add new ones. | Sure, you can customize admin VERY granularly by following the instructions [here](http://docs.djangoproject.com/en/1.0/ref/contrib/admin/) -- I believe that what you want can be obtained in part by overriding `ModelAdmin.save_model(self, request, obj, form, change)` in your own `ModelAdmin` subclass, to ensure nothing happens on the store when `change` is false (i.e. an attempt to add rather than change), and in part by overriding `ModelAdmin.add_view(self, request, form_url='', extra_context=None)` to display an "add view" that makes it very clear to the admin that they're NOT going to be allowed to add object through this route. I haven't actually done the specific admin customization you require, but I've done others and they do seem to work pretty smoothly! | See: [Django Admin - Disable the 'Add' action for a specific model](https://stackoverflow.com/questions/4143886/django-admin-disable-the-add-action-for-a-specific-model) for true solution. | Remove the "Add" functionality in Django admin | [
"",
"python",
"django",
"admin",
""
] |
How to optimize this line drawing routine ? Will memcpy work faster ?
```
void ScreenDriver::HorizontalLine(int wXStart, int wXEnd, int wYPos,
COLORVAL Color, int wWidth)
{
int iLen = wXEnd - wXStart + 1;
if (iLen <= 0)
{
return;
}
while(wWidth-- > 0)
{
COLORVAL *Put = mpScanPointers[wYPos] + wXStart;
int iLen1 = iLen;
while(iLen1--)
{
*Put++ = Color;
}
wYPos++;
}
}
``` | I think you mean to say "memset" instead of "memcpy". Replacing this bit of the code:
```
while (iLen--)
{
*Put++ = Color;
}
```
with
```
memset(Put, Color, iLen);
```
could be faster but so much depends on your target CPU, memory architecture and the typical values of iLen encountered. It's not likely to be a big win, but if you've got the time I encourage you to measure the alternatives as that kind of exercise is the only way to really understand optimization.
Of course, this memset() use will only work if COLORVAL is character sized. | Your best bet before doing anything else is to employ whatever low-level profiling tools you have available. At the very least get an overall timing for a hefty test case or 3. Without a baseline measurement you're shooting in the dark. (I should know, I'm as guilty of this as anyone else!)
That said I note that your code looks like it has a fair bit of overhead per pixel,
1. A memset() call could be a win (if COLORVAL is sizeof(char) ).
2. Alternately, unrolling the loop may help - this is heavily dependent on you input data, machine architecture etc.
3. If your iLen value is reasonably bounded you might consider writing a custom function for each iLen value that is fully unrolled (inline the first few smallish cases in a switch) and call the bigger cases through an array of function pointers.
4. The fastest option of course is usually to resort to assembly. | line drawing routine | [
"",
"c++",
"optimization",
"graphics",
""
] |
How do you get the identity column value after an insert in SQL Server Compact 3.5? | I think what you want is @@IDENTITY:
```
SELECT @@IDENTITY AS Identity
```
This will return the value of the last identity inserted. | I guess you have to use [@@IDENTITY](http://msdn.microsoft.com/en-us/library/ms174077.aspx). I figured compact would have [SCOPE\_IDENTITY()](http://msdn.microsoft.com/en-us/library/ms190315.aspx), but I guess not. Just try scope\_identity to be sure. :) | return Identity in SQLServer Compact | [
"",
"c#",
"sql-server",
"compact-framework",
"sql-server-ce",
"identity-column",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.