Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
What are some good conventions to follow if I want to make my application harder to crack? | As long as your entire application is client side, it's completely impossible to protect it from being cracked. The only way to protect an application from being cracked is to make it have to connect to a server to function (like an online game, for example).
And even then, I have seen some cracks that simulate a server and send a dummy confirmation to the program so it thinks it's talking to a real, legit server (in this case I'm talking about a "call home" verification strategy, not a game).
Also, keep in mind that where there is a will, there's a way. If someone wants your product badly, they will get it. And in the end you will implement protection that can cause complications for your honest customers and is just seen as a challenge to crackers.
Also, see [this thread](https://stackoverflow.com/questions/109997/how-do-you-protect-your-software-from-illegal-distribution) for a very thorough discussion on this topic. | A lot of the answers seem to miss the point that the question was how to make it harder, not how to make it impossible.
Obfuscation is the first critical step in that process. Anything further will be too easy to work out if the code is not Obfuscated.
After that, it does depend a bit on what you are trying to avoid. Installation without a license? The timed trial blowing up? Increased usage of the software (e.g. on more CPUs) without paying additional fees?
In today's world of virtual machines, the long term anti-cracking strategy has to involve some calling of home. The environment is just too easy to make pristine. That being said, some types of software are useless if you have to go back to a pristine state to use them. If that is your type of software, then there are rather obscure places to put things in the registry to track timed trials. And in general a license key scheme that is hard to forge.
One thing to be aware of though - don't get too fancy. Quite often the licensing scheme gets the least amount of QA, and hits serious problems in production where legitimate customers get locked out. Don't drive away real paying customers out of fear of copying by people would most likely wouldn't have paid you a dime anyway. | Conventions to follow to make Commercial software harder to crack? | [
"",
"c#",
"drm",
""
] |
Is it possible to programmatically place the contents of a web page into a Word file?
To further complicate this, I'd like to do these steps in Java (using JNI if I must).
Here are the steps I want to do programmatically, followed by ways that I would do this manually today:
1. Provide a method with a URL *(Manually: Open page in Firefox)*
2. Copy the contents of that URL *(Manually: Ctrl-A to select all)*
3. Create a new Word document *(Manually: Open Microsoft Word)*
4. Paste the contents of the URL into Word *(Manually: Ctrl-V to paste)*
5. Save the Word file *(Manually: Save the Word file)* | you could do better imho downloading the file using HTTP then create a new word file using [Apache POI](http://poi.apache.org/hwpf/index.html) and copying the HTTP stream inside the word file | [HTMLUnit](http://htmlunit.sourceforge.net/) can be used to programmatically open the page (posing as Firefox if necessary), and [Apache POI](http://poi.apache.org/) can be used to create a Microsoft Word file (in Word 97 format). | Programmatic way to place a website into a new Word file... in Java | [
"",
"java",
"url",
"ms-word",
""
] |
I have an instance of ObservableCollection bound to a WPF listbox with two separate data templates (one for display, one for editing). The data template for editing has a one-way binding on the textbox, and a Save button.
What changes do I need to make so that when I press the Save button (after putting the list item in edit mode), the value I change the textbox to replaces the value in the ObservableCollection (and the display)? | Items in your collection should be of type that implements INotifyPropertyChanged interface. This way your list box will be notified that property value in your single item object has changed. ObservableCollection raises CollectionChanged event only when collection changes (items added, removed, etc.)
Quote from the MSDN library article on ObservableCollection
> To fully support transferring data
> values from binding source objects to
> binding targets, each object in your
> collection that supports bindable
> properties must implement an
> appropriate property changed
> notification mechanism such as the
> INotifyPropertyChanged interface. | For change notification to occur in a binding between a bound client and a data source, your bound type should either:
* Implement the INotifyPropertyChanged
interface (preferred).
* Provide a change event for each
property of the bound type.
Do not do both.
Source: [MSDN: INotifyPropertyChanged Interface](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx) | How do I update an existing element of an ObservableCollection? | [
"",
"c#",
"wpf",
"datatemplate",
"observablecollection",
""
] |
How can I freeze Javascript in firebug so that i can inspect the changes made by it in the html? If for example i have a jQuery rollover effect and i want to inspect the html code in that point in time.
I believe Dreamweaver CS4 has this feature titled freeze javascript and live code. Is there a free equivalent either in Firebug or another Firefox extension? | By "freeze" I assume you mean debugging, and yes, Firebug definitely has that.
First you have to go into the Script tab on Firebug. If Script is disabled on the site, enable it.
Now, go to the dropdown and select which JavaScript file you want to debug. This is typically either the page itself with inline JavaScript, or a linked page. Find the line of code you want to freeze on, and click to the left of the line numbers. You'll see a red dot appear - this dot denotes that the code will freeze there during execution. Once the code is there, you can access the current HTML by going to the "HTML" tab. You'll also see the icons in the top-right corner of Firebug's Script pane light up, allowing you to either continue execution, step over, step into, or step out of each line of code, observing HTML changes for each line executed.
Note that Firebug lets you step through code line-by-line, which means that minimized JavaScript files (wherein all the code is compacted onto one line) are absolutely awful for debugging, because you can't tell where Firebug is. So for debugging purposes, I highly recommend getting the non-minimized versions of files.
If you need more help, I suggest checking out the [Firebug documentation](http://getfirebug.com/docs.html), which has some good guides. | Break on mutate (the pause button when the html tab is selected) is the closest thing I can find to this feature. It will pause the next time something is changed. It's just one off of what you want, but could be useful. | Firefox Firebug Extension - Freeze Javascript Feature? | [
"",
"javascript",
"jquery",
"debugging",
"firefox",
"firebug",
""
] |
Consider the following code:
```
class Program
{
static void Main(string[] args)
{
Department deathStar = new Department { Name = "Death Star" };
Console.WriteLine("The manager of {0} is {1}.", deathStar.Name, deathStar.Manager.FullName);
deathStar.Manager.FirstName = "Lord";
Console.WriteLine("The manager of {0} is {1}.", deathStar.Name, deathStar.Manager.FullName);
Console.ReadLine();
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return this.FirstName + " " + this.LastName;
}
}
}
public class Department
{
public string Name { get; set; }
public Person Manager { get; private set; }
public Department()
{
this.Manager = new Person { FirstName = "Darth", LastName = "Vader" };
}
}
```
which produces the following output:
> ```
> The manager of Death Star is Darth Vader.
> The manager of Death Star is Lord Vader.
> ```
Even though I can't change Manager to be a different or new instance of Person (private set accessor), I can change it's properties (which have public set accessors).
So, is assigning a value to a property through a set accessor via its container's get accessor a bad thing? In other words, is this a code smell?
**EDIT:**
This is just a sample to illustrate a point. Person and Department were created for this sample only. | Not necessarrily.
For example, look at the parameters collection on a SqlCommand object. You can change the items in the collection, but you can't assign a new parameters collection to the command object.
Take your example, if you had a UI maintaining Person objects, and you needed to change a persons first name, it's perfectly valid to change the persons first name, leave the last name and PersonId fields alone, then update a database table using the PersonId field.
It all sounds OK to me | Yes, this is a code smell.
While this seems like a fairly harmless practice, public properties expose the fields of your class to arbitrary change and create needless dependence on implementation details. You may as well be using a struct. *(I'm not implying that structs are bad either. Procedural programming is just as useful as OOP. It all depends on the problem being solved)* The point of encapsulation is to hide implementation details from the class' dependents. Rather you should expose abstract interfaces that allow dependent classes to modify the internal data without needing to know its implementation. Consider the following examples:
```
public interface Vehicle {
double FuelTankCapacityInGallons{get;}
double GallonsOfGasoline{get;}
}
public interface Vehicle {
double getPercentFuelRemaining();
}
```
Both interfaces will get you the amount of remaining gasoline. The first through concrete terms, the second through abstraction. If the size of the tank changes or you need to implement a European car the first example would require changes to both the Vehicle and whatever class is using it. While the second would only require changes to the Vehicle implementation.
The example I used is from the book *Clean Code - A Handbook of Agile Software Craftsmanship* by Robert C. Martin.
I would also look up [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter). | Is assigning a value to a property through a set accessor via its container's get accessor a bad thing? | [
"",
"c#",
"oop",
"properties",
""
] |
I have a simple udp listener written in c++ using win32 when I compile and run the program under debug mode it works perfectly, and I'm clearly able to see the information from the packets that I'm receiving. When I run this same code as a release build it compiles fine and seems to run fine, but its not printing out any packet information like it did under the release build. I've tried to mirror the build configurations to match exactly but its still happening. Any suggestions would be greatly appreciated. | This is more likely an issue of not initializing variables to some initial value, so in debug they have some sort of value, but in release, most things are initialized zero (NULL). So, some condition/branch may be taking place, that you do not expect... Without your source code for example, it's REALLY hard to spot issues.
This has bit me more than once.. :)
This is assuming you are not expecting to see anything using stuff like OutputDebugString() as [Mehrdad](https://stackoverflow.com/users/33708/mehrdad) suggested...
Also, make sure your packets are UNDER 1024 bytes in size, or you will NOT get them. Took me a while to figure this one out back when XP came out, and I couldn't figure out why my code worked on 2000, but not XP... Even though send (sendto) would return success, it never actually SENT the packet..
Anyways, I've dealt with UDP a lot on Win32, so if you give me some example code I should be able to help more...
But anyways, check that ALL your variables are initialized to some sort of default value on both the sender and the receiver, (which is just good practice), and then re-build it and try again. Also, check your packet size with a sizeof() before it sends, and if it's greater than 1024 bytes, don't bother... It's also a good idea to check size of the received packet, and if it's not exactly the size you expect, then drop the packet. This holds MORE true for broadcasts, but still applies.
Let me know if any of this helped, I posted a LOT of UDP code on [another question](https://stackoverflow.com/questions/390944/how-to-do-private-comms-between-private-apps-over-network/558279#558279) here a little while back, and that code works, you might want to refer to it. | The code that outputs debugging information about the packets is probably stripped out for performance reasons in the release build.
This is done mostly by two things:
* conditional preprocessor directives that check against debug mode and generate appropriate code in that mode.
* linking against debug version of libraries.
Dropping those stuff is in fact, the primary purpose you are building a release version. You ain't gonna need debugging info so you won't be sacrificing performance for it. If you're really want to do so, then why don't you just ship the debug build [*update: as noted in a comment, seems the license doesn't allow you to distribute software linked against debug libs*]? It's the most similar configuration (you can't get more a config similar than identical, can you?) | debug vs release build in Visual studio c++ 2008 win32 runtime issue | [
"",
"c++",
"visual-studio",
"debugging",
"winapi",
"winsock",
""
] |
I find myself constantly pressing ctrl-z to undo the automatic formatting that happens in templates. For example Resharper would like to format a foreach loop like this:
```
<%
foreach (var product in Model.Items)
{ %>
<li><%= product.Name %></li>
<% } %>
```
This is fine in c# code files but it just seems messy in templates.
I would prefer to format it like this
```
<% foreach (var product in Model.Items) { %>
<li><%= product.Name %></li>
<% } %>
``` | Open Visual Studio
Goto
Resharper > Options... > Langauges > C# > Formatting Style > Braces Layout > Other
Change to "At end of line (no space)"
Note this will affect your C# as well.
It is a bit annoying that you cant specify a different code sytle for you aspx pages since its often you do want something differnt. | Resharper does not allow you to create custom formatting. You can only change the predefined formatting under options. I poked around and did not see <% %> formatting options. Sorry :( | Is it possible to change the way Resharper 4.5 formats code in aspx/ascx files? | [
"",
"c#",
"resharper",
""
] |
I have RO access on a SQL View. This query below times out. How to avoid this?
```
select
count(distinct Status)
from
[MyTable] with (NOLOCK)
where
MemberType=6
```
The error message I get is:
> Msg 121, Level 20, State 0, Line 0
>
> A transport-level error has occurred when receiving results from the server (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.) | Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).
I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion). | Your query is probably fine. "The semaphore timeout period has expired" is a Network error, not a SQL Server timeout.
There is apparently some sort of network problem between you and the SQL Server.
edit: However, apparently the query runs for 15-20 min before giving the network error. That is a very long time, so perhaps the network error could be related to the long execution time. Optimization of the underlying View might help.
If [MyTable] in your example is a View, can you post the View Definition so that we can have a go at optimizing it? | How to avoid Sql Query Timeout | [
"",
"sql",
"sql-server",
""
] |
I have an Infragistics UltraNumericEditor (version 5.3, quite old) control on a form.
If I set the .Value field to something less than .MinValue or something more than .MaxValue then I get a System.Exception thrown with the following message:
> The 'Value' property cannot be set to a value that is outside the range determined by the 'MinValue' and 'MaxValue' properties
The signatures of the relevant fields on UltraNumericEditor are as follows:
```
public object MinValue { get; set; }
public object MaxValue { get; set; }
public object Value { get; set; }
```
This has potential to occur many hundreds of times through our codebase, so rather than check MinValue and MaxValue vs the value we're trying to set *every time*, I thought I'd subclass the control and put the check there:
```
public class OurNumericEditor : Infragistics.Win.UltraWinEditors.UltraNumericEditor
{
public object Value
{
get
{
return base.Value;
}
set
{
// make sure what we're setting isn't outside the min or max
// if it is, set value to the min or max instead
double min = (double)base.MinValue;
double max = (double)base.MaxValue;
double attempted = (double)value;
if (attempted > max)
base.Value = max;
else if (attempted < min)
base.Value = min;
else
base.Value = value;
}
}
}
```
Clearly this works fine when the type of value, MinValue and MaxValue can be casted to doubles, but I would expect an InvalidCastException when that's not possible.
Now I may just be having a blonde moment here but I think it should be possible to write a method that makes use of generics to do the comparison, but I'm struggling to visualise what that might look like.
Any ideas or input at all?
Thanks
Tom | You can't make any good use of generics, as you don't know the data type at compile time.
Just use the `Convert` class to convert any kind numeric data to `double` values:
```
double min = Convert.ToDouble(base.MinValue);
double max = Convert.ToDouble(base.MaxValue);
double attempted = Convert.ToDouble(value);
```
This has the benefit that it also handles cases with mixed data types, like when `MinValue` is an `int` and `value` is a `double`. | You could simply cast everything as [IComparable](http://msdn.microsoft.com/en-us/library/system.icomparable.aspx) and use that interface to do the comparison. | Struggling to come up with a generic C# method that compares different types of numeric objects | [
"",
"c#",
"generics",
"infragistics",
""
] |
I have a wrapper generic class that intended to be used with a set of types. Those types are generated by a utility and are all derived from a base class ClientBase. While ClientBase has only a default constructor, all generated types have default constructor as well as a constructor takes a string as parameter. In the constructor of the wrapper class, I instantiate an instance of the type with the constructor that takes a string. Here is a sample code:
```
public class ClientBase
{ }
public class GenericProxy<T>
where T: ClientBase, new()
{
T _proxy;
public GenericProxy(string configName)
{
_proxy = new T(configName);
}
}
```
This code does not compile because type T is not guaranteed to have a constructor that takes a string. Is there a way to define a constrain on the generic class to enforce that the type T must have a constructor that take a string? If this is not possible, what are good alternatives to handle this kind of situation? | It's not possible. I'd like to see ["static interfaces"](http://codeblog.jonskeet.uk/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces) to handle this, but don't expect them any time soon...
Alternatives:
* Specify a delegate to act as a factory for T
* Specify another interface to act as a factory for T
* Specify an interface on T itself for initialization (and add a constraint so that `T` implements the interface)
The first two are really equivalent. Basically you'd change your proxy class to something like this:
```
public class GenericProxy<T>
where T: ClientBase, new()
{
string _configName;
T _proxy;
Func<string, T> _factory;
public GenericProxy(Func<string, T> factory, string configName)
{
_configName = configName;
_factory = factory;
RefreshProxy();
}
void RefreshProxy() // As an example; suppose we need to do this later too
{
_proxy = _factory(_configName);
}
}
```
(I assume you're going to want to create more instances later - otherwise you might as well pass an instance of T into the constructor.) | Unfortunately what you're trying to do isn't possible.
[MSDN article on Type Constraints](http://msdn.microsoft.com/en-us/library/d5x73970.aspx) | How to constrain generic type to must have a construtor that takes certain parameters? | [
"",
"c#",
"generics",
"constraints",
""
] |
Say I have enum as follows (taken from MSDN example):
```
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
```
I can then use is in the code as follows:
```
int today = (int)Days.Sun;
```
Question:
Can I evaluate enums? Say I have a variable Day whose value is "Sun".
Will Days.Day evaluate to Days.Sun?
Thanks!
Please don't get hung up on the days example and tell me I should use comparison etc...i am looking to replace the usage of arrays with enums as it is more compact. So what I am looking for is essentially an ability to retrieve values from enum similar to an array:
myArray[Day] where day will evaluate to array key.... | Am I right in saying you've got:
```
string day = "Sun";
```
and you want to get back the value `Days.Sun`?
If so, use:
```
string day = "Sun";
Day day = (Day) Enum.Parse(typeof(Days), day);
``` | Yes, you can do that. You can freely cast between an `enum` and its underlying type.
```
using System;
class Program
{
static void Main()
{
// prints "zero"
Console.WriteLine((Foo)0);
// prints "1"
Console.WriteLine((int)Foo.one);
}
}
enum Foo { zero, one, two };
``` | Enum evaluation in c# | [
"",
"c#",
"enums",
"casting",
""
] |
I'm new to jQuery and would like to parse an XML document.
I'm able to parse regular XML with the default namespaces but with XML such as:
```
<xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
<s:Schema id="RowsetSchema">
<s:ElementType name="row" content="eltOnly" rs:CommandTimeout="30">
<s:AttributeType name="ows_ID" rs:name="ID" rs:number="1">
<s:datatype dt:type="i4" dt:maxLength="4" />
</s:AttributeType>
<s:AttributeType name="ows_DocIcon" rs:name="Type" rs:number="2">
<s:datatype dt:type="string" dt:maxLength="512" />
</s:AttributeType>
<s:AttributeType name="ows_LinkTitle" rs:name="Title" rs:number="3">
<s:datatype dt:type="string" dt:maxLength="512" />
</s:AttributeType>
<s:AttributeType name="ows_ServiceCategory" rs:name="Service Category" rs:number="4">
<s:datatype dt:type="string" dt:maxLength="512" />
</s:AttributeType>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row ows_ID="2" ows_LinkTitle="Sample Data 1" />
<z:row ows_ID="3" ows_LinkTitle="Sample Data 2" />
<z:row ows_ID="4" ows_LinkTitle="Sample Data 3" />
</rs:data>
</xml>
```
All I really want are the `<z:row>`.
So far, I've been using:
```
$.get(xmlPath, {}, function(xml) {
$("rs:data", xml).find("z:row").each(function(i) {
alert("found zrow");
});
}, "xml");
```
with really no luck. Any ideas? | I got it.
Turns out that it requires `\\` to escape the colon.
```
$.get(xmlPath, {}, function(xml) {
$("rs\\:data", xml).find("z\\:row").each(function(i) {
alert("found zrow");
});
}, "xml");
```
As Rich pointed out:
The better solution does not require escaping and works on all "modern" browsers:
```
.find("[nodeName=z:row]")
``` | I have spent several hours on this reading about plugins and all sorts of solutions with no luck.
ArnisAndy posted a link to a jQuery discussion, where this answer is offered and I can confirm that this works for me in Chrome(v18.0), FireFox(v11.0), IE(v9.08) and Safari (v5.1.5) using jQuery (v1.7.2).
I am trying to scrape a WordPress feed where content is named <content:encoded> and this is what worked for me:
```
content: $this.find("content\\:encoded, encoded").text()
``` | How to use jQuery for XML parsing with namespaces | [
"",
"javascript",
"jquery",
"xml",
"namespaces",
"xsd",
""
] |
If you have a `Point3` class and have a method called `Distance`, should you have it static like this:
```
Point3.Distance ( p1, p2 );
```
or an instance method like:
```
this.Distance ( p );
```
I realize using static methods hinders inheritance and overriding, right?
Which one is better, and why? | I prefer the static version. (And this is what we've done across the board in SlimDX, save for a few "special" operations.) The reasoning is that Distance is conceptually a function that processes two points, and has a result. You're not running the "Distance" operation on p1, with p2 as the value.
In short, I prefer that instance methods are conceptually an operation bound to a specific instance. For some, it goes either way. For example, SlimDX includes both static and non static versions of the Vector3 Normalize function, because both constructs are pretty handy. The instance one modifies its object, and the static one returns a new one.
[Edit] Another answer mentions a "DistanceTo" function that would be an instance function. While that's not necessarily unreasonable, it's a design direction that makes me uneasy. The problem is orthogonality. Once you add more of these overloads -- some static, some instance, maybe some in a MathHelper class, who knows -- you end up with more and more ways to do the same thing. This is bad news for library complexity, test complexity, bug surface area, etc. We've chosen to do it in places in SlimDX, but that's in just a select few places across a lot of classes (and every single one's been team reviewed). It can help usability of a library to an extent, but it's really dangerously easy to end up on the wrong side of the line. | I prefer the static version, but depending on how you use it or expect it to be used, I'd consider including an instance method `DistanceTo` that calls the static method. Sometimes instance methods like that can make code more concise and readable.
One big selling point frequently for static methods like this is that they can return results even when one or both of their operands is `null`. If you've only got an instance method, you'll need to test it for `null` before calling the method. `Object.Equals`/`ReferenceEquals` is a canonical example of this. | Instance vs Static methods for multiple variable methods | [
"",
"c#",
".net",
""
] |
I may be way off base, but I've been trying all afternoon to run [the curl post command](http://www.recessframework.org/page/restful-php-framework) in this recess PHP framework tutorial. What I don't understand is how is PHP supposed to interpret my POST, it always comes up as an empty array.
```
curl -i -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
```
(The slash in there is just to make me not look like an idiot, but I executed this from windows using PHP 5.2, also tried on a Linux server, same version with Linux curl)
There must be something I'm missing because it seems pretty straightforward, the post just isn't be interpreted right, if it was, everything would work great.
This is what I get back:
```
HTTP/1.1 409 Conflict
Date: Fri, 01 May 2009 22:03:00 GMT
Server: Apache/2.2.8 (Win32) PHP/5.2.6
X-Powered-By: PHP/5.2.6
Transfer-Encoding: chunked
Content-Type: text/html; charset=iso-8859-1
{"screencast":{"id":null,"subject":null,"body":null,
"dataUrl":null,"dataMedium":null,"createdOn":null,"author":null}}
``` | Jordans analysis of why the $\_POST-array isn't populated is correct. However, you can use
```
$data = file_get_contents("php://input");
```
to just retrieve the http body and handle it yourself. See [PHP input/output streams](https://www.php.net/wrappers.php).
From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request. | Normally the parameter `-d` is interpreted as form-encoded. You need the `-H` parameter:
```
curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
``` | How to post JSON to PHP with curl | [
"",
"php",
"rest",
"post",
""
] |
I am currently trying to complete a project using Qt4 and C++. I am using buttons to switch between states. While trying to connect the buttons' clicked() signals to the textEdit to display the relevant state, I got stuck on an error:
> Object::connect No such slot
> QTextEdit::append("move state")
> Object::connect No such slot
> QTextEdit::append("link state")
Only, QTextEdit definitely has an append(QString) slot.
Any ideas?
Some code samples:
```
QPushButton *move = new QPushButton("Move");
connect(move, SIGNAL(clicked()), textEdit, SLOT(append("move state")));
``` | You can't pass in an argument (literally) to the append() slot when making a signal to slot connection.
You refer to it like a method signature:
```
SLOT(append(QString)) //or const QString, I'm not sure
```
If you need the textbox to append the words "move state" every time that button is clicked, then you should define your own slot that will do the append. | Chris has it in a nutshell.
That is one of the many reasons I like boost::signals a lot more (you are allowed to use boost::bind). You are basically going to need to create another function that captures the signal and then performs the append.
```
...
QPushButton *move = new QPushButton("Move");
connect(move, SIGNAL(clicked()), textEdit, SLOT(MoveState()));
}
...
void MyTextEdit::MoveState()
{
append("move state");
}
``` | Qt4 existing slots are not recognized | [
"",
"c++",
"qt",
"qt4",
"signals-slots",
""
] |
Let's say you have some 3rd-party **library** class that you want to extend, simply to add convenience methods to it (so you can call an inherited method with default parameters for example).
Using jUnit/jMock, is it possible to write an assertion / mock expection that tests that the correct inherited method is called?
For example, something like this:
```
class SomeClass extends SomeLibraryClass {
public String method(String code) {
return method(code, null, Locale.default());
}
}
```
How can I assert that `method` is being called? | You can make a further subclass inside your unit test that actually tells you:
```
public class MyTest {
boolean methodCalled = false;
@Test
public void testMySubclass(){
TestSomeClass testSomeClass = new TestSomeClass();
// Invoke method on testSomeclass ...
assertTrue( methodCalled);
}
class TestSomeClass extends SomeClass{
public String method(String code){
methodCalled = true;
}
}
}
``` | Unit testing is more useful to verify the functionality of given methods, not to assert coverage. Unit tests that care more about what method got called know way more about the classes they are testing than they probably should, not to mention will be confusing to the reader.
Coverage tools like [Cobertura](http://cobertura.sf.net) or [EMMA](http://emma.sf.net) will tell you whether you properly covered your code. | jUnit - How to assert that inherited methods are invoked? | [
"",
"java",
"inheritance",
"junit",
"jmock",
""
] |
I'm trying to take two 7 digit numbers (source and target record counts) and calculate the percentage of missing records in the target count.
For example, my record counts could be 4084094 for the source, and 4081313 for the target. I'm also using the follow formula to calc the percentage: ((1 - (target / source)) \* 100)
For my example, I should get the value of about .0681%
I'm am new to Java and JSP, and I'm not able to get the percentage to display correctly. I seem to only get a value rounded down to 0.
I've also tried BigDecimal, to no avail.
Even the following simple code displays the value of 1-1, so I obviously am doing somthing seriously wrong:
```
<%
BigDecimal percentMiss;
long tmp = 600/500;
percentMiss = BigDecimal.valueOf(tmp);
%>
<%=percentMiss.toString()%>-<%=tmp%>
``` | The problem is in the following line
```
long tmp = 600/500;
```
You cannot store floating point numbers in a long, instead you should consider using the following code:
```
double tmp = (double)600 / (double)500;
```
and then display tmp, which should have a value somewhere between 0 and 1 (in your case 1.2, because you have to change your calculation to 500 / 600) | The problem is obviously that you are dividing two long numbers.
I would recommend using [DecimalFormat](http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormat.html) to display the number. If you are using JSTL, then an even better solution is to use the [format tags](http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fmt/formatNumber.html):
```
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatNumber value="${value}" minFractionDigits="2" maxFractionDigits="2"/>
``` | Calculating and displaying floating point numbers in JSP | [
"",
"java",
"jsp",
"floating-point",
""
] |
I have been researching the Java Memory Model all day today, in order to understand in detail the problems with the JMM pre-Java 5 and the changes made by JSR-133 implemented in Java 5.
What I cannot seem to find a definitive answer on is the scope of cache invalidation and flushing required on a particular synchronize.
Must all CPU registers and caches be invalidated when entering any synchronized portion of code and all flushed to main RAM when leaving, or is the JVM allowed to only invalidate those variables actually read, and flush only those actually written during the synchronized block of code?
If the former, why is the JMM so pedantic about insisting the that memory barrier only occurs between two threads which synchronize on exactly the same object?
If the latter, is there any good document that explains the details of how this is accomplished? (I would suppose the underlying implementation would have to set a "bypass caches" flag at the CPU level at the start of a synchronized block and clear it at the end, but I could be *way* off base.) | There is *very nice* tech talk on [Java Memory model](http://www.youtube.com/watch?v=WTVooKLLVT8&hd=1). If you dislike wideos google `'happens before'` in context of Java Memory Model.
Basically all writes are visible to other threads if there is happens before relationship, Lets assume thaat thread A writes to field X, and thread B reads from it, so happens before is establishend between write and read if:
* x is volatile
* write to x was in guarded by the same lock that read from x
* maybe some more.
So I think that the second option is true, how they implemented it, I dont know. | You need to understand that the pre-5.0 JMM was never really implemented exactly, because it wasn't actually feasible.
So pre-5.0 you did technically have to write everything out to shared memory. In 1.5 (actually 1.4) this is relaxed. In particular, if a lock cannot escape a thread, then the JVM is entitled to treat it as a nop. Further, an unlock followed by a lock of the same lock can be coalesced, which is not true of the old JMM. For an escaped lock, the JVM often has to be pessimistic and flush more than is technically necessary. | What is the scope of cache flushing required by Java's synchronize keyword? | [
"",
"java",
"synchronization",
""
] |
I heard that if I call form.ShowDialog() without specifying the owner, then there can be a case when I will not see the dialog form on screen (it will be hidden with other windows). Is it true? I used ShowDialog() without specifying the owner hundreds of times and I never had any problems with that.
Can you please explain in which situation I could get the described problem?
**UPDATE:**
Well, I did many experiments and I couldn't get any real unexpected problems with using ShowDialog() (without specifying the owner).
So I think it's just rumors that ShowDialog() can lead to problems.
If you don't agree - give me a code sample please that leads to a problem. | Just to better understand the owner-owned relationship:
> .NET allows a form to “own” other forms. Owned forms are useful for
> floating toolbox and command windows. One example of an owned form is
> the Find and Replace window in Microsoft Word. When an owner window is
> minimized, the owned forms are also minimized automatically. When an
> owned form overlaps its owner, it is always displayed on top.
(c) "Pro .NET 2.0 Windows Forms and Custom Controls" by Matthew MacDonald.
---
> As **ShowDialog** shows the new form, an **implicit relationship is
> established** between the currently active form, known as the owner
> form, and the new form, known as the owned form. This relationship
> ensures that the owned form is the active form and is always shown on
> top of the owner form.
>
> One feature of this relationship is that the owned form affects the
> behavior of its owner form (when using **ShowDialog**):
>
> * The owner form cannot be minimized, maximized, or even moved.
> * The owned form blocks mouse and keyboard input to the owner form.
> * The owner form is minimized when the owned form is.
> * Only the owned form can be closed.
> * If both owner and owned forms are minimized and if the user presses Alt+Tab to switch to the owned form, the owned form is activated.
>
> Unlike the ShowDialog method, however, a call to the **Show** method **does
> not establish an implicit owner-owned relationship**. This means that
> either form can be the currently active form.
>
> Without an implicit owner-owned relationship, owner and owned forms
> alike can be minimized, maximized, or moved. If the user closes any
> form other than the main form, the most recently active form is
> reactivated.
>
> Although **ShowDialog establishes an implicit owner-owned relationship**,
> there is no built-in way for the owned form to call back to or query
> the form that opened it. In the modeless case, you can set the new
> form's Owner property to establish the owner-owned relationship. As a
> shortcut, you could pass the owner form as an argument to an overload
> of the Show method, which also takes an IWin32Window parameter
> (IWin32Window is implemented by Windows Forms UI objects that expose a
> Win32 HWND property via the IWin32Window.Handle property).
>
> The behavior of forms in an explicit modal owner-owned form
> relationship is the same as its implicit modal counterpart, but the
> modeless owner-owned relationship provides additional behavior in the
> non-owner-owned modeless case. First, the modeless owned form always
> appears on top of the owner form, even though either can be active.
> This is useful when you need to keep a form, such as a floating tool
> window, on top of other forms within an application. Second, if the
> user presses Alt+Tab to switch from the owner, the owned forms follow
> suit. To ensure that the user knows which form is the main form,
> minimizing the owner hides the task bar buttons for all owned forms,
> leaving only the owner's task bar button visible.
(c) "Windows Forms 2.0 Programming" by Chris Sells, Michael Weinhardt. | One annoyance I found with `ShowDialog()` vs `ShowDialog(this)`.
Run the TestApp, show the `newform.ShowDialog()`, click "show Desktop" on your taskbar or Quick launch toolbar, click on the TestApp on the taskbar. It shows the Mainform. You have to do an Alt-Tab to get to your newform.
VS
Run the TestApp, show the `newform.ShowDialog(this)`, click "show Desktop" on your taskbar or Quick launch toolbar, click on the TestApp on the taskbar. It shows the newform on top. | Form.ShowDialog() or Form.ShowDialog(this)? | [
"",
"c#",
".net",
"winforms",
""
] |
Is there any way to debug a single file in Visual Studio.NET?
I'm still a noob with C++, but I want to start learning how to get comfortable with the debugger, and as of right now I am writing really small files.
It seems if there is only one source file, it won't let me debug, but the moment I add another one, I can. I am using VS.net 2008. | It doesn't want another source file, it wants a project file.
Visual Studio needs a bunch of information to know how to compile and debug your source code. Things like which optimization settings to use, where to look for the `boost` headers, that sort of thing.
Try this: go to `File->New->Project...` and pick a win32 console application. In the next wizard, go to `Application Settings`, and check "Empty Project", and hit OK.
Now you have empty project and solution files which you can copy/paste wherever you want them; to debug, just open the `.sln` file, drag in your single `.cpp` file, and hit F5. | Whenever I want to debug a console program quickly, I find the console is the best place to start. So I take one C++ program (blah.cpp):
```
int main ()
{
for (int i = 0; i < 100; i++)
printf ("Hello World ... etc \n");
}
```
Then set up my environment on the console (from cmd.exe):
```
vcvars32
```
Then compile my program (The Zi is so that I get a blah.pdp to debug with):
```
cl /Zi blah.cpp
```
And voila I have a blah.exe that I can run. If I want to debug blah.exe I just open a project from VS2008 and select blah.exe instead of a project file. I can open up blah.cpp in the IDE and run (F5), set breakpoints (F9) and generally debug to my hearts content (F10,F11). | How do I debug a single .cpp file in Visual Studio? | [
"",
"c++",
"visual-studio-2008",
"debugging",
""
] |
Is it possible to declare a variable in c++ without instantiating it? I want to do something like this:
```
Animal a;
if( happyDay() )
a( "puppies" ); //constructor call
else
a( "toads" );
```
Basially, I just want to declare a outside of the conditional so it gets the right scope.
Is there any way to do this without using pointers and allocating `a` on the heap? Maybe something clever with references? | You can't do this directly in C++ since the object is constructed when you define it with the default constructor.
You could, however, run a parameterized constructor to begin with:
```
Animal a(getAppropriateString());
```
Or you could actually use something like the `?: operator` to determine the correct string.
(Update: @Greg gave the syntax for this. See that answer) | You can't use references here, since as soon as you'd get out of the scope, the reference would point to a object that would be deleted.
Really, you have two choices here:
1- Go with pointers:
```
Animal* a;
if( happyDay() )
a = new Animal( "puppies" ); //constructor call
else
a = new Animal( "toads" );
// ...
delete a;
```
or with a smart pointer
```
#include <memory>
std::unique_ptr<Animal> a;
if( happyDay() )
a = std::make_unique<Animal>( "puppies" );
else
a = std::make_unique<Animal>( "toads" );
```
2- Add an Init method to `Animal`:
```
class Animal
{
public:
Animal(){}
void Init( const std::string& type )
{
m_type = type;
}
private:
std:string m_type;
};
Animal a;
if( happyDay() )
a.Init( "puppies" );
else
a.Init( "toads" );
```
I'd personally go with option 2. | Declaring an object before initializing it in c++ | [
"",
"c++",
"scope",
"declaration",
"instantiation",
""
] |
I have my main program window, and I would like to make a foldable panel. What I mean is, a panel which is aligned to one of the sides of the window, with a fold/unfold button. It's important that when the panel gets folded/unfolded, the other widgets change their size accordingly to take advantage of the space they have.
How do I do this? | Here is one way using wx.SplitterWindow
```
import wx, wx.calendar
class FoldableWindowContainer(wx.Panel):
def __init__(self, parent, left, right):
wx.Panel.__init__(self, parent)
sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(sizer)
self.splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE)
left.Reparent(self.splitter)
right.Reparent(self.splitter)
self.left = left
self.right = right
self.splitter.SplitVertically(self.left, self.right)
self.splitter.SetMinimumPaneSize(50)
self.sash_pos = self.splitter.SashPosition
sizer.Add(self.splitter, 1, wx.EXPAND)
fold_button = wx.Button(self, size=(10, -1))
fold_button.Bind(wx.EVT_BUTTON, self.On_FoldToggle)
sizer.Add(fold_button, 0, wx.EXPAND)
def On_FoldToggle(self, event):
if self.splitter.IsSplit():
self.sash_pos = self.splitter.SashPosition
self.splitter.Unsplit()
else:
self.splitter.SplitVertically(self.left, self.right, self.sash_pos)
class FoldTest(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
left = wx.Panel(self, style=wx.BORDER_SUNKEN)
right = wx.Panel(self, style=wx.BORDER_SUNKEN)
left_sizer = wx.BoxSizer(wx.VERTICAL)
left.SetSizer(left_sizer)
left_sizer.Add(wx.calendar.CalendarCtrl(left), 1, wx.EXPAND | wx.ALL, 5)
left_sizer.Add(wx.Button(left, label="Act"), 0, wx.EXPAND | wx.ALL, 5)
right_sizer = wx.BoxSizer(wx.VERTICAL)
right.SetSizer(right_sizer)
right_sizer.Add(
wx.StaticText(right, label="Fold panel", style=wx.BORDER_RAISED),
1, wx.EXPAND | wx.ALL, 5
)
FoldableWindowContainer(self, left, right)
app = wx.PySimpleApp()
app.TopWindow = FoldTest()
app.TopWindow.Show()
app.MainLoop()
```
Also, check out wx.CollapsiblePane in the wxPython demos. | The layout managers for wxPython (and Swing and others) should be able to do this for you if you create the hierarchy properly. Let's assume it's bound to the right hand side, thus:
```
+-----------------------------+
|+----------------+ +--------+|
|| | | This is||
|| | | your ||
|| Other stuff | | panel ||
|| | +--------+|
|| | +--------+|
|| | | Another||
|| | | panel ||
|+----------------+ +--------+|
+-----------------------------+
```
If your layout is done right, you will have a top-level layout with two columns, one for the other stuff and one for the right-side container.
*That* container will have it's own layout manager with two rows, one for the top panel, one for the bottom.
That way, when you resize the top panel (your foldable one) to be shorter (fold) or taller (unfold), the layout manager should expand or contract the bottom panel to fit.
Obviously you can use more complicated layout managers, I've chosen the simplest ones to illustrate how to do it without cluttering the discussion with column/row spans and anchors and so on. You can also change the direction of folding by reversing the window managers (horizontal <-> vertical). | wxPython: A foldable panel widget | [
"",
"python",
"user-interface",
"wxpython",
"widget",
""
] |
**Duplicate of** ["how does one get a count of rows in a datastore model in google appengine?"](https://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine)
---
I want to know how many users I have. Previously, I achieved this with the following code:
```
users = UserStore.all()
user_count = users.count()
```
But now I have more than 1,000 users and this method continues to return 1,000.
Is there an efficient programmatic way of knowing how many users I have? | It is indeed a duplicate and the other post describes how to theoretically do it, but I'd like to stress that you should really not be doing counts this way. The reason being that BigTable by its distributed nature is really bad for aggregates. What you probably want to do is add a transactional counter to that entity, and if there are lots of transactions a sharded counter. See: <http://code.google.com/appengine/articles/sharding_counters.html>
UPDATE: Since 1.3.1 cursors make stuff like this a lot easier: <http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Query_Cursors> | Use pagination like these examples [here](http://google-appengine.googlegroups.com/web/efficient_paging_using_key_instead_of_a_dedicated_unique_property.txt). | Google AppEngine: how to count a database's entries beyond 1000? | [
"",
"python",
"google-app-engine",
"count",
""
] |
Is it possible to capture the task manager end process of a windows application within the same windows application itself? I am using a C# 2.0 win app and I would like to do some database processing (change a flag from 'Y' to 'N' in the DB) when an end process happens. | No, it is not possible to hook the operating system's decision to end a process. Note, this is not done by task manger, ending a process is the responsibility of the kernel.
You will need to do two things here:
1. Connect event handlers to the normal user interface messages that tell a application to exit. Use these events to persist data, free resources, and otherwise exit cleanly.
2. Handle exceptions as appropriate to catch errors and clean up and save data if possible.
Here are a three links to Raymond's blog explaining why you cannot do what you are asking.
* [Why can't you trap TerminateProcess?](http://blogs.msdn.com/oldnewthing/archive/2004/07/22/191123.aspx)
* [Why do some process stay in Task Manager after they've been killed?](http://blogs.msdn.com/oldnewthing/archive/2004/07/23/192531.aspx)
* [The arms race between programs and users](http://blogs.msdn.com/oldnewthing/archive/2004/02/16/73780.aspx)
Also, I addressed a similar StackOverflow question [here](https://stackoverflow.com/questions/501523/c-deallocate-resources-on-process-termination). | How about a slightly different approach:
Have your application update a date time field e.g. LastPollDate every so often while it is running, and have a separate field e.g. "AppTerminatedNormally" which you set to N, and change to Y if you get a form close event.
If the app is killed via Task Manager, the date will not be updated any more, and your AppTerminatedNormally will still be no.
This way you could run a query that finds all rows where LastPollDate is older than 10 minutes and AppTerminatedNormally is N, and you would have all the sessions that were abnormally terminated. | Handling end process of a windows app | [
"",
"c#",
".net",
"event-handling",
""
] |
HI,
I am developing a web page using asp.net.
I am using some links in my web page. For that I have used some code like this.
```
<a href="javascript:void(0);" onclick="javascript:ChangeLoc('TEST','');">Test</a>
```
and in the `ChangeLoc()` method I have written `__doPostBack` event.
This works fine in IE7 installed in my machine. But in IE6 in another machine it does not invoke the `__doPostBack` event.
**Edit**
When I change the void(0) in href it works fine.
I would like to know whether it is a bug with IE or a JavaScript problem.
```
function ChangeLoc( param, arg )
{
__doPostBack ( param, arg )
}
``` | href and onclick both get fired when you click an element, you are overwriting the onclick event with void()
change to
```
<a href="#" onclick="ChangeLoc();return false">test</a>
```
or with jQuery.
```
$(function(){
$("#linkId").click(function(event){
ChangeLoc();
event.preventDefault();
});
});
``` | Do you get an error? If so, what error do you get in IE6? Can you post the code for ChangeLoc()? Also, try changing your markup to the following and see if you get the same result:
```
<a href="#" onclick="ChangeLoc(); return false;">Test</a>
```
**Edit:** removed 'javascript:' from the onclick | javascript void(0) problem in IE | [
"",
"javascript",
"internet-explorer",
""
] |
I'm new to jQuery and i'm trying to write some code to go through the page and rewrite anchor links href attribute so that spaces are removed and replaced with %20.
so far i have:
```
$(".row a").each(function(){
$(this).attr("href").replace(/\s/g,"%20");
});
```
I've tried a few variations of this with no luck. | Your approach is correct, but you're forgetting to set the new value once you replace it. Try this:
```
$(".row a").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});
``` | You'd be better off using the native javascript [`encodeURI`](http://www.w3schools.com/jsref/jsref_encodeURI.asp) function.
```
$(".row a").each(function(){
$(this).attr( 'href', encodeURI( $(this).attr("href") ) );
});
``` | jQuery / Javascript replace <space> in anchor link with %20 | [
"",
"javascript",
"jquery",
"html",
"replace",
""
] |
I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:
**Original string, 9 chars**
```
$string = 'abcdefghi';
```
**Example random string limiting to 6 chars**
```
$string = 'ibfeca';
```
UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.
UPDATE: The function should generate any amount of chars as required.
Please comment the parts if you reply. | Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:
```
function get_random_string($valid_chars, $length)
{
// start with an empty random string
$random_string = "";
// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);
// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}
// return our finished random string
return $random_string;
}
```
To call this function with your example data, you'd call it something like:
```
$original_string = 'abcdefghi';
$random_string = get_random_string($original_string, 6);
```
Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of `'AAAB'`, it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs. | If you want to allow repetitive occurences of characters, you can use this function:
```
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
{
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
```
The basic algorithm is to generate <*length*> times a random number between 0 and <*number of characters*> − 1 we use as index to pick a character from our set and concatenate those characters. The 0 and <*number of characters*> − 1 bounds represent the bounds of the `$charset` string as the first character is addressed with `$charset[0]` and the last with `$charset[count($charset) - 1]`. | How to create a random string using PHP? | [
"",
"php",
"string",
"random",
""
] |
Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.
I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same directory as everything else.
```
from snipplets.main import MainHandler
from snipplets.createnew import CreateNewHandler
from snipplets.db import DbSnipplet
from snipplets.highlight import HighLighter
from snipplets.options import Options
```
ImportError: No module named options
my \_\_init\_\_.py file in the snipplets directory is blank. | I suspect that one of your other imports redefined `snipplets` with an assignment statement. Or one of your other modules changed `sys.path`.
---
**Edit**
"so the flow goes like this: add snipplets packages to path import..."
No.
Do not modify `sys.path` -- that way lies problems. Modifying `site.path` leads to ambiguity about what is -- or is not -- on the path, and what order they are in.
The simplest, most reliable, most obvious, most controllable things to do are the following. Pick exactly one.
* Define `PYTHONPATH` (once, external to your program). A single, simple environment variable that is nearly identical to installation on site-packages.
* Install your package in site-packages. | your [master branch](http://github.com/woodenbrick/snipplets/tree/68e40dcfa1195cc63d4e1155b8353bb1aa1f8797/snipplets) doesn't have `options.py`. could it be that you dev and master branches are conflicting?
[if this is your actual code](http://github.com/woodenbrick/snipplets/blob/2c13a6de0ae5c6cb752bbc37e2620e823e498c97/bin/snipplets) then you have `option` variable at line 21. | import statement fails for one module | [
"",
"python",
""
] |
In Java, is it possible to create a class definition on the fly while an application is running, and then create an object of that class?
For example, a running application would read in a text file that contains a list of class members to include in the new class. The application would then define a class definition based on the list of members, and then insantiate it. | Yes its possible to do so in theory your class file is byte code which is at the end a byte array! you can then use the method defineClass(String, byte[], int, int) to get a Class instance that can be used to instantiate objects via reflection.
In practice you can use something like [CGLib](http://cglib.sourceforge.net/) or [javaassist](http://www.csg.is.titech.ac.jp/~chiba/javassist/).
You can also use the long way of generating the java code in a file, invoking the compiler, then loading the file. | You can dynamically generate classes using [ASM](http://asm.ow2.org/) | Defining a class while a Java application is running | [
"",
"java",
"on-the-fly",
"runtime-compilation",
""
] |
I need to gain access to the files and directories that the current IPrincipal has access to via the Directory.GetDirectories() and Directory.GetFiles() methods, without listing the other files. The process itself is running as NETWORK SERVICE, so it must change the principal to the current user (via IPrincipal) for the duration of these calls.
I have attempted to change Thread.CurrentPrincipal to the new IPrincipal prior to the file access part, but it doesn't appear to make a difference.
Is there something else I can do, or am I missing something? | Windows impersonation solves this problem by using the login details to acquire a user token. This token can then be used to obtain a WindowsIdentity, which is then used to generate an impersonation context. Within this context scope, you can then access the file system *as* the impersonated user.
Of course, you will need to store the user name and password for this approach to work.
First, define the Windows APIs required to obtain a user token from Windows:
```
internal class WindowsAPI
{
public const int LOGON32_PROVIDER_DEFAULT = 0;
public const int LOGON32_LOGON_INTERACTIVE = 2;
[DllImport( "advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode )]
public static extern bool LogonUser( String lpszUsername,
String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken
);
[DllImport( "kernel32.dll", CharSet = CharSet.Auto )]
public extern static bool CloseHandle( IntPtr handle );
}
```
Then, use these APIs to aquire a WindowsIdentity:
```
private WindowsIdentity GetIdentity( string userName, string password )
{
_userToken = IntPtr.Zero;
if ( !WindowsAPI.LogonUser(
userName,
AbbGrainDomain,
password,
WindowsAPI.LOGON32_LOGON_INTERACTIVE, WindowsAPI.LOGON32_PROVIDER_DEFAULT,
ref _userToken
) )
{
int errorCode = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception( errorCode );
}
return new WindowsIdentity( _userToken );
}
```
And finally, use this identity to generate an impersonation context:
```
public List<string> GetDirectories( string searchPath )
{
using ( WindowsImpersonationContext wic = GetIdentity().Impersonate() )
{
var directories = new List<string>();
var di = new DirectoryInfo( searchPath );
directories.AddRange( di.GetDirectories().Select( d => d.FullName ) );
return directories;
}
}
```
Finally it is important to clean up the windows handle using the IDisposable pattern, using the stored \_userToken:
```
if ( _userToken != IntPtr.Zero )
WindowsAPI.CloseHandle( _userToken );
``` | I don't think you're doing this the right way. You should look into using impersonation. For example take a look at [this](http://www.netomatix.com/ImpersonateUser.aspx) tutorial on how to do this. | File and Directory Security with IPrincipal | [
"",
"c#",
"security",
"iprincipal",
""
] |
I have some problems sending mails through SMTP using Spring's [MailSender](http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/mail/MailSender.html) interface and the concrete implementation [JavaMailSenderImpl](http://static.springframework.org/spring/docs/1.2.x/api/org/springframework/mail/javamail/JavaMailSenderImpl.html). I'm able to send mail through GMail, but not through our company SMTP-server ([Postfix](http://www.postfix.org/)).
## Correct configurations
To see that I have the correct configuration I used the excellent mail sender [ssmtp](http://www.google.com/search?q=ssmtp). It's a simple utility (which is able to emulate Sendmail) and is used solely for sending mail through SMTP.
Below are the two commands I used to send mail. The first one is for GMail and the second one for our company SMTP-server. Both mails arrived as they should and thus the configuration files that follow are correct.
```
$ ssmtp -C gmail-smtp.conf john.doe@gmail.com < gmail-message.txt
$ ssmtp -C other-smtp.conf john.doe@thecompany.net < other-message.txt
```
The contents of the ssmtp configuration files and the message files are listed below. How the configuration file is structured can be seen at: <http://linux.die.net/man/5/ssmtp.conf>:
*gmail-message.txt:*
```
To: john.doe@gmail.com
From: john.doe@gmail.com
Subject: Sent using the SMTP-server of GMail
Some content.
```
*gmail-smtp.conf:*
```
mailhub=smtp.gmail.com:587
UseSTARTTLS=yes
AuthUser=john.doe@gmail.com
AuthPass=john_password
```
*other-message.txt:*
```
To: john.doe@thecompany.net
From: john.doe@thecompany.net
Subject: Sent using the SMTP-server of TheCompany
Some content.
```
*other-smtp.conf:*
```
# No username or password = no authentication
hostname=thecompany.net
mailhub=mail.thecompany.net:25
```
## MailSender configuration which works against GMail
I'm sucessful in sending mail through GMail using this Spring MailSender configuration:
```
...
<bean id="mailSender" class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="john.doe@gmail.com" />
<property name="password" value="john_password" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
...
```
## The problem (sending through the company SMTP-server)
With this MailSender configuration:
```
...
<bean id="mailSender" class ="org.springframework.mail.javamail.JavaMailSenderImpl" >
<property name="host" value="mail.thecompany.net" />
<property name="port" value="25" />
</bean>
...
```
I get this exception:
```
org.springframework.mail.MailSendException; nested exceptions (1) are:
Failed message 1: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 504 5.5.2 <rat>: Helo command rejected: need fully-qualified hostname
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:422)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
... (The rest are methods I've created, which are irrelevant)
```
I **also** get *504 5.5.2 : Helo command rejected: need fully-qualified hostname* if I remove *hostname=thecompany.net* from *other-smtp.conf* using **ssmtp**. I guess I have to provide the hostname somehow. My computers name is *rat* but it seems like it wants *thecompany.net*.
Any and all help appreciated! | Try to add the property "mail.smtp.localhost" with correct value (*thecompany.net*). | To add to complete the previous [answer](https://stackoverflow.com/questions/854493/problem-configuring-springs-mailsender-for-our-smtp-server-but-gmail-works/854603#854603) by matt b, the correct option of the javamail is `smtp.mail.localhost`
```
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.localhost">thecompany.net</prop>
</props>
</property>
``` | Problem configuring Spring's MailSender for our SMTP-server (but GMail works) | [
"",
"java",
"spring",
"smtp",
"jakarta-mail",
""
] |
I'm trying to find a way to test how long it takes a block of C++ code to run. I'm using it to compare the code with different algorithms and under different languages, so ideally I would like a time in seconds / milliseconds. In Java I'm using something like this:
```
long startTime = System.currentTimeMillis();
function();
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
```
Is there a good way to get an accurate time like that in C++ (Or should I use some other means of benchmarking)? | Use the best counter available on your platform, fall back to time() for portability.
I am using QueryPerformanceCounter, but see the comments in the other reply.
General advise:
The *inner loop* should run at least about 20 times the resolution of your clock, to make the resolution error < 5%. (so, when using time() your inner loop should run at least 20 seconds)
Repeat these measurements, to see if they are consistent.
I use an additional *outer loop*, running ten times, and ignoring the fastest and the slowest measurement for calculating average and deviation. Deviation comes handy when comparing two implementations: if you have one algorithm taking 2.0ms +/-.5, and the other 2.2 +/- .5, the difference is not significant to call one of them "faster".
(max and min should still be displayed). So IMHO a valid performance measurement should look something like this:
```
10000 x 2.0 +/- 0.2 ms (min = 1.2, , max=12.6), 10 repetitions
```
If you know what you are doing, purging the cache and setting thread affinity can make your measurements much more robust.
However, this is not without pifalls. The more "stable" the measurement is, the less realistic it is as well. Any implementation will vary strongly with time, depending on the state of data and instruction cache. I'm lazy here, useing the max= value to judge first run penalty, this might not be sufficient for some scenarios. | Execute the function a few thousand times to get an accurate measurement.
A single measurement might be dominated by OS events or other random noise. | Testing the performance of a C++ app | [
"",
"c++",
"performance",
"testing",
""
] |
Quite often I will try and run a PHP script and just get a blank screen back. No error message; just an empty screen. The cause might have been a simple syntax error (wrong bracket, missing semicolon), or a failed function call, or something else entirely.
It is very difficult to figure out what went wrong. I end up commenting out code, entering "echo" statements everywhere, etc. trying to narrow down the problem. But there surely must be a better way, right?
Is there a way to get PHP to produce a useful error message, like Java does? | By default, displaying errors is turned off because you don't want a "customer" seeing the error messages.
[Check this page](http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) in the PHP documentation for information on the 2 directives: `error_reporting` and `display_errors`. `display_errors` is probably the one you want to change.
So you have 3 options:
(1) You can check the error log file as it will have all of the errors (unless logging has been disabled). To enable error logging make sure that `log_errors` configuration directive is set to `On`. Logs are also helpful when error is happened not in PHP but emitted by web-server.
(2) You can add the following 2 lines that will help you debug errors that are not syntax errors happened in the same file:
```
error_reporting(E_ALL);
ini_set('display_errors', 'On');
```
Note that on a live server the latter should be set to `Off` (but only the latter, because you still need to learn about all errors happened, from the log file).
However, for syntax errors happened in the same file, the above commands won't work and you need to enable them in the php.ini. If you can't modify the php.ini, you may also try to add the following lines to an .htaccess file, though it's seldom supported nowadays:
```
php_flag display_errors on
php_value error_reporting -1
```
(3) Another option is to use an editor that checks for errors when you type, such as [PhpEd](http://www.nusphere.com/products/phped.htm), VSCode or PHPStorm. They all come with a debugger which can provide more detailed information. (The PhpEd debugger is very similar to xdebug and integrates directly into the editor so you use 1 program to do everything.) | The following enables all errors:
```
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
```
Also see the following links
* <http://php.net/manual/en/errorfunc.configuration.php#ini.display-errors>
* <http://php.net/manual/en/errorfunc.configuration.php#ini.display-startup-errors>
* <http://php.net/manual/en/function.error-reporting.php> | How can I get useful error messages in PHP? | [
"",
"php",
"debugging",
"error-handling",
""
] |
If I have a
```
var t = document.createTextNode(text)
parent.appendChild(t);
```
Is it possible to simply update the contents of `t`?
I would like to change the text inside the `parent` without using `removeChild`, `createTextNode` and `appendChild`. Why would I need this instead of just using `innerHTML`? Because I don't want to update the contents of the element with HTML code and the `text` may contain special characters, such as < or & which should be parsed by `TextNode`'s DOM methods.
Thanks,
Tom | Be aware that adjacent text nodes are collapsed into one (since there is really no way to distinguish two adjacent text nodes).
The contents of a text node can be updated using it's `nodeValue` property (see [MDC](https://developer.mozilla.org/En/DOM/Node.nodeValue)).
Since a text node by it's very definition cannot contain any markup, there is no `innerHTML` property. | If you keep the instance of the TextNode object (t in your example code) then you can change the content using various functions like replaceData(), substringData(), etc..
See this page for a nice reference:
<http://msdn.microsoft.com/en-us/library/ms535905(VS.85).aspx#> | JavaScript TextNode update | [
"",
"javascript",
"dom",
"innerhtml",
"createtextnode",
""
] |
I'm searching the way(s) to fill an array with numbers from 0 to a random. For example, from 0 to 12 or 1999, etc.
Of course, there is a `for`-loop:
```
var arr = int[n];
for(int i = 0; i < n; i++)
{
arr[i] = i;
}
```
And I can make this method been an extension for `Array` class. But is there some more interesting ways? | This already exists(returns IEnumerable, but that is easy enough to change if you need):
```
arr = Enumerable.Range(0, n);
``` | The most interesting way in my mind produces not an array, but an `IEnumerable<int>` that enumerates the same number - it has the benefit of O(1) setup time since it defers the actual loop's execution:
```
public IEnumerable<int> GetNumbers(int max) {
for (int i = 0; i < max; i++)
yield return i;
}
```
This loop goes through all numbers from `0` to `max-1`, returning them one at a time - but it only goes through the loop when you actually need it.
You can also use this as `GetNumbers(max).ToArray()` to get a 'normal' array. | Ways in .NET to get an array of int from 0 to n | [
"",
"c#",
".net",
"arrays",
""
] |
Say I have two arrays, items and removeItems and I wanted any values found in removeItems to be removed from items.
The brute force mechanism would probably be:
```
var animals = ["cow","dog","frog","cat","whale","salmon","zebra","tuna"];
var nonMammals = ["salmon","frog","tuna","spider"];
var mammals = [];
var isMammal;
for(var i=0;i<animals.length;i++){
isMammal = true;
for(var j=0;j<nonMammals;j++){
if(nonMammals[j] === animals[i]){
isMammal = false;
break;
}
}
if(isMammal){
mammals.push(animals[i]);
}
}
```
This is what? O(N^2)? Is there a more efficient way? | That's actually `O(M * N)`.
Probably you could do better sorting the `animals` array first, then doing a binary search. You'll be able to reduce to `O(N * log N)` - well, that's if `log N < M` anyway.
Anyway, if you're working with JS and that runs client-side, then just try to keep amount of data at minimum, or their browsers will yell at you with every request. | Basically what you want to do is efficiently compute the set difference S \ T. The (asymptotically) fastest way I know is to put T into a hashmap (that makes |T| steps) and go over each s in S (that makes |S| steps) checking wether s in T (which is O(1)). So you get to O(|T| + |S|) steps. | What's the most efficient way of filtering an array based on the contents of another array? | [
"",
"javascript",
"arrays",
"filtering",
""
] |
I just started learning c# on vs 2008.
I found key combiations for
1. select current word
2. delete current line
is there a key combination to select current line? | You can also press CTRL+C to copy the whole line the cursor is currently in. You will not see a selection bar, but the entire line is copied to the clibboard. Then you can press CTRL+V to paste it anywhere you like.
EDIT: Make sure you don't have anything selected in the line, in that case only the selection will be copied to clipboard. | `HOME` , `SHIFT` + `END` | key combination to select current line in vs 2008? | [
"",
"c#",
"key",
"combinations",
""
] |
Is there a way I can set a ShowDialog() to not be topmost? I've looked at all the related SO questions, and none *quite* matched my situation.
What I do is open a new WinForm from a datagridview button column. This new form pulls information from a few SQLite tables and allows the user to add information to the row the button was clicked.
I open the WinForm using the code below. I use the ShowDialog() method so I can tell if the user saves the information in the form or cancels it.
```
Pay_Bill_Window paywindow = new Pay_Bill_Window(getClickedRowID);
if (paywindow.ShowDialog() == DialogResult.OK)
{
FillPendingPaymentDataGrid(dbAccess.GetPendingBills());
}
```
I do this so I can tell if I need to reload the information in the datagridview.
The information the user can fill into the window is from other sources, like a web browser, so having the form be on top of all applications is not ideal.
Is there a way I can stop the window from being on top of all applications (top-most in my series of windows is fine), or is there a way to tell what button a user clicks on another form (basically, using `paywindow.Show()` and watching for a different type of return)?
Thanks for any help! | use something like this :
form1 :
```
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
frm.FormIsClosing += frm_FormIsClosing;
}
void frm_FormIsClosing(object sender, DialogResult rsl)
{
if (rsl == System.Windows.Forms.DialogResult.Yes)
MessageBox.Show("We got it");
}
```
form2 :
```
public delegate void IsClosing(object sender, DialogResult rsl);
public event IsClosing FormIsClosing;
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
FormIsClosing(this, System.Windows.Forms.DialogResult.Yes);
}
```
then you close the form2 , FormIsClosing fires and you can catch it in from1 ;) | By default a form should not be TopMost in the "for all applications sense". If you're seeing that behavior it's likely because the property was set in the designer. Either unset the property in the designer or try the following.
```
using ( Form form = CreateMyForm() ) {
form.TopMost = false;
form.ShowDialog(parent);
...
}
``` | Can I set ShowDialog() to not be topmost? | [
"",
"c#",
"winforms",
"show",
"showdialog",
"topmost",
""
] |
I have an XML stored procedure in MS SQL 2005 which I use the SqlCommand.ExecuteXmlReader to get an XmlReader, then parse through the data and form an XML document. The problem is that the data in SQL contains some binary characters which are illegal within a UTF-8 XML document, so an exception is thrown.
Has anyone else dealt with this problem? I've considered filtering the data on input into the DB, but then I'd have to put the filtering everywhere, and every character would need to be checked.
Any other suggestions?
**EDIT:**
The data is typically stored in varchar columns of various length. The data is actually input from users on web forms (ASP .NET app). So sometimes they copy-paste from MS Word or something and it puts these strange binary characters in. | I've abstracted the making of SqlParameter objects everywhere in the application already, so I'll scrub the input at that point. My abstraction method creates and returns a SqlParameter object to use in a stored procedure call. If it's a varchar the caller wants, I'll loop through each character of the string they want to make into a SqlParameter object and filter out those illegal binary XML characters. That will eliminate the bad data from entering the database in the first place. | I've have seen the DotNet SqlClient "scramble" data from nvarchar columns in the database, our **theory** that was its something to do with "surrogate code points", see:
<http://www.siao2.com/2005/07/27/444101.aspx>
[http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=rzaaxsurrogate.htm](http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/ifs/rzaaxsurrogate.htm)
<http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/admin/c0004816.htm>
SqlClient seemed to "interpret" some of the bytes meaing that our Xml was no longer well formed, converting to nvarchar(max) seemed to stop this (although this did have a performance impact):
```
SELECT CONVERT(NVARCHAR(MAX), MyValue) FROM ...
```
Note that you need to use NVARCHAR(MAX), NVARCHAR( N ) doesnt work.
We also found that the OleDB provider works correctly as well (although it is slower than the SqlClient). | Filter Illegal XML Characters in .NET | [
"",
".net",
"sql",
"xml",
""
] |
I'm migrating a solution from visual studio 2005 to visual studio 2008. When I build the solution in 2005, I don't have any issues. However, after I use devenv.exe /Upgrade and then use msbuild on the solution, I get the following warnings:
CSC : warning CS1668: Invalid search path '\vc98\lib' specified in 'LIB environment variable' -- 'The system cannot find the path specified.'
CSC : warning CS1668: Invalid search path '\vc98\mfc\lib' specified in 'LIB environment variable' -- 'The system cannot find the path specified. '
CSC : warning CS1668: Invalid search path 'c:\program files\microsoft visual studio 9.0\vc\platformsdk\lib' specified in 'LIB environment variable' -- 'The system cannot find the path specified.'
I have checked <http://social.msdn.microsoft.com/Forums/en-US/Vsexpressinstall/thread/3f875480-fee2-4bc3-b829-95e220b22a01> and it doesn't offer me any help because my LIB and INCLUDE environment variables are not set either in the user vars or the system vars. I've looked at Studio's Tools > Options > Projects and Solutions> VC++ Directories and there's nothing that references anything old:
Library Files:
$(VCInstallDir)lib
$(VCInstallDir)atlmfc\lib
$(VCInstallDir)atlmfc\lib\i386
$(WindowsSdkDir)\lib
$(FrameworkSDKDir)lib
$(VSInstallDir)
$(VSInstallDir)lib
Include files:
$(VCInstallDir)include
$(VCInstallDir)atlmfc\include
$(WindowsSdkDir)include
$(FrameworkSDKDir)include
I used diagnostic output so that I could see exactly what the LIB variable includes when being called:
lib = c:\Program Files\Microsoft Visual Studio 9.0\VC\ATLMFC\LIB;c:\Program Files\Microsoft Visual Studio 9.0\VC\LIB;C:\Program Files\Microsoft SDKs\Windows\v6.0A\lib;\vc98\lib;\vc98\mfc\lib;c:\program files\microsoft visual studio 9.0\vc\platformsdk\lib;c:\program files\microsoft visual studio 9.0\vc\lib;c:\program files\microsoft visual studio 9.0\vc\atlmfc\lib;
LIBPATH = c:\Windows\Microsoft.NET\Framework\v3.5;c:\Windows\Microsoft.NET\Framework\v2.0.50727;c:\Program Files\Microsoft Visual Studio 9.0\VC\ATLMFC\LIB;c:\Program Files\Microsoft Visual Studio 9.0\VC\LIB
So if that vc98 is NOT in my env vars, or my studio settings and vc98 isn't even installed (nor the redist), where is that path coming from? What process sets up the LIB env var like that? | Found on [MSDN](http://social.msdn.microsoft.com/Forums/en-US/csharpide/thread/01e75a63-7d44-48c7-82c1-30cd25fc4745):
> Yes this is a known issue that occurs
> to some people. Look carefully in
> your LIB path. Right after ATLMFC, V,
> SDK -> \vc98\lib. Delete this entry
> (and the one that follows). If the
> LIB is a user variable then you'll
> need to restart VS or perhaps log off
> and back on. If it is a system
> variable then you'll have to reboot.
> Your error should then go away. | Here is the solution
<http://msdn.microsoft.com/en-us/library/tcbs315h(v=vs.80).aspx>
its refer to the LIB entry at Environment Variables | Migrating Visual Studio 2005 sln to 2008, warning with vc98 paths in LIB environment variable, how to fix? | [
"",
"c#",
".net",
"windows",
"visual-studio-2008",
""
] |
[EDIT]Whoops there was a mistake in the code, and now all the responses to the question seem bizzare, but basically the for loop used to be, for(i=0; i<15; i++). I also edited to make the question more clear.[/EDIT]
I am trying to make a for loop, that checks a 16 element array, so it loops from 0 to 15. I then use the i variable later, however sometimes i == 16, which causes problems by being out of bounds.
I have a solution but it doesnt seem elegant, which makes me think I am missing something. I've tried while loops, but I can never get any loop to go from 0 to 15, and never end at a value greater than 15.
Is there any way to make a loop go and check all 16 elements of the array, while never being greater than 15 at the end of the loop?
```
int i;
for(i=0; i<16; i++)
{
someClass.someMethod(i);
if(someClass.Test())
{
break;
}
}
if (i == 16)
{
i = 15;
}
``` | I suggest using some other variable other than `i` after your loop is finished. The criteria of using a for loop instead of a while loop is that you know beforehand exactly how many times a for loop will execute. If you already know this, just set some other variable to the ending value of your loop and use it instead of giving `i` a dual purpose.
```
int j = 15;
for(int i=0; i <= j; i++)
{
someClass.array[i];
}
// continue on using j, which value hasn't changed
``` | Maybe it's useful to know that:
```
for (before; check; after) { body }
```
it's the same as:
```
before
while(check) {
body
after
}
```
If you think at your for loop in that term, maybe you'll find out easily why i, at the exit, is 16. | Beginner for loop problem | [
"",
"c++",
"for-loop",
""
] |
I have a directory src/ that contain many .cc files and its binary.
For example:
```
src/
|_ foo.cc
|_ bar.cc
|_ qux.cc
|_ thehead.hh
|_ foo (executable/binary)
|_ bar (executable/binary)
|_ qux (executable/binary)
|_ makefile
```
In reality there are many .cc and executable files.
I need to remove those binaries in a global way without having to list
all the files. Is there a fast and compact way to do it?
I tried:
```
$ rm *
```
but it removes all the files include .cc and .hh files.
I am aware of this command:
```
$ rm foo bar qux ....
```
but then we still have to list all the files one by one. | you can run
```
find . -perm +100 -type f -delete
``` | Here you go:
```
ls | grep -v "\." | xargs rm
```
The `grep -v` says "only allow filenames that don't contain a dot", and the `xargs rm` says "then pass the list of filenames to `rm`". | How to remove/delete executable files (aka files without extension) only | [
"",
"c++",
"linux",
"unix",
"file",
""
] |
How can be styled a combo box? | You can't do much with regular CSS. Try with jQuery plugins, like [this one](http://jquery.sanchezsalvador.com/page/jquerycombobox.aspx) or read more about [enhancing dropdowns](http://www.reynoldsftw.com/2009/03/11-jquery-plugins-to-enhance-html-dropdowns/). | You can't do much, without replacing it with something that emulates the functionality without truly being a "select element".
If you're interested in that though, here's a couple good articles about it:
[`<select>` Something New, Part 1](http://v2.easy-designs.net/articles/replaceSelect/)
[`<select>` Something New, Part 2](http://v2.easy-designs.net/articles/replaceSelect2/) | How to stylize a combo box? | [
"",
"javascript",
"combobox",
""
] |
I'm writing a C++ library for an image format that is based on PNG. One stopping point for me is that I'm unsure as to how I ought to lay out the pixel data in memory; as far as I'm aware, there are two practical approaches:
1. An array of size (width \* height); each pixel can be accessed by array[y\*width + x].
2. An array of size (height), containing pointers to arrays of size (width).
The standard reference implementation for PNG (libpng) uses method 2 of the above, while I've seen others use method 1. Is one better than the other, or is each a method with its own pros and cons, to where a compromise must be made? Further, which format do most graphical display systems use (perhaps for ease of using the output of my library into other APIs)? | Off the top of my head:
* The one thing that would make me choose #2 is the fact that your memory requirements are a little relaxed. If you were to go for #1, the system will need to be able to allocate `height * width` amount of ***contiguous*** memory. Whereas, in case of #2, it has the freedom to allocate smaller chunks of contiguous memory of size `width` (could as well be `height`) off of areas that are free. (When you factor in the channels per pixel, the #1 may fail for even moderately sized images.)
* Further, it may be slightly better when swapping rows (or columns) if required for image manipulation purposes (pointer swap suffices).
* The downside for #2 is of course an extra level of indirection that seeps in for every access and the array of pointers to be maintained. But this is hardly a matter given todays processor speed and memory.
* The second downside for #2 is that the data isn't necessarily next to each other, which makes it harder for the processor the load the right memory pages into the cache. | The advantage of method 2 (cutting up the array in rows) is that you can perform memory operations in steps, e.g. resizing or shuffling the image without reallocating the entire chunk of memory at once. For really large images this may be an advantage.
The advantage of a single array is that you calculations are simpler, i.e. to go one row down you do
```
pos += width;
```
instead of having to reference pointers. For small to medium images this is probably faster. Unless you're dealing with images of hundreds of Mb, I would go with method 1. | Layout of Pixel-data in Memory? | [
"",
"c++",
"c",
"image",
""
] |
I'm wanting to print a standard sized envelope from a webpage using c#. Does anyone know how to do something like this? I would load the data from the system for the address and pass it. I just need the basic steps for doing so. | I did end up going with a PDF. We use [PDFSharp](http://www.pdfsharp.net), which is a free PDF creator tool for .NET. I create the PDF on the fly using the function here, and then on the page I just load this page as a new window. Here's the method I ended up creating for anyone who wants to do something similar.
```
protected void DisplayPDFEnvelope()
{
try
{
PdfDocument document = new PdfDocument();
PdfPage pdfpage = new PdfPage();
XUnit pdfWidth = new XUnit(4.125, XGraphicsUnit.Inch);
XUnit pdfHeight = new XUnit(9.5, XGraphicsUnit.Inch);
pdfpage.Height = pdfHeight;
pdfpage.Width = pdfWidth;
pdfpage.Orientation = PageOrientation.Landscape;
XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
document.AddPage(pdfpage);
// Create a font
XFont font = new XFont("ARIAL", 1, XFontStyle.Regular, options);
// Get an XGraphics object for drawing beneath the existing content
XGraphics gfx = XGraphics.FromPdfPage(pdfpage, XGraphicsPdfPageOptions.Append);
// This method just returns a formatted address from the DB using \n to
// do line breaks, i.e. 'Test Person\nAddress Line1\City, State Zip'
string address = GetAddress();
// Get the size (in point) of the text
XSize size = gfx.MeasureString(address, font);
// Create a graphical path
XGraphicsPath path = new XGraphicsPath();
path.AddString(address, font.FontFamily, XFontStyle.Regular, 10,
new XPoint(345, 160), XStringFormats.Default);
// Create a dimmed pen and brush
XPen pen = new XPen(XColor.FromGrayScale(0), 0); // XColor.FromArgb(50, 75, 0, 130), 3);
XBrush brush = new XSolidBrush(); // XColor.FromArgb(50, 106, 90, 205));
// Stroke the outline of the path
gfx.DrawPath(pen, brush, path);
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Page.Response.Clear();
Page.Response.ContentType = "application/pdf";
Page.Response.AppendHeader("Content-Length", stream.Length.ToString());
Page.Response.AppendHeader("Content-Type", "application/pdf");
Page.Response.AppendHeader("Content-Disposition", "inline;filename=envelope.pdf");
Page.Response.BinaryWrite(stream.ToArray());
Page.Response.Flush();
stream.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
throw ex;
}
}
``` | Theoretically you can do it using css <http://www.w3.org/TR/css-print/>. Depending on how many browsers you have to support it may be a route to a great deal of pain as they all work slightly differently.
You are likely to have some issues with page sizing and orientation as your users may me on many differant printers. Printing from flash, pdf or silverlight 3 may be the easy route out. | Print an Envelope from a website? | [
"",
"c#",
""
] |
I have a background worker running a long database task. i want to show the progress bar while the task is running. Somehow the background worker won't report the progress of the task.
This is what i have:
```
BackgroundWorker _bgwLoadClients;
_bgwLoadClients = new BackgroundWorker();
_bgwLoadClients.WorkerReportsProgress = true;
_bgwLoadClients.DoWork += new DoWorkEventHandler(_bgwLoadClients_DoWork);
_bgwLoadClients.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bgwLoadClients_RunWorkerCompleted);
_bgwLoadClients.ProgressChanged += new ProgressChangedEventHandler(_bgwLoadClients_ProgressChanged);
_bgwLoadClients.RunWorkerAsync(parms);
private void _bgwLoadClients_DoWork(object sender, DoWorkEventArgs e)
{
DataTable dt = getdate();
e.Result = dt;
}
void _bgwLoadClients_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
```
I am doing this in WPF, but i guess it won't make a difference.
Thanks in advance | You need to break your DoWork method down into reportable progress and then call ReportProgress.
Take for example the following:
```
private void Something_DoWork(object sender, DoWorkEventArgs e)
{
// If possible, establish how much there is to do
int totalSteps = EstablishWorkload();
for ( int i=0; i<totalSteps; i++)
{
// Do something...
// Report progress, hint: sender is your worker
(sender as BackgroundWorker).ReportProgress((int)(100/totalSteps)*i, null);
}
}
```
If your work can't be predetermined, try adding your own percentages:
```
private void Something_DoWork(object sender, DoWorkEventArgs e)
{
// some work
(sender as BackgroundWorker).ReportProgress(25, null);
// some work
(sender as BackgroundWorker).ReportProgress(50, null);
// some work
(sender as BackgroundWorker).ReportProgress(60, null);
// some work
(sender as BackgroundWorker).ReportProgress(99, null);
}
``` | Modify the **WorkReportProgress** property of the backgroundworker object to **true** either in the properties window or in code. | Backgroundworker won't report progress | [
"",
"c#",
"wpf",
"backgroundworker",
"progress",
""
] |
I'm doing some experimenting with AJAX in CakePHP and it seems to work except that the view that gets returned includes the default template. How can I get rid of that (or even just specify a different empty template for a view)? | ```
function ajaxFunction() {
//do stuff
$this->layout= 'ajax';
}
```
Ajax is an included blank layout to prevent extra markup being added, exactly what you want.
<http://book.cakephp.org/view/96/Layouts> | Try using RequestHandler component. This will be handled automatically for you. Then, you can do something like this in your AppController::beforeFilter()
```
if($this->RequestHandler->isAjax()) {
Configure::write('debug',0);
}
``` | How can I display ajax results in a view in CakePHP without including the default template in the ajax response? | [
"",
"php",
"cakephp",
""
] |
Are there automatic ways to sync comments between an interface and its implementation? I'm currently documenting them both and wouldn't like to manually keep them in sync.
UPDATE:
Consider this code:
```
interface IFoo{
/// <summary>
/// Commenting DoThis method
/// </summary>
void DoThis();
}
class Foo : IFoo {
public void DoThis();
}
```
When I create class like this:
```
IFoo foo=new Foo();
foo.DoThis();//comments are shown in intellisense
```
Here comments are not shown:
```
Foo foo=new Foo();
foo.DoThis();//comments are not shown in intellisense
```
The `<inheritDoc/>` tag will perfectly generate the documentation in Sand Castle, but it doesn't work in intellisense tooltips. | You can do this quite easily using the Microsoft Sandcastle (or NDoc) `inheritdoc` tag. It's not officially supported by the specification, but custom tags are perfectly acceptable, and indeed Microsoft chose to copy this (and one or two other tags) from NDoc when they created Sandcastle.
```
/// <inheritdoc/>
/// <remarks>
/// You can still specify all the normal XML tags here, and they will
/// overwrite inherited ones accordingly.
/// </remarks>
public void MethodImplementingInterfaceMethod(string foo, int bar)
{
//
}
```
[Here](http://www.ewoodruff.us/shfbdocs/html/79897974-ffc9-4b84-91a5-e50c66a0221d.htm) is the help page from the Sandcastle Help File Builder GUI, which describes its usage in full.
(Of course, this isn't specifically "synchronisation", as your question mentions, but it would seem to be exactly what you're looking for nonetheless.)
As a note, this sounds like a perfectly fair idea to me, though I've observed that some people think you should always respecify comments in derived and implemented classes. (I've actually done it myself in documenting one of my libraries and I haven't see any problems whatsoever.) There's almost always no reason for the comments to differ at all, so why not just inherit and do it the easy way?
**Edit:** Regarding your update, Sandcastle can also take care of that for you. Sandcastle can output a modified version of the actual XML file it uses for input, which means you can distribute *this modified version* along with your library DLL instead of the one built directly by Visual Studio, which means you have the comments in intellisense as well as the documentation file (CHM, whatever). | If you're not using it already, I strongly recommend a free Visual Studio addon called [GhostDoc](http://www.roland-weigelt.de/ghostdoc/). It eases the documentation process. Have a look at [my comment](https://stackoverflow.com/questions/461306/how-to-document-thrown-exceptions-in-c-net/461515#461515) on a somewhat related question.
Although GhostDoc won't make the synchronization automatically, it can help you with the following scenario:
You have a documented interface method. Implement this interface in a class, press the GhostDoc shortcut key, `Ctrl-Shift-D`, and the XML comment from the interface will be added to the implemented method.
Go to the **Options -> Keyboard** settings, and assign a key to `GhostDoc.AddIn.RebuildDocumentation` (I used `Ctrl-Shift-Alt-D`).
[](https://i.stack.imgur.com/zh77x.png)
Now, if you change the XML comment on the *interface*, just press this shortcut key on the implemented method, and the documentation will be updated. Unfortunately, this doesn't work vice-versa. | Ways to synchronize interface and implementation comments in C# | [
"",
"c#",
"documentation",
"xml-documentation",
""
] |
If I have a constant BAR in Foo, which I will use in a class C I'll have to write
```
Object o = Foo.BAR + "...";
```
which I can use Ctrl-Shift-M in Eclipse (with the cursor on BAR) to create a static import for like:
```
import static Foo.BAR;
Object o = BAR + "....";
```
I am current updating legacy code with literaly thousands of these I'd like to convert to static imports. Ctrl-Shift-O / Organize imports does not do it. Is there a trick I've missed?
---
EDIT: Actually, what I would prefer is a way to tell Eclipse that I want to have Ctrl-Shift-M do its magic on ALL instances in this particular class instead of just the single instance I have the cursor placed at. (It is legacy code so this actually IMPROVES readability :) )
---
EDIT: I've found that IntelliJ suggest doing this. | One cautionary note: excessive use of static imports can actually make your code less readable (imho), particularly if the constant name doesn't clearly indicate the class or enum from which it belongs. You can also get constant names from different classes/enums that sound similar or even have the same name.
So what you're forcing the reader to do is hope his IDE will tell him the class (via, say, a tool tip) or they have to navigate to it to find out what it is. Printouts and code snippets become that much less reeadable.
Honestly I use static imports extremely rarely for these reasons. | I don't know any other automated refactorings to do what you're looking for, but there are two key aspects to doing this - one is adding the imports and the other is removing the class name from the constants.
For adding the imports, I recommend pasting `import static application.KeyHolder.*;` after the package on every file which uses them.
For removing the class name, in eclipse do a Java search for `KeyHolder.*` and search for a field. You can then do a find/replace for "KeyHolder." and replace with "". In order to prevent mismatches make sure the replaced item count is equal to the number of matches for that file. Also, make sure you search down and start after the imports. | A simple way to create static imports for constants in existing code? | [
"",
"java",
"eclipse",
""
] |
Currently in my PHP scripts, I redirect the user to a custom 404 not found error page when he/she tries to access content that doesn't exist or doesn't belong to that user. Like so:
```
header('Location: http://www.mydomain.com/error/notfound/');
exit;
```
I realize the above header() call sends a 302 redirect status code by default.
What I don't understand, however, is when I should send the 404 not found status code. Before I redirect the user? Or when I display the */error/notfound/* page?
Thanks for your help! | You should do something like this:
```
header("HTTP/1.0 404 Not Found");
include 'error.php';
die();
``` | You don't execute 404 errors as a redirect at all.
What you really want to do is send the 404 status header, and then replace the current output with the body of a 404 page.
There are various ways to do this and it depends quite a bit on how your site is structured. MVC applications typically hand this with a forward. I've seen other systems that throw an Exception and then the registered exception handler takes care of displaying the 404 page.
At any rate, the rough steps are
1. Determine content is invalid
2. Break out of current execution
3. Clear any output, should there be any.
4. Send the 404 status header
5. Send the content of the 404 page | When to send HTTP status code? | [
"",
"php",
"http",
"header",
"http-headers",
""
] |
In my winforms project I'm looking for a Crystal Report's like solution free or open source that allows me printing and PDF'ing the Content of a DataSet. ¿Any suggestion or Ideas?
I need something simple but fast, Crystal seems very slow for me. Thanks in advance.
I'm aware of this [question](https://stackoverflow.com/questions/586239/are-there-any-open-source-alternatives-to-crystal-reports) but it seems to me there are just answers related to java | You could always roll your own. I'm getting rid of Crystal Reports in our project because currently, we can't update our old reports without upgrading everyone to XP, because we develop in VS 2008, and the new CR doesn't support Win2K. Also, CR takes about 30 seconds to build and load the report, mine is instantaneous.
I wrote [my own XML serializer](https://stackoverflow.com/questions/721537/streaming-xml-serialization-in-net/721591#721591), and I build custom objects that are populated from List<T>s, DataTables, etc..., serialize the object, load it into an XmlDocument, append an XSLT stylesheet, and write it to a directory containing that XSLT file and any CSS and images. The XSLT file then transforms it to HTML/CSS when the XML file is opened in the user's browser.
I could also probably load it into a WebBrowser control and use one of the free PDF libraries to convert it to PDF and print it. See these threads for more details:
* [Render PDF in iTextSharp from HTML with CSS](https://stackoverflow.com/questions/430280/render-pdf-in-itextsharp-from-html-with-css)
* [Maintain CSS styling when converting HTML to PDF in ASP.NET](https://stackoverflow.com/questions/415535/maintain-css-styling-when-converting-html-to-pdf-in-asp-net) | I would suggest that you use the [fyiReporting](http://www.fyireporting.com/) ([Forked and Moved Now Current as of 2012](http://reportingcloud.sourceforge.net/)) tool if you are looking to replace Crystal Reports. I have used both fyiReporting and Crystal and would have to say that I prefer fyiReporting(though their website is ghetto).
Reasons for choosing fyiReporting
1. If you want to replace Crystal then you are used to having a Report designer. FyiReporting has its own GUI just like Crystal Reports for creating and running reports(You could just create and distribute reports without building an application).
2. FyiReports allows you to export the Report as PDF, excel and mht(static web page) just to mention a few.
3. FyiReports are xml based so the report definition can be saved in a database and altered at anytime.
4. If you are using .Net FyiReporting has a Web and Windows Forms control for embedding the report in your applications(much like crystal reports). I am not so sure about Java as I am a .Net guy.
Anyway give FyiReports a try. | Reporting (free || open source) Alternatives to Crystal Reports in Winforms | [
"",
"c#",
"winforms",
"reporting",
""
] |
I always press `F6` to build my project. Suddenly some of my Visual Studio instances are wanting me to use `Ctrl`-`Shift`-`B`. It's not keyboard related - the actual text of the menu option changes from "`F6`" to "`Ctrl`-`Shift`-`B`".
Any answers as to how to fix, and **what causes this**? | This is because you might have selected "General Development Settings" as your default environment settings for your Visual Studio (which usually we do on the first launch of VS after installing it as it pops up a dialogue box to choose default environment settings).
If you only want to change the keyboard hotkeys settings, you just follow the solution proposed by others (**Tools > Options > Environment > Keyboard > Visual C# 2015**). ***BUT*** this will only change the keyboard settings to C# settings while keeping rest of the settings as General settings only.
If you are really intending to change complete environment to C# settings, then follow this approach.
**SOLUTION 1:**
1. Go to "Tools" (menu)
2. "Import and Export Settings"
3. "Import selected environment settings"
4. Either select "Yes, save my current settings" or "No, just import new settings, overwriting my current settings"
5. "Which collection of settings do you want to import?"
6. Under "Default Settings" tree select "Visual C#" node (you might see a yellow warning sign, NO need to worry about it) and then click "Finish" button.
or you can do the same like
**SOLUTION 2:**
1. Go to "Tools" (menu)
2. "Import and Export Settings"
3. "Reset all settings"
4. Either select "Yes, save my current settings" or "No, just import new settings, overwriting my current settings"
5. Select "Visual C#" from the list and then click "Finish" button.
Both approaches would give you the same result of changing your complete environment to 'Visual C#" there onward.
Enjoy Coding :) | Keyboard mapping corruption issue perhaps? Check Tools / Options, Environment / Keyboard. Should see a drop-down for your Keyboard mapping scheme and next to it a Reset button. Hit the reset button.
I'm not responsible for this screwing with your settings - save them prior to doing this just in case you screw the pooch.
Oh, in case the narcs out there care, I think this is a valid question and would be put out if someone voted to close it. Of course now that I've said that, its a certaintity, isn't it? | Visual Studio hot keys change occasionally, specifically F6 vs Ctrl-Shift-B for building. WHY? | [
"",
"c#",
"visual-studio-2008",
""
] |
Using C++ and the STL, does anybody know how to store integer arrays as nodes in an STL list or vector? I have an unknown number of pairs of numbers that I need to store, and coming from other languages my first thought was to use some sort of list- or vector-like data structure... but I'm running into some trouble. I am 100% sure that I'm making an obvious beginner's C++ mistake, and that somebody who actually knows the language will take one look at what I'm trying to do and be able to set me straight.
So, here's what I've tried. Declaring a list like so works:
```
stl::list<int[2]> my_list;
```
And then I can easily make a two-element array, like so:
```
int foo[2] = {1,2};
```
This compiles and runs just fine. However, as soon as I try to add `foo` to my list, like so:
```
my_list.push_back(foo);
```
I get a whole gnarly set of compiler errors, none of which I really understand (my C++-fu is almost non-existent):
```
/usr/include/c++/4.0.0/ext/new_allocator.h: In member function ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp = int [2]]’:
/usr/include/c++/4.0.0/bits/stl_list.h:440: instantiated from ‘std::_List_node<_Tp>* std::list<_Tp, _Alloc>::_M_create_node(const _Tp&) [with _Tp = int [2], _Alloc = std::allocator<int [2]>]’
/usr/include/c++/4.0.0/bits/stl_list.h:1151: instantiated from ‘void std::list<_Tp, _Alloc>::_M_insert(std::_List_iterator<_Tp>, const _Tp&) [with _Tp = int [2], _Alloc = std::allocator<int [2]>]’
/usr/include/c++/4.0.0/bits/stl_list.h:773: instantiated from ‘void std::list<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int [2], _Alloc = std::allocator<int [2]>]’
test.cpp:5: instantiated from here
/usr/include/c++/4.0.0/ext/new_allocator.h:104: error: ISO C++ forbids initialization in array new
```
So, anybody have ideas as to what I'm doing wrong here? Any pointers (no pun intended) would be most helpful. Is it just not possible to store arrays in a std::list? Should I be using a struct? Am I just missing a `*` or `&` somewhere? | You can't store arrays in STL containers. You'd use a vector of vectors or somesuch for the general case. For your specific case, I'd use a vector of std::pair, like so: `std::vector<std::pair<int, int> >`. `std::pair` is a class that has two members, `first` and `second`, of whatever type you templatize it to be.
Edit: I originally had it as `std::vector<std::pair<int> >`, but I wasn't sure if it was overloaded to accept only 1 parameter in the case that both types are the same... a little digging turned up no evidence of this, so I modified it to explicitly state that both `first` and `second` are `int`s. | The thing stored in a Standard Library container must be assignable and copyable - arrays are neither. Your best bet is to create a list of std::vector. Alternatively, you can wrap the array in a struct:
```
struct A {
int array[2];
};
std::list <A> alist;
``` | How do I store arrays in an STL list? | [
"",
"c++",
"arrays",
"stl",
""
] |
Is there any way to configure IIS or Web app to automatically open a new window when a hyperlink is clicked? My issue isn't as trivial as it sounds, let me explain... I understand you can use JavaScript or `target="_blank"` in the anchor tag, but I don't always know when an anchor tag might be listed on the page...
The reason is that it's a user forum, think of stack overflow ;) where a user might enter a URL (allowed) and it's not necessarily known, or it was entered aeons ago and there is no way to tell.
I'm pretty sure the answer is no and I'll just have to analyze for URLs when the post/entry is being saved and convert it to do this then. | ```
<html>
<head>
<base target='_blank'> <!-- Here's the interesting bit -->
</head>
<body>
<p><a href='http://google.com'>New window!</a></p>
</body>
</html>
```
Of course that really will do **all** links - if you want a link to be an exception to the rule, and to open in the current window, do this:
```
<p><a href='http://google.com' target='_self'>Not new window!</a></p>
``` | IIS wouldn't have anything to do with it - short of writing a filter that would rewrite all your links. I'd suggest JQuery, where it should be as easy as:
```
$(function() {
$('A').attr('target', '_blank');
});
``` | Open New Window from aspx page from *any* URL | [
"",
"asp.net",
"javascript",
"html",
"iis",
""
] |
Our client (a winforms app) includes a file-browser. I'd like the user to be able to open the selected file using the shell's default handler. How do I do that? I've read that I should use the Win32 API rather than the registry, but I'd prefer a solution that involves only .NET. | EDIT: Newer, simpler answer.
You can indeed just use `Process.Start(filename)`. This is specified in the [docs for `Process.Start`](http://msdn.microsoft.com/en-us/library/53ezey2s.aspx):
> Starting a process by specifying its
> file name is similar to typing the
> information in the Run dialog box of
> the Windows Start menu. Therefore, the
> file name does not need to represent
> an executable file. It can be of any
> file type for which the extension has
> been associated with an application
> installed on the system. For example
> the file name can have a .txt
> extension if you have associated text
> files with an editor, such as Notepad,
> or it can have a .doc if you have
> associated.doc files with a word
> processing tool, such as Microsoft
> Word. Similarly, in the same way that
> the Run dialog box can accept an
> executable file name with or without
> the .exe extension, the .exe extension
> is optional in the fileName parameter.
> For example, you can set the fileName
> parameter to either "Notepad.exe" or
> "Notepad".
EDIT: Original, complicated answer:
If you use `Process.Start` with the file as the "executable" and specify `UseShellExecute = true` it will just work. For example:
```
using System;
using System.Diagnostics;
class Test
{
static void Main()
{
ProcessStartInfo psi = new ProcessStartInfo("test.txt");
psi.UseShellExecute = true;
Process.Start(psi);
}
}
```
That opens test.txt in Notepad.
In fact, `UseShellExecute=true` is the default, but as it's definitely required I like to specify it explicitly to make that clearer to the reader. | Since this question is the first result in Google, I'm adding this updated answer for .NET Core and .NET 5 upwards. You will need to add `UseShellExecute = true`.
```
Process.Start(new ProcessStartInfo(filePath) { UseShellExecute = true });
```
It's more cumbersome than earlier with .NET Framework, but you can wrap it in a custom method:
```
public static void OpenFile(string filePath)
=> Process.Start(new ProcessStartInfo(filePath) { UseShellExecute = true });
``` | How do I open a file using the shell's default handler? | [
"",
"c#",
".net",
"winforms",
""
] |
i have form action file in another directory but some file send to this action file
and how to get url to send action
<http://www.test.com>
```
-> action to http://www.123456.com/ac.php
how to get http://www.test.com in http://www.123456.com/ac.php to goback http://www.test.com
``` | You could store the `$_SEVER["HTTP_REFERER"]` in a session or other variable and then use it when applicable. | You might consider using the predefined php variables to find out the request URL like this:
```
$_SERVER['HTTP_HOST']
$_SERVER['REQUEST_URI']
```
But if you just want to redirect to the root of your host, then you can simply send a HTTP redirect to '/' | How to get url to send action form back? | [
"",
"php",
"html",
""
] |
I'm Serializing an ArrayList to a binary file in order to send it across TCP/IP. The serialized file is created by the server and I hope to be able to deserialize it with the client that I'm writing at the moment.
However, when the client attempts to deserialize it throws a SerializationException because it can't find the assembly (presumably) which serialized the file to begin with.
How do I get around this? | Does your arraylist contain custom data type (i.e. your own classes)?
The arraylist won't be deserialized unless the code running the deserialize has access to all of the classes contained within the arraylist. | If you are using binary serialization, the client will need to have access to the DLL that contains the type that you are serializing in the ArrayList. I guess I don't really know about your setup to describe how that should be done but that's the gist of it.
If you use something like xml serialization (either using XmlSerializaer or DataContractSerializer), you will be able to produce Xml. You can duplicate the object code on both server/client side if you are truly unable to share the assembly. | Unable to find assembly | [
"",
"c#",
".net",
"serialization",
"arraylist",
""
] |
How i can insert data into more than one table of an Access database which have a join of inner by using C#? | I assume by join you mean a relationship with a foreign key to another table. Joins refer to queries not tables.
You can simply do multiple inserts, one to each table as required, add the record to the parent table, get the key of the new record you just added, then do the inserts to any child tables using that ID which would be the foreign key in the child table. | I agree the question is vague but implies the oft asked question for the ACE/Jet engine, "If I can create an `INNER JOIN` between two tables, can I `INSERT` into both tables with one SQL statement?" usually closely followed by the qualifier, "...and if there is a `FOREIGN KEY` (Access = Relationship with referential integrity enforced) between the tables, can the generated `INDENTITY`/AutoNumber number in the referenced table be automatically added to the referencing table?"
The answer to *these* questions is yes: create a `VIEW` with an `INNER JOIN` (or equivalent), including the `IDENTITY` column and the column referencing the `IDENTITY` column then `INSERT INTO` the `VIEW` omitting the `IDENTITY` column and its referencing column.
Here's a quick example in ANSI-92 Query Mode syntax (I assume you are using OLE DB):
```
CREATE TABLE TableA
(
ID IDENTITY NOT NULL UNIQUE,
a_col INTEGER NOT NULL
)
;
CREATE TABLE TableB
(
ID INTEGER NOT NULL UNIQUE
REFERENCES TableA (ID),
b_col INTEGER NOT NULL
)
;
CREATE VIEW TestAB
(
a_ID, a_col,
b_ID, b_col
)
AS
SELECT A1.ID, A1.a_col,
B1.ID, B1.b_col
FROM TableA AS A1
INNER JOIN TableB AS B1
ON A1.ID = B1.ID
;
INSERT INTO TestAB (a_col, b_col) VALUES (55, 99)
;
``` | How to Insert Data? | [
"",
"c#",
"ms-access",
"ado.net",
""
] |
Don't you hate it when you have
```
class Foobar {
public:
Something& getSomething(int index) {
// big, non-trivial chunk of code...
return something;
}
const Something& getSomething(int index) const {
// big, non-trivial chunk of code...
return something;
}
}
```
We can't implement either of this methods with the other one, because you can't call the non-`const` version from the `const` version (compiler error).
A cast will be required to call the `const` version from the non-`const` one.
Is there a real elegant solution to this, if not, what is the closest to one? | I recall from one of the Effective C++ books that the way to do it is to implement the non-const version by casting away the const from the other function.
It's not particularly pretty, but it is safe. Since the member function calling it is non-const, the object itself is non-const, and casting away the const is allowed.
```
class Foo
{
public:
const int& get() const
{
//non-trivial work
return foo;
}
int& get()
{
return const_cast<int&>(const_cast<const Foo*>(this)->get());
}
};
``` | How about:
```
template<typename IN, typename OUT>
OUT BigChunk(IN self, int index) {
// big, non-trivial chunk of code...
return something;
}
struct FooBar {
Something &getSomething(int index) {
return BigChunk<FooBar*, Something&>(this,index);
}
const Something &getSomething(int index) const {
return BigChunk<const FooBar*, const Something&>(this,index);
}
};
```
Obviously you'll still have object code duplication, but no source code duplication. Unlike the const\_cast approach, the compiler will check your const-correctness for both versions of the method.
You probably need to declare the two interesting instantiations of BigChunk as friends of the class. This is a good use of friend, since the friend functions are hidden away close to the friendee, so there is no risk of unconstrained coupling (ooh-er!). But I will not attempt the syntax for doing so right now. Feel free to add.
Chances are that BigChunk needs to deference self, in which case the above order of definition isn't going to work very well, and some forward declarations will be needed to sort it out.
Also, in order to avoid some numpty finding BigChunk in the header and deciding to instantiate and call it even though it's morally private, you can move the whole lot into the cpp file for FooBar. In an anonymous namespace. With internal linkage. And a sign saying "beware of the leopard". | Elegant solution to duplicate, const and non-const, getters? | [
"",
"c++",
"constants",
"function-qualifier",
""
] |
I have a function that processes a given vector, but may also create such a vector itself if it is not given.
I see two design choices for such a case, where a function parameter is optional:
Make it a pointer and make it `NULL` by default:
```
void foo(int i, std::vector<int>* optional = NULL) {
if(optional == NULL){
optional = new std::vector<int>();
// fill vector with data
}
// process vector
}
```
Or have two functions with an overloaded name, one of which leaves out the argument:
```
void foo(int i) {
std::vector<int> vec;
// fill vec with data
foo(i, vec);
}
void foo(int i, const std::vector<int>& optional) {
// process vector
}
```
Are there reasons to prefer one solution over the other?
I slightly prefer the second one because I can make the vector a `const` reference, since it is, when provided, only read, not written. Also, the interface looks cleaner (isn't `NULL` just a hack?). And the performance difference resulting from the indirect function call is probably optimized away.
Yet, I often see the first solution in code. Are there compelling reasons to prefer it, apart from programmer laziness? | I would definitely favour the 2nd approach of overloaded methods.
The first approach (**optional parameters**) blurs the definition of the method as it no longer has a single well-defined purpose. This in turn increases the *complexity* of the code, making it more difficult for someone not familiar with it to understand it.
With the second approach (**overloaded methods**), each method has a clear purpose. Each method is *well-structured* and *cohesive*. Some additional notes:
* If there's code which needs to be duplicated into both methods, this can be *extracted out into a separate method* and each overloaded method could call this external method.
* I would go a step further and *name each method differently* to indicate the differences between the methods. This will make the code more self-documenting. | I would not use either approach.
In this context, the purpose of foo() seems to be to process a vector. That is, foo()'s job is to process the vector.
But in the second version of foo(), it is implicitly given a second job: to create the vector. The semantics between foo() version 1 and foo() version 2 are not the same.
Instead of doing this, I would consider having just one foo() function to process a vector, and another function which creates the vector, if you need such a thing.
For example:
```
void foo(int i, const std::vector<int>& optional) {
// process vector
}
std::vector<int>* makeVector() {
return new std::vector<int>;
}
```
Obviously these functions are trivial, and if all makeVector() needs to do to get it's job done is literally just call new, then there may be no point in having the makeVector() function. But I'm sure that in your actual situation these functions do much more than what is being shown here, and my code above illustrates a fundamental approach to semantic design: **give one function one job to do**.
The design I have above for the foo() function also illustrates another fundamental approach that I personally use in my code when it comes to designing interfaces -- which includes function signatures, classes, etc. That is this: I believe that **a good interface is 1) easy and intuitive to use correctly, and 2) difficult or impossible to use incorrectly** . In the case of the foo() function we are implictly saying that, with my design, the vector is required to already exist and be 'ready'. By designing foo() to take a reference instead of a pointer, it is both intuitive that the caller must already have a vector, and they are going to have a hard time passing in something that isn't a ready-to-go vector. | Optional function parameters: Use default arguments (NULL) or overload the function? | [
"",
"c++",
"function",
"parameters",
"null",
"overloading",
""
] |
I'm normally a Java developer, but I'm writing a C++ library right now they will use LibCurl. And I'm very un-aware in the C++ world!
What I'm writing is infact a library for use by other developers (its a client code used to access our API).
Will end users be required to have libcurl installed, or can the developers somehow include this in the EXE or package it somehow?
Actually the same goes, I might use QT in the library, will they be required to have this installed? I'm guessing the way it works is that developers of course will need it, but once its compiled to binary its not required? Unlike java where you need the Jar files all along...
Cheers for any help,
Alan | If you link libcurl statically then the end-user does not require libcurl, as it will be linked into to the executable directly at compile time.
If you link libcurl dynamically, then the end-user does require libcurl to be installed on their system and available as a shared object library.
However, you're in a different spot. You're writing a library for use by other developers. Thus, your end-user is in fact not really an end-user. In such scenarios it is "better" to provide to link dynamically against libcurl.
If you linked statically then your library would encapsulate in its code a copy of the libcurl library. Now imagine a developer using your library is also using 10 other libraries, all statically linked against libcurl. That developer is basically going to be including 10 copies of libcurl in his/her end product. This is not very efficient and hence dynamic linking against dependencies is preferred when developing a library.
However...
If a developer is using 10 different libraries which require libcurl but some of those libraries require a specific older/newer version than others then static linking will be useful.
Hope that helps... | Many libraries can be used either [statically](http://en.wikipedia.org/wiki/Static_linking) or [dynamically](http://en.wikipedia.org/wiki/Dynamic_library#Dynamic_linking) linked. Curl is one of them (see e.g. [this message](http://curl.haxx.se/mail/lib-2006-09/0128.html), and I would say it's reasonable to do so. QT is rather huge, so you should dynamically link it if at all possible. However, even it can be [statically linked](http://doc.trolltech.com/4.1/deployment-windows.html#static-linking).
The essential difference between static and dynamic linking is that static linking includes the library in the application's object code, while with dynamic linking the application accesses the library on-demand from the system it's installed on. | C++ Library requires LibCurl - will users of the app need libcurl? | [
"",
"c++",
"libcurl",
""
] |
I'm trying to use a hardcoded 64bit integer in a string variable.
Simplfied I want to do something like this:
```
$i = 76561197961384956;
$s = "i = $i";
```
Which should result in `s` being:
```
i = 76561197961384956
```
This does obviously not work as PHP cast big integers to float, therefore `s` is:
```
i = 7.65611979614E+16
```
While several other methods like casting etc. fail, I found `number_format()` and use it like this:
```
$s = "i = " . number_format($i, 0, '.', '');
```
But this results in `s` being:
```
i = 76561197961384960
```
Looks like an approximation problem, but how to fix this? | You're losing the precision on the assignment, not on the string conversion. If this variable's value is actually hardcoded, and you can't change that, there's nothing you can do.
A line like:
```
$i = 76561197961384956;
```
will always lose precision. If you need to keep the whole thing, store it into a string, you can't store it as an int like that and keep all the digits. | I think the only way is to use the [`bcmath`](https://www.php.net/manual/en/book.bc.php) functions.
> For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.
It's your `$i` that's wrong, not the string conversion - PHP uses 32 bit ints internally. | PHP: Converting a 64bit integer to string | [
"",
"php",
"casting",
"64-bit",
"long-integer",
""
] |
Is there a C/C++/STL/Boost clean method to convert a date time string to epoch time (in seconds)?
```
yyyy:mm:dd hh:mm:ss
``` | See: [Date/time conversion: string representation to time\_t](https://stackoverflow.com/questions/321793/date-time-conversion-string-representation-to-timet)
And: [[Boost-users] [date\_time] So how come there isn't a to\_time\_t helper func?](http://archives.free.net.ph/message/20060504.123105.73e1c873.en.html#boost-users)
So, apparently something like this should work:
```
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time;
std::string ts("2002-01-20 23:59:59");
ptime t(time_from_string(ts));
ptime start(gregorian::date(1970,1,1));
time_duration dur = t - start;
time_t epoch = dur.total_seconds();
```
But I don't think it's much cleaner than [Rob's suggestion](https://stackoverflow.com/questions/321793/date-time-conversion-string-representation-to-timet/321847#321847): use `sscanf` to parse the data into a `struct tm` and then call `mktime`. | On Windows platform you can do something like this if don't want to use Boost:
```
// parsing string
SYSTEMTIME stime = { 0 };
sscanf(timeString, "%04d:%02d:%02d %02d:%02d:%02d",
&stime.wYear, &stime.wMonth, &stime.wDay,
&stime.wHour, &stime.wMinute, &stime.wSecond);
// converting to utc file time
FILETIME lftime, ftime;
SystemTimeToFileTime(&stime, &lftime);
LocalFileTimeToFileTime(&lftime, &ftime);
// calculating seconds elapsed since 01/01/1601
// you can write similiar code to get time elapsed from other date
ULONGLONG elapsed = *(ULONGLONG*)&ftime / 10000000ull;
```
If you prefer standard library, you can use struct tm and mktime() to do the same job. | C++ Converting a Datetime String to Epoch Cleanly | [
"",
"c++",
"datetime",
"stl",
"boost",
""
] |
I want to access a Session value in jquery method in the ASP.NET MVC view page. See the below code,
```
$('input[type=text],select,input[type=checkbox],input[type=radio]').attr('disabled', '<%= Session["CoBrowse"].ToString() %>');
```
How can I get the Session value in jquery. | ```
$('input,select').attr('disabled','<%=Session["CoBrowse"].ToString() %>');
``` | Not sure if this is the best route but within your aspx page you could create a method that returns the value of your session variable, e.g.
Server side:
```
using System.Web.Services;
[WebMethod(EnableSession = true)]
public static string GetSession()
{
return Session["CoBrowse"].ToString();
}
```
then call this method client side using jQuery:
```
$.ajax({
type: "POST",
url: "./Default.aspx/GetSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result){
('input[type=text],select,input[type=checkbox],input[type=radio]').attr('disabled', result.d);
}
});
``` | How to get asp.net Session value in jquery method? | [
"",
"c#",
"asp.net",
"jquery",
"asp.net-mvc",
""
] |
I'm using Spring AOP. I'm giving my pointcuts like:
```
@Pointcut("execution(* com.demo.Serviceable+.*(..))")
public void serviceMethodCalls() {
}
```
Is it possible to avoid the in-place pointcut expression in Spring AOP? | It depends on what style of AOP you choose with Spring. As you stick with the annotation based approach, there is not much you can get except having constants for the expressions located in an extenal class.
This is due to the @Aspect annotation based AOP style dedicated to colocate *where* and *what*. You can somehow get some configurability by using abstract method and binding the pointcut to it.
```
@Aspect
public abstract class MyAspect {
protected abstract pointcut();
@Before("pointcut()")
public void myAdviceMethod() {
// Advice code goes here
}
}
public class ConcreteAspect extends MyAspect {
@Pointcut("execution(* com.acme.*.*(..))")
protected pointcut() {
)
}
```
This is possible but seems rather awkward to me as the implementor has to know that `@Pointcut` is *required* on the method. If she forgets to place it, it will crash entirely.
If you need the flexibility to have advice and pointcut separated you better stick to the XML based configuration (see [Spring documentation](http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-schema) for example).
A kind of man in the middle is the possibility to tie your pointcut to a custom annotation and let the users decide where to place it and thus, when to get your advice applied. [Spring documentation (chapter 6.2.3.4)](http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-pointcuts) gives more info on that.
Regards,
Ollie | Here's how you could define a configurable Spring AOP Advice with Java Config:
```
@Configuration
public class ConfigurableAdvisorConfig {
@Value("${pointcut.property}")
private String pointcut;
@Bean
public AspectJExpressionPointcutAdvisor configurabledvisor() {
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.setExpression(pointcut);
advisor.setAdvice(new MyAdvice());
return advisor;
}
}
class MyAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Before method");
Object result = invocation.proceed();
System.out.println("After method");
return result;
}
}
```
`pointcut.property` can then be defined in your `application.properties` file | Avoiding in-place pointcut expression in Spring AOP | [
"",
"java",
"spring",
"aop",
""
] |
I have a linq query which returns the ID of a question based on the questions text.
This ID is then needed to be used to relate a date in a date table to that particular question. The question is already stored and the date is stored at a different time.
The problem is that the query returns the questionID as an anonymous type and so when I need to assign that questionID as the questionID in another table, it throws an error, stating that the table is expecting a Guid. Following this, I converted the anonymous type to a string and then used the GUIDs convert feature to convert the string to a GUID, however it is now giving me the error that a GUID should be 32 characters and 4 dashes.
My thoughts regarding this are that the anonymous type is returning the questionID as "QuestionID = jkj939-89239829- etc etc." - With the prefix of characters at the front, and thus when converting it to a GUID, the converted string contains these characters.
Have I missed something?
I really can't understand why it would do this, and is there a way to remove the prefix returned by the anonymous type?
Help would be greatly appreciated.
Here is the code:
```
public static void GetQuesID(string quesText)
{
ExamineDataContext dc = new ExamineDataContext();
var matchedques = from q in dc.GetTable<Question>()
where q.QuestionText.Contains(quesText)
select new{
q.QuestionID
};
foreach (var element in matchedques)
{
MessageBox.Show(element.ToString());
}
try
{
Guid g = Guid.NewGuid();
Table<DateLastUsed> dlused = Repository.GetDateLastUsedTable();
DateLastUsed dlu = new DateLastUsed(); ;
string qidGuidString = matchedques.ToString();
Guid convQuesGuid = new Guid(qidGuidString);
dlu.DLUID = g;
dlu.QuestionID = convQuesGuid;
dlu.DateLastUsed1 = DateTime.Now;
dlused.InsertOnSubmit(dlu);
dlused.Context.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
}
``` | Unless I'm missing something, why don't you just `select q.QuestionID` instead of making a new anonymous-type wrapper?
```
var matchedques = from q in dc.GetTable<Question>()
where q.QuestionText.Contains(quesText)
select q.QuestionID;
foreach (var element in matchedques)
{
MessageBox.Show(element.ToString());
}
```
Alternatively, give the field a name ("`theID`" below) and access it directly:
```
var matchedques = from q in dc.GetTable<Question>()
where q.QuestionText.Contains(quesText)
select new{
theID = q.QuestionID
};
foreach (var element in matchedques)
{
MessageBox.Show(element.theID.ToString());
}
```
---
Apparently, there was more to the question than I first thought. In response to the comment, keep in mind that you're returning an *enumeration* of results in matchedques (hence the foreach above, right?). So the following line is also in error:
```
string qidGuidString = matchedques.ToString();
```
You either want
```
string qidGuidString = matchedques.Single().ToString();
```
if matchedques should contain a single result, or a foreach loop if matchedques should contain multiple results.
---
Note that there's no reason to convert a GUID to string and back again, and you can also use the query to return something more useful (namely, a new `DateLastUsed` object):
```
var matchedques = from q in dc.GetTable<Question>()
where q.QuestionText.Contains(quesText)
select new DateLastUsed() {
DLUID = Guid.NewGuid(),
QuestionID = q.QuestionID,
DateLastUsed1 = DateTime.Now
};
Table<DateLastUsed> dlused = Repository.GetDateLastUsedTable();
foreach(var dlu in matchedques)
{
dlused.InsertOnSubmit(dlu);
dlused.Context.SubmitChanges();
}
``` | Why don't just `select q.QuestionID;` instead of this `select new { q.QuestionID };' stuff? | C# Linq Guid Anonymous Type Problem | [
"",
"c#",
"linq",
"linq-to-sql",
"guid",
"anonymous-types",
""
] |
To prevent impatient users from clicking on a link to a webstart application too often, I tried to disable the hyperlink for some seconds after it has been called the first time.
```
<a href="file.jnlp" onclick="if (!this.clicked){this.clicked = true; setTimeout('this.clicked = false' ,10000); return true;} return false">
```
The code above only works for disabling the link, but it doesn't get re-enabled after the timeout of 10 seconds.
I've seen that the 'this.clicked' variable isn't true (as it is supposed to be) when I check it in the setTimeout call. Maybe i'm missing some basic JS-knowledge here..
Or perhaps there is a different approach to solve this problem? | give this anchor an ID and then change your timeout call to:
```
setTimeout('document.getElementById("<id>").clicked = false;' , 10000);
```
I think the 'this' is not evaluated to anything when the timer comes around. | First add a this function to a Javascript Script block
```
function Debounce()
{
var self = this
if (this.clicked) return false;
this.clicked = true;
setTimeout(function() {self.clicked = false;}, 10000);
return true;
}
```
Now change your onclick to:-
```
onclick="return Debounce.call(this)"
``` | How to disable Link for some time after being clicked? | [
"",
"javascript",
"html",
""
] |
I am creating a functionality where our wcf services logs all changes that are stored thru them and the changes need to be sent to other systems.
After every service call with changes we store the changes in a table (the changes is serialized). Regulary we have biztalk to pull the changes from the table and delete the one that is pulled.
This means that during high load the amount of inserts and delete are high, and we struggle with that the select times out because it is blocked by the inserts.
I have tried to play with different Isolation levels, but have not found anything that works yet.
We use ado.net and sql server 2005 for this.
What is best practice for implementing a data table with many inserts, deletes and read, when using sql server 2005 and ado.net.
Edited:
Our problem in our today solution is that all the continues inserts are stopping all reads from the table. Probably because if a clustred index scan that I see no good way to remove for the moment. | On the DB side:
* Try using the locking hint called READPAST which skips rows that are locked by other transactions. See [MSDN](http://msdn.microsoft.com/en-us/library/ms187373(SQL.90).aspx) for details.
* Sql Server sometimes escalates locks from row level to page or table level if it thinks that it's more economical. You can force keeping the locks at the row level with the hint ROWLOCK.
* Drop any unnecessary indexes because they slow down inserts, updates and deletes and also can cause locking problems on the index data.
On the C# code side:
* Use the best practice of 'acquire resources as late as possible and release them as early as possible'. Open your ADO.NET connection, run your sql command and close your connection before doing any time consuming operations on the results. You don't have to worry about connection pooling, it is done automatically as long as you use the same connection string all the time. | This is something that your DBA should be doing. Are you the DBA? If so then you'll need to look at running some performance tests to see what the bottleneck is. This article should help as an introduction to performance tuning: <http://www.devx.com/getHelpOn/Article/8202/> | What is the best practice for implementing a data table with many inserts, deletes and reads? | [
"",
"c#",
"sql-server-2005",
"ado.net",
""
] |
I have a problem with a `Socket` connection closing too fast. I was told I need to temporarily load data from the `Socket` and the parse it. Here is my code:
```
ServerSocket listen = new ServerSocket(this.port);
Socket server;
while(i < this.maxConnections)
{
server = listen.accept();
processRequest(server);
i++;
}
```
## processRequest
```
protected void processRequest(Socket server) throws IOException
{
ProcessXML response = new ProcessXML(server.getInputStream());
new PrintWriter(server.getOutputStream(), true).println("response text");
}
```
## processXML
```
public ProcessXML(InputStream is)
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(false);
Document doc = factory.newDocumentBuilder().parse(new InputSource(is));
....
}
```
# error
```
[Fatal Error] :2:1: Premature end of file.
org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at ProcessXML.<init>(ProcessXML.java:22)
at Bank.processRequest(Bank.java:41)
at Bank.listen(Bank.java:25)
at BankStart.main(BankStart.java:6)
```
---
Now I could store content of `server.GetInputStream()` into a file and then supply that to `DocumentBuilder`, but I think its a bad solution. How could I store content to some temporary storage and also be able to supply that to `.parse()` without closing the socket? | I think the solution you are using expects the data to be avaible at construct time. You would need to use a stream parser. find a STAX implementation and you should be able to do this | Doesn't seem like a socket thing... Otherwise you'd see a socket closed exception or something like that. As a test just read the bytes and save it to a text file somewhere, don't worry about building the doc just yet. Check that the file is a properly formed XML and that the encoding matches that specified in the document. Look for any funny characters at the end of the file, could be that the client is inserting some weird EOF character or similar. | Java - DocumentBuilder closing Socket connection | [
"",
"java",
"sockets",
"connection",
""
] |
> **Possible Duplicate:**
> [Why is there not a ForEach extension method on the IEnumerable interface?](https://stackoverflow.com/questions/101265/why-is-there-not-a-foreach-extension-method-on-the-ienumerable-interface)
I've noticed when writing LINQ-y code that `.ForEach()` is a nice idiom to use. For example, here is a piece of code that takes the following inputs, and produces these outputs:
```
{ "One" } => "One"
{ "One", "Two" } => "One, Two"
{ "One", "Two", "Three", "Four" } => "One, Two, Three and Four";
```
And the code:
```
private string InsertCommasAttempt(IEnumerable<string> words)
{
List<string> wordList = words.ToList();
StringBuilder sb = new StringBuilder();
var wordsAndSeparators = wordList.Select((string word, int pos) =>
{
if (pos == 0) return new { Word = word, Leading = string.Empty };
if (pos == wordList.Count - 1) return new { Word = word, Leading = " and " };
return new { Word = word, Leading = ", " };
});
wordsAndSeparators.ToList().ForEach(v => sb.Append(v.Leading).Append(v.Word));
return sb.ToString();
}
```
Note the interjected `.ToList()` before the `.ForEach()` on the second to last line.
Why is it that `.ForEach()` isn't available as an extension method on `IEnumerable<T>`? With an example like this, it just seems weird. | Because [`ForEach(Action)`](http://msdn.microsoft.com/en-us/library/bwabdf9z(VS.80).aspx) existed before `IEnumerable<T>` existed.
Since it was not added with the other extension methods, one can assume that the C# designers felt it was a bad design and prefer the `foreach` construct.
---
### Edit:
If you want you can create your own extension method, it won't override the one for a `List<T>` but it will work for any other class which implements `IEnumerable<T>`.
```
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (T item in source)
action(item);
}
}
``` | According to Eric Lippert, this is [mostly for philosophical reasons](https://ericlippert.com/2009/05/18/foreach-vs-foreach/). You should read the whole post, but here's the gist as far as I'm concerned:
> I am philosophically opposed to
> providing such a method, for two
> reasons.
>
> The first reason is that doing so
> violates the functional programming
> principles that all the other sequence
> operators are based upon. Clearly the
> sole purpose of a call to this method
> is to cause side effects.
>
> The purpose of an expression is to
> compute a value, not to cause a side
> effect. The purpose of a statement is
> to cause a side effect. The call site
> of this thing would look an awful lot
> like an expression (though,
> admittedly, since the method is
> void-returning, the expression could
> only be used in a “statement
> expression” context.)
>
> It does not sit well with me to make
> the one and only sequence operator
> that is only useful for its side
> effects.
>
> The second reason is that doing so
> adds zero new representational power
> to the language. | Why is .ForEach() on IList<T> and not on IEnumerable<T>? | [
"",
"c#",
"list",
"linq",
"c#-3.0",
"ienumerable",
""
] |
I am trying to reuse Apple's Speak Here [sample code](http://developer.apple.com/iphone/library/samplecode/SpeakHere/index.html#//apple_ref/doc/uid/DTS40007802) in my own iPhone app. I downloaded and compiled the project with no problems, so I then added some of the files to my own application. When I try to compile my own application, the compiler gives me
MeterTable.h:54: error: syntax error before 'MeterTable'
The relevant code is:
```
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
class MeterTable // line 54
{
public:
```
It looks kind of like xcode isn't recognizing MeterTable.h and MeterTable.mm as C++ files. I've checked File>>GetInfo for MeterTable.mm, though, and it lists filetype as sourcecode.cpp.cpp.
Why won't this compile? | 1. You're including "MeterTable.h" in a non C++ file other than MasterTable.mm.
2. The error is not in 'MeterTable.h' but in the header included before it. Note that `<stdlib.h>`... can be a noop if they are included before.
If you want to make sure your file is compiled with C++, you can add this code to the begining of MasterTable.mm:
```
#ifdef __cplusplus
#error "compiled as C++"
#else
#error "compiled as C"
#endif
``` | DO the following things and then try:
1. Go to the Build Setting and search "Compile Sources As"
2. Select "According to file type"
3. If you are including CPP file in any of your Objective C class then its implementation class should be .mm, just change its extension to .mm from.m.
4. Remember, even if you are using CPP code hierarchically, you need to change the extension to .mm. | xcode gives syntax error on cpp code | [
"",
"c++",
"iphone",
"xcode",
""
] |
How can I check for nulls in a deep lamda expression?
Say for example I have a class structure that was nested several layers deep, and I wanted to execute the following lambda:
```
x => x.Two.Three.Four.Foo
```
I want it to return null if Two, Three, or Four were null, rather than throwing a System.NullReferenceException.
```
public class Tests
{
// This test will succeed
[Fact]
public void ReturnsValueWhenClass2NotNull()
{
var one = new One();
one.Two = new Two();
one.Two.Three = new Three();
one.Two.Three.Four = new Four();
one.Two.Three.Four.Foo = "blah";
var result = GetValue(one, x => x.Two.Three.Four.Foo);
Assert.Equal("blah", result);
}
// This test will fail
[Fact]
public void ReturnsNullWhenClass2IsNull()
{
var one = new One();
var result = GetValue(one, x => x.Two.Three.Four.Foo);
Assert.Equal(null, result);
}
private TResult GetValue<TModel, TResult>(TModel model, Expression<Func<TModel, TResult>> expression)
{
var func = expression.Compile();
var value = func(model);
return value;
}
public class One
{
public Two Two { get; set; }
}
public class Two
{
public Three Three { get; set; }
}
public class Three
{
public Four Four { get; set; }
}
public class Four
{
public string Foo { get; set; }
public string Bar { get; set; }
}
}
```
UPDATE:
One solution would be to catch the NullReferenceException like this:
```
private TResult GetValue<TModel, TResult>(TModel model, Expression<Func<TModel, TResult>> expression)
{
TResult value;
try
{
var func = expression.Compile();
value = func(model);
}
catch (NullReferenceException)
{
value = default(TResult);
}
return value;
}
```
But I hate to incur the expense of catching an exception that is not, in my mind, exceptional. I expect this to be the case quite often in my domain.
UPDATE 2:
Another solution would be modify the property getters like this:
```
public class One
{
private Two two;
public Two Two
{
get
{
return two ?? new Two();
}
set
{
two = value;
}
}
}
```
Which is mostly ok for my domain, but there are times when I really to expect a property to return null. I checked the answer from Josh E as helpful since it comes pretty close to what I need in some cases. | You can't do that in a concise way. You can either make the lambda multiple lines, or use nested ternary operators:
```
var result = GetValue(one, x => x.Two == null ? null :
x.Two.Three == null ? null :
x.Two.Three.Four == null ? null :
x.Two.Three.Four.Foo;
```
Ugly, I know. | You could do this with a generic helper extension method, something like:
```
public static class Get {
public static T IfNotNull<T, U>(this U item, Func<U, T> lambda) where U: class {
if (item == null) {
return default(T);
}
return lambda(item);
}
}
var one = new One();
string fooIfNotNull = one.IfNotNull(x => x.Two).IfNotNull(x => x.Three).IfNotNull(x => x.Four).IfNotNull(x => x.Foo);
``` | How to check for nulls in a deep lambda expression? | [
"",
"c#",
"linq",
"lambda",
""
] |
I am trying to get the latest record inserted in a SQL table based on its CreatedDate. For instance, in the table below, I would like to get the third row.
```
A B C 2009-05-04 19:30:52.847
A B D 2009-05-04 19:30:55.050
A B E 2009-05-04 19:30:57.003
```
I have a working query, but I am wondering if there is better way to achieve the same result. Below is the table, data and query I am using right now for my test. Is there any better way to do this?
```
CREATE TABLE TestTable (
ColumnA NVARCHAR(10),
ColumnB NVARCHAR(10),
ColumnC NVARCHAR(10),
CreatedDate DATETIME DEFAULT Getutcdate())
INSERT INTO TestTable(ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'C');
INSERT INTO TestTable(ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'D');
INSERT INTO TestTable(ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'E');
SELECT *
FROM TestTable
WHERE CreatedDate = (SELECT Max(CreatedDate)
FROM TestTable
WHERE ColumnA = 'A'
AND ColumnB = 'B'
GROUP BY ColumnA,
ColumnB)
```
Thanks! | you can also write
```
SELECT top 1 *
FROM TestTable
order by CreatedDate desc
``` | I like that outer join solution - it hadn't occured to me. But *Display Estimated Execution Plan* found it to be more expensive than the way I usually solve this problem. (Could be related to the indexes on my table - your mileage may vary) Give this one a try:
```
SELECT
T1.ColumnA,
T1.ColumnB,
T1.ColumnC,
T1.CreatedDate
FROM
dbo.TestTable T1
JOIN (SELECT ColumnA,
ColumnB,
max(CreatedDate) MaxDate
FROM
dbo.TestTable
GROUP BY ColumnA,
ColumnB) T2
ON T1.ColumnA = T2.ColumnA
AND T1.ColumnB = T2.ColumnB
AND T1.CreatedDate = T2.MaxDate
``` | Get the latest row inserted with the help of CreatedDate field | [
"",
"sql",
"sql-server-2005",
""
] |
Till this moment I used this method to invoke:
```
public string AddText
{
set
{
if (listView1.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
Textbox.text += value + "\n";
});
}
else
{
Textbox.text += value + "\n";
}
}
}
```
And here is the problem:
```
var form = Form.ActiveForm as Form1;
if (form != null)
form.AddText = "Test";
```
I'm writing an analyzer which analyze packets. I can't put the form on focus all the time, because I have to do actions on the application. I'm writing this analyzer in order to get a packet so I can analyze it.
If I touch the application I want to analyze Form.ActiveForm returns null.
Is there a way I can invoke and set the textbox to add text even if the form is not on Top of everything? | I think the root of the problem is the tight coupling between your packet analyzer and the main form. A packet analyzer should not have to know anything about the active form, or even that there is any form at all. It makes things hard to maintain because it only works under a very specific circumstance that's already untrue some of the time.
You could turn the problem around, and raise an event from the class that is analyzing the packets. That gives you much better encapsulation because now the packet analyzer needs to know nothing about the rest of the application. You can either create your own event args or reuse one like System.Diagnostics.DataReceivedEventArgs for example. Then your form can sink the DataReceived event and call its own AddText to invoke back to the main thread, and it will work whether the form is visible or not.
At least that will work but it is a blocking call so the packet analyzer thread will be stopped until the form fully handles the event and the marshalled call back to the main thread has returned. That would be okay if the paket rate isn't very high but usually you wouldn't want to stop a communication thread to wait for the main thread to update a textbox. Another approach would be to log the text using a StringBuilder inside the packet analyzer, and expose it (the accumulated text, not the StringBuilder) via a thread-safe public property. Or if you need to separate the invidual messages then you could add them to a List for example, and have the thread-safe property return an array of accumulated messages. Then your form could poll the analyzer for new logged data using a Timer at whatever rate is appropriate for your application, and only while the form is visible. It would not update quite as fast but the impact on the analyzer thread would be almost nil and it should run faster overall if it consolidates many messages inside the StringBuilder or List in between updates rather than concatenating on to the Text property with every single packet. | If the problem that you can't Invoke then your answer would be to use **SynchronizationContext** it's always available on the Application.Run thread. So do the following:
In Form OnLoad save SynchronizationContext.Current to static field anywhere.
After that you can easily use Post or Send methods for sync or async invokes in GUI Thread.
Description here: <http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx>
Nice article here: <http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx> | How to Invoke if the form is not active? | [
"",
"c#",
"winforms",
""
] |
Say I have some C++ project which builds an exe or dll file. The project is checked into a SVN repository. I want to automatically synchronize the revision from SVN with the version resource embedded in my exe/dll file, i.e. the version should be something like **$major.$minor.$svn\_revision**.
Any ideas on how to achieve this? Are there any out-of-the-box solutions available? | If you have TortoiseSVN installed, then there is a program installed with it, `SubWCRev`.
If, in your file, you have this value:
```
$WCREV$
```
Then it'll be replaced with the highest committed revision number if you execute something like this:
```
SubWCRev .\ yourfile.txt.template yourfile.txt
```
This will copy from `yourfile.txt.template`, do the substitutions, and write to `yourfile.txt`.
Note that there's a lot of other macros you can use as well, if you execute `SubWCRev` without any arguments, it'll list them all on the console. | The answer by Program.X works great. I'd like to add, though, that if you build your executable before committing your changes, the revision will be one less than the actual revision number of the running code. To mitigate this, you can set the versions to
```
"2.0.$WCREV$.$WCMODS?1:0$"
```
That will put a 1 on the end if there are any local modifications, and 0 if not. So if you look at your executable later and see 2.0.54.1, you know it's probably actually revision 55. | How to synchronize SVN revision and version ressources of EXE/DLL files? | [
"",
"c++",
"svn",
"resources",
"build-automation",
""
] |
This is probably a simple question, but I really don't know what I'm doing in Excel, so hopefully someone can help me out.
I've been given an Excel spreadsheet that has two relevant columns to my task. The first column is an "External ID", and the second column is an "Internal ID". I need to select a bunch of data out of our databases (with various joins) using the Internal ID as the key, but then all of this data needs to be linked back to the External ID, and the only link between Internal/External is this spreadsheet.
For example, say a row of the spreadsheet looks like this:
```
ExtID IntID
AB1234 2
```
I need to select all the data relevant to the item with ID #2 in our database, but I have no way to get "AB1234" from the database, so I need to somehow relate this data back to "AB1234" using the spreadsheet.
What's the easiest way to accomplish this? The version of Excel is Excel 2007, and the database is Oracle, if that's relevant.
Note that I only have read permission to the production databases, so creating tables and importing the spreadsheet data to do a join is not an option. | **Edited based on a comment**
**1 -** Use MS Access to import the Excel sheet as a table.
**2 -** Link to your database table, also from within MS Access
*External Data tab->other data sources->ODBC connection->choose yours->pick the table(s) you want*
**3 -** Write an Access query to compare the values you want
*Create->Query Design->Drop the tables you want, drag lines between them for relationships, click Run* | Usually I use copy-paste and a good column-mode editor with macros to accomplish such tasks. It works fine if you only have a couple of Excel files. | Combining data from Excel with database | [
"",
"sql",
"excel",
"excel-2007",
""
] |
I'm relatively new to C++ and am having a hard trouble understanding the instantiation of object and pointers to objects.
Whats the difference between these two declaration in terms of memory and usage? :
```
MyClass obj1;
MyClass *obj2;
```
And also the specific problem I am having is that I have a class which has an unsigned short array where the last space of the array changes if I do this:
```
MyClass obj;
obj = MyClass("123");
```
MyClass has two constructors one which will take an int and as default will assign it to zero and splice it in parts of 3 digits or less. And another which will take a string representation of a number and do the same... hope that makes sense!
It works well if I declare it
```
MyClass obj = MyClass("123123123");
```
but not if I do it the other way. Why? | The difference:
```
MyClass obj1;
MyClass *obj2;
```
Here obj1 is an instance of MyClass.
While obj2 can potentially hold the address of an instance of MyClass.
Also obj1 will automatically be initialized by the constructors, while obj2 is not initialized by default (and thus points to random memory). Once initialized obj2 may take the special value NULL which indicates that it is not pointing at an object.
```
obj2 = &obj1;
```
Here we initialize obj2 to point at the address in memory of obj1. If you change any of the members of obj1 then you can see the changes by looking at them through obj2 (but because obj2 is a pointer you need to de-reference).
```
obj1.plop = 5;
std::cout << obj1.plop << "\n";
std::cout << obj2->plop << "\n"; Should print the same values.
```
The following is actually two different things:
```
MyClass obj;
obj = MyClass("123");
```
* Line one initializes 'obj' with the default constructor.
* Line two: creates a temporary object constructed with the string "123". Once this temporary object is created it is copied onto 'obj' using the assignment operator. If you did not define an assignment operator the compiler will have generated one for you. If your class contains pointers then the default version will probably not work correctly (in most other situations the default assignment operator should work fine).
This line probably works:
```
MyClass obj = MyClass("123123123");
```
Because the compiler has optimised this into:
```
MyClass obj("123123123");
``` | When you say `MyClass obj1;` you create the object. `MyClass * obj2;` just saves space for the *address* of the object.
So `MyClass obj1;` does the following:
* it sets up the name in the compiler symbol table
* it allocates `sizeof(MyClass)` bytes of space — could be as big as you want
* it runs the default ctor of MyClass, MyClass::MyClass() 9or a ctor that has all default arguments intead) putting the initialized object in the space it allocated
* it remembers where that object is, associating it with the name 'obj1' in the symbol table.
while `MyClass * obj2;` instead
* sets up the name `obj2` in the symbol table
* allocates space only for the *address* of a MyClass object, `sizeof(MyClass*)` — probably 4 or 8 bytes
* doesn't run any constructor.
When you say `MyClass obj; obj = MyClass("123123123")` you
* create and allocate a `MyClass` object for obj using the default ctor
* create and allocate *another* `MyClass` object
* assign that new `MyClass` object to replace the old one. | C++ Problem initializing an object twice | [
"",
"c++",
"arrays",
"pointers",
"object",
""
] |
So I've been looking at a [blog post](http://couldbedone.blogspot.com/2007/08/restoring-lost-focus-in-update-panel.html) with some javascript in it and there is something I'm looking at which I don't quite follow:
```
function pageLoadedHandler(sender, args) {
if (typeof(lastFocusedControlId) !== "undefined"
&& lastFocusedControlId != "")
{
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
```
In the above method it calls **$get** which i assume is an alias to
```
function(id) {
return document.getElementById(id);
}
```
There is nowhere in the supplied js file where $get is declared.
Is this a reserved alias and can someone provide the link which provies it. If not how does it know what $get is? | Yes I've found them:
Quoting Msdn
**Sys.UI.DomElement $get Method**
> Provides a shortcut to the getElementById method of the Sys.UI.DomElement class. This member is static and can be invoked without creating an instance of the class.
<http://www.asp.net/AJAX/Documentation/Live/ClientReference/Global/GetShortCutMethod.aspx>
<http://msdn.microsoft.com/en-us/library/bb397717.aspx>
Very difficult to search for $get | I believe you're looking at ASP.NET's AJAX shortcuts.
<http://mattberseth.com/blog/2007/08/the_everuseful_get_and_find_as.html> | How does this js know $get is function(id) { return document.getElementById(id); } | [
"",
"javascript",
""
] |
I have a search form used to query service provisions, which I will call 'provisions'. Provisions may have certain eligibility requirements in a has and belongs to many relationship, but they may also have no requirements at all. My issue is that when I exclude certain provisions on the basis of a particular requirement, those provisions that have no requirements at all are also excluded.
Table structure:
```
provisions
* id
* title
requirements
* id
* title
provisions_requirements
* provision_id
* requirement_id
```
Suppose a requirement is like:
```
Canadian Citizenship (id 4)
```
This would be presented on the form like: "Exclude services that have the requirement of: Canadian Citizenship".
The exclusionary portion of the query would thus be:
```
requirements.id NOT IN (4)
```
However, I then only get provisions that have at least one requirement, because those provisions that have no requirements are not included in the join.
The actual query is like:
```
SELECT DISTINCT `provisions`.id
FROM `provisions`
LEFT OUTER JOIN `provisions_requirements`
ON `provisions_requirements`.provision_id = `provisions`.id
LEFT OUTER JOIN `requirements`
ON `requirements`.id = `provisions_requirements`.requirement_id
WHERE (requirements.id NOT IN ('1'))
LIMIT 0, 10
``` | So you want all services *except* those that have the requirement of Canadian Citizenship (req\_id 4)?
Try this: it *tries* to match against the `requirement_id` of 4, but the condition in the `WHERE` clause makes it so only provisions that found no such match satisfy the condition.
```
SELECT p.id
FROM provisions p LEFT OUTER JOIN provisions_requirements r
ON (p.id = r.provision_id AND r.requirement_id IN (4))
WHERE r.requirement_id IS NULL
LIMIT 0, 10;
```
No `DISTINCT` is necessary. No join to the `requirements` table is necessary. | ```
SELECT
P.id
FROM
Provisions P
WHERE
NOT EXISTS
(
SELECT
*
FROM
Provision_Requirements PR
WHERE
PR.provision_id = P.id AND
PR.requirement_id = 4
)
``` | How can I write a query that excludes certain results, but includes results that lack the association used for exclusion? | [
"",
"sql",
"mysql",
""
] |
I'm just starting my first C++ project. I'm using [Visual Studio 2008](https://stackoverflow.com/questions/820213/new-to-c-should-i-use-visual-studio). It's a single-form Windows application that accesses a couple of databases and initiates a WebSphere MQ transaction. I basically understand the differences among ATL, MFC, Win32 (I'm a little hazy on that one actually) and CLR, but I'm at a loss as to how I should choose.
Is one or more of these just there for backward-compatibility?
Is CLR [a bad idea](https://stackoverflow.com/questions/819191/is-c-net-dying)?
Any suggestions appreciated.
**Edit:**
I've chosen C++ for this project for reasons I didn't go into in the post, which are not entirely technical. So, *assuming* C++ is the only/best option, which should I choose? | It depends on your needs.
Using the CLR will provide you with the most expressive set of libraries (the entire .NET framework), at the cost of restricting your executable to requiring the .NET framework to be installed at runtime, as well as limiting you to the Windows platform (however, all 4 listed technologies are windows only, so the platform limitation is probably the least troublesome).
However, CLR requires you to use the C++/CLI extensions to the C++ language, so you'll, in essense, need to learn some extra language features in order to use this. Doing so gives you many "extras," such as access to the .net libraries, full garbage collection, etc.
ATL & MFC are somewhat trickier to decide between. I'd refer you to [MSDN's page for choosing](http://msdn.microsoft.com/en-us/library/bk8ytxz5(VS.80).aspx) in order to decide between them. The nice thing about ATL/MFC is that you don't need the .NET framework, only the VC/MFC runtimes to be installed for deployment.
Using Win32 directly provides the smallest executables, with the fewest dependencies, but is more work to write. You have the least amount of helper libraries, so you're writing more of the code. | Win32 is the raw, bare-metal way of doing it. It's tedious, difficult to use, and has a lot of small details you need to remember otherwise things will fail in relatively mysterious ways.
MFC builds upon Win32 to provide you an object-oriented way of building your application. It's not a replacement for Win32, but rather an enhancement - it does a lot of the hard work for you.
System.Windows.Forms (which is what I assume you meant by CLR) is completely different but has large similarities to MFC from its basic structure. It's by far the easiest to use but requires the .NET framework, which may or may not be a hindrance in your case.
My recommendation: If you need to avoid .NET, then use MFC, otherwise use .NET (in fact, in that case, I'd use C# as it's much easier to work with). | How do I decide whether to use ATL, MFC, Win32 or CLR for a new C++ project? | [
"",
"c++",
"winapi",
"mfc",
"clr",
"atl",
""
] |
Its been a while I have ready Mcconnell's "[Code Complete](http://cc2e.com/)". Now I read it again in Hunt & Thomas' "[The Pragmatic Programmer](http://www.pragprog.com/titles/tpp/the-pragmatic-programmer)": Use assertions! *Note: Not Unit Testing assertions, I mean `Debug.Assert()`.*
Following the SO questions [When should I use Debug.Assert()?](https://stackoverflow.com/questions/129120/when-should-i-use-debug-assert) and [When to use assertion over exceptions in domain classes](https://stackoverflow.com/questions/414182/when-to-use-assertion-over-exceptions-in-domain-classes) assertions are useful for development, because "impossible" situations can be found quite fast. And it seems that they are commonly used. As far as I understood assertions, in C# they are often used for checking input variables for "impossible" values.
To keep unit tests concise and isolated as much as possible, I do feed classes and methods with `null`s and "impossible" dummy input (like an empty string).
Such tests are explicitly documenting, that they don't rely on some specific input. *Note: I am practicing what Meszaros' "xUnit Test Patterns" is describing as [Minimal Fixture](http://xunitpatterns.com/Minimal%20Fixture.html).*
And that's the point: If I would have an assertions guarding these inputs, they would blow up my unit tests.
I like the idea of Assertative Programming, but on the other hand I don't need to force it. Currently I can't think of any use for `Debug.Assert()`. Maybe there is something I miss? Do you have any suggestions, where they could be *really* useful? Maybe I just overestimate the usefulness of assertions? Or maybe my way of testing needs to be revisited?
Edit: [Best practice for debug Asserts during Unit testing](https://stackoverflow.com/questions/409955/best-practice-for-debug-asserts-during-unit-testing) is very similar, but it does not answer the question which bothers me: Should I care about `Debug.Assert()` in C# if I test like I have described? If yes, in which situation are they *really* useful? In my current point of view such Unit Tests would make `Debug.Assert()` unnecessary.
Another point: If you really think that, this is a duplicate question, just post some comment. | In theory, you're right - exhaustive testing makes asserts redundant. In theory. In parctice, they're still useful for debugging your tests, and for catching attempts by future developers who might try to use interfaces not according to their intended semantics.
In short, they just serve a different purpose from unit tests. They're there to catch mistakes that by their very nature aren't going to be made when writing unit tests.
I would recommend keeping them, since they offer another level of protection from programmer mistakes.
They're also a local error protection mechanism, whereas unit tests are external to the code being tested. It's far easier to "inadvertently" disable unit tests when under pressure than it is to disable all the assertions and runtime checks in a piece of code. | I generally see asserts being used for sanity checks on internal state rather than things like argument checking.
IMO the inputs to a solid API should be guarded by checks that remain in place regardless of the build type. For example, if a public method expects an argument that is a number in between 5 and 500, it should be guarded with an ArgumentOutOfRangeException. Fail fast and fail often using exceptions as far as I'm concerned, particularly when an argument is pushed somewhere and is used much later.
However, in places where internal, transient state is being sanity-checked (e.g. checking that some intermediate state is within reasonable bounds during a loop), it seems the Debug.Assert is more at home. What else are you meant to do when your algorithm has gone wrong despite having valid arguments passed to it? Throw an EpicFailException? :) I think this is where Debug.Assert is still useful.
I'm still undecided on the best balance between the two. I've stopped using using Debug.Asserts so much in C# since I started unit testing, but there's still a place for them IMO. I certainly wouldn't use them to check correctness in API use, but sanity checking in hard to get to places? Sure.
The only downside is that they can pop up and halt NUnit, but you can write an NUnit plugin to detect them and fail any test that triggers an assert. | Does Unit Testing make Debug.Assert() unnecessary? | [
"",
"c#",
"unit-testing",
""
] |
I basically have something like this:
```
void Foo(Type ty)
{
var result = serializer.Deserialize<ty>(inputContent);
}
Foo(typeof(Person));
```
The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this?
I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`.
EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface.
EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly:
```
[JsonFilter(Param="test", JsonDataType=typeof(Person))]
```
## Solution
Based on Marc and Anton's answers:
```
var result = typeof(JavaScriptSerializer).GetMethod("Deserialize")
.MakeGenericMethod(JsonDataType)
.Invoke(serializer, new object[] { inputContent });
``` | If `ty` is known at compile-time, why don't just
```
void Foo<T>()
{
var result = serializer.Deserialize<T>(inputContext);
}
```
Otherwise,
```
MethodInfo genericDeserializeMethod = serializer.GetType().GetMethod("Deserialize");
MethodInfo closedDeserializeMethod = genericDeserializeMethod.MakeGenericMethod(ty);
closedDeserializeMethod.Invoke(serializer, new object[] { inputContext });
``` | Which serializer is that? If you only know the `Type` at runtime (not compile time), and it doesn't have a non-generic API, then you might have to use `MakeGenericMethod`:
```
void Foo(Type ty)
{
object result = typeof(ContainingClass).GetMethod("Bar").
.MakeGenericMethod(ty).Invoke(null, new object[] {inputContent});
}
public static T Bar<T>(SomeType inputContent) {
return serializer.Deserialize<T>(inputContent);
}
``` | How to turn a Type instance into a generic type argument | [
"",
"c#",
"generics",
"types",
"generic-type-argument",
""
] |
This problem occurs when I try to hide a file in my directory with a tool named [File Lock](http://www.toplang.com/filelock.htm). This is not a regular hide as I can not see it in windows explorer.
Code:
```
string[] textFiles = Directory.GetFiles(@"c:\mydir")
//0 files returned
string[] textFiles = Directory.GetFiles(@"c:\mydir", "*.txt")
//1 file returned: "c:\mydir\."
File.Exists(textFiles[0])
//false
```
How can the second function return a "c:\mydir\." file? I can remove all files that do not exist to solve my problem but I wonder why I get a "." file in the first place. | I don't have experience with the File Lock tool, but I can assume that it hooks FindFirstFile WinAPI function to protect some file from listing (that function is used by .NET Directory.GetFiles() function). And this hook can be written a little... buggy :)
Could you please try to disable the tool and redo your test?
Most likely you'll solve the problem.
But If you get the same result, blame Directory.GetFiles(). | A little more investigation:
* `C:\Test\` is a normal directory
* `C:\Test\text.txt` is a normal text file.
* `C:\Text\text2.txt` is a text file hidden by File Lock
The following code...
```
using System;
using System.IO;
public static class GetFilesTest {
public static void Main() {
int counter = 0;
DirectoryInfo dir = new DirectoryInfo(@"C:\Test");
foreach (FileSystemInfo fsi in dir.GetFileSystemInfos("*.txt")) {
Console.WriteLine("########### FileSystemInfo {0} ###########", ++counter);
Console.WriteLine("fsi: {0}", fsi);
Console.WriteLine("Exists: {0}", fsi.Exists);
Console.WriteLine("FullName: {0}", fsi.FullName);
Console.WriteLine("Name: {0}", fsi.Name);
Console.WriteLine("Extension: {0}", fsi.Extension);
Console.WriteLine("Attributes: {0}", fsi.Attributes);
}
counter = 0;
string[] files = {@"C:\Test\test.txt", @"C:\Test\test2.txt"};
foreach(string file in files) {
FileSystemInfo fi = new FileInfo(file);
Console.WriteLine("########### FileInfo {0} ###########", ++counter);
Console.WriteLine("fi: {0}", fi);
Console.WriteLine("Exists: {0}", fi.Exists);
Console.WriteLine("FullName: {0}", fi.FullName);
Console.WriteLine("Name: {0}", fi.Name);
Console.WriteLine("Extension: {0}", fi.Extension);
Console.WriteLine("Attributes: {0}", fi.Attributes);
Console.WriteLine("Contents: {0}", File.ReadAllText(fi.FullName));
}
}
}
```
... outputs:
```
########### FileSystemInfo 1 ###########
fsi: test.txt
Exists: True
FullName: C:\Test\test.txt
Name: test.txt
Extension: .txt
Attributes: Archive
########### FileSystemInfo 2 ###########
fsi: .
Exists: False
FullName: C:\Test\.
Name: .
Extension: .
Attributes: Directory
########### FileInfo 1 ###########
fi: C:\Test\test.txt
Exists: True
FullName: C:\Test\test.txt
Name: test.txt
Extension: .txt
Attributes: Archive
Contents: test
########### FileInfo 2 ###########
fi: C:\Test\test2.txt
Exists: True
FullName: C:\Test\test2.txt
Name: test2.txt
Extension: .txt
Attributes: Archive
Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'C:\Test\test2.txt' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path, Encoding encoding)
at System.IO.File.ReadAllText(String path, Encoding encoding)
at System.IO.File.ReadAllText(String path)
at GetFilesTest.Main() in c:\Users\Yvonne\Temp\GetFilesTest.cs:line 29
``` | Directory.GetFiles() gives weird return values | [
"",
"c#",
".net",
"file",
"io",
"locking",
""
] |
We're looking for someone to help us enhance & maintain our high-quality, php-based prototype of a transactional web app. Ideally, who can communicate well, and do both front- and back-end web development (as well as smart/gets things done, etc.). Among other more general things, I've been using this question:
> Given this:
>
> ```
> $foo = array(1, 3, 7);
> ```
>
> write a function (on this whiteboard) to sum the values of the array.
It seems trivially easy to me, but has caused a couple of deer-in-the-headlights situations, which always makes me feel like a villain.
I've read a number of posts here and there (including both Joel's and Jeff's) saying that how candidates think, design skills, passion, etc. are more important than any specific technical skill, and I agree with that. Also, I can see that programming at a whiteboard is a little unrealistic. OTOH, this seems so basic to me that I'm inclined to see it as a fine first-pass filter between front-end devs (who know their way around html, css, and how to copy-and-paste a js function or two), and people who can really code. Thoughts?
A touch more info: I'm open to all sorts of answers: array\_sum, a for loop, a foreach loop. Heck, if they want to write an ArraySum class, that would be overkill, but just fine. Using javascript, or another language would be fine, if they're more comfortable with that. Even attempts with minor errors would be ok, but I've had a couple of complete freezes, so I just wanted to sanity check myself. | in my opinion, the question is perfectly valid, and tells a bit (not a lot, but an important bit) about the candidate, depending on how much time you invest in it. just tell her that it's not a trick question beforehand, that it's really, really as simple as it appears, so she doesn't spend to much time thinking about the pitfalls and to minimize the deer-situation. throw in you do that just as a measure to filter out the people who apply for a programming without actually knowing anything about it but hoping they get hired anyway by pure luck (if they know how to code but are just nervous, that should take a bit of pressure away). let them code, but don't focus if there is a $ missing or if the `<?php` tags are present or not.
if she provides `array_sum` or `sum_array` as an answer almost doesn't matter, especially if the language in question is php (but if two candidates are equal otherwise ... *i can't even remember the last time i had to use this function*). and the use of an auto-completion and syntax-coloring (with predefined keywords) IDE vs. a dumb text editor matters a lot in this hindsight. in this case ask for an alternate, handcrafted solution.
if i was in the position of asking that question i wouldn't ask for *the right solution*, i'd ask for ways that come to her mind how this problem could be solved, what pitfalls could arise in special cases. try to find out what she knows about *programming*, not what she knows about php. try to find out about intelligence, problem solving and creativity. altought experience matters a lot even when it comes to bang out code fast, it's not a constant.
the solutions i'd provide, the pros/cons and what it tells about me ...
* **built-in `array_sum`** (very fast and definitley not buggy, but inflexible): *i have a bit of experience with traditional php projects*
* **for/loop constructs** (good enough, reinventing the wheel. but can be used if there are different objects than numbers. pros: everybody will understand it): *i can solve simple problems if there are no predefined copy&pasteable solutions*
* **`array_reduce`** (with an offering to implementat `array_reduce`, if the interviewer wants to see it): *unusual for a php programmer, so it seems i have knowledge and experience outside of the php sandbox*
* an **ArraySum-Object** (with an `ArraySum::add($value)` method that keeps all values stored but caches the sum): *i'm used to at least some of the oop-principles*
* **function () { return 11; }** (with the disclaimer that this is a joke solution, but valid): *i have (albeit crude) programmer-specific humour - a sign i'm personally interested in programming outside of work* ... some interviewers who are programmers (but not hackers) might interpret this as a willingness to use dirty hacks as placeholders *(aehm)* if time constraints are too tight
* **a recursive solution** would be nice. **i can probably solve a bit more complex, algorithily problems too and most likley know my way around simple trees and data structures**
* **recursive divide and conquer**: bonus! **i know even more about algorithms.**
try to get as much as possible out of this question (if time permits). in the end you'll know a little bit about programming capability and a lot about experience (altought not necessarily PHP specific).
i'd choose this question over letting the candidate write out quicksort - a very specific question about knowledge almost never needed in the web dev world - any time.
### disclaimer
the question is useless when ...
* the interviewer is not a programmer. forget it if a hr-guy is doing it
* there's a very tight time constraint when interviewing. then the result is almost random anyway.
additionally, who are you looking for? if you need a cheap grunt coder, even a simple question like this should work. if you need quality and experience, don't waste too much time on it (but do it anyway). | I would consider that much too easy of a question, personally. If someone asked me that question in an interview I'd probably be busy trying to figure out what the "trick" was, because it's so simple.
I think it's fine for weeding out the absolute worst programmers, but make sure that you don't have one particular "right" answer in mind and refuse to accept anything else. For example, don't only accept "use the array\_sum() function" as the correct answer, where it's really just a test to see if they know the function exists.
I mention this because my fiancee once had a programming interview where she was asked how she would reverse a string. She gave several different algorithms that would accomplish it, with the interviewer telling her that she was wrong after each one. She finally gave up, and he (disapprovingly) told her that she should have just used the String.Reverse() function.
Don't do that. Please. | Is this interview question too hard for a php dev. job? | [
"",
"php",
""
] |
Let's say I have a table:
```
SELECT SUM(quantity) AS items_sold_since_date,
product_ID
FROM Sales
WHERE order_date >= '01/01/09'
GROUP BY product_ID
```
This returns a list of products with the quantity sold since a particular date. Is there a way to select not only this sum, but ALSO the sum WITHOUT the where condition? I'd like to see sales since a particular date for each product alongside all (not date limited) sales. | ```
SELECT SUM(CASE WHEN order_date >= '01/01/09' THEN quantity ELSE 0 END) AS items_sold_since_date,
SUM(quantity) AS items_sold_total,
product_ID
FROM Sales
GROUP BY product_ID
``` | you can write
```
SELECT SUM(quantity) AS items_sold_since_date,(SELECT SUM(quantity) AS items_sold_since_date FROM Sales
GROUP BY product_ID) as items_sold,
product_ID
FROM Sales
WHERE order_date >= '01/01/09'
GROUP BY product_ID
``` | SQL Selecting multiple sums? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am trying to restrict the results returned from a query. If a user has access to more Entities than just those listed for the current user, then that user should not show up on the list. Using the data below, and assuming User 1 is running the query, since the user with UserId 2 has matches that User 1 does not have, even though they have overlapping values, user 2 should be excluded from the results of the query.
```
Table1
UserId EntityId
1 100
1 101
1 102
2 100
2 101
2 102
2 200
2 201
```
How do I do this? | You could do this with a series of nested queries:
```
select A.* from Table1 A where A.UserId NOT IN
(select B.UserId from Table1 B where B.EntityId NOT IN
(select C.EntityId from Table1 C where C.UserId=1));
```
The bottom, innermost query gives us the EntityIds belonging to UserId 1. We use that list in the next query up to find all the UserIds which have an EntityId *NOT* in this list. Armed with that list of UserIds we don't want, the outermost query dumps all the rows for the remaining UserIds. These will be ones which have a subset of UserId 1's set of EntityIds | It looks like you're trying to limit the users in SQL rather than in an application that interfaces with the database (e.g. webapp). If that is the case, you need to restrict access to the table using the built-in database permissions.
You could create a view that filters the results based on the User, deny the users the ability to edit the view, and deny the users access to the table. The only way to get results is to use the view, which will filter their results. | Restricting results from a SQL query | [
"",
"sql",
""
] |
Why do I receive a syntax error when printing a string in Python 3?
```
>>> print "hello World"
File "<stdin>", line 1
print "hello World"
^
SyntaxError: invalid syntax
``` | In Python 3, `print` [became a function](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function). This means that you need to include parenthesis now like mentioned below:
```
print("Hello World")
``` | It looks like you're using Python 3.0, in which [print has turned into a callable function](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function) rather than a statement.
```
print('Hello world!')
``` | Syntax error on print with Python 3 | [
"",
"python",
"python-3.x",
""
] |
We have an asp.net application that needs to be expanded to notify users when an update occurs. All users need to be notified even if they don't have the asp.net app opened. All notifications must occur at the same time for everyone, so email is not an option. The application will run on a corporate network with standardized client computers running Windows XP. Approximately 45 users/client computers need to receive these updates.
My initial thoughts are to create a windows service that runs on each client computer and polls a web service (say every minute) during business hours. When an update occurs it will set a notification time (say 5 minutes from the update). As the client computers poll the web service they will receive the update and use the notification time to schedule the notification on the client computer. The client computers will schedule the notification based on the time on the server not the time on the local computer. If this works properly all client computers will notify users at the exact same time.
Does this solution make sense? How would you do it differently?
**EDIT**: If a client is off or disconnected they will not receive the update and they do not need to receive the update in the future. These updates are only relevant for a short period of time. | Have you considered Full Duplex WCF? It could do what you need. | I'd say to use a "push" method, where each of the clients registers with the host (from a service), and when the host gets an update, it notifies all of the registered clients (services). But it sounds to me like there are some issues you need to consider as well; what if one (or more) of the clients are simply off at the time of the update? Do they get late notification, or none at all? What if the network is down for a set of users? Does that invalidate the update for all users? | How to design an app that requires synchronized notifications on all client computers | [
"",
"c#",
".net",
""
] |
I have an interface for a creaky property-map:
```
interface IPropertyMap
{
bool Exists(string key);
int GetInt(string key);
string GetString(string key);
//etc..
}
```
I want to create an extension method like so:
```
public static T GetOrDefault<T>(this IPropertyMap map, string key, T defaultValue)
{
if (!map.Exists(key))
return defaultValue;
else
{
if (typeof(T) == typeof(int)) return (T)map.GetInt(key);
//etc..
}
}
```
But the compiler won't let me cast to T. I tried adding `where T : struct` but that doesn't seem to help.
What am I missing? | I believe this is because the compiler doesn't know what type of operation it needs to perform. IIRC, you can get it to work if you introduce boxing:
```
if (typeof(T) == typeof(int)) return (T)(object)map.GetInt(key);
```
but that's not ideal in terms of performance.
I think it's just a limitation of generics, unfortunately. | I suppose it's just a typo, but `bool GetInt(string key)` seems weird. It should be `int GetInt(string key)`, or better yet `int GetInt32(string key)`.
Next, Jon has already noted that boxing is required for your code to work, so this is what you do.
And finally, add a "catch-all" method to your `IPropertyMap` interface -- say `object GetValue(string key)` and then rewrite `GetOrDefault<T>` to utilize this method instead of endless and error prone `Type` comparisons:
```
else
return (T)(object)map.GetValue(key);
``` | Casting value to T in a generic method | [
"",
"c#",
"generics",
""
] |
In C#, given the two methods
```
bool Action1(object Data);
bool Action2(object Data);
```
that are used in an `if` statement like this:
```
if ( Action1(Data) || (Action2(Data) )
{
PerformOtherAction();
}
```
will `Action2()` still be called if `Action1()` returned true, or is this prevented by compiler optimisation, since it is already known that the expression will evaluate to `true`? | Action2() will only be called if Action1() returns false
This is conceptually similar to
```
if (Action1(Data))
{
PerformOtherAction();
}
else if (Action2(Data))
{
PerformOtherAction();
}
``` | No, C# support logical short-circuiting so if `Action1` returned `true` it would never evaluate `Action2`.
This simple example shows how C# handles logical short-circuiting:
```
using System;
class Program
{
static void Main()
{
if (True() || False()) { } // outputs just "true"
if (False() || True()) { } // outputs "false" and "true"
if (False() && True()) { } // outputs just "false"
if (True() && False()) { } // outputs "true" and "false"
}
static bool True()
{
Console.WriteLine("true");
return true;
}
static bool False()
{
Console.WriteLine("false");
return false;
}
}
``` | Will all methods in a logical expressions be executed? | [
"",
"c#",
"optimization",
""
] |
I've got log4j configured on my Java project with the following log4j.properties:
```
log4j.rootLogger=WARNING, X
log4j.appender.X=org.apache.log4j.ConsoleAppender
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.ConversionPattern=%p %m %n
log4j.logger.org.hibernate.SQL=WARNING
log4j.logger.com.****.services.clarity.dao.impl=WARNING
log4j.logger.com.****.services.clarity.controller=WARNING
log4j.logger.com.****.services.clarity.services.impl=WARNING
log4j.logger.com.****.services.clarity.feeds.impl=WARNING
```
As configured, it should only print WARNING messages, however it prints all levels to DEBUG.
any ideas where this can come from ?
Thanks ! | The log level should be "WARN" and not "WARNING" | Isnt the severity level called "WARN"? | log4j prints all levels | [
"",
"java",
"log4j",
""
] |
I'm trying to pass story\_id into the innermost inline function, but its always 0 even though its not 0 in the outer function. How do I pass this value in?
```
function activateSearch(){
if($('story_filter')) Event.observe('story_filter', 'keyup',
function(event) {
$('stories_table').select(".story").each(
function(story) {
story_id = story.id.split('_')[1];
story.select('.tableCell', '.indexCardContent').each(
function(task, story_id) {
hideStoryRow(story_id);
task_filter = new RegExp($F('story_filter'), "i");
if (task.innerHTML.match( task_filter ))
{
showStoryRow(story_id);
throw $break;
}
}
);
}
);
}
);
}
``` | All you have to do to make this work is change this line:
```
function(task, story_id) {
```
to this:
```
function(task) {
```
You don't have to pass story\_id anywhere -- it's already in scope in the inner function! | You don't. The each method takes the function definition and then calls that function for each element in the Array. You'd need to write your own custom each method if you wanted to use the inline function definition.
For both readability and functionality, I would break out the inner most inline function and then for each element in the list, call out to your function. | How to pass a parameter to an inline javascript function | [
"",
"javascript",
"prototypejs",
""
] |
K so last year I made a family tree program in java as a group project and we used MVC but I really forget how it works, and the notes aren't online anymore.
To make things worse, since our project wasn't huge the prof said to combine the Model and Controller.
So now that I'm trying to make a sweet project to add to my employability portfolio I have no clue how MVC really works.
What would my relationships would have to look like between the model, view and controller in the following cases, I could probably figure out the rest from that
1. Model has a state called location and the view needs to know when this changes so it can update it's display
2. View has a button that the model needs to know when it is clicked
With those solved I can most likely do the rest myself.
Or if anyone knows of any good sites with information I'm not opposed to relearning this either. | > 1. Model has a state called location and the view needs to know
> when this changes so it can update
> it's display
Create a interface for the View called IMyScreen or something similar
Add a method UpdateLocation to the interface or something similar
Create a variable or property functions that are visible to the state of type IMyScreen AND to the view. Call it something like MyScreen
Have the View implement IMyScreen and put the code needed to update the View when the Location state changes in the UpdateLocation method.
In your initialization routine of the View have the View register itself as the current MyScreen.
Modify the code working with Location to fire MyScreen.UpdateLocation anytime it changes.
Ideally the View would create a Command object run it's execute method. THe execute method would pull in any parameters it needed, modify the locaction, and then call MyScreen.UpdateLocation. But you should focus on changing one thing at a time and save that for later.
> 2. View has a button that the model needs to know when it is clicked
This is a little vague. Generally buttons like this either do an action or indicate a status (check boxes, options, etc)
If it does an action then the ideal method is to create a ICommand Interface.
It has one method Execute.
Use the initialization routine to pass in any needed parameters.
Put the code that is needed to modify the model in the execute method.
When the button is click it would do something like
```
Sub MyButton_Click
ModifyCommand ThisCommand = New ModifyCommand(Parm1, Parm2, Parm3)
ModifyCommand.Execute
End Sub
```
If you need to query the status of the button then use the IMyScreen Interface and add a property called ButtonClicked.
When the button is clicked then set a flag that it has been clicked in the View
When the Model needs to know if the button has been clicked it called MyScreen.ButtonClicked. | Here is a CodeProject that may help: <http://www.codeproject.com/KB/cs/model_view_controller.aspx> | How would the mvc work in the following case -C# | [
"",
"c#",
"model-view-controller",
"design-patterns",
""
] |
I'm trying to brush up on my design pattern skills, and I'm curious what are the differences between these patterns? All of them seem like they are the same thing - encapsulate the database logic for a specific entity so the calling code has no knowledge of the underlying persistence layer. From my brief research all of them typically implement your standard CRUD methods and abstract away the database-specific details.
Apart from naming conventions (e.g. CustomerMapper vs. CustomerDAO vs. CustomerGateway vs. CustomerRepository), what is the difference, if any? If there is a difference, when would you chose one over the other?
In the past I would write code similar to the following (simplified, naturally - I wouldn't normally use public properties):
```
public class Customer
{
public long ID;
public string FirstName;
public string LastName;
public string CompanyName;
}
public interface ICustomerGateway
{
IList<Customer> GetAll();
Customer GetCustomerByID(long id);
bool AddNewCustomer(Customer customer);
bool UpdateCustomer(Customer customer);
bool DeleteCustomer(long id);
}
```
and have a `CustomerGateway` class that implements the specific database logic for all of the methods. Sometimes I would not use an interface and make all of the methods on the CustomerGateway static (I know, I know, that makes it less testable) so I can call it like:
```
Customer cust = CustomerGateway.GetCustomerByID(42);
```
This seems to be the same principle for the Data Mapper and Repository patterns; the DAO pattern (which is the same thing as Gateway, I think?) also seems to encourage database-specific gateways.
Am I missing something? It seems a little weird to have 3-4 different ways of doing the same exact thing. | Your example terms; DataMapper, DAO, DataTableGateway and Repository, all have a similar purpose (when I use one, I expect to get back a Customer object), but different intent/meaning and resulting implementation.
A **Repository** *"acts like a collection, except with more elaborate querying capability"* [[Evans, Domain Driven Design](https://web.archive.org/web/20210507021346/http://domaindrivendesign.org/books/evans_2003)] and may be considered as an *"objects in memory facade"* ([Repository discussion](https://web.archive.org/web/20210126033021/http://geekswithblogs.net/gyoung/archive/2006/05/03/77171.aspx))
A **DataMapper** *"moves data between objects and a database while keeping them independent of each other and the mapper itself"* ([Fowler, PoEAA, Mapper](https://martinfowler.com/eaaCatalog/dataMapper.html))
A **TableDataGateway** is *"a Gateway (object that encapsulates access to an external system or resource) to a database table. One instance handles all the rows in the table*" ([Fowler, PoEAA, TableDataGateway](https://martinfowler.com/eaaCatalog/tableDataGateway.html))
A **DAO** *"separates a data resource's client interface from its data access mechanisms / adapts a specific data resource's access API to a generic client interface"* allowing *"data access mechanisms to change independently of the code that uses the data"* ([Sun Blueprints](https://www.oracle.com/java/technologies/data-access-object.html))
Repository seems very generic, exposing no notion of database interaction.
A DAO provides an interface enabling different underlying database implementations to be used.
A TableDataGateway is specifically a thin wrapper around a single table.
A DataMapper acts as an intermediary enabling the Model object to evolve independently of the database representation (over time). | There is a tendency in software design world (at least, I feel so) to invent new names for well-known old things and patterns. And when we have a new paradigm (which perhaps slightly differs from already existing things), it usually comes with a whole set of new names for each tier. So "Business Logic" becomes "Services Layer" just because we say we do SOA, and DAO becomes Repository just because we say we do DDD (and each of those isn't actually something new and unique at all, but again: new names for already known concepts gathered in the same book). So I am not saying that all these modern paradigms and acronyms mean EXACTLY the same thing, but you really shouldn't be too paranoid about it. Mostly these are the same patterns, just from different families. | What is the difference between the Data Mapper, Table Data Gateway (Gateway), Data Access Object (DAO) and Repository patterns? | [
"",
"c#",
"repository",
"dao",
"datamapper",
"table-data-gateway",
""
] |
I'm trying to writing a generic method that will load a record of a specific type, with a specific ID. Here's one way that works:
```
public abstract class LinqedTable<T> where T : LinqableTable {
public static T Get(long ID) {
DataContext context = LinqUtils.GetDataContext<T>();
var q = from obj in context.GetTable<T>()
where obj.ID == ID
select obj;
return q.Single<T>();
}
}
public abstract class LinqableTable {
public abstract long ID { get; set; }
}
```
You can ignore the call to `LinqUtils.GetDataContext<T>()`; that's a utility function I've got to deal with the fact that I have multiple data contexts in my program. The point is that now I can declare any of my classes as subclasses of `LinqableTable`, and I can easily instantiate a record of that table just by calling `LinqedTable<MyType>.Get(ID)`.
This has some limitations, however. Firstly, it forces all of my tables to have an I
identity field of type `long`, named `ID`. Secondly, because I'm using an abstract method, I am forced to go to the O/R designer and change the inheritance property of every ID field in my system to "override".
I want more flexibility than that. So naturally, I tried reflection, and came out with the following:
```
public abstract class LinqedTable<T> where T : LinqableTable {
public static T Get(long ID) {
DataContext context = LinqUtils.GetDataContext<T>();
var q = from obj in context.GetTable<T>()
where obj.IDValue == ID
select obj;
return q.Single<T>();
}
}
public abstract class LinqableTable {
internal long IDValue {
get { return (long)IDProperty.GetValue(this, null); }
set { IDProperty.SetValue(this, value, null); }
}
internal PropertyInfo IDProperty {
get { return this.GetType().GetProperty(IDPropertyName); }
}
internal protected virtual string IDPropertyName {
get { return "ID"; }
}
}
```
Theoretically, this allows me to override the ID column name, the cast to `long` should be OK with any integral data type, and I don't need to go defining all my ID columns as `overrides`.
**BUT**
Linq doesn't like this. On the call to `q.Single<T>();` I get a runtime error:
`The member 'EISS.Utils.LinqableTable.IDValue' has no supported translation to SQL.`
OK, today I learned that Linq does some kind of magic on the back end; it doesn't instantiate `obj` and just read the `IDValue` property. So must be there's some attribute that needs to be set on the `IDValue` property that lets Linq do its thing.
But what? | Linq to SQL tries to translate your linq-query into SQL, but it does not know how to translate your property to a column name in the DB.
A good explanation can be found here on SO:
[simple linq to sql has no supported translation to SQL](https://stackoverflow.com/questions/332670/simple-linq-to-sql-has-no-supported-translation-to-sql)
But how to solve it, is another matter. I have with succes used the apporoach from this thread:
<http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/df9dba6e-4615-478d-9d8a-9fd80c941ea2/>
Or you can use dynamic query as mentioned here by scott guthrie:
<http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx> | Having read these posts: [Generic Data Access using LINQ to SQL and C#](http://www.c-sharpcorner.com/UploadFile/scottlysle/GenericL2SinCS07212008041344AM/GenericL2SinCS.aspx),
[LINQ-to-SQL: Generic Primary Key function](http://csainty.blogspot.com/2008/04/linq-to-sql-generic-primary-key.html) and
[Calling a generic method with Type](http://www.eggheadcafe.com/conversation.aspx?messageid=29446785&threadid=29446774)
My colleague and I came up with the following digest:
We added the following method to our datacontext (in a partial class).
```
public T GetInstanceByPrimaryKey<T>(object primaryKeyValue) where T : class
{
var table = this.GetTable<T>();
var mapping = this.Mapping.GetTable(typeof(T));
var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
if (pkfield == null)
throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));
var param = Expression.Parameter(typeof(T), "e");
var predicate =
Expression.Lambda<Func<T, bool>>(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(primaryKeyValue)), param);
return table.SingleOrDefault(predicate);
}
```
Then, where we need to instanciate from the type name and primary key value:
```
string name = "LinqObjectName";
int primaryKey = 123;
var dc = new YourDataContext();
Type dcType = dc.GetType();
Type type = dcType.Assembly.GetType(String.Format("{0}.{1}", dcType.Namespace, name));
MethodInfo methodInfoOfMethodToExcute = dc.GetType().GetMethod("GetInstanceByPrimaryKey");
MethodInfo methodInfoOfTypeToGet = methodInfoOfMethodToExcute.MakeGenericMethod(name);
var instance = methodInfoOfTypeToGet.Invoke(dc, new object[] { primaryKey });
return instance;
```
Hope this helps! | Using reflection to address a Linqed property | [
"",
"c#",
"linq",
"generics",
"reflection",
"or-designer",
""
] |
If you had to audit a Java application for worst-practices when it comes to high-availability and disaster recovery, you would probably look for hardcoded IP addresses and suboptimal caching of bind handles. What else should be considered? | Lack of action/state logging.
A Java application should be able to resume where it was when it crashed.
That means there should be a mechanism able to record what has already done (in order to not do everything all over again at the next run).
That also means such a Java program should always achieve the same state after the *same* set of actions. (Doing something twice would result in the same result, and the actions already done should not be done again, but simply skipped)
That record can take many form (file, database, metadata in a repository of sort, ...), but the point is: a Java application willing to recover as fast as possible should know what it has already done. | Lack of monitoring facilities. Sooner or later, all applications will fail. When that happens, you'll want to know about it before anyone else does. | High Availability and Disaster Recovery Software AntiPatterns | [
"",
"java",
"design-patterns",
"anti-patterns",
"high-availability",
"disaster-recovery",
""
] |
**Background:** I need to provide a weekly report package for my sales staff. This package contains several (5-10) crystal reports.
**Problem:**
I would like to allow a user to run all reports and also just run a single report. I was thinking I could do this by creating the reports and then doing:
```
List<ReportClass> reports = new List<ReportClass>();
reports.Add(new WeeklyReport1());
reports.Add(new WeeklyReport2());
reports.Add(new WeeklyReport3());
<snip>
foreach (ReportClass report in reports)
{
report.ExportToDisk(ExportFormatType.PortableDocFormat, @"c:\reports\" + report.ResourceName + ".pdf");
}
```
This would provide me a folder full of the reports, but I would like to email everyone a single PDF with all the weekly reports. So I need to combine them.
Is there an easy way to do this without install any more third party controls? I already have DevExpress & CrystalReports and I'd prefer not to add too many more.
Would it be best to combine them in the foreach loop or in a seperate loop? (or an alternate way) | I had to solve a similar problem and what I ended up doing was creating a small pdfmerge utility that uses the [**PDFSharp**](http://www.pdfsharp.net/) project which is essentially MIT licensed.
The code is dead simple, I needed a cmdline utility so I have more code dedicated to parsing the arguments than I do for the PDF merging:
```
using (PdfDocument one = PdfReader.Open("file1.pdf", PdfDocumentOpenMode.Import))
using (PdfDocument two = PdfReader.Open("file2.pdf", PdfDocumentOpenMode.Import))
using (PdfDocument outPdf = new PdfDocument())
{
CopyPages(one, outPdf);
CopyPages(two, outPdf);
outPdf.Save("file1and2.pdf");
}
void CopyPages(PdfDocument from, PdfDocument to)
{
for (int i = 0; i < from.PageCount; i++)
{
to.AddPage(from.Pages[i]);
}
}
``` | Here is a single function that will merge X amount of PDFs using PDFSharp
```
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
public static void MergePDFs(string targetPath, params string[] pdfs) {
using(var targetDoc = new PdfDocument()){
foreach (var pdf in pdfs) {
using (var pdfDoc = PdfReader.Open(pdf, PdfDocumentOpenMode.Import)) {
for (var i = 0; i < pdfDoc.PageCount; i++)
targetDoc.AddPage(pdfDoc.Pages[i]);
}
}
targetDoc.Save(targetPath);
}
}
``` | Combine two (or more) PDF's | [
"",
"c#",
".net",
"winforms",
"pdf",
""
] |
I'm using WatiN testing tool. Can I pass a key stroke (i.e., pressing a enter key) to the application using WatiN scripts?
This option was available in WatiR. Is this option available in WatiN? | **EDIT:** Upon further inspection, I found that the standard way of sending the ENTER key doesn't work in WatiN as it does in WatiR. You need to use [System.Windows.Forms.SendKeys](http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx)
Also, I recommend that you download the **[WatiN Test Recorder](http://watintestrecord.sourceforge.net/)**.
Here's the sample code.
```
using(IE ie = new IE("http://someurl"))
{
TextField myTxt = ie.TextField(Find.ById("myTextBox")).TypeText("some value");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
}
``` | There is a really good blog article about this at the
[Degree Dev Blog](http://blog.degree.no/2012/03/watinpressing-enter-key-in-a-textbox/)
It explains how you can add the Enter press as an extension method like this:
```
public static class MyWatiNExtensions
{
[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public static void TypeTextQuickly(this TextField textField, string text)
{
textField.SetAttributeValue("value", text);
}
public static void PressEnter(this TextField textField)
{
SetForegroundWindow(textField.DomContainer.hWnd);
SetFocus(textField.DomContainer.hWnd);
textField.Focus();
System.Windows.Forms.SendKeys.SendWait("{ENTER}");
Thread.Sleep(1000);
}
}
```
This makes it very easy to press the Enter key in a test.
```
browser.TextField("txtSearchLarge").PressEnter();
``` | Pass a key stroke (i.e., Enter Key) into application using WatiN scripts | [
"",
"c#",
"watin",
""
] |
How to create a installer using Java that combine tomcat, mysql and war file and come out a final exe? | You could use any installer, really. I personally have used [InnoSetup](http://www.innosetup.com/isinfo.php), which is quite simple, but can still perform almost any task at installation time.
In your case, you probably want to place the Tomcat files somewhere, webapp included. Customize some configuration files and run the MySQL installer in silent mode. All of which is perfectly possible with InnoSetup.
If you need more flexibility, you can look at [NSIS](http://nsis.sourceforge.net/Main_Page), another very simple but very powerful installer app. | The possible options have been largely covered in several questions already, especially:
* [What’s the best way to distribute Java applications?](https://stackoverflow.com/questions/80105/whats-the-best-way-to-distribute-java-applications)
* [What is the best installation tool for java?](https://stackoverflow.com/questions/173392/what-is-the-best-installation-tool-for-java)
* [What are good InstallAnywhere replacements for installing a Java EE application?](https://stackoverflow.com/questions/759855/what-are-good-installanywhere-replacements-for-installing-a-java-ee-application)
...and other questions [tagged java + installer](https://stackoverflow.com/questions/tagged/java+installer)
Although admittedly some options mentioned in those questions cannot produce self-sufficient .exe installers. If a commercial tool is ok for you, I can personally recommend [install4j](http://www.ej-technologies.com/products/install4j/overview.html) (costs $); among other things, it can create .exe installers ([details about my experiences with it](https://stackoverflow.com/questions/759855/what-are-good-installanywhere-replacements-for-installing-a-java-ee-application/786307#786307)). Or, for a simpler, free tool for producing Windows executables out of Java programs, see [Launch4j](http://launch4j.sourceforge.net/).
*Update* of my install4j recommendation, based on this comment by OP:
> Yes, the exe installer need to install the
> tomcat, mysql, web application, and db
> script all in once. At the end, users
> only need to start the tomcat and
> mysql service. Go to browser can
> access the web application.
With install4j,
* you can bundle Tomcat, MySQL and your webapp just fine
* you can automatically start the services too from the installer (or leave it to users as you suggest)
* if you want, the installer can even directly launch the browser and point it to your webapp :-)
I have just done a similar thing with install4j (bundle application server, webapp, run database scripts, and many other things; without bundling the database however), so I'm relatively sure it can be done. I do not know if you can do this (easily) with the free tools such as Launch4j. | How to create Java webapp installer (.exe) that includes Tomcat and MySQL?" | [
"",
"java",
"tomcat",
"installation",
"web-applications",
""
] |
I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.
The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread.
I could do it using one thread but the program halts.
I used to do it in C# using a BackgroundWorker which had an event for finishing.
Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit? | In the samples with [PyQt-Py2.6-gpl-4.4.4-2.exe](http://www.riverbankcomputing.co.uk/software/pyqt/download), there's the Mandelbrot app. In my install, the source is in C:\Python26\Lib\site-packages\PyQt4\examples\threads\mandelbrot.pyw. It uses a thread to render the pixmap and a signal (search the code for QtCore.SIGNAL) to tell the GUI thread its time to draw. Looks like what you want. | I had a similar issue with one of my projects, and used signals to tell my main GUI thread when to display results from the worker and update a progress bar.
Note that there are several examples to connect objects and signals in the [PyQt reference guide](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#signal-and-slot-support). Not all of which apply to python (took me a while to realize this).
Here are the examples you want to look at for connecting a python signal to a python function.
```
QtCore.QObject.connect(a, QtCore.SIGNAL("PySig"), pyFunction)
a.emit(QtCore.SIGNAL("pySig"), "Hello", "World")
```
Also, don't forget to add `__pyqtSignals__ = ( "PySig", )` to your worker class.
Here's a stripped down version of what I did:
```
class MyGui(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.worker = None
def makeWorker(self):
#create new thread
self.worker = Worker(work_to_do)
#connect thread to GUI function
QtCore.QObject.connect(self.worker, QtCore.SIGNAL('progressUpdated'), self.updateWorkerProgress)
QtCore.QObject.connect(self.worker, QtCore.SIGNAL('resultsReady'), self.updateResults)
#start thread
self.worker.start()
def updateResults(self):
results = self.worker.results
#display results in the GUI
def updateWorkerProgress(self, msg)
progress = self.worker.progress
#update progress bar and display msg in status bar
class Worker(QtCore.QThread):
__pyqtSignals__ = ( "resultsReady",
"progressUpdated" )
def __init__(self, work_queue):
self.progress = 0
self.results = []
self.work_queue = work_queue
QtCore.QThread.__init__(self, None)
def run(self):
#do whatever work
num_work_items = len(self.work_queue)
for i, work_item in enumerate(self.work_queue):
new_progress = int((float(i)/num_work_items)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.progress = new_progress
self.emit(QtCore.SIGNAL("progressUpdated"), 'Working...')
#process work item and update results
result = processWorkItem(work_item)
self.results.append(result)
self.emit(QtCore.SIGNAL("resultsReady"))
``` | Thread Finished Event in Python | [
"",
"python",
"delegates",
"multithreading",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.