Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm guessing that most built in random generators return something like this:
```
[0.0, 1.0)
```
so if I would like a 50% chance would I use something like this:
```
if random() < .5
```
or something like:
```
if random() <= .5
```
Thanks for the help. | Ah, the old ".5" problem. Here's the answer:
If you're going to divide 10 things into two **equal** parts, you need 5 things in each part. 0 thru 4 in the first part, 5-9 in the second part. So... `< .5` is correct. | Why do it yourself? Python has random.choice :)
random.choice([0, 1]) will give you 0/1 with equal chances -- and it is a standard part of Python, coded up by the same people who wrote random.random (and thus know more about its semantics than anyone else) | When using random, which form returns an equal 50% chance? | [
"",
"python",
"random",
""
] |
I have a feature where we need to merge user records. The user chooses a user to keep and and a user to discard.
We have 59 relations to user records in our database so for each one I need to do:
`UPDATE (Table) set UserNo=(userToKeep) WHERE UserNo=(userToDiscard)`
and then DELETE the userToDiscard and their user prefs (118).
Should I be worried about the transaction size? This is MS-SQL 2005.
Is there anything I could do?
Thanks | Have you tested how long the process actually takes? How often are users merged?
If you have indexes on the user ID in each of this table (and I would think that would be the natural thing to do anyway) then even with 59 tables it shouldn't take too long to perform those updates and deletes. If you only actually merge users a couple times a week then a little blip like that shouldn't be an issue. At worst, someone has to wait an extra couple seconds to do something once or twice a week.
Another option would be to save these user merge requests in a table and do the actual work in a nightly process (or whenever "off-hours" is for your application). You would need to make it clear to the users of your application though that merges do not take effect immediately. You would also need to account for a lot of possible contingencies: what if the same user is set to merge with two different users that night, etc. | It depends on how large your user table is, and what indexes you have in place. | When should I be concerned about transaction size? | [
"",
"sql",
""
] |
I am attempting to select a distinct list where duplicates are created over several fields. For example,
```
SELECT tablename.field1Date,
tablename.field2Number,
tablename.field3Text
FROM tablename;
```
Would select duplicating records over the date, number and text fields respectively.
Now, when I select distinct records to provide what I am looking for, the performance seems to decrease dramatically.
```
SELECT DISTINCT tablename.field1Date,
tablename.field2Number,
tablename.field3Text
FROM tablename;
```
Is there any known reasons for this? I must admit I am using MS Access 2003 which may be the issue. | Yes, basically it has to sort the results and then re-processed to eliminate the duplicates. This cull could also be being done during the sort, but we can only speculate as to how exactly the code works in the background. You could try and improve the performance by creating an index composed of all three (3) fields. | This page has tips on improving your query performance and also some information on using the performance analyzer. It will tell you what if any indexes are needed.
<http://support.microsoft.com/kb/209126> | In SQL, How does using DISTINCT affect performance? | [
"",
"sql",
"ms-access",
"performance",
""
] |
I have a method that uses the [`setTimeout`](https://developer.mozilla.org/en/window.setTimeout) function and makes a call to another method. On initial load method 2 works fine. However, after the timeout, I get an error that says `method2` is undefined. What am I doing wrong here?
ex:
```
test.prototype.method = function()
{
//method2 returns image based on the id passed
this.method2('useSomeElement').src = "http://www.some.url";
timeDelay = window.setTimeout(this.method, 5000);
};
test.prototype.method2 = function(name) {
for (var i = 0; i < document.images.length; i++) {
if (document.images[i].id.indexOf(name) > 1) {
return document.images[i];
}
}
};
``` | The issue is that `setTimeout()` causes javascript to use the global scope. Essentially, you're calling the `method()` class, but not from `this`. Instead you're just telling `setTimeout` to use the function `method`, with no particular scope.
To fix this you can wrap the function call in another function call that references the correct variables. It will look something like this:
```
test.protoype.method = function()
{
var that = this;
//method2 returns image based on the id passed
this.method2('useSomeElement').src = "http://www.some.url";
var callMethod = function()
{
that.method();
}
timeDelay = window.setTimeout(callMethod, 5000);
};
```
`that` can be `this` because `callMethod()` is within method's scope.
This problem becomes more complex when you need to pass parameters to the `setTimeout` method, as IE doesn't support more than two parameters to `setTimeout`. In that case you'll need to read up on [closures](http://www.jibbering.com/faq/faq_notes/closures.html).
Also, as a sidenote, you're setting yourself up for an infinite loop, since `method()` always calls `method()`. | A more elegant option is to append `.bind(this)` to the end of your function. E.g.:
```
setTimeout(function() {
this.foo();
}.bind(this), 1000);
// ^^^^^^^^^^^ <- fix context
```
So the answer to the OP's question could be:
```
test.prototype.method = function()
{
//method2 returns image based on the id passed
this.method2('useSomeElement').src = "http://www.some.url";
timeDelay = window.setTimeout(this.method.bind(this), 5000);
// ^^^^^^^^^^^ <- fix context
};
``` | setTimeout and "this" in JavaScript | [
"",
"javascript",
""
] |
I'm trying to determine how best to architect a .NET Entity Framework project to achieve a nice layered approach. So far I've tried it out in a browse-based game where the players own and operate planets. Here's how I've got it:
**Web Site**
This contains all the front end.
**C# Project - MLS.Game.Data**
This contains the EDMX file with all my data mappings. Not much else here.
**C# Project - MLS.Game.Business**
This contains various classes that I call 'Managers' such as PlanetManager.cs. The planet manager has various static methods that are used to interact with the planet, such as *getPlanet(int planetID)* which would return an generated code object from MLS.Game.Data.
From the website, I'll do something like this:
`var planet = PlanetManager.getPlanet(1);`
It returns a *Planet* object from from the MLS.Game.Data (generated from the EDMX). It works, but it bothers me to a degree because it means that my front end has to reference MLS.Game.Data. I've always felt that the GUI should only need to reference the Business project though.
In addition, I've found that my Manager classes tend to get very heavy. I'll end up with dozens of static methods in them.
So... my question is - how does everyone else lay out their ASP EF projects?
**EDIT**
After some more though, there's additional items which bother me. For example, let's say I have my Planet object, which again is generated code from the wizard. What if a time came that my Planet needed to have a specialized property, say "Population" which is a calculation of some sort based on other properties of the Planet object. Would I want to create a new class that inherits from Planet and then return that instead? (hmm, I wonder if those classes are sealed by the EF?)
Thanks | You could try the following to improve things:
* Use EF to fetch DTOs in your Data layer, then use these DTOs to populate richer business objects in your Business layer. Your UI would only then need to reference the Business layer.
* Once you have created the rich business objects, you can begin to internalise some of the logic from the manager classes, effectively cleaning up the business layer.
I personally prefer the richer model over the manager model because, as you say, you end up with a load of static methods, which you inevitibly end up chaining together inside other static methods. I find this both too messy and, more importantly, harder to understand and guarantee the consistency of your objects at any given point in time.
If you encapsulate the logic within the class itself you can be more certain of the state of your object regardless of the nature of the external caller.
A good question by the way. | IMHO, your current layout is fine. It's perfectly normal for your UI to reference the 'Data' layer as you are calling it. I think that perhaps your concern is arising due to the terminology. The 'Data' you have described more often referred to as a 'business objects' (BOL) layer. A common layout would then be to have a business logic layer (BLL) which is your 'Managers' layer and a data access layer (DAL). In your scenario, LINQ to Entites (presuming you will use that) is your DAL. A normal reference pattern would then be:-
UI references BLL and BOL.
BLL refences BOL and DAL (LINQ to Entites).
Have a look at [this series of articles](http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=476) for more detail. | .NET Entity framework project layout (architecture) | [
"",
"c#",
"asp.net",
"entity-framework",
"architecture",
"web-architecture",
""
] |
I'm using C++ with the OpenCV library, which is a library image-processing although that's not relevant for this question. Currently I have a design decision to make.
OpenCV, being a C library, has its data structures (such as CvMat) declared as structs. To create them, you use functions like cvCreateMat, and to release them, you use functions like cvReleaseMat. Being a C++ programmer, I created a special `cv_scoped` class which would automatically call cvReleaseMat when it went out of scope (like `boost::scoped_ptr`).
What I'm realising now is that I wish I could use `auto_ptr` and `shared_ptr` in cases as well. I just feel that writing code for my own `cv_auto_ptr` and `cv_shared_ptr` classes would be a bad idea, not to mention a waste of time. So I've been looking for solutions, and I've come up with three possibilities.
**First**, I could use the cv\_scoped class I've already made. I'd rename it to `cv_ptr` and then use smart pointers like so: `std::auto_ptr<cv_ptr>`. The annoying thing about this though is, I'd always have to dereference twice:
```
std::auto_ptr<cv_ptr> matrix(cv_ptr(cvCreateMat(320, 240, CV_32FC3)));
cvPow(matrix.get()->get()); // one get for the auto_ptr, one for the cv_ptr
```
I know it looks like I could declare an implicit conversion, but I couldn't actually - most of OpenCV's functions have the parameter void\* - so no implicit conversion would be called. I would really like a way of doing this where I didn't have to do the double dereference.
**Second**, I could somehow override `operator delete`. I don't want to override the global operator delete because I'd only want this to apply to CvMat (and a few other) types. However, I can't change the library, so I can't add `operator delete` to the CvMat struct. So I don't know how this would work.
**Third**, I could just rewrite my own `auto_ptr`, `scoped_ptr`, and `shared_ptr`. They're not large classes so it wouldn't be too difficult, but I just feel like this is bad design. If I were to do this, I would probably do something along these lines:
```
class cv_auto_ptr {
public:
cv_auto_ptr();
~cv_auto_ptr();
// each method would just be a proxy for the smart pointer
CvMat* get() { return this->matrix_.get()->get(); }
// all the other operators/methods in auto_ptr would be the same, you get the idea
private:
auto_ptr<cv_ptr> matrix_; // cv_ptr deletes CvMat properly
}
```
What would you do in my situation? Please help me figure this one out. | The auto\_ptr are really designed for RAII on C++ class with constructs/destructors you are pushing their uses here to things they probably should not be used for (but can).
Anyway don'y you want to be able to use your C++ object as if it was a normal stack variable without dynamically allocating each time?
The standard solution to your problem is to create a wrapper with constructor/destructor.
But to make it usable by the C functions just add an internal cast operator so it auto-magically converts itself back to the C object when passed to a C function
Write a wrapper class.
```
class Mat
{
CvMat* impl;
public:
Mat(/* Constructor Arguments */)
{
impl = cvCreateMat(/* BLAH */);
}
~Mat()
{
cvReleaseMat(impl);
}
operator CvMat*()
{ // Cast opertator. Convert your C++ wrapper object into C object
// when you use it with all those C functions that come with the
// library.
return impl;
}
};
void Plop(CvMat* x)
{ // Some C function dealing with CvMat
}
int main()
{ // Don't need to dynamically allocate
Mat m; // Just create on the stack.
Plop(m); // Call Plop directly
std::auto_ptr<Mat> mP(new Mat);
Plop(*mP);
}
``` | One approach that you could consider is to used the fact that `std::tr1::shared_ptr` has the functionality to provide a custom deleter. I have no familiarity with OpenCV so I'm inferring from what you've written.
```
struct CvMatDeleter
{
void operator( CvMat* p ) { cvReleaseMat( p ) ; }
};
void test()
{
std::tr1::shared_ptr< CvMat > pMat( cvCreateMat(320, 240, CV_32FC3), CvMatDeleter() );
// . . .
}
```
Because the deleter is store in the shared pointer you can just use it as normal and when the shared raw pointer finally needs to be deleted, `cvReleaseMat` will be called as required. Note that `auto_ptr` and `scoped_ptr` are much lighter classes so don't have the functionality for custom deleters, but if you're prepared for the small overhead then `shared_ptr` can be used in their place. | Smart pointers with a library written in C | [
"",
"c++",
"opencv",
"smart-pointers",
"raii",
""
] |
We have a very strange error occurring at a developer site which we are unable to replicate ourselves.
A developer in Poland has recently upgraded his Windows XP Service Pack 3 machine to 4Gb of Ram
When he did so he started experiencing graphical errors in java programs using IBM JDK 1.5
This errors only occur in IBM JDK 1.5 and not in any other version.
The problem manifests itself when you create a button or control on a form and move the mouse over it.
We have a test program
```
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GraphicTest {
public static void main(String args[]) {
JFrame frame = new JFrame("GraphicTest");
frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(200, 200);
JButton button = new JButton("Test button");
button.setVisible(true);
frame.getContentPane().add(button);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
which shows the problem straight away.
However the problem doesn't arise on my own machine when I upgrade the same windows version to 4Gb of Ram.
Has anyone else ever seen an issue like this?
Just to clarify this a bit, this issue only happens with IBM JDK 1.5 and only happens when we have 4Gb of Ram. It doesn't happen on any other version of the JDKs and if we reduce the amount of memory to 3 Gb the problem disappears. | Try reducing the hardware optimization in Windows' graphics drivers (accessible through the extended display control panel). If the machine in question has an onboard graphics adapter that uses a part of the main memory, then upgrading RAM might expose problems in the driver (or the RAM may even be faulty). | The first obvious thing to always say is: Confine usage of Swing components to the AWT Event Dispatch Thread (EDT).
```
public class GraphicTest {
public static void main(final String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
runEDT();
}
});
}
private static void runEDT() {
assert java.awt.EventQueue.isDispatchThread();
JFrame frame = new JFrame("GraphicTest");
...
```
I don't know why memory size would be important. Perhaps it affects the timings in someway. Perhaps the JVM decides it is running on a server-class machine and runs with more aggressive optimisation. | Button text disappearing with 4Gb Ram and IBM Java 1.5 | [
"",
"java",
"graphics",
"java-5",
""
] |
I'm trying to create an SQL query that will order the results by a version number (e.g. 1.1, 4.5.10, etc.)
Here's what I tried:
```
SELECT * FROM Requirements
WHERE Requirements.Release NOT LIKE '%Obsolete%'
ORDER BY Requirements.ReqNum
```
Now, the ReqNum field is a string field and unfortunately I can't change it to a float or something like that because I have requirement numbers like `162.1.11`.
When I get the results back, I'll get ordering like this:
```
1.1
1.10
1.11
1.3
```
**How can I write a query that will sort by lexicographic order?**
... or,
**How can I correctly sort the data?**
Thanks for the input in advance! | For best results, refactor version number storage so that each section has it's own column: MajorVersion, MinorVersion, Revision, Build. Then the ordering problem suddenly becomes trivial. You can also build a computed column for easy retrieval of the full string. | In PostgreSQL you can do:
```
SELECT * FROM Requirements
ORDER BY string_to_array(version, '.')::int[];
```
This last `::int[]` makes it convert string values into integers and then compare as such. | SQL sort by version "number", a string of varying length | [
"",
"sql",
""
] |
I've been trying to use decimal values as params for a field attribute but I get a compiler error.
I found this blog post [link](http://salamakha.com/blog/2007/09/21/decimal-in-c-attributes/) saying it wasn't possible in .NET to use then, does anybody know why they choose this or how can I use decimal params? | This is a CLR restriction. Only primitive constants or arrays of primitives can be used as attribute parameters. The reason why is that an attribute must be encoded entirely in metadata. This is different than a method body which is coded in IL. Using MetaData only severely restricts the scope of values that can be used. In the current version of the CLR, metadata values are limited to primitives, null, types and arrays of primitives (may have missed a minor one).
Decimals while a basic type are not a primitive type and hence cannot be represented in metadata which prevents it from being an attribute parameter. | I have the same problem. I consider to use **strings**. This is not type-safe, but it's readable and I think we will be able to write valid numbers in strings :-).
```
class BlahAttribute : Attribute
{
private decimal value;
BlahAttribute(string number)
{
value = decimal.Parse(number, CultureInfo.InvariantCulture);
}
}
[Blah("10.23")]
class Foo {}
```
It's not a beauty, but after considering all the options, it's good enough. | use decimal values as attribute params in c#? | [
"",
"c#",
"parameters",
"attributes",
"decimal",
""
] |
Is there a way to declare an iterator which is a member variable in a class and that can be incremented using a member function even though the object of that class is const. | That would be with the "mutable" keyword.
```
class X
{
public:
bool GetFlag() const
{
m_accessCount++;
return m_flag;
}
private:
bool m_flag;
mutable int m_accessCount;
};
``` | Are you sure you need iterator as a member? Iterators have an ability: they become invalid. It is a small sign of a design problem. | how to declare volatile iterator in c++ | [
"",
"c++",
"iterator",
"volatile",
""
] |
What I need to do is provide a file browser box on a web page where a user selects a file from their computer and, through javascript (or flash if necessary), some sort of Hash is returned such as CRC, MD5 or SHA1. I would prefer not to have to upload the entire file to the web server, as I expect some rather large files to be used in this.
Basically I am making a script that associates these values with META data of sorts, allowing the files to be identified without having to be uploaded completely.
Any idea how I would go about doing this? It'd be easy for me to do it on the server side, but, as I said, there will be some rather large files checked and I don't want to eat up too much of the server's bandwidth. | You can do it with Flash, provided that the user has Flash Player 10.
Here is a [tutorial](http://www.gotoandlearn.com/play?id=76)
Also: [Reading and writing local files in FP10](http://www.mikechambers.com/blog/2008/08/20/reading-and-writing-local-files-in-flash-player-10/) | This is *traditionally* not possible with JavaScript, but it may be if the [W3 File Upload](http://www.w3.org/TR/file-upload/) spec ever catches on.
A variant is available in Firefox 3:
```
var content= input.files[0].getAsBinary();
```
For other browsers you would have to fall back to Flash and/or server-side hashing.
Here's a bonus JS implementation of SHA-1 for you:
```
function sha_hexdigest(bytes) {
var digest= sha_bytes(sha_calculate(sha_ints(bytes), bytes.length*8));
var digits= '0123456789abcdef';
var hex= '';
for (var i= 0; i<digest.length; i++) {
var c= digest.charCodeAt(i);
hex+= digits.charAt((c>>4)&0xF) + digits.charAt(c&0xF);
}
return hex;
}
function sha_ints(bytes) {
while (bytes.length%4!=0)
bytes+= '\x00';
var ints= new Array();
for (var i= 0; i<bytes.length; i+= 4) {
ints[ints.length]= (
(bytes.charCodeAt(i)&0xFF)<<24 | (bytes.charCodeAt(i+1)&0xFF)<<16 |
(bytes.charCodeAt(i+2)&0xFF)<<8 | (bytes.charCodeAt(i+3)&0xFF)
); }
return ints;
}
function sha_bytes(ints) {
var bytes= '';
for (var i= 0; i<ints.length; i++)
bytes+= String.fromCharCode((ints[i]>>24)&0xFF, (ints[i]>>16)&0xFF, (ints[i]>>8)&0xFF, ints[i]&0xFF)
return bytes;
}
function sha_calculate(ints, bitn) {
while (ints.length*32<=bitn) ints[ints.length]= 0;
ints[ints.length-1]|= 1<<(31-bitn%32)
while (ints.length%16!=14) ints[ints.length]= 0;
ints[ints.length]= Math.floor(bitn/0x100000000);
ints[ints.length]= bitn&0xFFFFFFFF;
var h0= 1732584193, h1= -271733879, h2= -1732584194, h3= 271733878, h4= -1009589776;
var a, b, c, d, e, f, k, temp, w= new Array(80);
for(var inti= 0; inti<ints.length; inti+= 16) {
a= h0; b= h1; c= h2; d= h3; e= h4;
for (var i= 0; i<16; i++) w[i]= ints[inti+i];
for (; i<80; i++) w[i]= sha_rol(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);
for(var i= 0; i<80; i++) {
switch (Math.floor(i/20)) {
case 0: f= sha_add(1518500249, (b & c) | ((~b) & d)); break;
case 1: f= sha_add(1859775393, b ^ c ^ d); break;
case 2: f= sha_add(-1894007588, (b & c) | (b & d) | (c & d)); break;
case 3: f= sha_add(-899497514, b ^ c ^ d); break;
}
temp= sha_add( sha_add(sha_rol(a, 5), w[i]), sha_add(e, f) );
e= d; d= c; c= b; b= a; a= temp;
c= sha_rol(c, 30);
}
h0= sha_add(h0, a); h1= sha_add(h1, b); h2= sha_add(h2, c); h3= sha_add(h3, d); h4= sha_add(h4, e);
}
return new Array(h0, h1, h2, h3, h4);
}
function sha_add(a, b) {
var lsw= (a&0xFFFF) + (b&0xFFFF);
var msw= (a>>16) + (b>>16) + (lsw>>16);
return (msw<<16) | (lsw&0xFFFF);
}
function sha_rol(n, bits) {
return (n<<bits) | (n>>>(32-bits));
}
``` | How would I get a Hash value of a users file with Javascript or Flash? | [
"",
"javascript",
"flash",
"md5",
"sha1",
"crc",
""
] |
My company is developing an application that receives data from another company via TCP sockets and xml messages. This is delivered to a single gateway application which then broadcasts it to multiple copies of the same internal application on various machines in our organisation.
WCF was chosen as the technology to handle the internal communications (internally bi-directional). The developers considered two methods.
1. Individual methods exposed by the
WCF service for each different
message received by the gateway
application. The gateway
application would parse the incoming
external message and call the
appropriate WCF service method. The
incoming XML would be translated
into DataContract DTO’s and supplied
as argument to the appropriate WCF
method.
2. The internal application
exposed a WCF service with one
method “ProcessMessage” which
accepted an Xml string message as
argument. The internal app would
parse then deserialize the received
xml and process it accordingly.
The lead developer thought option two was the better option as it was “easier” to serialized/deserialize the xml. I thought the argument didn’t make sense because DataContracts are serialized and deserialized by WCF and by using WCF we had better typing of our data. In option 2 someone could call the WCF service and pass in any string. I believe option 1 presents a neater interface and makes the application more maintainable and useable.
Both options would still require parsing and validation of the original xml string at some point, so it may also be a question where is the recommended place to perform this validation.
I was wondering what the current thoughts are for passing this kind of information and what people’s opinions on both alternatives are. | I recently asked a couple of questions around this area: [XML vs Objects](https://stackoverflow.com/questions/368521/api-design-expose-xml-or-objects) and [XML vs Objects #2](https://stackoverflow.com/questions/375548/api-design-expose-xml-or-objects-2). You'll find the answers to those questions interesting.
For our particular problem we've decided on a hybrod approach, with the interface looking something like this:
```
// Just using fields for simplicity and no attributes shown.
interface WCFDataContract
{
// Header details
public int id;
public int version;
public DateTime writeDateTime;
public string xmlBlob;
// Footer details
public int anotherBitOfInformation;
public string andSoemMoreInfo;
public book andABooleanJustInCase;
}
```
The reason we use an xmlBlob is because we own the header and footer schema but not the blob in the middle. Also, we don't really have to process that blob, rather we just pass it to another library (created by another department). The other library returns us more strongly typed data.
Good luck - I know from experience that your option 2 can be quite seductive and can sometimes be hard to argue against without being accused of being overly pure and not pragmatic enough ;) | Option 1 is suited if you can ensure that the client **always** sends serialized representations of data contracts to the server.
However if you need some flexibility in the serialization/deserialization logic and not get tightly coupled with DataContracts, then option 2 looks good. Particularly useful when you want to support alternate forms of xml (say Atom representations, raw xml in custom format etc)
Also in option 2 inside the ProcessMessage() method, you have the option of deciding **whether or not** to deserialize the incoming xml payload (based on request headers or something that is specific to your application).
In option 1, the WCF runtime will **always** deserialize the payload. | WCF: Individual methods or a generic ProcessMessage method accepting xml | [
"",
"c#",
"xml",
"wcf",
"architecture",
""
] |
I have this code:
> ```
> if(!mysql_connect($host,$user,$passwd)){
> die("Hoops, error! ".mysql_error());
> }
> ```
...no error from here.
```
if(!mysql_select_db($db,$connect)){
$create_db = "CREATE DATABASE {$db}";
mysql_query($create_db,$connect);
mysql_query("USE DATABASE {$db}",$connect);
}
```
..."no database selected" error from here.
I would like to select database if it exists and if doesn't then create it and select it.
Why is my code not right?
Thank you in advance | Where are you saving the value returned by mysql\_connect()? Don't see it here. I assume $host, $user, $password and $db are properly set ahead of time. But you're passing a param to mysql\_select\_db that may not be properly set.
```
$connect = mysql_connect($host,$user,$passwd);
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($db,$connect)) ...
```
Start by checking to see if you can select *without* the CREATE query first. Try a simple SELECT query to start. If you can connect, select the db, and execute a SELECT query, that's one step. *Then* try the CREATE query. If that doesn't work, it's almost certainly a matter of permissions. | You might need database create permissions for the user attempting to create the database.
Then you need to operate on a valid connection resource. $connect never looks to be assigned to the connection resource. | How do I select mysql database in php? | [
"",
"php",
"mysql",
""
] |
In SQL Server this inserts 100 records, from the Customers table into tmpFerdeen :-
```
SELECT top(100)*
INTO tmpFerdeen
FROM Customers
```
Is it possible to do a SELECT INTO across a UNION ALL SELECT :-
```
SELECT top(100)*
FROM Customers
UNION All
SELECT top(100)*
FROM CustomerEurope
UNION All
SELECT top(100)*
FROM CustomerAsia
UNION All
SELECT top(100)*
FROM CustomerAmericas
```
Not too sure where to add the INTO clause. | This works in SQL Server:
```
SELECT * INTO tmpFerdeen FROM (
SELECT top 100 *
FROM Customers
UNION All
SELECT top 100 *
FROM CustomerEurope
UNION All
SELECT top 100 *
FROM CustomerAsia
UNION All
SELECT top 100 *
FROM CustomerAmericas
) as tmp
``` | You don't need a derived table at all for this.
Just put the `INTO` after the first `SELECT`
```
SELECT top(100)*
INTO tmpFerdeen
FROM Customers
UNION All
SELECT top(100)*
FROM CustomerEurope
UNION All
SELECT top(100)*
FROM CustomerAsia
UNION All
SELECT top(100)*
FROM CustomerAmericas
``` | Is it possible to use the SELECT INTO clause with UNION [ALL]? | [
"",
"sql",
"sql-server",
""
] |
I'm trying to compile code from an open source project, and I'm running into a problem where gcc claims that a particular line of code has an ambiguous interpretation. The problem involves a templated class and these two methods:
```
template <class X>
class A {
public:
X& operator[] (int i) { ... }
operator const X* () { ... }
};
```
When this is used along the lines of this:
```
A<B*> a;
B* b = a[i];
```
gcc complains about the ambiguous resolution of a[i]. The problem is made more clear by replacing the definition of A with its specific instantiation:
```
class A_B {
public:
B*& operator[] (int i) { ... }
operator B* const * () { ... }
};
```
The problem is that there are two ways of interpreting B\* b = a[i]:
```
// First interpretation (array-like behaviour first)
B*& b1 = a[i];
B* b2 = (B*) b1;
// Second interpretation (casting behaviour first)
B* const * b1 = (B* const *) a;
B* b2 = b1[a];
```
My question is this: Is there some way to provide a preferred interpretation, preferably by making the casting version undesirable without an explicit cast, so that I don't have to modify every line that tries to invoke A[]? I realize that the interpretation is legitimately ambiguous, but I know what the intention of the code is, and I would like to communicate that to the compiler with minimal changes.
**Edit:** It seems my example doesn't cause the bug in question, so I'm not correctly summarizing the original code, nor correctly identifying the problem. I'll try to get an example that produces the problem first, sorry folks. | The following code compiles for me with g++ 3.x. I don't think your analysis of the problem is correct, but in any case could you post the error message you are getting.
```
template <class X>
struct A {
X& operator[] (int i) { static X x; return x; }
operator const X* () { return 0; }
};
class B {};
int main() {
A<B*> a;
B* b = a[0];
}
``` | You could use braces:
```
A<B*> a;
B* b = (a[i]); // Now it must evaluate the sub-expression a[i]
```
NB. Your example above compiles fine and calls the operator[] as expected. | Disambiguate operator[] binding | [
"",
"c++",
""
] |
Quick question; do I always need to check for a null value after performing a safe cast? I do it this way now, but in a situation like this:
```
void button1_Click(object sender, EventArgs e)
{
Button = sender as Button;
if (button != null) // <-- necessary?
{
// do stuff with 'button'
}
}
```
I am just wondering if I am not thinking of something. I check for null every time out of habit, but in a case like this I think that I would prefer a crash if a non-Button object was hooked up to a handler that should only be for buttons.
EDIT: OK, thanks guys. I was just curious if there was an angle that I was missing. | I agree - maybe you're better off having the app crash if a non-Button is hooked up, since this handler only makes sense for Buttons. Going with a normal cast might even be better than an "as" cast, because you'll end up with an InvalidCastException rather than a NullReferenceException, which make the problem very obvious. | If you want to crash if a non-Button was passed in, do:
```
var button = (Button)sender;
```
Note that it could still be null, if a null object was passed in. | Do I *always* have to check for null after a safe cast? | [
"",
"c#",
""
] |
I am getting a strange runtime error from my code:
```
"Found interface [SomeInterface] but class was expected"
```
How can this happen? How can an interface get instantiated?
**Update:** (In response to some answers) I am compiling and running against the same set of libraries, but I **am** using [Guice](http://code.google.com/p/google-guice/) to inject a Provider for this particular Interface.
The problem went away when I bound an implementation to the interface (seems like the @ImplementedBy annotation was not enough).
I was more interested in the mechanics through which Guice managed to actually instantiate an interface. | This happens when your runtime classpath is different than your compile time classpath.
When your application was compiled, a class (named `SomeInterface` in your question) existed as a class.
When your application is running at compile time, `SomeInterface` exists as an interface (instead of a class.)
This causes an `IncompatibleClassChangeError` to be thrown at runtime.
This is a common occurence if you had a different version of a jar file on the compile time classpath than on the runtime classpath. | Most likely the code was compiled against a class in a library, which was then changed to an interface in the version you run against. | Java error: Found interface ... but class was expected | [
"",
"java",
"guice",
""
] |
Bit of oddness, seen if I do the following:
```
import javax.swing.*;
public class FunkyButtonLayout {
public static void main(String[] args) {
JFrame frame = new JFrame("");
JPanel j0 = new JPanel(); // j0 gets added to the root pane
j0.setLayout(null);
JPanel j1 = new JPanel(); // j1 gets added to j0
j1.setLayout(null);
JButton b1 = new JButton(""); // b1 gets added to j1
j1.add(b1);
b1.setBounds(0, 0, 40, 32); // b1 is big
j0.add(j1);
j1.setBounds(0, 0, 32, 32); // j1 is not so big - b1 gets 'trimmed'
frame.getContentPane().setLayout(null); // <- seems to be needed :-(
frame.getContentPane().add(j0);
j0.setBounds(10, 10, 32, 32); // end result: a 32x32 button with
frame.setSize(125, 125); // a trimmed right border
frame.setVisible(true); // in the top-left corner
}
}
```
I get pretty much what I'm looking for, apart from the ability to position j0 in the root pane with a layout manager. If I change the
```
frame.getContentPane().setLayout(null);
```
line to
```
frame.getContentPane().setLayout(new java.awt.FlowLayout());
```
I see j0 draw as a 1x1 pixel @ the middle of the screen :-(
Any ideas why? Note that this isn't just a FlowLayout thing - pretty much every layout manager messes this up.
I really want to have the net effect of the 'border trimmed on one side' button - it allows me to do the toolbar-button-cluster thing (the kind of thing that [cage fighter](http://www.otierney.net/cagefighter/) tries to get rid of) with native-looking button controls - I cannot see another way of doing this, thanks to OS-level skins. So any ideas appreciated :-) | If you set the layout manager to null, you have to explicitly set the container's preferred size (that's why it's showing up so small).
If you are using setBounds on a component, you are over-riding the work that the layout manager for the parent container does.
I would remove all calls to setBounds and all calls to setLayout(null) and try to achieve the effect you are after using just layout managers. | For a really good explanation of how layout managers work, check out an old article I wrote at Sun
<http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/>
It's old, but talks about preferredSize and layout nesting pretty well.
Enjoy,
-- Scott | java swing - layout oddness when using different layout managers | [
"",
"java",
"swing",
"layout",
""
] |
In my php application user able to enter the tags(like here while ask question).
I assume it will be regexp, and I used one - mb\_split('\W+', $text) - to split by non-word characters.
But I want to allow users to enter characters like "-,\_,+,#" etc which are valid ones to be in url and are common.
Is there exiting solutions for this, or may be best practicles?
thanks. | Use the [explode()](https://www.php.net/manual/en/function.explode.php) function and separate by either spaces or commas. Example:
```
$string = 'tag1 tag-2 tag#3';
$tags = explode(' ', $string); //Tags will be an array
``` | Split by whitespace `\s+` instead. | best way to create/split string to tags | [
"",
"php",
"regex",
""
] |
I am looking to allow users to select a pre-uploaded image to a user generated web page.
I have a list of the available images, so I could easily do this with a select control, however, I'd really like to allow the users to select from a pop up of thumbnails, rather than text, then have that populate a text form element with the resulting file name. I'm hoping the end result will be like a calendar pop-up date selector.
I'm sure there is a simple way to do this using Jquery / other javascript. Does anyone know of a pre built widget / example of this, or can people point me in the right direction of where to start? I'm pretty new to Javascript, but willing to invest some time in learning...
---
Clarification: A grid or list of thumbnails is what I'm after ideally, but the main thing is to give the user a visual representation of the picture, rather than it's filename... | ```
function fillBox(myImg){
imageSource = myImg.src;
imgName = // do some stuff to get only the filename, minus the dirs
document.getElementById("yourTextBox").value = imgName;
}
```
and as you're generating your thumbnails, add this to the img tag:
```
onclick="javascript:fillBox(this);"
```
I haven't tested any of this, but it should get you most of the way there. | I was able to find this jQuery plugin called ["Select Box Factory 2.0"](http://www.headcircus.com/uiguy/selectboxfactory/selectboxfactory.html)
Open the "Other Features: Images" accordion, and I think this is more or less what you want.
Alternatively, you could do something like:
```
<select id='images'>
<option value='tiger.jpg'>Tiger</option>
<option value='owl.jpg'>Owl</option>
<option value='bear.jpg'>Bear</option>
</select>
<div id='preview'></div>
```
And then jQuery code like this:
```
$('#images').change(function() {
var image = $(this).val();
var img = $('<img/>').attr('src', image);
$('#preview').html(img);
});
```
Good luck. | jquery select image | [
"",
"javascript",
"jquery",
"user-interface",
"web-applications",
""
] |
How can I query a particular website with some fields and get the results to my webpage using php?
Let's say website xyz.com will give you the name of the city if you give them the zipcode. How can I achieve this easliy in php? Any code snap shot will be great. | If I understand what you mean (You want to submit a query to a site and get the result back for processing and such?), you can use [cURL](http://php.net/curl).
Here is an [example](http://php.net/manual/en/curl.examples-basic.php):
```
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
?>
```
You can grab the Lat/Long from [this site](http://www.ip-adress.com/ip_tracer/) with some regexp like this:
```
if ( preg_match_all( "#<td>\s+-?(\d+\.\d+)\s+</td>#", $output, $coords ) ) {
list( $lat, $long ) = $coords[1];
echo "Latitude: $lat\nLongitude: $long\n";
}
```
Just put that after the curl\_close() function.
That will return something like this (numbers changed):
```
Latitude: 53.5100
Longitude: 60.2200
``` | You can use file\_get\_contents (and other similar fopen-class functions) to do this:
```
$result = file_get_contents("http://other-site.com/query?variable=value");
``` | How to scrape a webpage after supplying input data | [
"",
"php",
"web-scraping",
""
] |
* The value of $total\_results = 10
* $total\_results in an object, according to gettype()
* I cannot use mathematical operators on $total\_results because it's not numeric
* Tried $total\_results = intval($total\_results) to convert to an integer, but no luck
* The notice I get is: Object of class Zend\_Gdata\_Extension\_OpenSearchTotalResults could not be converted to int
How can I convert to an integer? | Does this work?
```
$val = intval($total_results->getText());
``` | ```
$results_numeric = (int) $total_results;
```
or maybe this:
```
$results_numeric = $total_results->count();
``` | Convert object to integer in PHP | [
"",
"php",
"types",
""
] |
Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this? | It's compiled to bytecode which can be used much, much, much faster.
The reason some files aren't compiled is that the main script, which you invoke with `python main.py` is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.
*Important addition by [Ben Blank](https://stackoverflow.com/users/46387/ben-blank):*
> It's worth noting that while running a
> compiled script has a faster *startup*
> time (as it doesn't need to be
> compiled), it doesn't *run* any
> faster. | The .pyc file is Python that has already been compiled to byte-code. Python automatically runs a .pyc file if it finds one with the same name as a .py file you invoke.
"An Introduction to Python" [says](http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html) this about compiled Python files:
> A program doesn't run any faster when
> it is read from a ‘.pyc’ or ‘.pyo’
> file than when it is read from a ‘.py’
> file; the only thing that's faster
> about ‘.pyc’ or ‘.pyo’ files is the
> speed with which they are loaded.
The advantage of running a .pyc file is that Python doesn't have to incur the overhead of compiling it before running it. Since Python would compile to byte-code before running a .py file anyway, there shouldn't be any performance improvement aside from that.
How much improvement can you get from using compiled .pyc files? That depends on what the script does. For a very brief script that simply prints "Hello World," compiling could constitute a large percentage of the total startup-and-run time. But the cost of compiling a script relative to the total run time diminishes for longer-running scripts.
The script you name on the command-line is never saved to a .pyc file. Only modules loaded by that "main" script are saved in that way. | Why compile Python code? | [
"",
"python",
"compilation",
""
] |
Our application depends on numerous resources that are provided by another system.
To ensure the existence of those resources, we currently have a JUnit test case (probably more an integration test), that takes a list of all the resources as a textfile, fetches each and tracks success/failure.
This is a very long running testCase that is not very "tool friendly". What we would really like to have is something along the lines of one test-method per resource.
I am aware that this is not what JUnit was meant to do. But is there a way to generate those testmethods on the fly?
Maybe something a bit more "elegant" than writing a perl-script to generate hundreds of methods?
Thanks a lot! | You may want to look at parameterized tests. This is easier to achieve in JUnit 4, though can be done in JUnit 3. See this question for code: [JUnit test with dynamic number of tests](https://stackoverflow.com/questions/358802/junit-test-with-dynamic-number-of-tests) | This: <http://github.com/adewale/cq-challenge-markup/blob/b99c098f0b31307c92bd09cb6a324ef2e0753a0b/code/acceptance-tests/AcceptanceTest.java> is an example of a class that dynamically generates one test per resource using the JUnit4 @Parameterized annotation | Generating JUnit Testcases | [
"",
"java",
"junit",
""
] |
I have an ArrayList of objects in Java. The objects have four fields, two of which I'd use to consider the object equal to another. I'm looking for the most efficient way, given those two fields, to see if the array contains that object.
The wrench is that these classes are generated based on XSD objects, so I can't modify the classes themselves to overwrite the `.equals`.
Is there any better way than just looping through and manually comparing the two fields for each object and then breaking when found? That just seems so messy, looking for a better way.
**Edit:** the ArrayList comes from a SOAP response that is unmarshalled into objects. | It depends on how efficient you need things to be. Simply iterating over the list looking for the element which satisfies a certain condition is O(n), but so is ArrayList.Contains if you could implement the Equals method. If you're not doing this in loops or inner loops this approach is probably just fine.
If you really need very efficient look-up speeds at all cost, you'll need to do two things:
1. Work around the fact that the class
is generated: Write an adapter class which
can wrap the generated class and
which implement [equals()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals(java.lang.Object)) based
on those two fields (assuming they
are public). Don't forget to also
implement [hashCode()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#hashCode()) (\*)
2. Wrap each object with that adapter and
put it in a HashSet.
[HashSet.contains()](http://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#contains(java.lang.Object)) has constant
access time, i.e. O(1) instead of O(n).
Of course, building this HashSet still has a O(n) cost. You are only going to gain anything if the cost of building the HashSet is negligible compared to the total cost of all the contains() checks that you need to do. Trying to build a list without duplicates is such a case.
---
\*
(*) Implementing hashCode() is best done by XOR'ing (^ operator) the hashCodes of the same fields you are using for the equals implementation (but [multiply by 31](https://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier/299748) to reduce the chance of the XOR yielding 0)* | You could use a Comparator with Java's built-in methods for sorting and binary search. Suppose you have a class like this, where a and b are the fields you want to use for sorting:
```
class Thing { String a, b, c, d; }
```
You would define your Comparator:
```
Comparator<Thing> comparator = new Comparator<Thing>() {
public int compare(Thing o1, Thing o2) {
if (o1.a.equals(o2.a)) {
return o1.b.compareTo(o2.b);
}
return o1.a.compareTo(o2.a);
}
};
```
Then sort your list:
```
Collections.sort(list, comparator);
```
And finally do the binary search:
```
int i = Collections.binarySearch(list, thingToFind, comparator);
``` | Most efficient way to see if an ArrayList contains an object in Java | [
"",
"java",
"algorithm",
"optimization",
"search",
"arraylist",
""
] |
I have an associative array in JavaScript:
```
var dictionary = {
"cats": [1,2,3,4,5],
"dogs": [6,7,8,9,10]
};
```
How do I get this dictionary's keys? I.e., I want
```
var keys = ["cats", "dogs"];
```
---
Just to get the terminology correct - there is no such thing as an 'associative array' in JavaScript - this is technically just an `object` and it is the object keys we want. | You can use: `Object.keys(obj)`
Example:
```
var dictionary = {
"cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
"dogs": [4, 5, 6, 3, 2]
};
// Get the keys
var keys = Object.keys(dictionary);
console.log(keys);
```
See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, and Internet Explorer 9. *[Object.keys()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys)* contains a code snippet that you can add if `Object.keys()` is not supported in your browser. | Try this:
```
var keys = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
keys.push(key);
}
}
```
`hasOwnProperty` is needed because it's possible to insert keys into the prototype object of `dictionary`. But you typically don't want those keys included in your list.
For example, if you do this:
```
Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};
```
and then do a `for...in` loop over `dictionary`, you'll get `a` and `b`, but you'll also get `c`. | Getting a list of associative array keys | [
"",
"javascript",
"arrays",
""
] |
Why in the ADVANCE section when I 'configure data source' is the 'GENERATE INSERT UPDATE AND SELECT STATEMENT' greyed out? On some tables it isn't greyed out and works fine.
I know that a way around this can be achieved by changing the autogenerateeditbutton tag to true in properties and you can edit this way - but when this is done there is no update to the database when you attempt.
It was also mentioned that this could be to do with setting up a primary key when I looked on forums on this matter. I couldn't get a conclusive answer though.
The error in the browser is as follows:
`NotSupportedException: Updating is not supported by data source 'AccessDataSource1' unless UpdateCommand is specified.`
Any ideas how to update the database with these problematic tables? Why are they problematic?
How is the Primary Key alocated to the table. Should this be done in Access? Can it be done in VS08 and how? | In order for the insert/select/update statements to be automatically generated, the table has to have a primary key so that code to select the correct row upon insert or to update knows which row to select. If you don't have a column in the table that has unique values it is possible for more than one row to match the one that should be updated. Using a primary key allows designer to generate code that reliably chooses the correct row to update. | see tvanfosson's answer re primary key, that is one possibility. You will also get this behavior if your select statement uses a view instead of a direct table.
you can get around this by generating or hand-coding the xml in the .xsd file, but that is a fairly hardcore solution ;-) | WHY is - 'GENERATE INSERT UPDATE AND SELECT STATEMENT' greyed out? | [
"",
"sql",
"visual-studio-2008",
"ms-access",
"databound-controls",
""
] |
Under Windows is there a way to modify a file/executable opened by another process using c++? | The OS holds the executable file open for read-only sharing as long as it's running, so there's no way to modify it directly. You can, however, open it for *reading* (if you specify read-sharing in your `CreateFile` call), and make a modified copy of it, while it's running.
I don't know if that's what you had in mind, but if it's your own program you're doing this to, you can start the new copy and have it pick up where the previous one left off... not straightforward, but not all that difficult either. | > Is there a way to modify an open executable in windows?
No.
> Is there a way to modify an open file in windows using c++?
Yes. If it has been opened with the proper share permissions. See <http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx> FILE\_SHARE\_WRITE | modify an open file c++ | [
"",
"c++",
"winapi",
""
] |
I've used Spring and Spring.NET quite a bit, but I would like to see what else is out there. Can anyone recommend a good Java or .NET framework that I could try to learn? | [Here](http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx) is a list of IoC containers from the good Mr. Hanselman... | Castle Windsor is very popular, you could do worse than learn that. | What DI/IoC framework should I learn next? | [
"",
"java",
".net",
"dependency-injection",
"inversion-of-control",
""
] |
I am trying to insert all values of one table into another. But the insert statement accepts values, but i would like it to accept a select \* from the initial\_Table. Is this possible? | The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "\*" though:
```
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
-- optionally WHERE ...
```
I'd better clarify this because for some reason this post is getting a few down-votes.
The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new\_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.
You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists. | Try this:
```
INSERT INTO newTable SELECT * FROM initial_Table
``` | Insert all values of a table into another table in SQL | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I'm trying to decide whether to use a custom ASP.Net Ajax Extender or jQuery to perform a simple web service call. The web service method accepts a customer ID and returns the customer name. I'm leaning towards jQuery because of it's simplicity. The only problem is that due to my company's IE7 Group Policy settings, the first time jQuery invokes a web service it prompts the user with the following message:
> A script is accessing some software
> (an ActiveX control) on this page
> which has been marked safe for
> scripting. Do you want to allow this?
The Extender does not cause this message to be displayed. I'm assuming the ASP.Net Ajax library has some javascript voodoo that suppresses it. So my questions is, **How do I suppress this message using javascript?**
Here's my aspx markup:
```
<h1>
Finder Test</h1>
<div>
<h2>
Extender</h2>
Customer ID:
<asp:TextBox ID="txtCustomerId" runat="server" MaxLength="9" Width="4em" />
<belCommon:FinderExtender ID="extCustomerId" runat="server" TargetControlID="txtCustomerId"
ResultLabelID="lblResult" ServicePath="~/Customer.asmx" ServiceMethod="Name" />
<asp:Label ID="lblResult" runat="server" />
</div>
<div>
<h2>
jQuery</h2>
Customer ID:
<input id="txtCustomerId2" type="text" maxlength="9" style="width: 4em;" value="0000" />
<span id="txtCustomerName2"></span>
<script type="text/javascript">
$(document).ready(function()
{
$("#txtCustomerId2").change(
function()
{
updateCustomerDescription(this.value, "txtCustomerName2");
}).change();
});
function updateCustomerDescription(id, descriptionControlId)
{
// if we don't have a value, then don't bother calling the web service
if (id == null || id.length == 0)
{
$("#" + descriptionControlId).text("");
return;
}
jsonAjax("customer.asmx/Name", "{'id':'" + id + "'}", true,
function(result)
{
var name = result.d == null ? "" : result.d;
$("#" + descriptionControlId).text(name);
}, null);
}
function jsonAjax(url, data, async, onSuccess, onFailed)
{
$.ajax({
async: async,
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
error: onFailed
});
}
</script>
</div>
```
[Update]
I'm assuming that the ActiveX control referenced in the message is XMLHttpRequest. I'm also assuming that the internals of jQuery and ASP.Net Ajax both use it for IE7.
[Update]
The difference appears to be in how ASP.Net Ajax and jQuery construct an instance of XMLHttpRequest.
ASP.Net Ajax (thanks @Jesse Dearing):
```
window.XMLHttpRequest = function window$XMLHttpRequest() {
var progIDs = [ 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP' ];
for (var i = 0, l = progIDs.length; i < l; i++) {
try {
return new ActiveXObject(progIDs[i]);
}
catch (ex) { }
}
return null;
}
}
```
jQuery 1.3.2:
```
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
// This function can be overriden by calling jQuery.ajaxSetup
xhr:function(){
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
}
``` | I solved this by overriding jQuery's xhr function as so:
```
function overrideJqueryXhr()
{
$.ajaxSetup({
xhr: function()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
var progIDs = ['Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var i = 0; i < progIDs.length; i++)
{
try
{
var xmlHttp = new ActiveXObject(progIDs[i]);
return xmlHttp;
}
catch (ex)
{
}
}
return null;
}
}
});
}
```
This function tells jQuery to create an instance of the XMLHttpRequest class for non-IE browsers, and then creates an ActiveX object the MS Ajax way for IE. It tries the latest version first, Msxml2.XMLHTTP.3.0, then Msxml2.XMLHTTP and finally Microsoft.XMLHTTP. | This doesn't sound right to me. If there is a security policy in place, you should not be able to override it with javascript.
I would double check the two pages and see if they both really access the same ActiveX control. I assume that the pages are coming from the same host (so there's no issue of different WinInet trust zones). | How do you suppress IE7 ActiveX messages using javascript? | [
"",
"asp.net",
"javascript",
"jquery",
"ajax",
"activex",
""
] |
Say I have a string in php, that prints out to a text file like this:
nÖ§9q1Fª£
How do I get the byte codes of this to my text file rather than the funky ascii characters? | Use the ord function
<http://ca.php.net/ord>
eg.
```
<?php
$var = "nÖ§9q1Fª£ˆæÓ§Œ_»—Ló]j";
for($i = 0; $i < strlen($var); $i++)
{
echo ord($var[$i])."<br/>";
}
?>
``` | If You wish to get the string as an array of integer codes, there's a nice one-liner:
```
unpack('C*', $string)
```
Beware, the resulting array is indexed from 1, not from 0! | How do I get the byte values of a string in PHP? | [
"",
"php",
"string",
"ascii",
"bytecode",
""
] |
So I admit that I'm new to javascript and that I come from a C.+ background ("Hi, I'm Bob, I'm a class-based static language user", *chorus* "hi Bob!").
I find that I often end up writing functions like:
```
function someFunc()
{
if (arguments.length === 0 ){
...
} else {
...
}
}
```
(where there might be three such cases). Or, alternatively, I write the difference into the name:
```
function someFuncDefault() { ... };
function someFuncRealArg(theArg) { ... };
```
(Substitute "RealArg" for some semantically contentful phrase).
Is there a better pattern for this kind of thing? | Have a look at [this post](http://ejohn.org/blog/javascript-method-overloading/). | I don't know that I would do it this way, but it seems like it might make your code mildly less unmanageable:
```
function someFunc() {
switch (arguments.length) {
case 0: noArgs();
case 1: oneArg(arguments[0]);
case 2: twoArgs(arguments[0], arguments[1]);
}
function noArgs() {
// ...
}
function oneArg(a) {
// ...
}
function twoArgs(a, b) {
// ...
}
}
```
Another example might be:
```
function someFunc(a, b) {
if ('string' == typeof a) {
// ...
} else if ('number' == typeof a) {
// ...
}
}
```
And of course you can probably create something quite unmanageable by combining both examples (using conditions to determine behaviour based on number of arguments and types of arguments). | "method overloading" in javascript | [
"",
"javascript",
"overriding",
""
] |
I am trying to build a site with news links that can be voted, I have the following code:
```
case 'vote':
require_once('auth/auth.php');
if(Auth::isUserLoggedIn())
{
require_once('data/article.php');
require_once('includes/helpers.php');
$id = isset($_GET['param'])? $_GET['param'] : 0;
if($id > 0)
{
$article = Article::getById($id);
$article->vote();
$article->calculateRanking();
}
if(!isset($_SESSION)) session_start();
redirectTo($_SESSION['action'], $_SESSION['param']);
}
else
{
Auth::redirectToLogin();
}
break;
```
The problem right now is how to check so the same user does not vote twice, here is the article file:
```
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
require_once(SITE_ROOT.'includes/exceptions.php');
require_once(SITE_ROOT.'data/model.php');
require_once(SITE_ROOT.'data/comment.php');
class Article extends Model
{
private $id;
private $user_id;
private $url;
private $title;
private $description;
private $ranking;
private $points;
function __construct($title = ' ', $description = ' ', $url = ' ', $username = ' ', $created = ' ', $modified = '') {
$this->setId(0);
$this->setCreated($created);
$this->setModified($modified);
$this->setUsername($username);
$this->setUrl($url);
$this->setTitle($title);
$this->setDescription($description);
$this->setRanking(0.0);
$this->setPoints(1);
}
function getId(){
return $this->id;
}
private function setId($value){
$this->id = $value;
}
function getUsername(){
return $this->username;
}
function setUsername($value){
$this->username = $value;
}
function getUrl(){
return $this->url;
}
function setUrl($value){
$this->url = $value;
}
function getTitle()
{
return $this->title;
}
function setTitle($value) {
$this->title = $value;
}
function getDescription() {
return $this->description;
}
function setDescription($value)
{
$this->description = $value;
}
function getPoints()
{
return $this->points;
}
function setPoints($value)
{
$this->points = $value;
}
function getRanking()
{
return $this->ranking;
}
function setRanking($value)
{
$this->ranking = $value;
}
function calculateRanking()
{
$created = $this->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
$time = $diff['days'] * 24;
$time += $diff['hours'];
$time += ($diff['minutes'] / 60);
$time += (($diff['seconds'] / 60)/60);
$base = $time + 2;
$this->ranking = ($this->points - 1) / pow($base, 1.5);
$this->save();
}
function vote()
{
$this->points++;
$this->save();
}
function getUrlDomain()
{
/* We extract the domain from the URL
* using the following regex pattern
*/
$url = $this->getUrl();
$matches = array();
if(preg_match('/http:\/\/(.+?)\//', $url, $matches))
{
return $matches[1];
}
else
{
return $url;
}
}
function getTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo( "Ending date/time is earlier than the start date/time");
}
}
else
{
echo( "Invalid date/time data detected");
}
return( false );
}
function getElapsedDateTime()
{
$db = null;
$record = null;
$record = Article::getById($this->id);
$created = $record->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
//echo 'new date is '.date('F d, Y h:i:s A');
//print_r($diff);
if($diff['days'] > 0 )
{
return sprintf("hace %d dias", $diff['days']);
}
else if($diff['hours'] > 0 )
{
return sprintf("hace %d horas", $diff['hours']);
}
else if($diff['minutes'] > 0 )
{
return sprintf("hace %d minutos", $diff['minutes']);
}
else
{
return sprintf("hace %d segundos", $diff['seconds']);
}
}
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
throw $e;
}
}
function delete()
{
try
{
$db = parent::getConnection();
if($this->id != 0)
{ ;
/*$comments = $this->getAllComments();
foreach($comments as $comment)
{
$comment->delete();
}*/
$this->deleteAllComments();
$query = "delete from articles where id = $this->id";
}
parent::execSql($query);
}
catch(Exception $e){
throw $e;
}
}
static function getAll($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$db = null;
$results = null;
$records = array();
$query = "select id, created, modified, username, url, title, description, points, ranking from articles $conditions";
try
{
$db = parent::getConnection();
$results = parent::execSql($query);
while($row = $results->fetch_assoc())
{
$r_id = $row['id'];
$r_created = $row['created'];
$r_modified = $row['modified'];
$r_title = $row['title'];
$r_description = $row['description'];
if(!get_magic_quotes_gpc())
{
$r_title = stripslashes($r_title);
$r_description = stripslashes($r_description);
}
$r_url = $row['url'];
$r_username = $row['username'];
$r_points = $row['points'];
$r_ranking = $row['ranking'];
$article = new Article($r_title, $r_description , $r_url, $r_username, $r_created, $r_modified);
$article->id = $r_id;
$article->points = $r_points;
$article->ranking = $r_ranking;
$records[] = $article;
}
parent::closeConnection($db);
}
catch(Exception $e)
{
throw $e;
}
return $records;
}
static function getById($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select id, username, created, modified, title, url, description, points, ranking from articles where id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Record not found', EX_RECORD_NOT_FOUND);
}
$row = $results->fetch_assoc();
parent::closeConnection($db);
if(!get_magic_quotes_gpc())
{
$row['title'] = stripslashes($row['title']);
$row['description'] = stripslashes($row['description']);
}
$article = new Article($row['title'], $row['description'], $row['url'], $row['username'], $row['created'], $row['modified']);
$article->id = $row['id'];
$article->points = $row['points'];
$article->ranking = $row['ranking'];
return $article;
}
catch (Exception $e){
throw $e;
}
}
static function getNumberOfComments($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select count(*) as 'total' from comments where article_id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Comments Count Query Query Failed', EX_QUERY_FAILED);
}
$row = $results->fetch_assoc();
$total = $row['total'];
parent::closeConnection($db);
return $total;
}
catch (Exception $e){
throw $e;
}
}
function deleteAllComments()
{/*
* Return one record from the database by its id */
$db = null;
try
{
$db = parent::getConnection();
$query = "delete from comments where article_id = $this->id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Deletion Query Failed', EX_QUERY_FAILED);
}
parent::closeConnection($db);
}
catch (Exception $e){
throw $e;
}
}
function getAllComments($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$conditions = "where article_id = $this->id";
$comments = Comment::getAll($conditions);
return $comments;
}
static function getTestData($url)
{
$page = file_get_contents($url);
}
}
?>
```
Any suggestion or comment is appreciated, Thanks. | make another table user\_votes for example with structure:
user\_id int not null
article\_id int not null
primary key (user\_id, article\_id)
in vote function first try to insert and if insert is successfull then increase $this->points | Have a table that keeps track of a user's vote for an article (something like UserID,ArticleID,VoteTimeStamp). Then you can just do a check in your `$article->vote();` method to make sure the currently logged in user doesn't have any votes for that article.
If you want to keep thing fast (so you don't always have to use a join to get vote counts) you could have a trigger (or custom PHP code) that when adding/removing a vote updates the total vote count you currently keep in the article table. | How can I implement a voting system on my site limiting votes to a single vote? | [
"",
"php",
""
] |
I am debugging a problem in Django with **Pydev**.
I **can set breakpoint** in my django **project code** with out a problem.
However I **can't set breakpoints** in the **Django library source code** (in site-packages).
The PyDev debugger user interface in this case **simply does nothing when I click** to set the breakpoint and does not break at that location when I run the debugger.
Am I missing some PyDev configuration? In other debuggers I have used, this behavior indicates a problem relating the debug information with the source code.
Any ideas on next steps would be a help.
I also have the **site-packages** configured in PyDev to be in my **PYTHONPATH**
I am using Eclipse on Max OS X if that helps.
Thanks | Have you imported the Django source as a project? To do that you just create a new PyDev project and set it's location to the Django source folder. | Hey, this is timely! Eric Moritz just announced the release of an interesting new way to debug views using pdb called [django-viewtools](http://eric.themoritzfamily.com/2009/02/17/announcing-django-viewtools/). | Eclipse PyDev: setting breakpoints in site-packages source | [
"",
"python",
"django",
"eclipse",
"pydev",
""
] |
I have a developer tool that modifies the local file system using php. These projects are often checked out from SVN. The issue that I would like to avoid is the moving / deleting / renaming of version controlled directoires - and the breakage that occurs to a checked out SVN when doing those alterations locally.
Is there a simple way to apply the SVN commands (move add, delete, rename etc) when I also perform the matching file system operations?
Or is it easier just to delete .svn dirs if found in move / rename targets?
To clarify this:
A checked out svn that has a structure of:
somedir/
--foo/
--cheese/
User 1 alters this file system structure (using the dev tool), renaming the 'foo' dir (which is under version control) to 'modified', when they go to commit their changes the svn will error due to the change in name not being done via SVN commands.
This could be running on a variety of development servers (usually desktop machines running apache on win or mac)
Dont want to ignore or disconnect from the svn. | In your PHP file, you could use the `svn` commands via `exec()`
```
<?php
$Output = '';
$ExitCode = 0;
exec('svn mv "'.$Current.'" "'.$New.'"', $Output, $ExitCode);
```
`$Output` is the output of the command and `$ExitCode` will be `0` if the command was successful.
Keep in mind however, that for security reasons the `exec()` command might be disabled on some systems. If you have control of your `php.ini` file, you can choose to enable/disable it. | Programmatically you may be better off just removing .svn folders. It probably is just one or two lines of code.
Another thing to try, why dont you export the module? that way you dont get .svn folders.
Also note that you can script all svn commands and run them. | Manage local SVN file structures with PHP | [
"",
"php",
"svn",
"filesystems",
""
] |
I understand that you can easily mix groovy&java, clojure&java, whateverJvmLang&java.
Does this also mean I can have clojure and groovy code interact as well? If I use Grails or jRoR, can I also make use of clojure in that environment? | As long as the languages in question actually produce Java classes (that is: classes that are known to the Java platform, not necessarily written in the Java language), then yes: they can easily interact with each other.
At least for Groovy I know that it's entirely possible to write classes that can be used from "normal" Java code. | Clojure can be compiled to .class files via `gen-class` and used from Java like any other code; see [here](http://clojure.org/compilation). | Can you mix the JVM languages? ie: Groovy & Clojure | [
"",
"java",
"groovy",
"jvm",
"clojure",
"mixing",
""
] |
I am implementing an undo/redo buffer with generic LinkedList.
In this state:
[Top]
state4 (undone)
state3 (undone)
state2 <-- current state
state1
[bottom]
When I do a Push, I would like to remove all states after the current one, and push the new one.
My current bypass is to do `while (currentState != list.last), list.removeLast();` but it sucks
LinkedList just support Remove, RemoveFirst & removeLast...
I would like something like RemoveAllNodesAfter(LinkedListNode ...) ?
How can I code that nicely, without iterating throught all nodes ? Maybe with extensions ?... | I can't see anything in the standard `LinkedList<T>` which lets you do this. You could look in [PowerCollections](http://www.codeplex.com/PowerCollections) and the [C5 collections](http://www.itu.dk/research/c5/) if you want - or just roll your own `LinkedList` type. It's one of the simpler collections to implement, especially if you can add functionality in a "just in time" manner. | Linked List (especially the singly linked list) is one of the most basic fundamental collection structures. I'm certain that you could probably implement it (and add the behavior your need) with little effort.
In reality, you don't actually need a collection class to manage the list. You could manage the nodes without a collection class.
```
public class SingleLinkedListNode<T>
{
private readonly T value;
private SingleLinkedListNode<T> next;
public SingleLinkedListNode(T value, SingleLinkedListNode<T> next)
{
this.value = value;
}
public SingleLinkedListNode(T value, SingleLinkedListNode<T> next)
: this(value)
{
this.next = next;
}
public SingleLinkedListNode<T> Next
{
get { return next; }
set { next = value; }
}
public T Value
{
get { return value; }
}
}
```
If you're interested in a possible implementation, however, here's a somewhat simple SingleLinkedList implementation.
```
public class SingleLinkedList<T>
{
private SingleLinkedListNode<T> head;
private SingleLinkedListNode<T> tail;
public SingleLinkedListNode<T> Head
{
get { return head; }
set { head = value; }
}
public IEnumerable<SingleLinkedListNode<T>> Nodes
{
get
{
SingleLinkedListNode<T> current = head;
while (current != null)
{
yield return current;
current = current.Next;
}
}
}
public SingleLinkedListNode<T> AddToTail(T value)
{
if (head == null) return createNewHead(value);
if (tail == null) tail = findTail();
SingleLinkedListNode<T> newNode = new SingleLinkedListNode<T>(value, null);
tail.Next = newNode;
return newNode;
}
public SingleLinkedListNode<T> InsertAtHead(T value)
{
if (head == null) return createNewHead(value);
SingleLinkedListNode<T> oldHead = Head;
SingleLinkedListNode<T> newNode = new SingleLinkedListNode<T>(value, oldHead);
head = newNode;
return newNode;
}
public SingleLinkedListNode<T> InsertBefore(T value, SingleLinkedListNode<T> toInsertBefore)
{
if (head == null) throw new InvalidOperationException("you cannot insert on an empty list.");
if (head == toInsertBefore) return InsertAtHead(value);
SingleLinkedListNode<T> nodeBefore = findNodeBefore(toInsertBefore);
SingleLinkedListNode<T> toInsert = new SingleLinkedListNode<T>(value, toInsertBefore);
nodeBefore.Next = toInsert;
return toInsert;
}
public SingleLinkedListNode<T> AppendAfter(T value, SingleLinkedListNode<T> toAppendAfter)
{
SingleLinkedListNode<T> newNode = new SingleLinkedListNode<T>(value, toAppendAfter.Next);
toAppendAfter.Next = newNode;
return newNode;
}
public void TruncateBefore(SingleLinkedListNode<T> toTruncateBefore)
{
if (head == toTruncateBefore)
{
head = null;
tail = null;
return;
}
SingleLinkedListNode<T> nodeBefore = findNodeBefore(toTruncateBefore);
if (nodeBefore != null) nodeBefore.Next = null;
}
public void TruncateAfter(SingleLinkedListNode<T> toTruncateAfter)
{
toTruncateAfter.Next = null;
}
private SingleLinkedListNode<T> createNewHead(T value)
{
SingleLinkedListNode<T> newNode = new SingleLinkedListNode<T>(value, null);
head = newNode;
tail = newNode;
return newNode;
}
private SingleLinkedListNode<T> findTail()
{
if (head == null) return null;
SingleLinkedListNode<T> current = head;
while (current.Next != null)
{
current = current.Next;
}
return current;
}
private SingleLinkedListNode<T> findNodeBefore(SingleLinkedListNode<T> nodeToFindNodeBefore)
{
SingleLinkedListNode<T> current = head;
while (current != null)
{
if (current.Next != null && current.Next == nodeToFindNodeBefore) return current;
current = current.Next;
}
return null;
}
}
```
Now you can do this:
```
public static void Main(string[] args)
{
SingleLinkedList<string> list = new SingleLinkedList<string>();
list.InsertAtHead("state4");
list.AddToTail("state3");
list.AddToTail("state2");
list.AddToTail("state1");
SingleLinkedListNode<string> current = null;
foreach (SingleLinkedListNode<string> node in list.Nodes)
{
if (node.Value != "state2") continue;
current = node;
break;
}
if (current != null) list.TruncateAfter(current);
}
```
The thing is depending on your situation, it's not much better than this:
```
public static void Main(string[] args)
{
SingleLinkedListNode<string> first =
new SingleLinkedListNode<string>("state4");
first.Next = new SingleLinkedListNode<string>("state3");
SingleLinkedListNode<string> current = first.Next;
current.Next = new SingleLinkedListNode<string>("state2");
current = current.Next;
current.Next = new SingleLinkedListNode<string>("state1");
current = first;
while (current != null)
{
if (current.Value != "state2") continue;
current.Next = null;
current = current.Next;
break;
}
}
```
This eliminates the need for the collection class altogether. | C# - LinkedList - How to remove all nodes after specified node? | [
"",
"c#",
"linked-list",
""
] |
I am interested in writing a very minimalistic compiler.
I want to write a small piece of software (in C/C++) that fulfills the following criteria:
* output in ELF format (\*nix)
* input is a single textfile
* C-like grammar and syntax
* no linker
* no preprocessor
* very small (max. 1-2 KLOC)
Language features:
* native data types: char, int and floats
* arrays (for all native data types)
* variables
* control structures (if-else)
* functions
* loops (would be nice)
* simple algebra (div, add, sub, mul, boolean expressions, bit-shift, etc.)
* inline asm (for system calls)
Can anybody tell me how to start? I don't know what parts a compiler consists of (at least not in the sense that I just could start right off the shelf) and how to program them. Thank you for your ideas. | Firstly, you need to decide whether you are going to make a compiler or an interpreter. A compiler translates your code into something that can be run either directly on hardware, in an interpreter, or get compiled into another language which then is interpreted in some way. Both types of languages are turing complete so they have the same expressive capabilities. I would suggest that you create a compiler which compiles your code into either .net or Java bytecode, as it gives you a very optimized interpreter to run on as well as a lot of standard libraries.
Once you made your decision there are some common steps to follow
1. **Language definition** Firstly, you have to define how your language should look syntactically.
2. **Lexer** The second step is to create the keywords of your code, known as tokens. Here, we are talking about very basic elements such as numbers, addition sign, and strings.
3. **Parsing** The next step is to create a grammar that matches your list of tokens. You can define your grammar using e.g. a context-free grammar. A number of tools can be fed with one of these grammars and create the parser for you. Usually, the parsed tokens are organized into a parse tree. A parse tree is the representation of your grammar as a data structure which you can move around in.
4. **Compiling or Interpreting** The last step is to run some logic on your parse tree. A simple way to make your own interpreter is to create some logic associated to each node type in your tree and walk through the tree either bottom-up or top-down. If you want to compile to another language you can insert the logic of how to translate the code in the nodes instead.
Wikipedia is great for learning more, you might want to start [here](http://en.wikipedia.org/wiki/Lexing).
Concerning real-world reading material I would suggest "Programming language processors in JAVA" by David A Watt & Deryck F Brown. I used that book in my compilers course and learning by example is great in this field. | With all that you hope to accomplish, the most challenging requirement might be "very small (max. 1-2 KLOC)". I think your first requirement alone (generating ELF output) might take well over a thousand lines of code by itself.
One way to simplify the problem, at least to start with, is to generate code in assembly language text that you then feed into an existing assembler ([nasm](http://www.nasm.us/) would be a good choice). The assembler would take care of generating the actual machine code, as well as all the ELF specific code required to build an actual runnable executable. Then your job is reduced to language parsing and assembly code generation. When your project matures to the point where you want to remove the dependency on an assembler, you can rewrite this part yourself and plug it in at any time.
If I were you, I might start with an assembler and build pieces on top of it. The simplest "compiler" might take a language with just a few very simple possible statements:
```
print "hello"
a = 5
print a
```
and translate that to assembly language. Once you get that working, then you can build a lexer and parser and abstract syntax tree and code generator, which are most of the parts you'll need for a modern block structured language.
Good luck! | Compiler-Programming: What are the most fundamental ingredients? | [
"",
"c++",
"c",
"compiler-construction",
"low-level",
""
] |
I'm working on a web application. There is one place where the user can upload files with the HTTP protocol. There is a choice between the classic HTML file upload control and a Java applet to upload the files.
The classic HTML file upload isn't great because you can only select one file at a time, and it's quite hard to get any progress indication during the actual upload (I finally got it using a timer refreshing a progress indicator with data fetched from the server via an AJAX call). The advantage: it's always working.
With the Java applet I can do more things: select multiple files at once (even a folder), compress the files, get a real progress bar, drag'n'drop files on the applet, etc...
BUT there are a few drawbacks:
* it's a nightmare to get it to work properly on Mac Safari and Mac Firefox (Thanks Liveconnect)
* the UI isn't exactly the native UI and some people notice that
* the applet isn't as responsive as it should (could be my fault, but everything looks ok to me)
* there are bugs in the Java `UrlConnection` class with HTTPS, so I use the Apache common HTTP client to do the actual HTTP upload. It's quite big a package and slows down the download of the .jar file
* the Apache common HTTP client has sometimes trouble going through proxies
* the Java runtime is quite big
I've been maintaining this Java applet for a while but now I'm fed up with all the drawbacks, and considering writing/buying a completely new component to upload theses files.
**Question**
If you had the following requirements:
* upload multiple files easily from a browser, through HTTP or HTTPS
* compress the files to reduce the upload time
* upload should work on any platform, with native UI
* must be able to upload huge files, up to 2gb at least
* you have carte blanche on the technology
**What technology/compontent would you use?**
---
Edit :
* Drag'n'Drop of files on the component would be a great plus.
* It looks like there are a lot of issues related to bugs with the Flash Player ([swfupload known issues](http://demo.swfupload.org/Documentation/#knownissues)). Proper Mac support and upload through proxies with authentication are options I can not do without. This would probably rule out all Flash-based options :-( .
* I rule out all HTML/Javascript-only options because you can't select more than one file at a time with the classic HTML control. It's a pain to click n-times the "browse" button when you want to select multiple files in a folder. | **OK this is my take on this**
I did some testing with swfupload, and I have my previous experience with Java, and my conclusion is that **whatever technology is used there is no perfect solution to do uploads on the browser** : you'll always end up with bugs when uploading huge files, going through proxies, with ssl, etc...
**BUT :**
* a flash uploader (a la swfupload) is really lightweight, doesn't need authorization from the user and has a native interface which is REALLY cool, me thinks
* a java uploader needs authorization but you can do whatever you want with the files selected by the user (aka compression if needed), and drag and drop works well. Be prepared for some epic bugs debuggin' though.
* I didn't get a change to play with Silverlight as long as I'd like maybe that's the real answer, though the technology is still quite young so ... I'll edit this post if I get a chance to fiddle a bit with Silverlight
Thanks for all the answers !! | I implemented something very recently in Silverlight.
Basically uses HttpWebRequest to send a chunk of data to a GenericHandler.
On the first post, 4KB of data is sent. On the 2nd chunk, I send another 4K chunk.
When the 2nd chunk is received, I calculate the round trip it took between first and 2nd chunk and so now
the 3rd chunk when sent will know to increase speed.
Using this method I can upload files of ANY size and I can resume.
Each post I send along this info:
[PARAMETERS]
[FILEDATA]
Here, parameters contain the following:
[Chunk #]
[Filename]
[Session ID]
After each chunk is received, I send a response back to my Silverlight saying how fast it took so that it can now send a larger
chunk.
Hard to put my explaination without code but that's basically how I did it.
At some point I will put together a quick writeup on how I did this. | Best way to upload multiple files from a browser | [
"",
"java",
"flash",
"silverlight",
"http",
"upload",
""
] |
Greetings everyone. This is my first question here at stackoverflow so please bear with me.
My programming class this semester is Java; last semester was C++. My Java teacher feels (justifiably, I think) that it is very important for we students to understand the mechanics of memory management.
Since Java has automatic garbage collection, he has seen fit to give us an assignment in which we must write a very basic program in C++ that creates a two-dimensional array using pointers. Specifically, we are to first create an array of pointers; each pointer in the first array should reference its own array of integers. Then we must deallocate the memory associated with the two arrays.
This assignment is supposed to consist of two functions: one to allocate the 2-D array, and a second to deallocate. I just want to make sure that the following code is logically sound before I proceed.
I'm sure this all seems very simple, but the hitch is that my C++ teacher spent all of two days on pointers. While I *somewhat* understand the mechanics, I am pretty clueless on implementation. That being said, the following is a very rough start. Is this logically sound? Am I completely off the mark? My most profound thanks in advance for any help.
EDIT: I have created a new question with updated code. You can view it by clicking [Here](https://stackoverflow.com/questions/550223/update-c-pointer-snippet). | When you use
```
int* i = new int;
```
you pair it with
```
delete i;
```
and when you use
```
int* i = new int [12];
```
you pair it with
```
delete [] i;
```
If there are brackets in the new, there should be brackets in the delete. Otherwise, your program looks reasonable to me, except that you haven't implemented those two functions that your prof wants you to. | Looks correct to me, with one exception - when you delete arrays you need the following syntax:
```
delete [] arrayName;
``` | C++ Pointer Snippet | [
"",
"c++",
"pointers",
""
] |
I'm trying to design a solid server side architecture and came up with this :
<http://www.monsterup.com/image.php?url=upload/1235488072.jpg>
The client side only talks to a single server file called process.php, where user rights are checked; and where the action is being dispatched. The business classes then handle the business logic and perform data validation. They all have contain a DataAccessObject class that performs the db operations.
Could you point the different weaknesses such an architecture may have? As far as security, flexibility, extensiveness, ...? | Your architecture isn't perfect. It never will be perfect. Ever. Being perfect is impossible. This is the nature of application development, programming, and the world in general. A requirement will come in to add a feature, or change your business logic and you'll return to this architecture and say "What in the world was I thinking this is terrible." (Hopefully... otherwise you probably haven't been learning anything new!)
Take an inventory of your goals, should it be:
> this architecture perfect
or instead:
> this architecture functions where I need it to and allows me to [get stuff done](http://www.joelonsoftware.com/items/2007/06/05.html) | One way that you could improve this is to **add a view layer**, using a template engine such as Smarty, or even roll-your-own. The action classes would prepare the data, assign it to the template, then display the template itself.
That would help you to *separate your business logic from your HTML*, making it easier to maintain.
This is a common way to design an application.
Another thing you could do is **have another class handle the action delegation**. It really depends on the complexity of your application, though.
The book [PHP Objects, Patterns and Practice](https://rads.stackoverflow.com/amzn/click/com/1590599098) can give you a real leg-up on application architecture. | is my php architecture solid? | [
"",
"php",
"architecture",
""
] |
I have a system tray icon that receives incoming phone calls. When a call comes in, I want to send the phone number into a web app that does stuff on that phone number. We can launch the web app with the phone number in a query string, but if I launch a new window for every call, it will junk up the user's computer with lots of browser instances, would not preserve the location/size the user moved the browser window to, and would take longer than just refreshing the page. Instead, I'd like to make the Win32 app re-use the same IE browser window and just send the web app the new phone number every time a new call comes in. I'm envisioning somehow sending a Windows message, or somehow instructing the IE browser to run a certain javascript event with some data? I can see why doing the reverse (javascript out to Win32) would be a security issue, but this would be just sending a message from Win32 to javascript.
So I'm specifically NOT asking how to do what's been answered in this question: [How to Interact Between Web App and Windows Form Application](https://stackoverflow.com/questions/126048/how-to-interact-between-web-app-and-windows-form-application)
That user was asking how to launch a Win32 app from Javascript and pass data to the win32 app. Roughly, I need to do the opposite. I need to send data from a Win32 app into a running javascript program.
Note also that I'm not asking how to launch one IE window with arguments to Javascript one time; I can easily do that with query strings. What I'm asking is how can I / is it possible to pass data from a running Win32 app outside the browser to a running Javascript app inside a browser window. | Since you can send the phone number to the site through a querystring, all you really need to do is tell IE to navigate to a URL of your choosing.
To that end, you can use what is in this KB article to help you find the instance of IE you want to connect to.
<http://support.microsoft.com/kb/299356/de>
Granted, its in Visual J++ of all things, but since you are interacting through COM Automation, the calls should be easy to translate.
Once you have the instance of IE (in the form of an IWebBrowser2 interface implementation) you can simply call the Navigate or Navigate2 method with the URL you need (with the phone number in the query string of course). | You should be able to find the handle of the IE window, and then send messages (keypresses perhaps) to it. Use a bit of javascript to capture all keypress activity and you have a very simple method to transfer information.
It won't be easy (the devil is in the details - issues of focus, etc) but it should be possible.
-Adam | How might I send messages (strings) from a Win32 app to a Javascript program running in an existing IE window? | [
"",
"javascript",
"winapi",
""
] |
**EDIT**: Duplicate of [How do I return random numbers as a column in SQL Server 2005?](https://stackoverflow.com/questions/94906/how-do-i-return-random-numbers-as-a-column-in-sql-server-2005)
Hello
How can I generate random numbers in mssql server 2005.
for example: when I select 500rows from table, each row must have one generated random number, numbers must be generated at runtime
UPDATE: I need the fastest method, generate numbers from large tables, datepart, same magic computations is realatively slow with big amount of rows
UPDATE thanks for answers, but o finally used this solution
```
SELECT ABS(CHECKSUM(NewId())) % 10 - 5 AS Random
```
for random numbers from -5 to 5 and bonus is approximately the same number of occurances for each number | ```
SELECT TOP 500
CONVERT(INT, CONVERT(VARBINARY(16), NEWID()))
FROM
dbo.MyTable
``` | I love this trick, its awesome ...
```
-- 500 random numbers from 0 to 499
select top 500 ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 500 from sysobjects
``` | Random numbers from database | [
"",
"sql",
"random",
""
] |
I cannot get my code to work :/ | Here's a quick example from Microsoft.
```
static TCHAR hdrs[] =
_T("Content-Type: application/x-www-form-urlencoded");
static TCHAR frmdata[] =
_T("name=John+Doe&userid=hithere&other=P%26Q");
static LPSTR accept[2]={"*/*", NULL};
// for clarity, error-checking has been removed
HINTERNET hSession = InternetOpen("MyAgent",
INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect(hSession, _T("ServerNameHere"),
INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = HttpOpenRequest(hConnect, "POST",
_T("FormActionHere"), NULL, NULL, accept, 0, 1);
HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
// close any valid internet-handles
```
The example comes from [here](http://support.microsoft.com/kb/165298). | Eventually I found some working example on the [web](http://forum.powweb.com/showthread.php?t=69737)
```
static char szRawData[5000];
memset(szRawData, 0x11, sizeof(szRawData));
//
// CIHandle is just a wrapper class for HINTERNET, that closes handle in destructor
//
CIHandle hIntrn = InternetOpen( "LiveUpdate"),
INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY,
NULL,
NULL,
0);
if (!hIntrn)
return printf("No Internet connection: %li.\n", GetLastError());
CIHandle hConn = InternetConnect( hIntrn,
"65.254.250.104",
INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
0,
NULL);
if (!hConn)
return printf("Connection to update server failed: %li.\n", GetLastError());
DWORD dwOpenRequestFlags = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_KEEP_CONNECTION |
INTERNET_FLAG_NO_AUTO_REDIRECT |
INTERNET_FLAG_NO_COOKIES |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_RELOAD;
CIHandle hReq = HttpOpenRequest(hConn,
"POST",
"upload.php",
"HTTP/1.0",
NULL,
NULL,
dwOpenRequestFlags,
NULL);
ZString strBoundary = "---------------------------autoupdater";
ZString strContentHeader = "Host: www.mydomain_at_powweb.com\r\n"
"Content-Type: multipart/form-data; boundary=";
strContentHeader+=strBoundary;
HttpAddRequestHeaders(hReq, strContentHeader, strContentHeader.length(), HTTP_ADDREQ_FLAG_ADD);
ZString strHeaders;
strHeaders.precache(16384);
sprintf(strHeaders,
"--%s\r\n"
"Content-Disposition: form-data; name=\"userfile\"; "
"filename=\"test.raw\"\r\n"
"Content-Type: application/octet-stream\r\n\r\n",
(LPCTSTR)strBoundary);
tCharSeq s;//this is a just a dynamic array of bytes;
//
// append headers and file to request:
//
s.precache(16384);
s.append(strHeaders.length(), strHeaders);
//append with file data:
s.append(2000, szRawData); //<------------------- depending on this size, SendRequest fails.
//trailing end of data:
s.append(4,"\r\n--");
s.append(strBoundary.length(), (LPTSTR)strBoundary);
s.append(4,"--\r\n");
InternetSetOption(hReq, INTERNET_OPTION_USERNAME, "username\0", 9);
InternetSetOption(hReq, INTERNET_OPTION_PASSWORD, "password\0", 9);
if (!HttpSendRequest(hReq, NULL, 0, (void*)s.getBuffer(), s.length()))
return printf("HttpSendRequest failed: %li.\n", GetLastError());
``` | Is there any good example of http upload using WinInet c++ library | [
"",
"c++",
"http",
"upload",
"wininet",
""
] |
I need to allow a user to click a link in "page-1.htm" and open a popup window. Then, when the user browses to "page-2.htm" in the main browser window I need to be able to reference the popup window.
**JavaScript in "page-1.htm"**
```
var playerWin = window.open("player.htm", "playerWin", "width=300,height=130");
playerWin.play("song.mp3"); // play() is a function in player.htm
```
**JavaScript in "page-2.htm"**
```
playerWin.play("tune.mp3");
```
This code in page-2.htm generates an error "playerWin is not defined". That is understandable because no variable named *playerWin* has been defined on page-2.htm.
My question is: Am I able to reference the popup window from page-2.htm? | I just did a quick test even after you leave the opener page, the popup still have 'opener' object and you can access it. So either poll the opener and reset the reference, or add a timer after you leave the page to wait and then relink.
1.htm
```
<script>
var w = window.open("p.htm", "playerWin", "width=300,height=130");
</script>
<a href="2.htm">2</a>
```
p.htm
```
<a href="javascript:opener.w=this;">re-link</a>
```
2.htm
```
<script>
var w;
</script>
<a href="javascript:alert(w);">check</a>
``` | The answer is no. Most browsers will completely isolate the window and document from one navigation to the next. There is no where you could place the reference to the popup which will survive when you navigate to page2. | How can I reference a popup window from two different pages? | [
"",
"javascript",
"popup",
""
] |
how do i do this with regex?
i want to match this string: `-myString`
but i don't want to match the `-myString` in this string: `--myString`
myString is of course anything.
is it even possible?
EDIT:
here's a little more info with what i got so far since i've posted a question:
```
string to match:
some random stuff here -string1, --string2, other stuff here
regex:
(-)([\w])*
```
This regex returns me 3 matches:
`-string1`, `-` and `-string2`
ideally i'd like it to return me only the `-string1` match | Assuming your regex engine supports (negative) lookbehind:
```
/(?<!-)-myString/
```
Perl does, Javascript doesn't, for example. | Without using any look-behinds, use:
```
(?:^|(?:[\s,]))(?:\-)([^-][a-zA-Z_0-9]+)
```
Broken out:
```
(
?:^|(?:[\s,]) # Determine if this is at the beginning of the input,
# or is preceded by whitespace or a comma
)
(
?:\- # Check for the first dash
)
(
[^-][a-zA-Z_0-9]+ # Capture a string that doesn't start with a dash
# (the string you are looking for)
)
``` | A regex problem I can't figure out (negative lookbehind) | [
"",
"c#",
"regex",
"lookbehind",
"negative-lookbehind",
""
] |
What is the use of a static class?
I mean what are benefits of using static class and how CLR deals with static classes? | A static class simply denotes that you don't expect or need an *instance*. This is useful for utility logic, where the code is not object-specific. For example, extension methods can *only* be written in a static class.
Pre C# 2.0, you could just have a regular class with a private constructor; but `static` makes it formal that you can *never* have an instance (there is **no** constructor\*, and all members **must** be static).
(\*=see comment chain; you can optionally have a type initializer (static constructor aka `.cctor`), but you cannot have an instance constructor (aka `.ctor`)). | The compilation and metadata model for .net requires that all functions are defined within a class. This makes life somewhat easier and simpler for the reflection api's since the concepts of the owning class and its visibility is well defined. It also makes the il model simpler.
since this precludes free functions (ones not associated with a class) this makes the choice of where to put functions which have no associated state (and thus need for an instance). If they need no state associated with them nor have any clear instance based class to which they can be associated and thus defined within there needs to be some idiom for their definition.
Previously the best way was to define the methods within a class whose constructor was private and have none of the functions within the class construct it.
This is a little messy (since it doesn't make it crystal clear why it was done without comments) and the reflection api can still find the constructor and invoke it.
Thus static classes were allowed, making the intent of the class, that of a place for the definition of static methods, clear to users and to the type system. Static classes have no constructor at all. | What is the use of a static class | [
"",
"c#",
".net",
""
] |
I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful. | You can also do it as part of the declaration:
```
int[] a = new int[] {0, 0, 0, 0};
``` | Check out the [Arrays.fill](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#fill%28boolean%5B%5D,%20boolean%29) methods.
```
int[] array = new int[4];
Arrays.fill(array, 1); // [1, 1, 1, 1]
``` | How do I fill arrays in Java? | [
"",
"java",
"arrays",
""
] |
In my initial basic tests it is perfectly safe to do so. However, it has struck me that attempting to manipulate `this` later in a function that `delete`s `this` could be a runtime error. Is this true, and is it normally safe to `delete this`? or are there only certain cases wherein it is safe? | `delete this` is legal and does what you would expect: it calls your class's destructor and free the underlying memory. After `delete this` returns, your `this` pointer value does *not* change, so it is now a dangling pointer that should *not* be dereferenced. That includes implicit dereferencing using the class's member variables.
It is usually found in reference-counted classes that, when the ref-count is decremented to 0, the `DecrementRefCount()`/`Release()`/whatever member function calls `delete this`.
`delete this` is typically considered very bad form for many reasons. It is easy to accidentally access member variables after `delete this`. Caller code might not realize your object has self-destructed.
Also, `delete this` is a "code smell" that your code might not have a symmetric strategy for object ownership (who allocates and who deletes). An object could not have allocated itself with `new`, so calling `delete this` means that class A is allocating an object, but class B is later freeing it[self]. | It's safe to delete "this" as long as it's essentially the last operation in the method. In fact several professional level APIs do so (see ATL's CComObject implementation for an example).
The only danger is attempting to access any other member data after calling "delete this". This is certainly unsafe. | Is it safe to `delete this`? | [
"",
"c++",
"runtime-error",
"self-destruction",
""
] |
Since I am completely useless at regex and this has been bugging me for the past half an hour, I think I'll post this up here as it's probably quite simple.
```
<a href="/folder/files/hey/">hey.exe</a>
<a href="/folder/files/hey2/">hey2.dll</a>
<a href="/folder/files/pomp/">pomp.jpg</a>
```
In PHP I need to extract what's between the `<a>` tags example:
```
hey.exe
hey2.dll
pomp.jpg
``` | Avoid using '.\*' even if you make it ungreedy, until you have some more practice with RegEx. I think a good solution for you would be:
```
'/<a[^>]+>([^<]+)<\/a>/i'
```
Note the '/' delimiters - you must use the preg suite of regex functions in PHP. It would look like this:
```
preg_match_all($pattern, $string, $matches);
// matches get stored in '$matches' variable as an array
// matches in between the <a></a> tags will be in $matches[1]
print_r($matches);
``` | `<a href="[^"]*">([^<]*)</a>` | Get text from all <a> tags in string | [
"",
"php",
"html",
"regex",
"html-parsing",
"text-extraction",
""
] |
I usually use SQLDeveloper to browse the database, but I couldn't make it work with HSQLDB and I don't know which tables are already created…
I guess it's a vendor-specific question and not plain SQL, but the point is: how can I see the tables so I can drop/alter them? | The ANSI SQL92 standard for querying database metadata is contained within the `INFORMATION_SCHEMA` data structures.
I have no idea whether your database supports this or not, but try the following:
```
SELECT *
FROM INFORMATION_SCHEMA.TABLES
```
On further research, it appears that HSQLDB does support `INFORMATION_SCHEMA`, but with slightly non-standard naming.
All of the tables have `SYSTEM_*` prepended to them, so the above example would read
```
SELECT *
FROM INFORMATION_SCHEMA.SYSTEM_TABLES
```
I have no means of testing this, and the answer was found on [sourceforge](http://sourceforge.net/forum/message.php?msg_id=5978227). | Awesome, thanks! Been scouring the Web for that info.
This will fetch only your tables' field info:
```
SELECT TABLE_NAME, COLUMN_NAME, TYPE_NAME, COLUMN_SIZE, DECIMAL_DIGITS, IS_NULLABLE FROM INFORMATION_SCHEMA.SYSTEM_COLUMNS WHERE TABLE_NAME NOT LIKE 'SYSTEM_%'
```
You can retrieve indexes, primary key info, all kinds of stuff from `INFORMATION_SCHEMA.SYSTEM_TABLES`.
Gotta love oo documentation :p | How to see all the tables in an HSQLDB database? | [
"",
"sql",
"hsqldb",
""
] |
If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred. | Set the PYTHONINSPECT environment variable. This can also be done in the script itself:
```
import os
os.environ["PYTHONINSPECT"] = "1"
```
For debugging unexpected exceptions, you could also use this nice recipe <http://code.activestate.com/recipes/65287/> | You want the [code module](http://docs.python.org/library/code.html).
```
#!/usr/bin/env python
import code
code.interact("Enter Here")
``` | How can you programmatically tell the CPython interpreter to enter interactive mode when done? | [
"",
"cpython",
"python",
""
] |
I have a C# application that has a webbrowser and need to be able to completely disable it at times. What is the best method of doing this?
I was thinking about creating a transparent panel to put over the webbrowser when needed, but am not sure if this is the best approach. I also noticed that C# doesn't easily allow making a panel transparent.
Edit: To clarify what I mean by disable...I don't want to allow the user to be able to click or change\edit anything in the webbrowser. | Strangely the WebBrowser control doesn't have an Enabled property as you might expect it to. You can set the AllowNavigation property to false which will stop the user clicking on links.
Turns out it does have an Enabled property, inherited from Control. But you have to explicitly cast it to Control to access it:
```
((Control)webBrowser1).Enabled = false;
```
You should be aware though that setting Enabled *completely* disables any user interaction with the WebBrowser control. That includes the scroll bar, so once you set Enabled to false the user can't even scroll the web page in the control.
If that was more than you wanted then setting the AllowNavigation property to false will stop the user clicking on links but still allow them to scroll the page. You'd need to check though that it also stops Javascript onclick events from firing.
If you wanted to stop any events from firing in the page you could probably achieve that will some DOM work from the WebForms code into the WebBrowser control. You also probably need to start disabling input controls within the WebBrowser. It all depends how disabled you want it. | Based on your last comment, I would assume you are using WinForms. (WPF does allow for transparent panels quite easily :-)) This means you are using the [`WebBrowser`](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx) control. Have you tried setting its [`Enabled`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.enabled.aspx) property to false? | C# how to disable webbrowser usage | [
"",
"c#",
"winforms",
""
] |
**I get a file via a HTTP upload and need to make sure its a PDF file.** The programing language is Python, but this should not matter.
I thought of the following solutions:
1. Check if the first bytes of the string are `%PDF`. *This is not a good check but prevents the user from uploading other files accidentally.*
2. Use `libmagic` (the `file` command in `bash` uses it). *This does exactly the same check as in (1)*
3. Use a library to try to read the page count out of the file. *If the lib is able to read a page count it should be a valid PDF file. Problem: I don't know a Python library that can do this*
Are there solutions using a library or another trick? | The two most commonly used PDF libraries for Python are:
* [pypdf](https://pypi.org/project/pypdf/)
* [ReportLab](http://www.reportlab.org/downloads.html)
Both are pure python so should be easy to install as well be cross-platform.
With pypdf it would probably be as simple as doing:
```
from pypdf import PdfReader
reader = PdfReader("upload.pdf")
```
This should be enough, but `reader` will now have the `metadata` and `pages` attributes if you want to do further checking.
As Carl answered, pdftotext is also a good solution, and would probably be faster on very large documents (especially ones with many cross-references). However it might be a little slower on small PDF's due to system overhead of forking a new process, etc. | The current solution (as of 2023) is to use [`pypdf`](https://pypi.org/project/pypdf/) and catch exceptions (and possibly analyze [`reader.metadata`](https://pypdf.readthedocs.io/en/stable/modules/PdfReader.html#pypdf.PdfReader.metadata))
```
from pypdf import PdfReader
from pypdf.errors import PdfReadError
with open("testfile.txt", "w") as f:
f.write("hello world!")
try:
PdfReader("testfile.txt")
except PdfReadError:
print("invalid PDF file")
else:
pass
``` | Check whether a PDF file is valid with Python | [
"",
"python",
"file",
"pdf",
""
] |
I am using jQuery to simulate a popup, where the user will select a series of filters, which I hope to use to rebind a ListView in the original window.
The "popup" is opened via an ajax request and the content is actually a diferent aspx file (the rendered output is injected into a div that acts as the popup).
I have another ListView in this popup, and it has pagination.
My problem is that since the popup is in reality html content inside a div in the same page, when I try to paginate, the whole page postbacks and is replaced with the aspx that has the filters.
How can I fix this?
I tried using an update panel to contain the ListView but it didn't work. | $("div.yourthingie").hide();
Will hide the part you want to show :) Instead of generating the popup on the fly, leave a small part already made, and hide it in the begining, when you need to show, unhide and add the information you need to.
Hope it helps | Either get rid of the HTML "crust" and just produce the <div> with its contents, or use an IFRAME. | Popups with complex functionality using jQuery | [
"",
"c#",
"asp.net",
"jquery",
"listview",
"popup",
""
] |
I have
```
var previous = new BitArray(new bool[]{true});
var current = new BitArray(new bool[]{false});
```
I want to concatenate them. I have already tried:
```
var next = new BitArray(previous.Count + current.Count);
var index = 0;
for(;index < previous.Count; index++)
next[index] = previous[index];
var j = 0;
for(;index < next.Count; index++, j++)
next[index] = current[j];
previous = current;
```
But it doesn't look like the best way to do it. | Unfortunately it looks like your method might be as good as it gets - if BitArray implemented IEnumerable<T> (instead of just IEnumerable) then we could use LINQ extension methods to make it a bit prettier.
If I were you, I'd wrap this up into an extension method on BitArray:
```
public static BitArray Prepend(this BitArray current, BitArray before) {
var bools = new bool[current.Count + before.Count];
before.CopyTo(bools, 0);
current.CopyTo(bools, before.Count);
return new BitArray(bools);
}
public static BitArray Append(this BitArray current, BitArray after) {
var bools = new bool[current.Count + after.Count];
current.CopyTo(bools, 0);
after.CopyTo(bools, current.Count);
return new BitArray(bools);
}
``` | One can do this with LINQ, after `Cast<bool>()` the bitarray 'becomes' `IEnumerable<bool>`:
```
var previous = new BitArray(new bool[] { true });
var current = new BitArray(new bool[] { false });
BitArray newBitArray =
new BitArray(previous.Cast<bool>().Concat(current.Cast<bool>()).ToArray());
```
I don't think this LINQ method will be fast. | Is there any simple way to concatenate two BitArray (C# .NET)? | [
"",
"c#",
".net",
"bitarray",
""
] |
I have a text box that will have a *currency* string in it that I then need to convert that string to a double to perform some operations on it.
`"$1,100.00"` → `1100.00`
This needs to occur all client side. I have no choice but to leave the *currency* string as a *currency* string as input but need to cast/convert it to a double to allow some mathematical operations. | Remove all non dot / digits:
```
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
``` | [accounting.js](https://openexchangerates.github.io/accounting.js/) is the way to go. I used it at a project and had very good experience using it.
```
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000
```
You can find it at [GitHub](https://github.com/openexchangerates/accounting.js) | How to convert a currency string to a double with Javascript? | [
"",
"javascript",
"jquery",
""
] |
I'm designing a multilingual application using .resx files.
I have a few files like GlobalStrings.resx, GlobalStrings.es.resx, GlobalStrings.en.resx, etc.
When I want to use this, I just need to set Thread.CurrentThread.CurrentCulture.
The problem:
I have a combobox with all the available languages, but I'm loading this manually:
```
comboLanguage.Items.Add(CultureInfo.GetCultureInfo("en"));
comboLanguage.Items.Add(CultureInfo.GetCultureInfo("es"));
```
I've tried with
```
cmbLanguage.Items.AddRange(CultureInfo.GetCultures(CultureTypes.UserCustomCulture));
```
without any success. Also tried with all the elements in CultureTypes, but I'm only getting a big list with a lot more languages that I'm not using, or an empty list.
Is there any way to get only the supported languages? | Using what Rune Grimstad said I end up with this:
```
string executablePath = Path.GetDirectoryName(Application.ExecutablePath);
string[] directories = Directory.GetDirectories(executablePath);
foreach (string s in directories)
{
try
{
DirectoryInfo langDirectory = new DirectoryInfo(s);
cmbLanguage.Items.Add(CultureInfo.GetCultureInfo(langDirectory.Name));
}
catch (Exception)
{
}
}
```
or another way
```
int pathLenght = executablePath.Length + 1;
foreach (string s in directories)
{
try
{
cmbLanguage.Items.Add(CultureInfo.GetCultureInfo(s.Remove(0, pathLenght)));
}
catch (Exception)
{
}
}
```
I still don't think that this is a good idea ... | You can programatically list the cultures available in your application
```
// Pass the class name of your resources as a parameter e.g. MyResources for MyResources.resx
ResourceManager rm = new ResourceManager(typeof(MyResources));
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
foreach (CultureInfo culture in cultures)
{
try
{
ResourceSet rs = rm.GetResourceSet(culture, true, false);
// or ResourceSet rs = rm.GetResourceSet(new CultureInfo(culture.TwoLetterISOLanguageName), true, false);
string isSupported = (rs == null) ? " is not supported" : " is supported";
Console.WriteLine(culture + isSupported);
}
catch (CultureNotFoundException exc)
{
Console.WriteLine(culture + " is not available on the machine or is an invalid culture identifier.");
}
}
``` | Programmatic way to get all the available languages (in satellite assemblies) | [
"",
"c#",
".net",
"localization",
"cultureinfo",
""
] |
The code segment below prints out "The types ARE NOT the same.". Why? I am aware of the fact that using `interfaceOnMyType.GetGenericTypeDefinition()` will solve the problem, but why should I have to do that?
```
class Program
{
static void Main(string[] args)
{
var myType = typeof(Baz<>);
var interfaceOnMyType = myType.GetInterfaces().SingleOrDefault();
var exactType = typeof(IBar<>);
if (exactType == interfaceOnMyType)
{
Console.WriteLine("The types ARE the same.");
}
else
{
Console.WriteLine("The types ARE NOT the same.");
}
Console.ReadLine();
}
}
interface IBar<T>
{
}
class Baz<T> : IBar<T>
{
}
``` | The reason is that `interfaceOnMyType.IsGenericTypeDefinition` returns false, whilst `myType.IsGenericTypeDefinition` and `exactType.IsGenericTypeDefinition` both return true. That is, just because you're retrieving a non-constructed generic type from a generic type definition does not mean that the type you retrieve is itself a generic type definition. | ```
interfaceOnMyType.GetGenericTypeDefinition()
```
returns you the closed constructed type of the interface which is different from the type returned from
```
typeof(IBar<>)
```
[Here is the MSDN article on `GetGenericTypeDefinition`](http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx), and here is a good quote from it explaining how it works:
> Given a `Type` object representing this constructed type, the `GetGenericTypeDefinition` method returns the generic type definition.
---
Edit (the answer above is correct in some cases but wrong in this one):
I think I may have found it now. The reason that the type comparison is failing is because the `Type` returned from `myType.GetInterfaces()` is close to but not identical to the type of the interface itself.
According to [MSDN](http://msdn.microsoft.com/en-us/library/system.type.fullname.aspx):
> If you use the `BaseType` property to obtain the base type of `Derived`, the `FullName` property of the resulting Type object returns `null` (Nothing in Visual Basic). To get a non-null `FullName`, you can use the `GetGenericTypeDefinition` method to get the generic type definition.
So I think this is the problem you are seeing. Since base interfaces are retrieved via `GetInterfaces` any type retrieved by that call will not have a `FullName` ([source](http://msdn.microsoft.com/en-us/library/system.type.basetype.aspx)). Since it does not have a `FullName` the types will fail in comparison.
What I orginally wrote would be true if you were comparing the constructed type which you are not. So unfortunately my first answer is dead wrong - I have left it so that the comments left will make sense. | Generic types not equal | [
"",
"c#",
".net",
"generics",
""
] |
Here is the code
```
$i=0;
while ($row = mysql_fetch_array($result))
{
$output.="idno".$i."=".urlencode($row['usr_id']).
'&'."res".$i."=".urlencode($row['responce']).
'&'."sex".$i."=".urlencode($row['sex']).
'&'."com1".$i."=".urlencode($row['com1']).
'&'."com2".$i."=".urlencode($row['com2']);
$i++;
}
```
OUTPUT i get idno is part of com2 string how do I seperate them. | You need to add an `&` when `$i` is not zero:
```
$i=0;
while ($row = mysql_fetch_array($result))
{
$output .= ($i ? '&' : '') . "idno".$i."=".urlencode($row['usr_id']).
'&'."res".$i."=".urlencode($row['responce']).
'&'."sex".$i."=".urlencode($row['sex']).
'&'."com1".$i."=".urlencode($row['com1']).
'&'."com2".$i."=".urlencode($row['com2']);
$i++;
}
``` | Another solution would be using an array and join its elements afterwards:
```
$array = array();
$i = 0;
while ($row = mysql_fetch_array($result)) {
$array[] = "idno$i=".urlencode($row['usr_id']);
$array[] = "res$i=".urlencode($row['responce']);
$array[] = "sex$i=".urlencode($row['sex']);
$array[] = "com1$i=".urlencode($row['com1']);
$array[] = "com2$i=".urlencode($row['com2']);
$i++;
}
$output .= implode('&', $array);
```
Furthermore you could use the *`argName`*`[]` declaration that PHP will convert into an array when receiving such a request query string. | php string formatting? | [
"",
"php",
"string",
"formatting",
""
] |
What happens in jQuery when you `remove()` an element and `append()` it elsewhere?
It appears that the events are unhooked - as if you were just inserting fresh html (which I guess is what happening). But its also possible my code has a bug in it - so I just wanted to verify this behavior before I continue.
If this is the case - are there any easy ways to rehookup the events to just that portion of HTML, or a different way to move the element without losing the event in the first place. | Yes, jQuery's approach with `remove()` is to unbind everything bound with jQuery's own `bind` (to prevent memory leaks).
However, if you just want to move something in the DOM, you don't have to `remove()` it first. Just `append` to your heart's content, the event bindings *will* stick around :)
For example, paste this into your firebug on this page:
```
$('li.wmd-button:eq(2)').click(function(){ alert('still here!') }).appendTo(document.body)
```
And now scroll down to the bottom of this page and click on the little globy icon now buried under the SO footer. You will get the `alert`. All because I took care to not `remove` it first. | The jQuery *detach()* function is the same as *remove()* but preserves the event handlers in the object that it returns. If you have to remove the item and place it somewhere else with everything you can just use this.
```
var objectWithEvents = $('#old').detach();
$('#new').append(objectWithEvents);
```
Check the API docs here: <http://api.jquery.com/detach/> | Are events lost in jQuery when you remove() an element and append() it elsewhere? | [
"",
"javascript",
"jquery",
"dom",
"event-handling",
"jquery-events",
""
] |
I am having a hard time tracking down a lock issue, so I would like to log every method call's entry and exit. I've done this before with C++ without having to add code to every method. Is this possible with C#? | Probably your best bet would be to use an AOP (aspect oriented programming) framework to automatically call tracing code before and after a method execution. A popular choice for AOP and .NET is [PostSharp](http://www.postsharp.net/). | If your primary goal is to log function entry/exit points and occasional information in between, I've had good results with an **Disposable** logging object where the ***constructor traces the function entry***, and ***Dispose() traces the exit***. This allows calling code to simply wrap each method's code inside a single **using** statement. Methods are also provided for arbitrary logs in between. Here is a complete C# ETW event tracing class along with a function entry/exit wrapper:
```
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace MyExample
{
// This class traces function entry/exit
// Constructor is used to automatically log function entry.
// Dispose is used to automatically log function exit.
// use "using(FnTraceWrap x = new FnTraceWrap()){ function code }" pattern for function entry/exit tracing
public class FnTraceWrap : IDisposable
{
string methodName;
string className;
private bool _disposed = false;
public FnTraceWrap()
{
StackFrame frame;
MethodBase method;
frame = new StackFrame(1);
method = frame.GetMethod();
this.methodName = method.Name;
this.className = method.DeclaringType.Name;
MyEventSourceClass.Log.TraceEnter(this.className, this.methodName);
}
public void TraceMessage(string format, params object[] args)
{
string message = String.Format(format, args);
MyEventSourceClass.Log.TraceMessage(message);
}
public void Dispose()
{
if (!this._disposed)
{
this._disposed = true;
MyEventSourceClass.Log.TraceExit(this.className, this.methodName);
}
}
}
[EventSource(Name = "MyEventSource")]
sealed class MyEventSourceClass : EventSource
{
// Global singleton instance
public static MyEventSourceClass Log = new MyEventSourceClass();
private MyEventSourceClass()
{
}
[Event(1, Opcode = EventOpcode.Info, Level = EventLevel.Informational)]
public void TraceMessage(string message)
{
WriteEvent(1, message);
}
[Event(2, Message = "{0}({1}) - {2}: {3}", Opcode = EventOpcode.Info, Level = EventLevel.Informational)]
public void TraceCodeLine([CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0,
[CallerMemberName] string memberName = "", string message = "")
{
WriteEvent(2, filePath, line, memberName, message);
}
// Function-level entry and exit tracing
[Event(3, Message = "Entering {0}.{1}", Opcode = EventOpcode.Start, Level = EventLevel.Informational)]
public void TraceEnter(string className, string methodName)
{
WriteEvent(3, className, methodName);
}
[Event(4, Message = "Exiting {0}.{1}", Opcode = EventOpcode.Stop, Level = EventLevel.Informational)]
public void TraceExit(string className, string methodName)
{
WriteEvent(4, className, methodName);
}
}
}
```
Code that uses it will look something like this:
```
public void DoWork(string foo)
{
using (FnTraceWrap fnTrace = new FnTraceWrap())
{
fnTrace.TraceMessage("Doing work on {0}.", foo);
/*
code ...
*/
}
}
``` | How can I add a Trace() to every method call in C#? | [
"",
"c#",
"logging",
"trace",
""
] |
I develop Joomla websites/components/modules and plugins and every so often I require the ability to use JavaScript that triggers an event when the page is loaded. Most of the time this is done using the `window.onload` function.
**My question is:**
1. Is this the best way to trigger JavaScript events on the page loading or is there a better/newer way?
2. If this is the only way to trigger an event on the page loading, what is the best way to make sure that multiple events can be run by different scripts? | `window.onload = function(){};` works, but as you might have noticed, **it allows you to specify only 1 listener**.
I'd say the better/newer way of doing this would be to use a framework, or to just to use a simple implementation of the native `addEventListener` and `attachEvent` (for IE) methods, which allows you to *remove* the listeners for the events as well.
Here's a cross-browser implementation:
```
// Cross-browser implementation of element.addEventListener()
function listen(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}
// Use: listen("event name", elem, func);
```
For the window.onload case use: `listen("load", window, function() { });`
---
**EDIT** I'd like to expand my answer by adding precious information that was pointed by others.
This is about the **`DOMContentLoaded`** (Mozilla, Opera and webkit nightlies currently support this) and the **`onreadystatechange`** (for IE) *events* which can be applied to the **document** object to understand when the document is available to be manipulated (without waiting for all the images/stylesheets etc.. to be loaded).
There are a lot of "hacky" implementations for cross-browsers support of this, so I strongly suggest to use a framework for this feature. | The window.onload events are overridden on multiple creations. To append functions use the
window.addEventListener(W3C standard) or the window.attachEvent(for IE). Use the following code which worked.
```
if (window.addEventListener) // W3C standard
{
window.addEventListener('load', myFunction, false); // NB **not** 'onload'
}
else if (window.attachEvent) // Microsoft
{
window.attachEvent('onload', myFunction);
}
``` | Best practice for using window.onload | [
"",
"javascript",
"joomla",
"joomla1.5",
"onload",
""
] |
I'm developing an app with a Flex-based front end and a Spring/Hibernate back-end.
To get Facebook integration working in the way I've got it currently, I need to read the cookies set in javascript on the front end on the back-end and do some validation during login to see whether the user is attempting to spoof his Facebook login.
This would be pretty easy, but I can't figure out how to get the HttpServletRequest. I'm using a pretty basic Spring config (this is my first real Spring app, and I'm pretty familiar with it now, but there's lots to it I've never looked at.)
I'm not using Spring MVC or Spring WebFlow or anything like that. I can get the ServletContext, but I haven't yet figured out how to get the request.
Any help? | If FlexContext is not available:
Solution 1: inside method (>= Spring 2.0 required)
```
HttpServletRequest request =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
.getRequest();
```
Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)
```
@Autowired
private HttpServletRequest request;
``` | This is kind of Flex/BlazeDS specific, but here's the solution I've come up with. Sorry if answering my own question is a faux pas.
```
HttpServletRequest request = flex.messaging.FlexContext.getHttpRequest();
Cookie[] cookies = request.getCookies();
for (Cookie c:cookies)
{
log.debug(String.format("Cookie: %s, %s, domain: %s",c.getName(), c.getValue(),c.getDomain()));
}
```
It works, I get the cookies. My problem was looking to Spring - BlazeDS had it. Spring probably does too, but I still don't know how to get to it. | How do I get a HttpServletRequest in my spring beans? | [
"",
"java",
"apache-flex",
"spring",
"facebook",
""
] |
If I have a string such as
"17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"
what is the best way to extract just the x3 load average values at the end? I have written a regexp that does this but is this the most efficient / fastest method?
```
>>> s = "17:31:51 up 134 days, 11:26, 1 user, load average: 0.22, 0.15, 0.10"
>>> print re.findall(r"([0-9]\.\d+)", s)
['0.22', '0.15', '0.10']
``` | This should work:
```
# s is the string to parse
loadavg = [float(x) for x in s.rsplit('load average: ', 1)[1].split(', ')]
``` | You have the same information in `/proc/loadavg` special file, so you can do:
```
>>> open("/proc/loadavg").readline().split(" ")[:3]
``` | What is the best way to extract load average float values from a string in Python? | [
"",
"python",
"string",
"floating-point",
""
] |
Just been looking at the Spring framework for JDBC - it looks like there is a bit of a learning curve - and I'm still not able to find a nice up to date quick start Spring/JDBC tutorial of any quality!
Is there something lighter than Spring for basic JDBC operations - or has anyone got any good links for tutorials
Many thanks | Quite the opposite. JDBC support in Spring is very simple. Here is basic example:
```
dataSource = ... obtain data source... (e.g. via Spring config)
SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
Map<String, Object> row = jdbcTemplate.queryForMap(
"SELECT * FROM MyTable WHERE ID=? LIMIT 1", 100);
```
JdbcTemplate and SimpleJdbcTemplate has lot of query methods you may find useful. For mapping rows to your objects, take a look at RowMapper and ParameterizedRowMapper < T >.
For your datasource you usually want to use some advanced DataSource with pooling support. For testing, simple BasicDataSource will do:
```
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("driverClassName");
ds.setUrl("jdbc://...");
ds.setUsername("username");
ds.setPassword("password");
``` | Check out <http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html> to choose a style (full 'automagic' Spring vs. most of the work done by the programmer) and learn about the basic operations on `JdbcTemplate`.
The site has nice examples, like
```
int countOfActorsNamedJoe =
this.jdbcTemplate.queryForInt(
"select count(0) from t_actors where first_name = ?",
new Object[]{"Joe"});
```
Anyhow, you *will* need to invest some time into it. No matter which tutorial on Spring JDBC you will use, it will still be Spring JDBC underneath. And in this case it doesn't hurt to learn from the source, i.e. the Spring docs, which are quite well written. | Is Spring too complex for JDBC operations? | [
"",
"java",
"spring",
"jdbc",
""
] |
I have a number of VC 6.0 projects (dsps) which build into dlls which don't have resource files. Any idea how to add resources into an existing project?
The project is due for a major release shortly and I want to add a fileversion to those dlls currently lacking one. The dlls will be recompilied before release so I'm just trying to make these dsps like all the others I've inherited with this project (that do have a file and product version etc so that we can easily tell exactly what is running on a customer's machine.
One answer : Create an \*.rc and resource.h file (copy from another project?) and add it to the source folder of ypur project in VC6 file view. The resource view is automatically created. Thanks for your help guys, gave me the pointers I needed. | Just add a VERSIONINFO block to the resource file for the DLL.
Open the .rc file, and use "Insert/Resource.../Version" and you'll get a new VERSIONINFO resource with a bunch of defaults. If the project does not already have a resource file, you can add one using "File/New.../Resource Script".
If you want to roll your own, an example `VERSIONINFO` block is given on the [MSDN page for VERSIONINFO](http://msdn.microsoft.com/en-us/library/aa381058.aspx):
```
#define VER_FILEVERSION 3,10,349,0
#define VER_FILEVERSION_STR "3.10.349.0\0"
#define VER_PRODUCTVERSION 3,10,0,0
#define VER_PRODUCTVERSION_STR "3.10\0"
#ifndef DEBUG
#define VER_DEBUG 0
#else
#define VER_DEBUG VS_FF_DEBUG
#endif
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILEVERSION
PRODUCTVERSION VER_PRODUCTVERSION
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
FILEFLAGS (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG)
FILEOS VOS__WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904E4"
BEGIN
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", VER_FILEDESCRIPTION_STR
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "InternalName", VER_INTERNALNAME_STR
VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR
VALUE "LegalTrademarks1", VER_LEGALTRADEMARKS1_STR
VALUE "LegalTrademarks2", VER_LEGALTRADEMARKS2_STR
VALUE "OriginalFilename", VER_ORIGINALFILENAME_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
VALUE "ProductVersion", VER_PRODUCTVERSION_STR
END
END
BLOCK "VarFileInfo"
BEGIN
/* The following line should only be modified for localized versions. */
/* It consists of any number of WORD,WORD pairs, with each pair */
/* describing a language,codepage combination supported by the file. */
/* */
/* For example, a file might have values "0x409,1252" indicating that it */
/* supports English language (0x409) in the Windows ANSI codepage (1252). */
VALUE "Translation", 0x409, 1252
END
END
``` | You can always try use `editbin /VERSION:#[.#]` to change the version within the dll itself. Otherwise, it should be an entry in the resource file of the project. | Adding resource file to VC6 dll | [
"",
"c++",
"version-control",
"visual-c++",
"visual-c++-6",
""
] |
How widespread, supported, developed is testing in the PHP world? On par with Java? Up there with Ruby/Rails? I Googled and found that testing frameworks exist but I'm wondering if they're widely used.
Do the major PHP IDE's have built-in test runners the way Eclipse's Java tools do or NetBeans's Ruby/Rails tools do? Is testing built into PHP's MVC frameworks as with Rails?
I ask because a group where I work wants to hire someone to develop a PHP app for them. I'm concerned about quality and maintenance as I might be called on to support this thing. | There are at least two mature, stand-alone, JUnit style test suites available, named [PHPUnit](http://www.phpunit.de/) and [SimpleTest](http://www.simpletest.org/), respectively.
As far the MVC Frameworks go, Symfony has its own testing framework named [lime](http://www.symfony-project.org/book/1_0/15-Unit-and-Functional-Testing), Code Igniter has a [unit\_test](http://codeigniter.com/user_guide/libraries/unit_testing.html) library and [CakePHP](http://bakery.cakephp.org/articles/view/testing-models-with-cakephp-1-2-test-suite) relies on the aforementioned SimpleTest.
I know that Zend Studio has built in support for PHPUnit tests, and both PHPUnit and SimpleTest have command-line runners so integration into any workflow is possible.
The tools are there in the PHP world if a developer wants to take advantage of them, and smart shops do take advantage of them.
The caveats are your par for the course PHP complaints. There are two PHP communities; PHP as a platform for building software, and PHP as a way to interact with a web server, web browser, and database to produce application-like things on the web. It's less a black and white thing and more a continuum; Among those more on the software developer side unit testing and TDD is supported and used as much as it is on any other platform. Among the "cobble together a bunch of stuff I don't understand but still get results people", it's unheard of.
There's a lot of non-framework/custom-framework legacy PHP code around that's difficult to get a useful test harness around. PHP also lends itself easily to patterns that rely on the existence of a browser environment to run. I don't have any evidence to back this up other than my own observations, but a lot of PHP shops that care about testing end up relying on acceptance testing (i.e. Selenium) as a substitute for actual Unit Testing, test-first, etc. development.
In your specific situation, interview the hell out of the developer your group is going to hire.
1. Ask them what unit testing framework they use
2. Ask them to describe, in general terms, a real world example of a time they developed a new feature and its supporting tests
3. Ask them to describe, in general terms, a real world example of a time their tests failed and what they did to resolve the situation
You're less interested in the specific situation they're going to describe and more interested in how comfortable they are discussing their knowledge of code testing in general. | Whenever I TDD a project with XUnit style tools, I have difficulty getting my head in the right spot. I find that using tools designed for Behaviour Driven Development or "[Specification by example](http://specificationbyexample.com/key_ideas.html)" makes it easier for me to [do TDD right](http://gojko.net/2010/12/02/the-principle-of-symmetric-change/) -- i.e. focus on design, exposing intent and [describing behaviour in specific contexts](http://martinfowler.com/bliki/SpecificationByExample.html). ***Not*** testing.
That said, I would like to introduce [pecs](https://github.com/noonat/pecs) into the conversation. From the readme on the project site.
> pecs is a tiny behavior-driven development library for PHP 5.3, a la RSpec or JSpec.
If you've used JSpec or better yet, [Jasmine-BDD](http://pivotal.github.com/jasmine) (for JavaScript) the pecs style of describing behaviour should be really familiar. I find this style great for component level specs. If you are looking for a PHP tool for feature level specifications (stories or user acceptance tests) consider [Behat](http://everzet.com/Behat/).
Going back to pecs, here's an example culled from the pecs project site:
```
describe("Bowling", function() {
it("should score 0 for a gutter game", function() {
$bowling = new Bowling();
for ($i=0; $i < 20; $i++) {
$bowling->hit(0);
}
expect($bowling->score)->to_equal(0);
});
});
```
Yes that is a PHP spec. Looking through the pecs source, it looks like the author is able to pull this off by leveraging the new hotness in PHP 5.3+, Lambdas and closures. So I guess this means that you cannot use pecs in any project based on PHP < 5.3 (just FYI).
Also, pecs is not as mature as PHPUnit or SimpleTest. However, I think the proponents of BDD in the PHP community should support the growth of tools like pecs that encourage "Specification by example" or BDD without the confusion brought on by having to use legacy XUnit testing tools.
These days I work more in Python than PHP. However, the next time I pick up a PHP project, I'll be extremely happy if I have a mature, community supported tool like pecs to craft the specifications for the software. | What's the state of TDD and/or BDD in PHP? | [
"",
"php",
"testing",
"tdd",
"bdd",
""
] |
I have little problem with databinding in my current project.
I have an ObservableCollection I want to bind to an ListBox.
```
public ObservableCollection<GeoDataContainer> geoList = new ObservableCollection<GeoDataContainer>();
```
...later...
```
geoListBox.ItemsSource = geoList;
```
This code works fine. The Listbox has a datatemplate and everything looks perfect.
But I don't want to use C# code for binding. I want to make the binding in the XAML Code.
I am searching for days but I don't get it. These are two lines C# code but to archive this in XAML it seems impossible without creating my own class for my collection or adding a DataProvider or resources or whatever.
Is there no easy way to do it? | Another good way would be instantiating geoList as a resource
```
<WindowResources>
<l:GeoCollection x:Key="geoList"/>
</WindowResources>
```
Then you have
```
GeoCollection geoList = FindResource("geoList") as GeoCollection;
```
Of course, this is for cases when the data is related to the view only. If this is related to model or modelview, you use DataContext and bind to its properties. | All you have to do is expose the collection and bind to it. For example, if you expose it as:
```
public ICollection<GeoDataContainer> GeoList
{
get { return geoList; }
}
```
You will be able to bind to it as:
```
<ListBox ItemsSource="{Binding GeoList}"/>
```
The "trick" is to make sure that the `DataContext` of the `ListBox` is the class that exposes the `GeoList` property. | WPF Databinding in XAML | [
"",
"c#",
"wpf",
"data-binding",
"xaml",
"itemssource",
""
] |
I have an order by clause that looks like:
```
( user_id <> ? ), rating DESC, title
```
Where ? is replaced with the current user's id.
On postgresql this gives me the ordering I'm looking for i.e. by current user, then highest rating, then title (alphabetically).
However on MySQL I get an unclear order current user is neither first nor last, nor is it by rating or title.
Is my only option for cross database compatibility to replace this quick and dirty boolean expression with a CASE WHEN .. THEN .. ELSE .. END statement?
Edit: Thanks all for the assistance, it is as correctly pointed out by Chaos and Chad Birch the case that the problem lies elsewhere *(specifically that I'm using the results of the above query as input into the next - then acting surprised that the order of the first is lost ;)* | I tested several variations on this in mysql and they all worked correctly (the way you're expecting). I suppose your problem has to be somewhere other than the query. To verify for yourself, I suggest running an equivalent query directly from mysql client. | MySQL has no *real* notion of booleans, and simply maps `TRUE` and `FALSE` to the numeric values `1` and `0` repectively.
In this case `user_id <> ?` will return 0 for the majority of the rows in your table and 1 for the other rows. The default sort order is `ASC`, meaning in all likelihood the rows you want are at the **bottom** of your result set (`0/FALSE` come *before* `1/TRUE`). Try modifying your query to accommodate this.
```
( user_id <> ? ) DESC, rating DESC, title
```
Assuming this is indeed the issue, cross-database compatibility can be achieved with ease.
```
IF(user = ?, 0, 1), rating DESC, title
``` | Using boolean expression in order by clause | [
"",
"sql",
"mysql",
"postgresql",
""
] |
Is there a simple way to sort rows in a JTable with Java 1.5 (`setAutoCreateRowSorter` and `TableRowSorter` appear to be Java 1.6 features)? | Sorting in Java 1.5 is only possible via libraries.
E.g. use the JXTable mentioned from Kaarel or VLTable from [here](http://www.vlsolutions.com/en/documentation/articles/jtable/index.php).
Another good library is [glazedlists](http://publicobject.com/glazedlists/)
which is also used in the Spring Rich Client project.
There are even ways to use [Glazed Lists with JXTable](http://sites.google.com/site/glazedlists/documentation/swingx) | Use the `JXTable` from the [SwingX](http://swinglabs.org) project, see e.g.
* [SwingLabs: How to Use the SwingX JXTable: Sorting Rows](http://wiki.java.net/bin/view/Javadesktop/SwingLabsSwingXJXTableHowTo#RowSorting) | JTable sorting rows in Java 1.5 | [
"",
"java",
"jtable",
""
] |
Currently we use gcov with our testing suite for Linux C++ application and it does a good job at measuring line coverage.
Can gcov produce function/method coverage report in addition to line coverage?
Looking at the parameters gcov accepts I do not think it is possible, but I may be missing something. Or, probably, is there any other tool that can produce function/method coverage report out of statistics generated by gcc?
**Update:** By function/method coverage I mean percentage of functions that get executed during tests. | I guess what you mean is the -f option, which will give you the percentage of lines covered per function. There is an interesting article about gcov at [Dr. Dobb's](http://www.ddj.com/development-tools/184401989) which might be helpful. If "man gcov" doesn't show the -f flag, check if you have a reasobably recent version of the gcc suite.
**Edit:** to get the percentage of functions not executed you can simply parse through the function coverage output, as 0.00% coverage should be pretty much equivalent to not called. This small script prints the percentage of functions not executed:
```
#!/bin/bash
if test -z "$1"
then
echo "First argument must be function coverage file"
else
notExecuted=`cat $1 | grep "^0.00%" | wc -l`
executed=`cat $1 | grep -v "^0.00%" | wc -l`
percentage=$(echo "scale=2; $notExecuted / ($notExecuted + $executed) * 100" |bc)
echo $percentage
fi
``` | We have started to use gcov and [lcov](http://ltp.sourceforge.net/coverage/lcov.php) together. The results from lcov do include the percentage of functions that are executed for the "module" you're looking at.
**EDIT:** The *module* can go from directories down to files.
I also want to add that if you are already using the GNU compiler tools, then gcov/lcov won't be too difficult for you to get running and the results it produces are very impressive. | Is it possible to measure function coverage with gcov? | [
"",
"c++",
"unit-testing",
"code-coverage",
"gcov",
""
] |
How to embed a Jukebox or a media player in C# .NET?
Or rather create a playlist which can play WAV files. | You can embed microsoft media player COM component and control it from code.
[How to interact with Windows Media Player in C#](https://stackoverflow.com/questions/56478/how-to-interact-with-windows-media-player-in-c) | Soundplayer to just play sound, windows media player for audio/video playback on a form
[Soundplayer](http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx)
[Windows media player](http://www.c-sharpcorner.com/UploadFile/satisharveti/EnhancedWindowsMediaPlayer07072008021113AM/EnhancedWindowsMediaPlayer.aspx) | How to embed a Media Player | [
"",
"c#",
".net",
"media",
""
] |
I have a Javascript class that contains a few functions and member objects:
```
function MyUtils()
{
// Member Variables (Constructor)
var x = getComplexData();
var y = doSomeInitialization();
// Objects
this.ParamHash = function()
{
// Member variables
this.length = 0;
this.items = new Array();
// Constructor
for (var i = 0; i < arguments.length; i += 2)
{
// Fill the items array.
this.items[arguments[i]] = arguments[i+1];
this.length++;
}
}
// Functions
this.doSomething = function()
{
// Do something.
// Uses the items in the ParamHash object.
for (var i in this.ParamHash.items)
{
// Really do something!
}
// Clear the ParamHash object -- How??
}
}
```
This is invoked in the following manner:
```
// First call - works fine.
var utils = new MyUtils();
utils.paramHash = new utils.ParamHash("a", 1, "b", 2);
utils.doSomething();
// Don't want to re-initialize.
// utils = new MyUtils();
// Consequent call - crashes ["Object doesn't support this action."].
utils.paramHash = new utils.ParamHash("c", 3);
utils.doSomething();
```
The problem arises from the restriction that I want to reuse the same `utils` object throughout the code without having to re-initialize it. Also, I want the ParamHash object to be recreated from scratch everytime I call it. However, consequent calls to the ParamHash constructor throw an error "Object doesn't support this action." At this stage, I can see that the utils.paramHash object still contains the old values ("a", "b").
I have tried various ways to clear the ParamHash object such as setting it's items and length to null, popping items from the array. Nothing seemed to work until I used the following way (in the `doSomething()` function):
```
this.paramHash.items = new Array();
this.paramHash.length = 0;
```
This seems wrong because what if I had a lot of member variables... would I have to reset each of them individually?
So, the question is: What is the best way to reset the `ParamHash` object to the initial state? I'm sure hoping that there is a cleaner/more direct way. Something like :
```
// Doesn't work! :-(
this.paramHash = new function() {};
```
**EDIT: I'm looking for a cross-browser solution - One that works atleast in IE6+ and FF 2+.**
---
**Solution:** Thanks to Cristoph, I was able to do it by creating a separate variable/property within `MyUtils` which only holds the instance of the `ParamHash` function.
```
function MyUtils()
{
// Same ol' stuff.
var myParamHash;
}
// First call - works fine.
var utils = new MyUtils();
utils.myParamHash = new utils.ParamHash("a", 1, "b", 2);
utils.doSomething();
// Consequent call - works fine now.
utils.myParamHash = new utils.ParamHash("c", 3);
utils.doSomething();
``` | This
```
utils.ParamHash = new utils.ParamHash("a", 1, "b", 2);
```
overwrites the the property which holds the `ParamHash()` constructor function with an instance object. You could get the constructor back via
```
utils.ParamHash.constructor
```
but the cleaner way would be to not overwrite it in the first place and use a seperate property to hold the instance.
---
I don't know the exact problem Cerebrus is trying to solve, so there might be valid reasons for what he's doing. But in my opinion, his solution is overly complicated. I'd do something like this:
```
function MyUtils() {
this.x = getComplexData();
this.y = doSomeInitialization();
this.params = {};
}
MyUtils.prototype.doSomething = function() {
for(var prop in this.params) {
if(this.params.hasOwnProperty(prop)) {
// do stuff
}
}
};
var utils = new MyUtils;
utils.params = { a : 1, b : 2 };
utils.doSomething();
```
The check for `hasOwnProperty()` is unnecessary if you can be sure that no one messed with `Object.prototype`.
---
Some additional comments:
* in JavaScript, normally only the names of constructor functions are capitalized
* `items` shouldn't be an array, but a plain object, ie `this.items = {};` | when you did this
```
utils.ParamHash = new utils.ParamHash("a", 1, "b", 2);
```
you replaced the ParamHash constructor function with an object instance. Subsequent `new ParamHash()` fails because utils.ParamHash is no longer a constructor function.
Try this:
```
var utils = new MyUtils();
utils.paramHashInstance = new utils.ParamHash("a", 1, "b", 2);
utils.DoSomething();
``` | Correct way to reset or clear a Javascript object? | [
"",
"javascript",
"function",
"object",
"reset",
""
] |
I'm attempting to call a javascript function (in our code) from a silverlight control. I'm attempting to call the function via:
`HtmlPage.Window.Invoke("showPopup", new string[] { "http://www.example.com" });`
and I get the error "Failed to Invoke: showPopup"
I can call `HtmlPage.Window.Invoke("alert", new string[]{"test"});` without issue, but not my own function.
I can also open up the page in question in the IE developer tools and manually call `showPopup("http://www.example.com")` and it works as expected.
So the js function works, and the Silverlight binary can find other js functions. What am I missing here?
Additional Notes:
* The function call is in a button click event handler, so it happens after the page (and the script) have been loaded) | Aha! I figured it out. Our app uses an iframe, so the rendered html looks something like this
```
<html>
<head></head>
<body>
Stuff
<iframe>
<html>
<head></head>
<body>Other Stuff</body>
</html>
</iframe>
<body>
</html>
```
And the Silverlight control in question is in the iframe. The problem was that the file that contained the `showPopup` function was referenced in the outer `<head>` (why I could call the function with the IE toolbar) but not the inner `<head>`. Adding a reference to the file in the in-the-iframe `<head>` solved the problem.
Sort of anticlimactic, but thanks for all the help. | Is the showPopup javascript function on the same html or aspx page as the Silverlight control? You will normally get the "Failed to Invoke ..." error if the javascript function does not exist:
```
HtmlPage.Window.Invoke("functionThatDoesNotExist", new [] { "Testing" });
```
[](https://i.stack.imgur.com/2AwxU.png)
What browser are you using when you are getting this problem?
Are you using the latest version of Silverlight?
Are you using the ScriptableType attrbiute anywhere?
Is it possible to list the code for a short but complete program that causes this problem to happen on your machine... | Calling A Javascript function from Silverlight | [
"",
"javascript",
"silverlight",
""
] |
I'm developing a small windows app using c++ and i would like to get some kind of fingerprint of the software/hardware on a pc so that i can allow the app to be run only on certain pc's.
I am aware that the app can be cracked but i'm really interested in implementing something like this.
Any ideas how could i achieve this? | It basically depends on how tight you want to couple your software to the underlying hardware. For example you could get some hardware information from the registry, read out the MAC address from the LAN card, retrieve the gfx manufacturer, the CPU id, etc. and hash all these data.
You could then use this hash as a [challenge](http://en.wikipedia.org/wiki/Challenge-response_authentication) code which is sent to your company. The customer then receives the signed (with your private key) version of this hash.
Upon start up your application is able to check if the signature of the hash is good or bad (i.e. has been signed by your company).
This not only binds your software to a certain hardware configuration, but also forces the crackers to patch your application (because they would need to patch the public key from your executable and replace it in order to write a keygen). Many people consider twice installing a crack obtained from various sources in contrast to just entering a valid serial copied from a keygen.
**Edit:**
In order to check the signature of the hash, anything from [RSA](http://en.wikipedia.org/wiki/Rsa) over [DSA](http://en.wikipedia.org/wiki/Digital_Signature_Algorithm) to [ECC](http://en.wikipedia.org/wiki/Elliptic_curve_cryptography) can be used. I can recommend [Crypto++](http://www.cryptopp.com/) or [libTomCrypt](http://libtomcrypt.com/index.old.html) for that. | There's no reliable way known to do this in a vanilla PC; people have been trying for years. The problem is that you might change any component at any time, including the CPU and the BIOS ROMs. The closest people have come is using a cryptographically protected "[dongle](http://en.wikipedia.org/wiki/Dongle)" but that has proven both to be unsatisfactory in operation, and not very secure.
If you come up with something, patent it; it would be very valuable. | How to get unique hardware/software signature from a windows pc in c/c++ | [
"",
"c++",
"windows",
"copy-protection",
""
] |
I have a Django app that requires a `settings` attribute in the form of:
```
RELATED_MODELS = ('appname1.modelname1.attribute1',
'appname1.modelname2.attribute2',
'appname2.modelname3.attribute3', ...)
```
Then hooks their post\_save signal to update some other fixed model depending on the `attributeN` defined.
I would like to test this behaviour and tests should work even if this app is the only one in the project (except for its own dependencies, no other wrapper app need to be installed). How can I create and attach/register/activate mock models just for the test database? (or is it possible at all?)
Solutions that allow me to use test fixtures would be great. | You can put your tests in a `tests/` subdirectory of the app (rather than a `tests.py` file), and include a `tests/models.py` with the test-only models.
Then provide a test-running script ([example](https://github.com/carljm/django-model-utils/blob/master/runtests.py)) that includes your `tests/` "app" in `INSTALLED_APPS`. (This doesn't work when running app tests from a real project, which won't have the tests app in `INSTALLED_APPS`, but I rarely find it useful to run reusable app tests from a project, and Django 1.6+ doesn't by default.)
(**NOTE**: The alternative dynamic method described below only works in Django 1.1+ if your test case subclasses `TransactionTestCase` - which slows down your tests significantly - and no longer works at all in Django 1.7+. It's left here only for historical interest; don't use it.)
At the beginning of your tests (i.e. in a setUp method, or at the beginning of a set of doctests), you can dynamically add `"myapp.tests"` to the INSTALLED\_APPS setting, and then do this:
```
from django.core.management import call_command
from django.db.models import loading
loading.cache.loaded = False
call_command('syncdb', verbosity=0)
```
Then at the end of your tests, you should clean up by restoring the old version of INSTALLED\_APPS and clearing the app cache again.
[This class](http://www.djangosnippets.org/snippets/1011/) encapsulates the pattern so it doesn't clutter up your test code quite as much. | @paluh's answer requires adding unwanted code to a non-test file and in my experience, @carl's solution does not work with `django.test.TestCase` which is needed to use fixtures. If you want to use `django.test.TestCase`, you need to make sure you call `syncdb` before the fixtures get loaded. This requires overriding the `_pre_setup` method (putting the code in the `setUp` method is not sufficient). I use my own version of `TestCase` that lets me add apps with test models. It is defined as follows:
```
from django.conf import settings
from django.core.management import call_command
from django.db.models import loading
from django import test
class TestCase(test.TestCase):
apps = ()
def _pre_setup(self):
# Add the models to the db.
self._original_installed_apps = list(settings.INSTALLED_APPS)
for app in self.apps:
settings.INSTALLED_APPS.append(app)
loading.cache.loaded = False
call_command('syncdb', interactive=False, verbosity=0)
# Call the original method that does the fixtures etc.
super(TestCase, self)._pre_setup()
def _post_teardown(self):
# Call the original method.
super(TestCase, self)._post_teardown()
# Restore the settings.
settings.INSTALLED_APPS = self._original_installed_apps
loading.cache.loaded = False
``` | Django: How to create a model dynamically just for testing | [
"",
"python",
"django",
"unit-testing",
"django-models",
"mocking",
""
] |
I have a function that gets passed the document object like:
```
toggle( $('username') );
function Toggle(id)
{
/// ??
}
```
How can I get the actual name of the object passed i.e. username? | If I understand you correctly, can't you:
```
$(id).attr("id");
```
or
```
$(id).attr("name");
```
Or am I mistaken? | Either what [Jonathon said](https://stackoverflow.com/questions/511630/how-to-get-id-when-you-pass-my-id/511656#511656) or with
```
$(id).val();
``` | How to get ID when you pass my ID | [
"",
"javascript",
"jquery",
""
] |
I want to use object serialization to communicate over the network between a [Mono](http://en.wikipedia.org/wiki/Mono_%28software%29) server and Silverlight clients.
It is pretty important that serialization is space efficient and pretty fast, as the server is going to host multiple real time games.
What technique should I use? The BinaryFormatter adds a lot of overhead to serialized classes (Version, culture, class name, property names, etc.) that is not required within this application.
What can I do to make this more space efficient? | You can use [Protocol Buffers](https://github.com/google/protobuf). I'm changing all my serialization code from BinaryFormatter with compression to Protocol Buffers and obtaining very good results. It's more efficient in both time and space.
There are two .NET implementations by [Jon Skeet](https://github.com/jskeet/protobuf-csharp-port) and [Marc Gravell](https://github.com/mgravell/protobuf-net).
**Update**: Official .NET implementation can be found [here](https://github.com/google/protobuf/tree/master/csharp). | I have some [benchmarks for the leading .NET serializers](http://www.servicestack.net/benchmarks/NorthwindDatabaseRowsSerialization.100000-times.2010-08-17.html) available based on the Northwind dataset.

@marcgravell binary protobuf-net is the fastest implementations benchmarked that is about **7x** faster than Microsoft fastest serializer available (the XML DataContractSerializer) in the BCL.
I also maintain some open-source high-performance .NET text serializers as well:
* [JSV TypeSerializer](http://www.servicestack.net/mythz_blog/?p=176) a compact, clean, JSON+CSV-like format that's 3.1x quicker than the DataContractSerializer
* as well as a [JsonSerializer](http://www.servicestack.net/mythz_blog/?p=344) that's 2.6x quicker. | Fast and compact object serialization in .NET | [
"",
"c#",
".net",
"serialization",
""
] |
I'm working on a project at the moment where I've come up against a rather frustrating problem in Internet Explorer. I have a series of pop ups on a particular page that are opened with JavaScript when help links are clicked. The JavaScript for them is:
```
function openHelpPopUp(url) {
newwindow=window.open(url,'name','width=620,height=440');
if (window.focus) {newwindow.focus()}
return false;
}
```
The HTML used is:
```
<a href="help.html" onclick="return openHelpPopUp('help.html')" title="More information" class="help-popup-link">Help</a>
```
Now, the pop up works perfectly in every browser except Internet Explorer. The main priority at the moment is making it work in IE7.
What happens is that, it pops up fine, but the text is not visible. If you click and drag the cursor over it and highlight it though, it becomes visible. Once you click away from the highlighted area to deselect it, it stays visible. Any area that wasn't highlighted stays invisible. When you refresh the pop up though, it sometimes becomes visible without any highlighting, it sometimes doesn't.
Also peculiar is that some text within an unordered list is visible, but when I use the same list encompass the rest of the text, it stays invisible bar the bit that was already visible.
Have you come across this or anything like it before? Have you got any tips or suggestions? I'm running out of things to try so any feedback or help on this is greatly appreciated! | By adding a z-index of 100 to every P tag for IE, I seem to have gotten it visible now. Weird. I haven't used any z-index's elsewhere and the structure of the HTML should put the P's on the top anyway. | > it pops up fine, but the text is not visible. If you click and drag the cursor over it and highlight it though, it becomes visible
Sounds like it might be an [IE7 variant](http://www.small-software-utilities.com/css/88/ie7-peekaboo-bug-disappearing-text/) [Peekaboo bug](http://www.positioniseverything.net/explorer/peekaboo.html), an IE rendering problem which is nothing to do with being opened in a pop-up. You'd have to show us the page that's being popped up to be sure though.
Whilst we're here:
> if (window.focus) {newwindow.focus()}
Probably should be ‘if (newwindow.focus)’ assuming the aim is to avoid focusing a blocked ‘window.open()=null’. | Javascript Pop Up Page Makes Text Invisible In Internet Explorer | [
"",
"javascript",
"popup",
"onclick",
""
] |
In java, im creating a SortedSet from a list which is always going to be ordered (but is only of type ArrayList). I figure adding them one by one is going to have pretty poor performance (in the case for example of an AVL tree), as it will have to reorder the tree a lot.
my question is, how *should* i be creating this set? in a way that it is as fast as possible to build a balanced tree?
the specific implementation i was planning on using was either IntRBTreeSet or IntAVLTreeSet from <http://fastutil.dsi.unimi.it/docs/it/unimi/dsi/fastutil/ints/IntSortedSet.html>
after writing this up, I think the poor performance wont affect me too much anyway (too small amount of data), but im still interested in how it would be done in a general case. | A set having a tree implementation would have the middle element from your list in the top. So the algorithm would be as following:
1. find the middle element of the List
2. insert it into set
3. repeat for both sub-lists to the left and to the right of the middle element | Red-Black trees are a good choice for the general case, and they have very fast inserts. See [Chris Okasaki's paper](http://www.eecs.usma.edu/webs/people/okasaki/jfp99.ps) for an elegant and fast implementation. The [Functional Java](http://functionaljava.org) library has a generic [Set](http://functionaljava.googlecode.com/svn/artifacts/2.17/javadoc/fj/data/Set.html) class that is backed by a red-black tree implemented according to this paper. | Tree construction from an ordered list | [
"",
"java",
"performance",
"tree",
""
] |
I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of [open source crawlers](http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers) but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.
Thanks in advance. Also, this is my first SO question! | * [Mechanize](http://wwwsearch.sourceforge.net/mechanize/) is my favorite; great high-level browsing capabilities (super-simple form filling and submission).
* [Twill](http://twill.idyll.org/) is a simple scripting language built on top of Mechanize
* [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) + [urllib2](http://docs.python.org/library/urllib2.html) also works quite nicely.
* [Scrapy](http://scrapy.org/) looks like an extremely promising project; it's new. | Use [Scrapy](http://scrapy.org/).
It is a twisted-based web crawler framework. Still under heavy development but it works already. Has many goodies:
* Built-in support for parsing HTML, XML, CSV, and Javascript
* A media pipeline for scraping items with images (or any other media) and download the image files as well
* Support for extending Scrapy by plugging your own functionality using middlewares, extensions, and pipelines
* Wide range of built-in middlewares and extensions for handling of compression, cache, cookies, authentication, user-agent spoofing, robots.txt handling, statistics, crawl depth restriction, etc
* Interactive scraping shell console, very useful for developing and debugging
* Web management console for monitoring and controlling your bot
* Telnet console for low-level access to the Scrapy process
Example code to extract information about all torrent files added today in the [mininova](http://www.mininova.org/) torrent site, by using a XPath selector on the HTML returned:
```
class Torrent(ScrapedItem):
pass
class MininovaSpider(CrawlSpider):
domain_name = 'mininova.org'
start_urls = ['http://www.mininova.org/today']
rules = [Rule(RegexLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')]
def parse_torrent(self, response):
x = HtmlXPathSelector(response)
torrent = Torrent()
torrent.url = response.url
torrent.name = x.x("//h1/text()").extract()
torrent.description = x.x("//div[@id='description']").extract()
torrent.size = x.x("//div[@id='info-left']/p[2]/text()[2]").extract()
return [torrent]
``` | Anyone know of a good Python based web crawler that I could use? | [
"",
"python",
"web-crawler",
""
] |
I'm useing MySQL and I have three tables, a table of tasks, a table of products and a table that describes the relation between the two: Each product is composed of several tasks, and each task may be found in multiple products.
The table that describes the relationship between the two has two primary keys, ProductID and TaskID that are both foreign keys as well. In this table I have a field called TaskOrder that for a given Product lists the order that tasks must be performed.
What I want is to say that for any product you can't have two tasks with the same TaskOrder, however I can't just set TaskOrder to unique because diffrent products will (and should) have duplicate values for TaskOrder
Is there some way to do this? | You want a UNIQUE constraint:
```
create table ProductTasks
( ProductID ...
, TaskId ...
, TaskOrder ...
, primary key (ProductId, TaskId)
, unique (ProductId, TaskOrder)
);
``` | Create a unique index on the combination of the two fields ProductID *and* TaskOrder by adding the following to the table creation command:
```
CONSTRAINT UNIQUE (ProductID, TaskOrder)
``` | In SQL how can I have two fields that can't both be identical, only one is a primary key | [
"",
"sql",
"mysql",
""
] |
Is Django a good choice for a security critical application?
I am asking this because most of the online banking software is built using Java. Is there any real reason for this? | Actually, the security in Java and Python is the same. Digest-only password handling, cookies that timeout rapidly, careful deletion of sessions, multi-factor authentication. None of this is unique to a Java framework or a Python framework like Django.
Django, indeed, has a security backend architecture that allows you to add your own LDAP (or AD) connection, possibly changing the digest technique used.
Django has a Profile model where you can keep additional authentication factors.
Django offers a few standard decorators for view function authorization checking. Since Python is so flexible, you can trivially write your own decorator functions to layer in different or additional authentication checking.
Security is a number of first-class features in Django. | Probably the reason behind Java is not in the in the security. I think Java is more used in large development companies and banks usually resort to them for their development needs (which probably are not only related to the web site but creep deeper in the backend).
So, I see no security reasons, mostly cultural ones. | Is Django a good choice for a security critical application? | [
"",
"python",
"django",
"security",
""
] |
Similar to this [question](https://stackoverflow.com/questions/124121/how-to-create-excel-2003-udf-with-a-c-excel-add-in-using-vsto-2005-se) (but in my case not VSTO SE), however, I just want to confirm that it is not possible to create a UDF using pure VSTO in Visual Studio 2005 and Excel 2003 - so, to absolutely clear, my question is:
Is it possible to create a Excel 2003 UDF using Visual Studio 2005 and a VSTO solution without using any VBA or other tricks?
I'm aware of ManagedXLL, ExcelDNA, Excel4Net etc but don't want to consider those for the moment.
Thanks | Concerning whether there is a way around COM or VBA I don't think that it is possible (at least not without any very dirty tricks). The reason is that the only way Office can execute external code (i.e. you add-in) is via COM. Even VSTO is still using the old IDTExtensibility2 COM interface underneath. IDTExtensibility2 is a COM interface that all add-ins for Microsoft Office applications must implement.
Before VSTO, Office add-ins had to implement this IDTExtensibility2 interface themselves. In such a COM based add-in (or COM-visible managed add-in) you can simply add your UDF as described [here](http://blogs.msdn.com/eric_carter/archive/2004/12/01/273127.aspx).
However, now with VSTO, there is an additional layer of abstraction: VSTO uses a so-called [Solution Loader](http://msdn.microsoft.com/en-us/library/bb608603.aspx#UnmanagedLoader) implementing IDTExtensibility2, which is a dll provided by the VSTO runtime. This means that your add-in is no longer COM-visible. Hence, if you added a UDF to your VSTO add-in it won't be visible to Office.
Paul Stubbs explains on his blog how to do with VSTO and VBA: [**How to create Excel UDFs in VSTO managed code**](http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx)
> 1. Create a class with your functions in VSTO
>
> ```
> <System.Runtime.InteropServices.ComVisible(True)>
> Public Class MyManagedFunctions
> Public Function GetNumber() As Integer
> Return 42
> End Function
> End Class
> ```
> 2. Wire up your class to VBA in VSTO
>
> ```
> Private Sub ThisWorkbook_Open() Handles Me.Open
> Me.Application.Run("RegisterCallback", New MyManagedFunctions)
> End Sub
> ```
> 3. Create Hook for managed code and a wrapper for the functions in VBA
>
> In a VBA module in your spreadsheet or document
>
> ```
> Dim managedObject As Object
>
> Public Sub RegisterCallback(callback As Object)
> Set managedObject = callback
> End Sub
>
> Public Function GetNumberFromVSTO() As Integer
> GetNumberFromVSTO = managedObject.GetNumber()
> End Function
> ```
>
> Now you can enter `=GetNumberFromVSTO()`
> in a cell, when excel starts the cell
> value should be 42. | I don't understand why you want to do this?
VSTO and exposing UDFs via COM interop (from .NET) are two different tasks.
Why do you want to host a UDF method inside of a VSTO project?
The way you register the .net UDF assembly means it will have to be in a seperate project to the VSTO project. However if you wanted to share data between the two apps then you have a variety of native .net methods for this, or simply "call" the UDF function from the appropriate range object within your VSTO project.
Is there a reason that you feel it is necessary to have UDF in VSTO? | Create UDF using VSTO and no VBA | [
"",
"c#",
"vsto",
"excel-interop",
""
] |
How can I re-direct the user to the standard SharePoint "access denied" page, similar to the image below?
Currently, I am throwing an UnauthorizedAccessException, but this error message is not as elegant as SP message.
```
throw new UnauthorizedAccessException("User does not have permission to access this list");
```
Any help will be highly appreciated.
 | You should be able to use SPUtility.HandleAccessDenied to do this. (You can pass in null for the exception parameter if you just want to force the Access Denied page to be displayed, but aren't actually handling an exception.) | Not exactly sure what you are looking for, but if you throw an [SPException](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spexception.aspx) you have greater control over the contents of the error page. | How to display a standard SharePoint "Access Denied" message | [
"",
"c#",
"sharepoint",
"exception",
""
] |
I'm trying to write a custom STL allocator that is derived from `std::allocator`, but somehow all calls to `allocate()` go to the base class. I have narrowed it down to this code:
```
template <typename T> class a : public std::allocator<T> {
public:
T* allocate(size_t n, const void* hint = 0) const {
cout << "yo!";
return 0;
}
};
int main()
{
vector<int, a<int>> v(1000, 42);
return 0;
}
```
I expect "Yo!" to get printed, followed by some horrible error because I don't actually allocate anything. Instead, the program runs fine and prints nothing. What am I doing wrong?
I get the same results in gcc and VS2008. | You will need to provide a rebind member template and the other stuff that is listed in the allocator requirements in the C++ Standard. For example, you need a template copy constructor which accepts not only `allocator<T>` but also `allocator<U>`. For example, one code might do, which a std::list for example is likely to do
```
template<typename Allocator>
void alloc1chunk(Allocator const& alloc) {
typename Allocator::template rebind<
wrapper<typename Allocator::value_type>
>::other ot(alloc);
// ...
}
```
The code will fail if there either exist no correct rebind template, or there exist no corresponding copy constructor. You will get nowhere useful with guessing what the requirements are. Sooner or later you will have to do with code that relies on one part of those allocator requirements, and the code will fail because your allocator violates them. I recommend you take a look at them in some working draft your your copy of the Standard in `20.1.5`. | In this case, the problem is that I didn't override the rebind member of the allocator. This version works (in VS2008):
```
template <typename T> class a : public std::allocator<T> {
public:
T* allocate(size_t n, const void* hint = 0) const {
cout << "yo!";
return 0;
}
template <typename U> struct rebind
{
typedef a<U> other;
};
};
int main() {
vector<int, a<int>> v(1000, 42);
return 0;
}
```
I found this by debugging through the STL headers.
Whether this works or not will be completely dependent on the STL implementation though, so I think that ultimately, Klaim is right in that this shouldn't be done this way. | Why doesn't this C++ STL allocator allocate? | [
"",
"c++",
"stl",
"allocation",
""
] |
[Judy array](http://en.wikipedia.org/wiki/Judy_array) is fast data structure that may represent a sparse array or a set of values. Is there its implementation for managed languages such as C#? Thanks | It's worth noting that these are often called Judy Trees or Judy Tries if you are googling for them.
I also looked for a .Net implementation but found nothing.
Also worth noting that:
The implementation is heavily designed around efficient cache usage, as such implementation specifics may be highly dependent on the size of certain constructs used within the sub structures. A .Net managed implementation may be somewhat different in this regard.
There are some significant hurdles to it that I can see (and there are probably more that my brief scan missed)
* The API has some fairly anti OO aspects (for example a null pointer is viewed as an empty tree) so simplistic, move the state pointer to the LHS and make functions instance methods conversion to C++ wouldn't work.
* The implementation of the sub structures I looked at made heavy use of pointers. I cannot see these efficiently being translated to references in managed languages.
* The implementation is a distillation of a lot of very complex ideas that belies the simplicity of the public api.
* The code base is about 20K lines (most of it complex), this doesn't strike me as an easy port.
You could take the library and wrap the C code in C++/CLI (probably simply holding internally a pointer that is the c api trie and having all the c calls point to this one). This would provide a simplistic implementation but the linked libraries for the native implementation may be problematic (as might memory allocation).
You would also probably need to deal with converting .Net strings to plain old byte\* on the transition as well (or just work with bytes directly) | Judy really doesn't fit well with managed languages. I don't think you'll be able to use something like SWIG and get the first layer done automatically.
I wrote PyJudy and I ended up having to make some non-trivial API changes to fit well in Python. For example, I wrote in the documentation:
> JudyL arrays map machine words to
> machine words. In practice the words
> store unsigned integers or pointers.
> PyJudy supports all four mappings as
> distinct classes.
* pyjudy.JudyLIntInt - map unsigned
integer keys to unsigned integer
values
* pyjudy.JudyLIntObj - map unsigned
integer keys to Python object values
* pyjudy.JudyLObjInt - map Python
object keys to unsigned integer
values
* pyjudy.JudyLObjObj - map Python
object keys to Python object values
I haven't looked at the code for a few years so my memories about it are pretty hazy. It was my first Python extension library, and I remember I hacked together a sort of template system for code generation. Nowadays I would use something like genshi.
I can't point to alternatives to Judy - that's one reason why I'm searching Stackoverflow.
Edit: I've been told that my timing numbers in the documentation are off from what Judy's documentation suggests because Judy is developed for 64-bit cache lines and my PowerBook was only 32 bits.
Some other links:
* Patricia tries (<http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Tree/PATRICIA/> )
* Double-Array tries (<http://linux.thai.net/~thep/datrie/datrie.html>)
* HAT-trie (<http://members.optusnet.com.au/~askitisn/index.html>)
The last has comparison numbers for different high-performance trie implementations. | Judy array for managed languages | [
"",
"c#",
"arrays",
"data-structures",
"managed",
""
] |
I'm a game programmer working in Korea.
I started Stackoverflow recently and I found it helps me a lot.
Also I think communicating with other developers is a good way to learning and improving myself.
Stackoverflow is the only site I know to communicate (especially in English).
Any other nice place to communicate(ask/answer/talk) with game developers(or C++ programmers, network programmers)? | [Gamedev.net](http://www.gamedev.net) has a great community of game developers, along with tons of great articles and resources related to game programming. | [Beyond3D.com](http://www.beyond3d.com/) is another good site (and [forum](http://forum.beyond3d.com/)) frequented by game developers and gaming enthusiasts. | Any nice place to communicate with c++/game developers? | [
"",
"c++",
"communication",
""
] |
I know for CTP VS 2010 Images, but can I download only .NET Framework 4.0 and C# compiler? | AFAIK, the VS 2010 CTP is only available as a VM image. I do not believe Microsoft released an installer for VS. One is definitely not available for a standalone CLR/SDK. | Not at this time. Guessing maybe when the Betas start shipping. | Where I can download compiler for C# 4.0 without Visual Studio 2010? | [
"",
"c#",
".net",
"compiler-construction",
"c#-4.0",
""
] |
I can't think of an easy one or two liner that would get the previous months first day and last day.
I am LINQ-ifying a survey web app, and they squeezed a new requirement in.
The survey must include all of the service requests for the previous month. So if it is April 15th, I need all of Marches request ids.
```
var RequestIds = (from r in rdc.request
where r.dteCreated >= LastMonthsFirstDate &&
r.dteCreated <= LastMonthsLastDate
select r.intRequestId);
```
I just can't think of the dates easily without a switch. Unless I'm blind and overlooking an internal method of doing it. | ```
var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);
var first = month.AddMonths(-1);
var last = month.AddDays(-1);
```
In-line them if you really need one or two lines. | The way I've done this in the past is first get the first day of this month
```
dFirstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
```
Then subtract a day to get end of last month
```
dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);
```
Then subtract a month to get first day of previous month
```
dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);
``` | Get the previous month's first and last day dates in c# | [
"",
"c#",
".net",
"datetime",
"date",
""
] |
We're creating a demonstration mode for our web application. We're going about this by creating new user that is tied to a real client, showing all of their data, but filtering certain fields to be non-identifiable (names, important numbers, etc...)
**The weird part here is that the data is correctly filtered for standard "show one" pages where I am calling the first function. When I try to call the second on a list page, the filter doesn't work.** I have stepped through the functions, and it appears that in the first function, the values are being set, but are being reset back to the original values when the foreach iterates to the next row.
List mask is the list of column names that should be masked and is statically defined in the model.
```
public static void ApplyDemoMask(DataRow row, List<string> mask)
{
foreach (DataColumn column in row.Table.Columns)
{
if (mask.Contains(column.ColumnName))
{
if (column.ColumnName == "ClientName")
row[column] = "Demo Client";
// More fields follow...
}
}
}
public static void ApplyDemoMask(FindResponse response, List<string> mask)
{
foreach (DataRow row in response.ResultTable.Rows)
ApplyDemoMask(row, mask);
}
```
I appreciate any help that can be given. I'm kind of dumb when it comes to System.Data for some reason.
Edit: If it helps, when my debugger lands on the "}" in the second function, row["ClientName"] is "Demo Client" as it should be, but response.ResultTable.Rows[0]["ClientName"] is "The Original Client". Weird!
Edit: When binding to my grid, I have to specify column names. For one, we're using ASP.NET MVC and are using a custom control we wrote to help us transition from ASP.NET. Secondly, we have a lot of template fields. There can't be any huge, sweeping changes to this web application shares code with a pretty big WinForms line-of-business application. | **I am an absent-minded imbecile!**
Check out ResultTable's definition...
```
public DataTable ResultTable { get { return this[_resultKey]; } }
public DataTable this[string tableName]
{
get { return _data.Tables[tableName].DefaultView.ToTable(); }
}
```
I was making changes to the DataTable's DefaultView.ToTable(), which was being lost when going back to read ResultTable again. I completely forgot about this behavior and how our internal FindResponse class worked. It makes sense for our application, so I just added a similar BaseTable accessor that does not filter through DataTable.DefaultView, made my changes to that, and everything worked.
Thanks for the responses and sorry I didn't provide enough information. | Maybe you deleted and added the same records many times. so you are updating the deleted one. change second method as :
```
public static void ApplyDemoMask(FindResponse response, List<string> mask)
{
foreach (DataRow row in response.ResultTable.Rows)
{
if (row.RowState != DataRowState.Deleted)
{
ApplyDemoMask(row, mask);
}
}
}
```
or like that :
```
public static void ApplyDemoMask(FindResponse response, List<string> mask)
{
response.ResultTable.AcceptChanges();
foreach (DataRow row in response.ResultTable.Rows)
{
ApplyDemoMask(row, mask);
}
}
```
hope this helps. | How do I prevent DataRow cell values from being reset? | [
"",
"c#",
"ado.net",
""
] |
What different ways are Machine Keys useful in asp.net?
I think the following are correct but thought there may be more.
1. Multiple applications can use the same cookie
2. Multiple servers can work with the same viewstate | MachineKey is used for:
* ViewState encryption and validation
* Forms Authentication (or Federated Authentication) uses this key for signing the authentication ticket
Having a Web App installed on multiple servers requires same Machine Key configured on all of them in order for Load Balancing to work.
To see all details, please refer to: [MSDN How To: Configure MachineKey in ASP.NET 2.0](http://msdn.microsoft.com/en-us/library/ms998288.aspx#paght000007_machinekeyexplained) | Machine key is also used to encrypt/decrypt the webresources.axd parameters.
Even on a single server the machine key should be configured, because any recycle of the app domain will generate a new key when it is set to auto. This causes the next postback just for pages rendered before the recycle, to cause a viewstate validation error, and also issues with the resources during that time. | Uses for MachineKey in ASP.NET | [
"",
"c#",
"asp.net",
"cookies",
"viewstate",
"machinekey",
""
] |
In Oracle 10g, I have this SQL:
```
select dog.id as dogId from CANINES dog order by dog.codename asc
```
which returns:
```
id
--
204
203
206
923
```
I want to extend this query to determine the oracle rownum of a dog.id in this resultset.
I have tried
```
select rownum from
(select dog.id as dogId from CANINES dog order by dog.codename asc)
where dog.id=206
```
But this does not work out very well (it returns 1 no matter which dog.id I match on). I was expecting to get back 3.
Thanks for your help!
---
*Notes*
<http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html>
I am pretty sure I do not need to use rowid | I suspect what you want is to use an analytic function (RANK, `DENSE_RANK`, or `ROW_NUMBER`), i.e.
```
SELECT rnk
FROM (select dog.id as dogId,
ROW_NUMBER() OVER( ORDER BY dog.codename ASC ) rnk
from CANINES dog )
WHERE dogId = 206
```
If the ID column in the CANINES table were not unique, RANK, `DENSE_RANK`, and `ROW_NUMBER`) would treat ties differently.
If you want to do this solely with ROWNUM,
```
SELECT rn
FROM (
SELECT dogId, rownum rn
FROM (select dog.id as dogId
from CANINES dog
order by dog.codename ASC) inner
) middle
WHERE dogId = 206
``` | If you're after the unique identifier of each row in the table you need ROWID, not ROWNUM.
ROWNUM is a pseudocolumn that can change each time a bit of SQL is executed (it's worked out at query time) | SQL to return the rownum of a specific row? (using Oracle db) | [
"",
"sql",
"oracle",
"oracle10g",
"rowid",
""
] |
My winforms app isn't shutting down nicely when I log off/shutdown. I have a main form, whose Closing event is fired correctly, but there must be something else keeping my application around. If I check Application.OpenForms there's just my one main form.
The tricky bit, and where the problem probably lies, is that my application uses ShellWindows to hook into Internet Explorer, and occassionally opens up forms when IE events fire. It's after one or more of these forms has been opened and closed that my app stops closing on shutdown.
I think I'm cleaning up all form objects etc and calling FinalReleaseComObject() appropriately, but I guess there are references somewhere that are holding my process open. Is there any way to work out what it is that's stopping my app from closing gracefully? | The most likely cause is that you have a background thread hanging around that is not being closed when the main window of your application is closed. Depending on your settings and framework version background threads can keep an application alive when the main thread is terminated.
During shutdown windows asks every running app to terminate usually by sending a WM\_QUIT to the main window on a process. WinForms will happily use this message to shutdown the main window but if any background threads are left the actual process could continue. | An application will also stay open if there are threads running that have not been set to background. If you are creating any of your own threads, make sure that they are terminating appropriately.
If it is not critical that the thread finishes, set [IsBackground](http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx) to true. You can also call Abort on a thread to (somewhat)forcibly kill it. | Why does my application not close on logoff/shutdown (c#/.net winforms)? | [
"",
"c#",
".net",
"winforms",
"com",
"shutdown",
""
] |
I'm trying to understand what the Java *java.security.Signature* class does. If I compute an SHA1 message digest, and then encrypt that digest using RSA, I get a different result to asking the *Signature* class to sign the same thing:
```
// Generate new key
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
String plaintext = "This is the message being signed";
// Compute signature
Signature instance = Signature.getInstance("SHA1withRSA");
instance.initSign(privateKey);
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
// Compute digest
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
byte[] digest = sha1.digest((plaintext).getBytes());
// Encrypt digest
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digest);
// Display results
System.out.println("Input data: " + plaintext);
System.out.println("Digest: " + bytes2String(digest));
System.out.println("Cipher text: " + bytes2String(cipherText));
System.out.println("Signature: " + bytes2String(signature));
```
Results in (for example):
> Input data: This is the message being signed
> Digest: 62b0a9ef15461c82766fb5bdaae9edbe4ac2e067
> Cipher text: 057dc0d2f7f54acc95d3cf5cba9f944619394711003bdd12...
> Signature: 7177c74bbbb871cc0af92e30d2808ebae146f25d3fd8ba1622...
I must have a fundamental misunderstanding of what *Signature* is doing - I've traced through it, and it appears to be calling update on a *MessageDigest* object, with the algorithm set to SHA1 as I would expect, then getting the digest, then doing the encryption. What's making the results differ?
**EDIT:**
Leonidas made me check whether the signature scheme is supposed to do what I think it does. There are two types of signature defined in the [RFC](http://www.apps.ietf.org/rfc/rfc3447.html):
* [RSASSA-PKCS1-v1\_5](http://www.apps.ietf.org/rfc/rfc3447.html#sec-9.2)
* [RSASSA-PSS](http://www.apps.ietf.org/rfc/rfc3447.html#sec-9.1)
The [first of these](http://www.apps.ietf.org/rfc/rfc3447.html#sec-9.2) (PKCS1) is the one I describe above. It uses a hash function to create a digest, and then encrypts the result with a private key.
The [second algorithm](http://www.apps.ietf.org/rfc/rfc3447.html#sec-9.1) uses a random salt value, and is more secure but non-deterministic. The signature produced from the code above does not change if the same key is used repeatedly, so I don't think it can be PSS.
**EDIT:**
Here's the `bytes2string` method I was using:
```
private static String bytes2String(byte[] bytes) {
StringBuilder string = new StringBuilder();
for (byte b : bytes) {
String hexString = Integer.toHexString(0x00FF & b);
string.append(hexString.length() == 1 ? "0" + hexString : hexString);
}
return string.toString();
}
``` | OK, I've worked out what's going on. Leonidas is right, it's not just the hash that gets encrypted (in the case of the Cipher class method), it's the ID of the hash algorithm concatenated with the digest:
```
DigestInfo ::= SEQUENCE {
digestAlgorithm AlgorithmIdentifier,
digest OCTET STRING
}
```
Which is why the encryption by the Cipher and Signature are different. | To produce the same results:
```
MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("1.3.14.3.2.26");
AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);
byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);
``` | Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher | [
"",
"java",
"encryption",
"cryptography",
"rsa",
"digital-signature",
""
] |
I'm just trying to do some simple validation in MVC RC and am getting an error. For the purposes of this question, I am **not using the UpdateModel**.
Here is the code in the form:
```
<%= Html.TextBox("UserId")%>
<%= Html.ValidationMessage("UserId") %>
```
If I add the following line in the controller, I will get a NullReferenceException on the TextBox:
```
ModelState.AddModelError("UserId", "*");
```
So to fix this, I've also added the following line:
```
ModelState.SetModelValue("UserId", ValueProvider["UserId"]);
```
Why am I having to rebind the value? **I only have to do this if I add the error**, but it seems like I shouldn't have to do this. I feel like Im doing something incorrectly or just not familiar enough with binding.
It looks like Im not the only one who has seen this. Per request, here is the controller code:
```
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
AppUser newUser = new AppUser();
try
{
newUser.UserId = collection["UserId"];
AppUserDAL.AddUser(newUser);
return RedirectToAction("Index");
}
catch (Exception ex)
{
ViewData["ReturnMessage"] = ex.Message;
ModelState.AddModelError("UserId", "*");
ModelState.SetModelValue("UserId", ValueProvider["UserId"]);
return View(newUser);
}
``` | Call this extension method:
```
public static void AddModelError (this ModelStateDictionary modelState, string key, string errorMessage, string attemptedValue) {
modelState.AddModelError (key, errorMessage);
modelState.SetModelValue (key, new ValueProviderResult (attemptedValue, attemptedValue, null));
}
```
From: [Issues with AddModelError() / SetModelValue with MVC RC1](http://www.crankingoutcode.com/2009/02/01/IssuesWithAddModelErrorSetModelValueWithMVCRC1.aspx) | You definitely don't need to call SetModelValue.
Perhaps you just need your view to pull the Textbox from the model you passed in?
```
<%= Html.TextBox("UserId", Model.UserId)%>
```
That's how I do it. | MVC RC Validation: Is this right? | [
"",
"c#",
"asp.net-mvc",
"validation",
"binding",
"html-helper",
""
] |
In which situations I should use LINQ to Objects?
Obviously I can do everything without LINQ. So in which operations LINQ actually helps me to code **shorter** and/or **more readable**?
*[This question triggered by this](https://stackoverflow.com/questions/573026/how-to-convert-this-code-to-linq)* | I find LINQ to Objects useful all over the place. The problem it solves is pretty general:
* You have a collection of some data items
* You want another collection, formed from the original collection, but after some sort of transformation or filtering. This might be sorting, projection, applying a predicate, grouping, etc.
That's a situation I come across pretty often. There are an awful lot of areas of programming which basically involve transforming one collection (or stream of data) into another. In those cases the code using LINQ is almost always shorter and more readable. I'd like to point out that LINQ shouldn't be regarded as being synonymous with query expressions - if only a single operator is required, [the normal "dot notation" (using extension methods) can often be shorter and more readable](http://msmvps.com/blogs/jon_skeet/archive/2009/01/07/you-don-t-have-to-use-query-expressions-to-use-linq.aspx).
One of the reasons I particularly like LINQ to Objects is that it *is* so general - whereas LINQ to SQL is likely to only get involved in your data layer (or pretty much become the data layer), LINQ to Objects is applicable in every layer, and in all kinds of applications.
Just as an example, here's a line in my MiniBench benchmarking framework, converting a `TestSuite` (which is basically a named collection of tests) into a `ResultSuite` (a named collection of results):
```
return new ResultSuite(name,
tests.Select(test => test.Run(input, expectedOutput)));
```
Then again if a `ResultSuite` needs to be scaled against some particular "standard" result:
```
return new ResultSuite(name,
results.Select(x => x.ScaleToStandard(standard, mode)));
```
It wouldn't be *hard* to write this code without LINQ, but LINQ just makes it clearer and lets you concentrate on the real "logic" instead of the details of iterating through loops and adding results to lists etc.
Even when LINQ itself isn't applicable, some of the features which were largely included for the sake of LINQ (e.g. implicitly typed local variables, lambda expressions, extension methods) can be very useful. | LINQ is great for the "slippery slope". Think of what's involved in many common operations:
* **Where**. Just write a foreach loop and an "if"
* **Select**. Create an empty list of the target type, loop through the originals, convert each one and add it to the results.
* **OrderBy**. Just add it to a list and call .Sort(). Or implement a bubble sort ;)
* **ThenBy** (from order by PropertyA, then by PropertyB). Quite a bit harder. A custom comparer and Sort should do the trick.
* **GroupBy** - create a `Dictionary<key, List<value>>` and loop through all items. If no key exists create it, then add items to the appropriate list.
In each of those cases, the procedural way takes more code than the LINQ way. In the case of "if" it's a couple of lines more; in the case of GroupBy or OrderBy/ThenBy it's a lot more.
Now take an all too common scenario of combining them together. You're suddenly looking at a 10-20 line method which could be solved with 3-4 lines in LINQ. And the LINQ version is guaranteed to be easier to read (once you are familiar with LINQ).
So when do you use LINQ? My answer: whenever you see "foreach" :) | Where and When to use LINQ to Objects? | [
"",
"c#",
".net",
"vb.net",
"linq",
""
] |
I'm porting a c++ Qt application from Windows to OSX and cannot wrap my head around the .app bundle concept. I hope someone can help me understand.
My executable lives here: MyProgram.app/Content/MacOS/MyProgram.exe
My resource folder lives here: MyProgram.app/Content/Resources/
In my code I use a relative path to reference items in the resource folder:
"../Resources/something.png"
This works great if I open the .app bundle and run the .exe directly.
But that is not how the .app bundle is meant to work. The user is supposed to click on the .app bundle in the Finder to run the program. But in that case my relative path no longer works, and this is what I don't understand.
Does anyone understand my problem and how I can fix it? | ```
QApplication::applicationDirPath()
```
<http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath> | We use:
```
QDir
CoreDir::bundle()
{
// Trolltech provided example
CFURLRef appUrlRef = CFBundleCopyBundleURL( CFBundleGetMainBundle() );
CFStringRef macPath = CFURLCopyFileSystemPath( appUrlRef, kCFURLPOSIXPathStyle );
QString path = CFStringToQString( macPath );
CFRelease(appUrlRef);
CFRelease(macPath);
return QDir( path );
}
```
So do CoreDir::bundle().filePath( "../Resources" ); | How to reference Resources folder in code | [
"",
"c++",
"macos",
"qt",
"bundle",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.