Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Just a quick database design question: Do you ALWAYS use an ID field in EVERY table, or just most of them? Clearly most of your tables will benefit, but are there ever tables that you might not want to use an ID field?
For example, I want to add the ability to add tags to objects in another table (foo). So I've got a table FooTag with a varchar field to hold the tag, and a fooID field to refer to the row in foo. Do I really need to create a clustered index around an essentially arbitrary ID field? Wouldn't it be more efficient to use fooID and my text field as the clustered index, since I will almost always be searching by fooID anyway? Plus using my text in the clustered index would keep the data sorted, making sorting easier when I have to query my data. The downside is that inserts would take longer, but wouldn't that be offset by the gains during selection, which would happen far more often?
What are your thoughts on ID fields? Bendable rule, or unbreakable law?
edit: I am aware that the example provided is not normalized. If tagging is to be a major part of the project, with multiple tables being tagged, and other 'extras', a two-table solution would be a clear answer. However in this simplest case, would normalization be worthwhile? It would save some space, but require an extra join when running queries | As in much of programming: **rule, not law**.
Proof by exception: Some two-column tables exist only to form relationships between other more meaningful tables. | If you are making tables that bridge between two or more other tables and the only fields you need are the dual PK/FK's, then I don't know why you would need ID column in there as well.
ID columns generally can be very helpful, but that doesn't mean you should go peppering them in at every occasion. | ID fields in SQL tables: rule or law? | [
"",
"sql",
""
] |
As a fairly junior developer, I'm running into a problem that highlights my lack of experience and the holes in my knowledge. Please excuse me if the preamble here is too long.
I find myself on a project that involves my needing to learn a number of new (to me) technologies, including LINQ (to OBJECTS and to XML for purposes of this project) among others. Everything I've read to this point suggests that to utilize LINQ I'll need to fully understand the following (Delegates, Anonymous Methods and Lambda Expressions).
OK, so now comes the fun. I've CONSUMED delegates in the past as I have worked with the .NET event model, but the majority of the details have been hidden from me (thanks Microsoft!). I understand that on a basic level, delegate instances are pointers to methods (a gross over-simplification, I know).
I understand that an anonymous method is essentially an in-line unnamed method generally (if not exclusively) created as a target for a delegate.
I also understand that lambdas are used in varying ways to simplfy syntax and can be used to point a simple anonymous method to a delegate.
Pardon me if my any of my descriptions are WAY off here, this is the basic level to which I understand these topics.
So, the challenge:
1. Can anyone tell me if at least on a basic level if my understanding of these items is even close? I'm not looking for complex esoteric minutiae, just the basics (for now).
2. To what degree do I need to truly understand these concepts before applying LINQ in a project to reasonable effect? I want to understand it fully and am willing to spend the time. I simply may not HAVE the time to fully grok all of this stuff before I need to produce some work.
3. Can anyone point me to some good articles that explain these subjects and apply them to "real world" examples so that I can get my head around the basics of the topics and application of them? What I mean by real world, is how might I use this in the context of "Customers and Invoices" rather than abstract "Vectors and Shapes" or "Animals and Cows". The scenario can be somewhat contrived for demonstration purposes, but hopefully not strictly academic. I have found a number of examples on-line and in books, but few seem to be "Plain English" explanations.
Thank you all in advance for your patience, time and expertise. | 1) Those descriptions sound pretty accurate to me. Sometimes anonymous methods and lambda expressions will need to create a new type to put the target of the delegate in, so they can act as [closures](http://csharpindepth.com/Articles/Chapter5/Closures.aspx).
2/3) I would read up a bit until you're happy with delegates, anonymous methods and lambda expressions. I dedicate a chapter to the delegate-related changes in each of C# 2.0 and C# 3.0 in C# in Depth, although of course other books go into detail too. I have an [article](http://pobox.com/~skeet/csharp/events.html) as well, if that helps.
As for examples - delegates are used for many different purposes. They're all different ways of looking at the same functionality, but they can *feel* very different:
* Providing the code to call when you start a new thread
* Reacting to UI events
* Providing the filter, selection, ordering etc for a LINQ query
* Providing a callback for when an asynchronous operation has finished
If you have any specific situations you'd like an example of, that would be easier to answer.
EDIT: I should point out that it's good news that you're only working with LINQ to Objects and LINQ to XML at the moment, as that means you don't need to understand expression trees yet. (They're cool, but one step at a time...) LINQ to XML is really just an XML API which works nicely with LINQ - from what I remember, the only times you'll use delegates with LINQ to XML are when you're actually calling into LINQ to Objects. (That's very nice to do, admittedly - but it means you can reuse what you've already learned.)
As you've already got C# in Depth, chapters 10 and 11 provide quite a few examples of *using* lambda expressions (and query expressions which are translated into lambda expressions) in LINQ. Chapter 5 has a few different examples of delegate use. | [Where can i find a good in depth guide to C# 3?](https://stackoverflow.com/questions/170772/where-can-i-find-a-good-in-depth-guide-to-c-3)
1) Your knowledge so far seems ok. Lambda expressions are turned into anonymous methods or System.Linq.Expressions.Expression's, depending on context. Since you aren't using a database technology, you don't need to understand expressions (all lambdas will be anonymous methods). You didn't list Extension methods, but those are very important (and easy) to understand. Make sure you see how to apply an extension method to an interface - as all the functionality in linq comes from System.Linq.Enumerable - a collection of extention methods against IEnumerable(Of T).
2) You don't need a deep understanding of lambdas.
The arrow syntax ( => ) was the biggest hurdle for me. The arrow separates the signature and the body of the lambda expression.
Always remember : **Linq methods are not executed until enumerated.**
Watch out for using [loop variables in a lambda](https://stackoverflow.com/questions/295593/linq-query-built-in-foreach-loop-always-takes-parameter-value-from-last-iteration). This is a side effect from deferred execution that is particularly tricky to track down.
3) Sure, Here are some of my answers that show linq method calls - some with xml.
* [List splitting](https://stackoverflow.com/questions/69748/split-a-list-feature-in-c-possibly-linq)
* [Simple Xml existence search](https://stackoverflow.com/questions/239951/how-to-determine-if-xelement-elements-contains-a-node-with-a-specific-name)
* [Xml projection - shape change](https://stackoverflow.com/questions/425087/how-to-write-this-nested-linq-to-xml-query) | Delegates and Lambdas and LINQ, Oh My! | [
"",
"c#",
"linq",
"delegates",
"lambda",
"anonymous-methods",
""
] |
A `JComponent` of mine is firing a `mouseDragged` event too vigorously. When the user is trying to click, it interprets is as a drag even if the mouse has only moved 1 pixel.
How would I add a rule for a particular component that amounted to:
> Do not consider it a drag event unless
> the mouse has moved 10 pixels from the
> point at which is was pressed down.
Note: I know it's not a system setting in my OS, since only events on that component suffer from this over sensitivity.
Thank you. | I've had to do exactly this before. Here's my mouse event processing code, cut down to just the bits relating to making drag require a few pixels before being treated as a drag.
```
public void mousePressed(int mod, Point loc) {
pressLocation=copyLocation(loc,pressLocation);
dragLocation=null;
}
public void mouseReleased(int mod, Point loc) {
if(pressLocation!=null && dragLocation!=null) {
// Mouse drag reverted to mouse click - not dragged far enough
// action for click
pressLocation=null;
}
else if(dragLocation!=null) {
// action for drag completed
}
else {
// do nothing
}
pressLocation=null;
dragLocation=null;
}
public void mouseDragged(int mod, Point loc) {
if(pressLocation!=null) { // initial drag actions following mouse press
dragLocation=pressLocation; // consider dragging to be from start point
if(Math.abs(loc.x-pressLocation.x)<dragMinimum && Math.abs(loc.y-pressLocation.y)<dragMinimum) {
return; // not dragged far enough to count as drag (yet)
}
// action drag from press location
pressLocation=null;
}
else {
// action drag from last drag location
dragLocation=copyLocation(loc,dragLocation);
}
}
```
And note, I also had problems with Java some JVM's generating click events after dragging, which I had to detect and suppress. | Previous answers combined together, with proper event type:
```
public class DragInsensitiveMouseClickListener implements MouseInputListener {
protected static final int MAX_CLICK_DISTANCE = 15;
private final MouseInputListener target;
public MouseEvent pressed;
public DragInsensitiveMouseClickListener(MouseInputListener target) {
this.target = target;
}
@Override
public final void mousePressed(MouseEvent e) {
pressed = e;
target.mousePressed(e);
}
private int getDragDistance(MouseEvent e) {
int distance = 0;
distance += Math.abs(pressed.getXOnScreen() - e.getXOnScreen());
distance += Math.abs(pressed.getYOnScreen() - e.getYOnScreen());
return distance;
}
@Override
public final void mouseReleased(MouseEvent e) {
target.mouseReleased(e);
if (pressed != null) {
if (getDragDistance(e) < MAX_CLICK_DISTANCE) {
MouseEvent clickEvent = new MouseEvent((Component) pressed.getSource(),
MouseEvent.MOUSE_CLICKED, e.getWhen(), pressed.getModifiers(),
pressed.getX(), pressed.getY(), pressed.getXOnScreen(), pressed.getYOnScreen(),
pressed.getClickCount(), pressed.isPopupTrigger(), pressed.getButton());
target.mouseClicked(clickEvent);
}
pressed = null;
}
}
@Override
public void mouseClicked(MouseEvent e) {
//do nothing, handled by pressed/released handlers
}
@Override
public void mouseEntered(MouseEvent e) {
target.mouseEntered(e);
}
@Override
public void mouseExited(MouseEvent e) {
target.mouseExited(e);
}
@Override
public void mouseDragged(MouseEvent e) {
if (pressed != null) {
if (getDragDistance(e) < MAX_CLICK_DISTANCE) return; //do not trigger drag yet (distance is in "click" perimeter
pressed = null;
}
target.mouseDragged(e);
}
@Override
public void mouseMoved(MouseEvent e) {
target.mouseMoved(e);
}
}
``` | Making a component less sensitive to Dragging in Swing | [
"",
"java",
"swing",
"drag-and-drop",
""
] |
In a WinApp I am simply trying to get the absolute path from a Uri object:
```
Uri myUri = new Uri(myPath); //myPath is a string
//somewhere else in the code
string path = myUri.AbsolutePath;
```
This works fine if no spaces in my original path. If spaces are in there the string gets mangled; for example 'Documents and settings' becomes 'Documents%20and%20Setting' etc.
Any help would be appreciated!
**EDIT:**
LocalPath instead of AbsolutePath did the trick! | It's encoding it as it should, you could probably UrlDecode it to get it back with spaces, but it's not "mangled" it's just correctly encoded.
I'm not sure what you're writing, but to convert it back in asp.net it's Server.UrlDecode(path). You also might be able to use LocalPath, rather than AbsolutePath, if it's a Windows app. | This is the way it's supposed to be. That's called URL encoding. It applies because spaces are not allowed in URLs.
If you want the path back with spaces included, you must call something like:
```
string path = Server.URLDecode(myUri.AbsolutePath);
```
You shouldn't be required to import anything to use this in a web application. If you get an error, try importing System.Web.HttpServerUtility. Or, you can call it like so:
```
string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath);
``` | Uri.AbsolutePath messes up path with spaces | [
"",
"c#",
".net-2.0",
"system.net",
"winapp",
""
] |
There is a simple [http server API](http://blogs.oracle.com/michaelmcm/entry/http_server_api_in_java) that allow you do some [simple stuff](http://www.java2s.com/Code/Java/JDK-6/LightweightHTTPServer.htm) quickly, without any addition dependency/installation required.
Are there any similar API/library in .NET ***WITHOUT IIS***?
For example, I am a small window service running, I'd like to add a simple stupid web interface to allow local/remote control/monitoring. | [`HttpListener`](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) hooks into HTTP.SYS even without IIS, I believe.
You'll need to add priveleges to the service account, though - `netsh` on vista, `httpcfg` on xp ("how" covered [here](https://stackoverflow.com/questions/169904)). | In addition to the previously mentioned [webserver project on codeplex](http://www.codeplex.com/webserver), which I've used in a production application, another simple HTTP server API option is [Kayak](http://kayakhttp.com/). Kayak appears to be in an early development stage. It hasn't reached 1.0 yet.
UPDATE: I noticed that my original link to Kayak broke recently. The main website for Kayak has moved to <http://kayakhttp.com/> but the code is hosted on Google code: <http://code.google.com/p/kayak/>.
UPDATE 2: Apparently, the Kayak source code has moved yet again, this time to GitHub: <https://github.com/kayak/kayak/>.
UPDATE 3: the webserver is "being migrated" to a networking library, also at GitHub: <https://github.com/jgauffin/griffin.networking> | Create simple embedded http and https applications in C# | [
"",
"c#",
"http",
"webserver",
""
] |
I'm having difficulty throwing away the bits of the expression I don't want, and keeping the bits I do.
The problem is - given the input string:
```
{if cond}foo{else}bar{/if}
```
I'd like just to have:
```
0: {if cond}foo{else}bar{/if}
1: cond
2: foo
3: bar
```
And for the input string:
```
{if cond}foo{/if}
```
I'd like just to have:
```
0: {if cond}foo{else}bar{/if}
1: cond
2: foo
3:
```
The regex I've got at present looks like this:
```
\{if ([a-z0-9]+)\}([^\{]*?)(((?:\{else\})?)(.*?)?)\{/if\}
```
I get the following data back:
```
0: {if cond}foo{else}bar{/if}
1: cond
2:
3: foo{else}bar
4:
5: foo{else}bar
```
Which would require further parsing of the `foo{else}bar` bit to get the respective values.
Is my regex anywhere near close?
I'm not too concerned about the sort of data this might be run over - including `{` in the body of an if statement is allowed to break the regex. The values of `foo` and `bar` can be anything that does not include a `{`.
Thanks,
Dom | What about this?
```
\{if ([a-z0-9]+)\}([^\{]*)(?:\{else\})?([^\{]*)\{/if\}
``` | This should work :
```
{if\s+([^}]*)}([^{]*)(?:{else}([^{]*))?{/if}
```
Escape it according to your needs | Regular Expression to match {if cond}foo{else}bar{/if} | [
"",
"c++",
"regex",
"boost",
"smarty",
""
] |
I've been messing around with the free Digital Mars Compiler at work (naughty I know), and created some code to inspect compiled functions and look at the byte code for learning purposes, seeing if I can learn anything valuable from how the compiler builds its functions. However, recreating the same method in MSVC++ has failed miserably and the results I am getting are quite confusing. I have a function like this:
```
unsigned int __stdcall test()
{
return 42;
}
```
Then later I do:
```
unsigned char* testCode = (unsigned char*)test;
```
I can't seem to get the C++ static\_cast to work in this case (it throws a compiler error)... hence the C-style cast, but that's besides the point... I've also tried using the reference &test, but that helps none.
Now, when I examine the contents of the memory pointed to by testCode I am confused because what I see doesn't even look like valid code, and even has a debug breakpoint stuck in there... it looks like this (target is IA-32):
0xe9, 0xbc, 0x18, 0x00, 0x00, 0xcc...
This is clearly wrong, 0xe9 is a relative jump instruction, and looking 0xbc bytes away it looks like this:
0xcc, 0xcc, 0xcc...
i.e. memory initialised to the debug breakpoint opcode as expected for unallocated or unused memory.
Where as what I would expect from a function returning 42 would be something like:
0x8b, 0x2a, 0x00, 0x00, 0x00, 0xc3
or at least some flavour of mov followed by a ret (0xc2, 0xc3, 0xca or 0xcb)a little further down
Is MSVC++ taking steps to prevent me from doing this sort of thing for security reasons, or am I doing something stupid and not realising it? This method seems to work fine using DMC as the compiler...
I'm also having trouble going the other way (executing bytes), but I suspect that the underlying cause is the same.
Any help or tips would be greatly appreciated. | I can only guess, but I'm pretty sure you are inspecting a debug build.
In debug mode the MSVC++ compiler replaces all calls by calls to jump stubs. This means, that every function starts with a jump to the real function and this is exactly what you are facing here.
The surrounding 0xCC bytes are indeed breakpoint instructions, in order to fire a possibly attached debugger in case you're executing code where you shouldn't.
Try the same with a release build. That should work as expected.
**Edit:**
This is actually affected by the linker setting /INCREMENTAL. The reason that the effect you're describing doesn't show up in release builds is that these jump stubs are simply optimized away if any kind of optimization is turned on (which is of course usually the case for release builds). | For your cast you want:
```
unsigned char* testCode = reinterpret_cast<unsigned char*>( test );
```
Switch Debug Information Format from 'Program Database for Edit & Continue (/ZI)' to 'Program Database (/Zi)' in Project -> Properties -> C/C++ -> General. I believe it's that setting which causes the compiler to insert jump code so the debugger can rebuild a function and hot patch it in while the program is running. Probably turn off 'Enable Minimal Rebuild' also.
A much simpler way of inspecting the code in MSVC is to simply set a break point and inspect the disassembly (right click on the line and select 'Goto disassembly' from the pop-up menu. It annotates the disassembly with the source code so you can see what each line is compiled to. | Trouble examining byte code in MSVC++ | [
"",
"c++",
"visual-c++",
"bytecode",
"x86",
""
] |
I have a string of digits, e.g. "123456789", and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int?
I've looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on it. Is there a better way? | You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (*see comments below for more on this*).
Therefore the integer value for any digit is the digit minus '0' (or 48).
```
char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'
```
is synonymous to
```
char c = '1';
int i = c - 48; // i is now equal to 1, not '1'
```
However I find the first `c - '0'` far more readable. | ```
#define toDigit(c) (c-'0')
``` | How to convert a single char into an int | [
"",
"c++",
"char",
""
] |
I'm looking for a library that will allow me to programatically modify Excel files to add data to certain cells. My current idea is to use named ranges to determine where to insert the new data (essentially a range of 1x1), then update the named ranges to point at the data. The existing application this is going to integrate with is written entirely in C++, so I'm ideally looking for a C++ solution (hence why [this thread](https://stackoverflow.com/questions/292551/modifying-excel-spreadsheet-with-net) is of limited usefulness). If all else fails, I'll go with a .NET solution if there is some way of linking it against our C++ app.
An ideal solution would be open source, but none of the ones I've seen so far ([MyXls](http://myxls.in2bits.org/) and [XLSSTREAM](http://members.wibs.at/herz/xlsstream/www/index.html)) seem up to the challenge. I like the looks of [Aspose.Cells](http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx), but it's for .NET or Java, not C++ (and costs money). I need to support all Excel formats from 97 through the present, including the XLSX and XLSB formats. Ideally, it would also support formats such as OpenOffice, and (for output) PDF and HTML.
Some use-cases I need to support:
* reading and modifying any cell in the spreadsheet, including formulas
* creating, reading, modifying named ranges (the ranges themselves, not just the cells)
* copying formatting from a cell to a bunch of others (including conditional formatting) -- we'll use one cell as a template for all the others we fill in with data.
Any help you can give me finding an appropriate library would be great. I'd also like to hear some testimonials about the various suggestions (including the ones in my post) so I can make more informed decisions -- what's easy to use, bug-free, cheap, etc? | I ended up using Aspose.Cells as I mentioned in my original post, since it seemed like the easiest path. I'm very happy with the way it turned out, and their support is very good. I had to create a wrapper around it in C# that exported a COM interface to my C++ application. | The safest suggestion is to just use OLE. It uses the COM, which does not require .NET at all.
<http://en.wikipedia.org/wiki/OLE_Automation> <--about halfway down is a C++ example.
You may have to wrap a few functionalities into functions for usability, but it's really not ugly to work with.
EDIT: Just be aware that you need a copy of Excel for it to work. Also, there's some first-party .h files that you can find specific to excel. (it's all explained in the Wikipedia article) | best way to programmatically modify excel spreadsheets | [
"",
"c++",
"excel",
""
] |
I'm creating a win service that monitors ftp logs, when a file has been uploaded I want to start an external application, like a powershell script, to do stuff with the file. my Question is do i want to spin this off into another thread when i do it or should I just wait until it finishes before moving on.
This process is already going to be in a thread (the service is going to be monitoring multiple servers) and the idea of threads starting threads worries me. Is this something to be worried about or is this a case of too much tinfoil in my hat. | Well, code it in a modular fashion and don't worry about threads. If, down the road, you find that your application will benefit from a multi-threaded approach then address it then. If you have build your components orthogonally then the threading part will fit more naturally.
Addressing threading concerns at the very beginning of an application always feel like premature optimization to me. Build the components first and worry about how to thread them later.
[Edit] I am in no way advising you to not think about threading at all. Every component needs to be build with the potential for use by multiple threads - this is a defensive and intelligent practice in all applications. What I meant was don't worry so much about how the application will handle threads and how to set up the thread management of the application first. | Although somewhat off-topic, since you mentioned that you'll be launching a powershell script, I wanted to point out the option to run the script in-process via a powershell "runspace". Here's a **minimal** example:
```
using System.Management.Automation;
static class PoshExec
{
static void Exec(string scriptFilePath)
{
(new RunspaceInvoke()).Invoke("& " + scriptFilePath);
}
}
```
add a reference to
c:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll | To Thread or not to Thread when starting an external application in C# | [
"",
"c#",
"multithreading",
"external-process",
""
] |
I wrote a quick and dirty wrapper around svn.exe to retrieve some content and do something with it, but for certain inputs it occasionally and reproducibly hangs and won't finish. For example, one call is to svn list:
```
svn list "http://myserver:84/svn/Documents/Instruments/" --xml --no-auth-cache --username myuser --password mypassword
```
This command line runs fine when I just do it from a command shell, but it hangs in my app. My c# code to run this is:
```
string cmd = "svn.exe";
string arguments = "list \"http://myserver:84/svn/Documents/Instruments/\" --xml --no-auth-cache --username myuser --password mypassword";
int ms = 5000;
ProcessStartInfo psi = new ProcessStartInfo(cmd);
psi.Arguments = arguments;
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Normal;
psi.UseShellExecute = false;
Process proc = Process.Start(psi);
StreamReader output = new StreamReader(proc.StandardOutput.BaseStream, Encoding.UTF8);
proc.WaitForExit(ms);
if (proc.HasExited)
{
return output.ReadToEnd();
}
```
This takes the full 5000 ms and never finishes. Extending the time doesn't help. In a separate command prompt, it runs instantly, so I'm pretty sure it's unrelated to an insufficient waiting time. For other inputs, however, this seems to work fine.
I also tried running a separate cmd.exe here (where exe is svn.exe and args is the original arg string), but the hang still occurred:
```
string cmd = "cmd";
string arguments = "/S /C \"" + exe + " " + args + "\"";
```
What could I be screwing up here, and how can I debug this external process stuff?
EDIT:
I'm just now getting around to addressing this. Mucho thanks to Jon Skeet for his suggestion, which indeed works great. I have another question about my method of handling this, though, since I'm a multi-threaded novice. I'd like suggestions on improving any glaring deficiencies or anything otherwise dumb. I ended up creating a small class that contains the stdout stream, a StringBuilder to hold the output, and a flag to tell when it's finished. Then I used ThreadPool.QueueUserWorkItem and passed in an instance of my class:
```
ProcessBufferHandler bufferHandler = new ProcessBufferHandler(proc.StandardOutput.BaseStream,
Encoding.UTF8);
ThreadPool.QueueUserWorkItem(ProcessStream, bufferHandler);
proc.WaitForExit(ms);
if (proc.HasExited)
{
bufferHandler.Stop();
return bufferHandler.ReadToEnd();
}
```
... and ...
```
private class ProcessBufferHandler
{
public Stream stream;
public StringBuilder sb;
public Encoding encoding;
public State state;
public enum State
{
Running,
Stopped
}
public ProcessBufferHandler(Stream stream, Encoding encoding)
{
this.stream = stream;
this.sb = new StringBuilder();
this.encoding = encoding;
state = State.Running;
}
public void ProcessBuffer()
{
sb.Append(new StreamReader(stream, encoding).ReadToEnd());
}
public string ReadToEnd()
{
return sb.ToString();
}
public void Stop()
{
state = State.Stopped;
}
}
```
This seems to work, but I'm doubtful that this is the best way. Is this reasonable? And what can I do to improve it? | One standard issue: the process could be waiting for you to read its output. Create a separate thread to read from its standard output while you're waiting for it to exit. It's a bit of a pain, but that may well be the problem. | Jon Skeet is right on the money!
If you don't mind polling after you launch your svn command try this:
```
Process command = new Process();
command.EnableRaisingEvents = false;
command.StartInfo.FileName = "svn.exe";
command.StartInfo.Arguments = "your svn arguments here";
command.StartInfo.UseShellExecute = false;
command.StartInfo.RedirectStandardOutput = true;
command.Start();
while (!command.StandardOutput.EndOfStream)
{
Console.WriteLine(command.StandardOutput.ReadLine());
}
``` | Hanging process when run with .NET Process.Start -- what's wrong? | [
"",
"c#",
"processstartinfo",
""
] |
I would like to have a `SynchronousQueue` where I insert elements from one thread with `put()`, so the input is blocked until the element is taken in another thread.
In the other thread I perform lots of calculations and from time to time want to check if an element is already available, and consume it. But it seems that `isEmpty()` always returns true, even if another thread is waiting at the `put()` call.
How on earth is this possible? Here is the sample code:
```
@Test
public void testQueue() throws InterruptedException {
final BlockingQueue<Integer> queue = new SynchronousQueue<Integer>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (!queue.isEmpty()) {
try {
queue.take();
System.out.println("taken!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// do useful computations here (busy wait)
}
}
});
t.start();
queue.put(1234);
// this point is never reached!
System.out.println("hello");
}
```
**EDIT:** Neither isEmpty() nor peek() work, one has to use poll(). Thanks! | From <http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/SynchronousQueue.html#put(E)> :
**isEmpty**
public boolean isEmpty()
Always returns true. A SynchronousQueue has no internal capacity.
(haven't looked into this in great detail, but you might want to take a look at either *poll* or *take* instead) | In addition to Tim's answer - you are doing nothing in the consumer thread but continuously calling isEmpty() in a tight loop. Rather than asking the OS to not run it until there is something useful for it to do, the consumer thread is continuously busy. Even if isEmpty worked correctly, the producer thread would rarely get a chance to run.
You could (if isEmpty() did work, or you switched to using poll()) make the consumer sleep for a bit between tests when the queue is empty to give the producer a chance to run, or (preferably) just take out the isEmpty() test and let the thread block on the mutex inside the take() in a sensible manner instead of polling. | BlockingQueue: put() and isEmpty() do not work together? | [
"",
"java",
"multithreading",
"collections",
"producer-consumer",
""
] |
I am exposing a web service using CXF. I am using the @XmlID and @XmlIDREF JAXB annotations to maintain referential integrity of my object graph during marshalling/unmarshalling.
The WSDL rightly contains elements with the xs:id and xs:idref attributes to represent this.
On the server side, everything works really nicely. Instances of Types annotated with @XmlIDREF are the same instances (as in ==) to those annotated with the @XmlID annotation.
However, when I generate a client with WSDLToJava, the references (those annotated with @XmlIDREF) are of type java.lang.Object.
Is there any way that I can customise the JAXB bindings such that the types of references are either java.lang.String (to match the ID of the referenced type) or the same as the referenced type itself? | OK, so this isn't going to work. It's not possible for JAXB to generate code with the correct types for the IDREFs because the schema can't specify the types of references and there may be IDREF's pointing to different complex types. How would JAXB know what are the types of the references? An extension to XML Schema would do it! :) | Use the inline JAXB bindings to indicate the type to be used. Then JAXB generated code will have correct type.
```
<complexType name="Column">
<sequence>
<element name="name" type="string" maxOccurs="1" minOccurs="1"></element>
<element name="referencedColumn" type="IDREF" maxOccurs="1" minOccurs="0">
<annotation>
<appinfo>
<jaxb:property>
<jaxb:baseType name="Column"/>
</jaxb:property>
</appinfo>
</annotation>
</element>
</sequence>
<attribute name="id" type="ID" use="required"></attribute>
</complexType>
```
Also note that you have to declare the `jaxb` namespace and JAXB version in the `schema` element.
```
<schema targetNamespace="http://example.com/schema"
elementFormDefault="qualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="1.0">
``` | JAXB XmlID and XmlIDREF annotations (Schema to Java) | [
"",
"java",
"wsdl",
"jaxb",
"jax-ws",
"cxf",
""
] |
I have a web page with three dropdowns for day, month and year. If I use the JavaScript `Date` constructor that takes numbers, then I get a `Date` object for my current timezone:
```
new Date(xiYear, xiMonth, xiDate)
```
Give the correct date, but it thinks that date is GMT+01:00 due to daylight savings time.
The problem here is that I then pass this `Date` to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one.
Now I could just pass the day, month, and year individually into the Ajax method, but it seems that there ought to be a better way.
The accepted answer pointed me in the right direction, however just using `setUTCHours()` by itself changed:
```
Apr 5th 00:00 GMT+01:00
```
to
```
Apr 4th 23:00 GMT+01:00
```
I then also had to set the UTC date, month and year to end up with
```
Apr 5th 01:00 GMT+01:00
```
which is what I wanted. | using `.setUTCHours()` it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.
You cannot set it using UTC in the constructor though, unless you specify a date-string.
Using `new Date(Date.UTC(year, month, day, hour, minute, second))` you can create a Date-object from a specific UTC time. | **Simply Set the Time Zone and Get Back According**
```
new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
```
> Other **Time-zones** are as Following
```
var world_timezones =
[
'Europe/Andorra',
'Asia/Dubai',
'Asia/Kabul',
'Europe/Tirane',
'Asia/Yerevan',
'Antarctica/Casey',
'Antarctica/Davis',
'Antarctica/DumontDUrville',
'Antarctica/Mawson',
'Antarctica/Palmer',
'Antarctica/Rothera',
'Antarctica/Syowa',
'Antarctica/Troll',
'Antarctica/Vostok',
'America/Argentina/Buenos_Aires',
'America/Argentina/Cordoba',
'America/Argentina/Salta',
'America/Argentina/Jujuy',
'America/Argentina/Tucuman',
'America/Argentina/Catamarca',
'America/Argentina/La_Rioja',
'America/Argentina/San_Juan',
'America/Argentina/Mendoza',
'America/Argentina/San_Luis',
'America/Argentina/Rio_Gallegos',
'America/Argentina/Ushuaia',
'Pacific/Pago_Pago',
'Europe/Vienna',
'Australia/Lord_Howe',
'Antarctica/Macquarie',
'Australia/Hobart',
'Australia/Currie',
'Australia/Melbourne',
'Australia/Sydney',
'Australia/Broken_Hill',
'Australia/Brisbane',
'Australia/Lindeman',
'Australia/Adelaide',
'Australia/Darwin',
'Australia/Perth',
'Australia/Eucla',
'Asia/Baku',
'America/Barbados',
'Asia/Dhaka',
'Europe/Brussels',
'Europe/Sofia',
'Atlantic/Bermuda',
'Asia/Brunei',
'America/La_Paz',
'America/Noronha',
'America/Belem',
'America/Fortaleza',
'America/Recife',
'America/Araguaina',
'America/Maceio',
'America/Bahia',
'America/Sao_Paulo',
'America/Campo_Grande',
'America/Cuiaba',
'America/Santarem',
'America/Porto_Velho',
'America/Boa_Vista',
'America/Manaus',
'America/Eirunepe',
'America/Rio_Branco',
'America/Nassau',
'Asia/Thimphu',
'Europe/Minsk',
'America/Belize',
'America/St_Johns',
'America/Halifax',
'America/Glace_Bay',
'America/Moncton',
'America/Goose_Bay',
'America/Blanc-Sablon',
'America/Toronto',
'America/Nipigon',
'America/Thunder_Bay',
'America/Iqaluit',
'America/Pangnirtung',
'America/Atikokan',
'America/Winnipeg',
'America/Rainy_River',
'America/Resolute',
'America/Rankin_Inlet',
'America/Regina',
'America/Swift_Current',
'America/Edmonton',
'America/Cambridge_Bay',
'America/Yellowknife',
'America/Inuvik',
'America/Creston',
'America/Dawson_Creek',
'America/Fort_Nelson',
'America/Vancouver',
'America/Whitehorse',
'America/Dawson',
'Indian/Cocos',
'Europe/Zurich',
'Africa/Abidjan',
'Pacific/Rarotonga',
'America/Santiago',
'America/Punta_Arenas',
'Pacific/Easter',
'Asia/Shanghai',
'Asia/Urumqi',
'America/Bogota',
'America/Costa_Rica',
'America/Havana',
'Atlantic/Cape_Verde',
'America/Curacao',
'Indian/Christmas',
'Asia/Nicosia',
'Asia/Famagusta',
'Europe/Prague',
'Europe/Berlin',
'Europe/Copenhagen',
'America/Santo_Domingo',
'Africa/Algiers',
'America/Guayaquil',
'Pacific/Galapagos',
'Europe/Tallinn',
'Africa/Cairo',
'Africa/El_Aaiun',
'Europe/Madrid',
'Africa/Ceuta',
'Atlantic/Canary',
'Europe/Helsinki',
'Pacific/Fiji',
'Atlantic/Stanley',
'Pacific/Chuuk',
'Pacific/Pohnpei',
'Pacific/Kosrae',
'Atlantic/Faroe',
'Europe/Paris',
'Europe/London',
'Asia/Tbilisi',
'America/Cayenne',
'Africa/Accra',
'Europe/Gibraltar',
'America/Godthab',
'America/Danmarkshavn',
'America/Scoresbysund',
'America/Thule',
'Europe/Athens',
'Atlantic/South_Georgia',
'America/Guatemala',
'Pacific/Guam',
'Africa/Bissau',
'America/Guyana',
'Asia/Hong_Kong',
'America/Tegucigalpa',
'America/Port-au-Prince',
'Europe/Budapest',
'Asia/Jakarta',
'Asia/Pontianak',
'Asia/Makassar',
'Asia/Jayapura',
'Europe/Dublin',
'Asia/Jerusalem',
'Asia/Kolkata',
'Indian/Chagos',
'Asia/Baghdad',
'Asia/Tehran',
'Atlantic/Reykjavik',
'Europe/Rome',
'America/Jamaica',
'Asia/Amman',
'Asia/Tokyo',
'Africa/Nairobi',
'Asia/Bishkek',
'Pacific/Tarawa',
'Pacific/Enderbury',
'Pacific/Kiritimati',
'Asia/Pyongyang',
'Asia/Seoul',
'Asia/Almaty',
'Asia/Qyzylorda',
'Asia/Qostanay',
'Asia/Aqtobe',
'Asia/Aqtau',
'Asia/Atyrau',
'Asia/Oral',
'Asia/Beirut',
'Asia/Colombo',
'Africa/Monrovia',
'Europe/Vilnius',
'Europe/Luxembourg',
'Europe/Riga',
'Africa/Tripoli',
'Africa/Casablanca',
'Europe/Monaco',
'Europe/Chisinau',
'Pacific/Majuro',
'Pacific/Kwajalein',
'Asia/Yangon',
'Asia/Ulaanbaatar',
'Asia/Hovd',
'Asia/Choibalsan',
'Asia/Macau',
'America/Martinique',
'Europe/Malta',
'Indian/Mauritius',
'Indian/Maldives',
'America/Mexico_City',
'America/Cancun',
'America/Merida',
'America/Monterrey',
'America/Matamoros',
'America/Mazatlan',
'America/Chihuahua',
'America/Ojinaga',
'America/Hermosillo',
'America/Tijuana',
'America/Bahia_Banderas',
'Asia/Kuala_Lumpur',
'Asia/Kuching',
'Africa/Maputo',
'Africa/Windhoek',
'Pacific/Noumea',
'Pacific/Norfolk',
'Africa/Lagos',
'America/Managua',
'Europe/Amsterdam',
'Europe/Oslo',
'Asia/Kathmandu',
'Pacific/Nauru',
'Pacific/Niue',
'Pacific/Auckland',
'Pacific/Chatham',
'America/Panama',
'America/Lima',
'Pacific/Tahiti',
'Pacific/Marquesas',
'Pacific/Gambier',
'Pacific/Port_Moresby',
'Pacific/Bougainville',
'Asia/Manila',
'Asia/Karachi',
'Europe/Warsaw',
'America/Miquelon',
'Pacific/Pitcairn',
'America/Puerto_Rico',
'Asia/Gaza',
'Asia/Hebron',
'Europe/Lisbon',
'Atlantic/Madeira',
'Atlantic/Azores',
'Pacific/Palau',
'America/Asuncion',
'Asia/Qatar',
'Indian/Reunion',
'Europe/Bucharest',
'Europe/Belgrade',
'Europe/Kaliningrad',
'Europe/Moscow',
'Europe/Simferopol',
'Europe/Kirov',
'Europe/Astrakhan',
'Europe/Volgograd',
'Europe/Saratov',
'Europe/Ulyanovsk',
'Europe/Samara',
'Asia/Yekaterinburg',
'Asia/Omsk',
'Asia/Novosibirsk',
'Asia/Barnaul',
'Asia/Tomsk',
'Asia/Novokuznetsk',
'Asia/Krasnoyarsk',
'Asia/Irkutsk',
'Asia/Chita',
'Asia/Yakutsk',
'Asia/Khandyga',
'Asia/Vladivostok',
'Asia/Ust-Nera',
'Asia/Magadan',
'Asia/Sakhalin',
'Asia/Srednekolymsk',
'Asia/Kamchatka',
'Asia/Anadyr',
'Asia/Riyadh',
'Pacific/Guadalcanal',
'Indian/Mahe',
'Africa/Khartoum',
'Europe/Stockholm',
'Asia/Singapore',
'America/Paramaribo',
'Africa/Juba',
'Africa/Sao_Tome',
'America/El_Salvador',
'Asia/Damascus',
'America/Grand_Turk',
'Africa/Ndjamena',
'Indian/Kerguelen',
'Asia/Bangkok',
'Asia/Dushanbe',
'Pacific/Fakaofo',
'Asia/Dili',
'Asia/Ashgabat',
'Africa/Tunis',
'Pacific/Tongatapu',
'Europe/Istanbul',
'America/Port_of_Spain',
'Pacific/Funafuti',
'Asia/Taipei',
'Europe/Kiev',
'Europe/Uzhgorod',
'Europe/Zaporozhye',
'Pacific/Wake',
'America/New_York',
'America/Detroit',
'America/Kentucky/Louisville',
'America/Kentucky/Monticello',
'America/Indiana/Indianapolis',
'America/Indiana/Vincennes',
'America/Indiana/Winamac',
'America/Indiana/Marengo',
'America/Indiana/Petersburg',
'America/Indiana/Vevay',
'America/Chicago',
'America/Indiana/Tell_City',
'America/Indiana/Knox',
'America/Menominee',
'America/North_Dakota/Center',
'America/North_Dakota/New_Salem',
'America/North_Dakota/Beulah',
'America/Denver',
'America/Boise',
'America/Phoenix',
'America/Los_Angeles',
'America/Anchorage',
'America/Juneau',
'America/Sitka',
'America/Metlakatla',
'America/Yakutat',
'America/Nome',
'America/Adak',
'Pacific/Honolulu',
'America/Montevideo',
'Asia/Samarkand',
'Asia/Tashkent',
'America/Caracas',
'Asia/Ho_Chi_Minh',
'Pacific/Efate',
'Pacific/Wallis',
'Pacific/Apia',
'Africa/Johannesburg'
];
``` | Create a Date with a set timezone without using a string representation | [
"",
"javascript",
"timezone",
""
] |
I want to create a really easy to use 2D Grid. Each cell in the grid needs to be able to store a load of data. Ideally I would like to be able to traverse through the grid one cell at a time, as well as obtain the immediate neighbours of any of the grid cells.
My first thought was to store a vector of pointers to a Cell's neighbours (4 in total), then create convenience functions for leftNeighbour, rightNeighbour, etc. Connecting up the grid after initialization.
The std::vector is supposed to be a dynamically resizeable array, so this strikes me as rather unnecessary if I'm only going to hard-code the positions of the pointers (0 == left, 1 == right, etc). However, it does allow a nicer way of iterating through the neighbours of a cell. The other thing I have to consider is if the cell is on a border with the edge of the grid (whether to test for this or just implicitly extend the grid by one cell so that this will never happen).
Can anyone suggest a better alternative, or does this sound like a reasonable design?
Thanks, Dan | If you want a four-direction iterator, make your own:
```
template<typename T, int width, int height>
class Grid {
public:
T data[width * height];
iterator begin() {
return iterator(data);
}
iterator end() {
return iterator(data + width * height);
}
class iterator {
public:
iterator(const iterator &other) :
ptr(other.ptr)
{
}
iterator &left() const {
return iterator(ptr - 1);
}
iterator &right() const {
return iterator(ptr + 1);
}
iterator &up() const {
return iterator(ptr - width);
}
iterator &down() const {
return iterator(ptr + width);
}
iterator &operator++() {
++ptr;
return *this;
}
iterator &operator--() {
--ptr;
return *this;
}
iterator operator++(int) {
++*this;
return iterator(ptr + 1);
}
iterator operator--(int) {
--*this;
return iterator(ptr - 1);
}
T operator*() const {
return *ptr;
}
private:
iterator();
iterator(T *ptr_) :
ptr(ptr_)
{
}
T *ptr;
friend class Grid;
};
};
```
You may want to detect if you hit the edge of your grid, among other things, and that would have to be implemented. | I would go for Boost.MultiArray | How to create an efficient 2D grid in C++? | [
"",
"c++",
"stl",
"vector",
""
] |
The general advice is that you should not call `GC.Collect` from your code, but what are the exceptions to this rule?
I can only think of a few very specific cases where it may make sense to force a garbage collection.
One example that springs to mind is a service, that wakes up at intervals, performs some task, and then sleeps for a long time. In this case, it may be a good idea to force a collect to prevent the soon-to-be-idle process from holding on to more memory than needed.
Are there any other cases where it is acceptable to call `GC.Collect`? | If you have good reason to believe that a significant set of objects - particularly those you suspect to be in generations 1 and 2 - are now eligible for garbage collection, and that now would be an appropriate time to collect in terms of the small performance hit.
A good example of this is if you've just closed a large form. You know that all the UI controls can now be garbage collected, and a very short pause as the form is closed probably won't be noticeable to the user.
UPDATE 2.7.2018
As of .NET 4.5 - there is `GCLatencyMode.LowLatency` and `GCLatencyMode.SustainedLowLatency`. When entering and leaving either of these modes, it is recommended that you force a full GC with `GC.Collect(2, GCCollectionMode.Forced)`.
As of .NET 4.6 - there is the `GC.TryStartNoGCRegion` method (used to set the read-only value `GCLatencyMode.NoGCRegion`). This can itself, perform a full blocking garbage collection in an attempt to free enough memory, but given we are disallowing GC for a period, I would argue it is also a good idea to perform full GC before and after.
Source: Microsoft engineer Ben Watson's: *Writing High-Performance .NET Code*, 2nd Ed. 2018.
See:
* <https://msdn.microsoft.com/en-us/library/system.runtime.gclatencymode(v=vs.110).aspx>
* <https://msdn.microsoft.com/en-us/library/dn906204(v=vs.110).aspx> | I use `GC.Collect` only when writing crude performance/profiler test rigs; i.e. I have two (or more) blocks of code to test - something like:
```
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestA(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
TestB(); // may allocate lots of transient objects
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
...
```
So that `TestA()` and `TestB()` run with as similar state as possible - i.e. `TestB()` doesn't get hammered just because `TestA` left it very close to the tipping point.
A classic example would be a simple console exe (a `Main` method sort-enough to be posted here for example), that shows the difference between looped string concatenation and `StringBuilder`.
If I need something precise, then this would be two completely independent tests - but often this is enough if we just want to minimize (or normalize) the GC during the tests to get a rough feel for the behaviour.
During production code? I have yet to use it ;-p | When is it acceptable to call GC.Collect? | [
"",
"c#",
".net",
"garbage-collection",
""
] |
I have a canvas with user controls arranged on it. When a tooltip is assigned to the usercontrol or one of its children, that tooltip does not show (open event does not get fired either). I do not explicitly disable any of them.
I've placed plenty of tooltips elsewhere in the application and they all show, except the ones on the usercontrol I created.
Any ideas?
Hierarchy is roughly as follow:
```
<Grid>
<Canvas>
<UserControl>
<Canvas>
<Line/>
<Rectangle/>
</Canvas>
</UserControl>
</Canvas
</Grid>
``` | I finally figured it out.
On my canvas, I was drawing pointer lines (horizontal and vertical to show on the grid where I am and the values on the left/bottom), it turns out that when the hit test was being performed, it was hitting those lines and stopping. By setting IsHitTestVisible to false on all unrelevant geometry, my tooltip now shows properly.
The reason I was seeing the mouse enter/leave event was because when moving the cursor, the lines would drag 1 frame behind and thus allow the mouse to enter/leave but not move.
This resolves my issue. | If the background of the Usercontrol is x:Null, then the mouse events will fall through to the underlying content. You can use "Transparent" to ensure mouse events go to the usercontrol.
This behaviour isn't unique to usercontrols; it's the general behaviour for all of WPF. In your example, assuming you have a fill on child elements, you should be able to hover over those, and see the tooltips you have set. | wpf tooltip not shown on usercontrol or its children | [
"",
"c#",
"wpf",
"tooltip",
""
] |
I'd like to know how to limit an input value to signed decimals using `std::cin`. | ```
double i;
//Reading the value
cin >> i;
//Numeric input validation
if(!cin.eof())
{
peeked = cin.peek();
if(peeked == 10 && cin.good())
{
//Good!
count << "i is a decimal";
}
else
{
count << "i is not a decimal";
cin.clear();
cin >> discard;
}
}
```
This also gives an error message with the input -1a2.0 avoiding the assignation of just -1 to i. | If the backing variable of the `cin` is a number, and the string provided is not a number, the return value is false, so you need a loop:
```
int someVal;
while(!(cin >> someVal)) {
cin.reset();
cout << "Invalid value, try again.";
}
``` | How to validate numeric input in C++ | [
"",
"c++",
"visual-c++",
""
] |
Say I have a `div` containing an unlimited number of child `div`s. Is there an easy way to get jQuery to select the *n*th `div` and every `div` after it so I can change those (in this case, call `remove()` on old `div`s)? | You can use the [":gt()"](http://docs.jquery.com/Selectors/gt#index) selector:
```
// div's 10 and higher
$('div:gt(9)').show()
``` | Typing this out of my head and the jQuery API doc (read: this is not tested), but the first thing I'd do is to
```
$('#container div').slice(-n).remove();
``` | selecting nth div (and beyond) in jQuery | [
"",
"javascript",
"jquery",
"traversal",
""
] |
Is there any widely used SQL coding standard out there? SQL is little bit different from C/C++ type of programming languages. Really don't know how to best format it for readability. | Wouldn't call it coding standard - more like coding style
```
SELECT
T1.col1,
T1.col2,
T2.col3
FROM
table1 T1
INNER JOIN ON Table2 T2 ON T1.ID = T2.ID
WHERE
T1.col1 = 'xxx'
AND T2.Col3 = 'yyy'
```
* capitalize reserved words
* main keywords on new line
* can't get used to commas before columns
* always use short meaningful table aliases
* prefix views with v
* prefix stored procs with sp (however don't use "sp\_" which is reserved for built in procs)
* don't prefix tables
* table names singular | I like the comma preceding way:
```
SELECT
column1
, column2
, column3
, COALESCE(column4,'foo') column4
FROM
tablename
WHERE
column1 = 'bar'
ORDER BY
column1
, column2
```
it makes it the easiest to read and debug in my opinion. | What SQL coding standard do you follow? | [
"",
"sql",
"coding-style",
""
] |
I know this should be simple and I should know it but it's eluding me for the time being.
I am using a singleton pattern to help with logging stuff. However, logging only happens in one class, and the singleton is basically a watcher for a boolean that opens and closes the log file. Because I don't want the file to be opened more than once, or closed more than once, I'm using the singleton pattern. However, I don't want it to be a global value, and I sure as hell don't want other classes, even inside the package accessing it. How can I make it so only this one class use it? | Make it a private class inside the class in which you want to use it. Also, consider making it a static class. | If you don't want it to be accessed by other classes, why is it a Singleton in the first place? Just make it a private, instanced class and keep a reference to it. | Class Access question | [
"",
"c#",
"singleton",
""
] |
I've downloaded an HttpHandler class that concatenates JS files into one file and it keeps appending the `` characters at the start of each file it concatenates.
Any ideas on what is causing this? Could it be that onces the files processed they are written to the cache and that's how the cache is storing/rendering it?
Any inputs would be greatly appreciated.
```
using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Configuration;
using System.Web;
public class HttpCombiner : IHttpHandler {
private const bool DO_GZIP = false;
private readonly static TimeSpan CACHE_DURATION = TimeSpan.FromDays(30);
public void ProcessRequest (HttpContext context) {
HttpRequest request = context.Request;
// Read setName, contentType and version. All are required. They are
// used as cache key
string setName = request["s"] ?? string.Empty;
string contentType = request["t"] ?? string.Empty;
string version = request["v"] ?? string.Empty;
// Decide if browser supports compressed response
bool isCompressed = DO_GZIP && this.CanGZip(context.Request);
// Response is written as UTF8 encoding. If you are using languages
// like Arabic, you should change this to proper encoding
UTF8Encoding encoding = new UTF8Encoding(false);
// If the set has already been cached, write the response directly
// from cache. Otherwise generate the response and cache it
if (!this.WriteFromCache(context, setName, version, isCompressed,
contentType))
{
using (MemoryStream memoryStream = new MemoryStream(5000))
{
// Decide regular stream or GZipStream based on whether the
// response can be cached or not
using (Stream writer = isCompressed
? (Stream)(new GZipStream(memoryStream,
CompressionMode.Compress))
: memoryStream)
{
// Load the files defined in <appSettings> and process
// each file
string setDefinition = System.Configuration
.ConfigurationManager.AppSettings[setName] ?? "";
string[] fileNames = setDefinition.Split(
new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string fileName in fileNames)
{
byte[] fileBytes = this.GetFileBytes(
context, fileName.Trim(), encoding);
writer.Write(fileBytes, 0, fileBytes.Length);
}
writer.Close();
}
// Cache the combined response so that it can be directly
// written in subsequent calls
byte[] responseBytes = memoryStream.ToArray();
context.Cache.Insert(
GetCacheKey(setName, version, isCompressed),
responseBytes, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
CACHE_DURATION);
// Generate the response
this.WriteBytes(responseBytes, context, isCompressed,
contentType);
}
}
}
private byte[] GetFileBytes(HttpContext context, string virtualPath,
Encoding encoding)
{
if (virtualPath.StartsWith("http://",
StringComparison.InvariantCultureIgnoreCase))
{
using (WebClient client = new WebClient())
{
return client.DownloadData(virtualPath);
}
}
else
{
string physicalPath = context.Server.MapPath(virtualPath);
byte[] bytes = File.ReadAllBytes(physicalPath);
// TODO: Convert unicode files to specified encoding.
// For now, assuming files are either ASCII or UTF8
return bytes;
}
}
private bool WriteFromCache(HttpContext context, string setName,
string version, bool isCompressed, string contentType)
{
byte[] responseBytes = context.Cache[GetCacheKey(setName, version,
isCompressed)] as byte[];
if (null == responseBytes || 0 == responseBytes.Length) return false;
this.WriteBytes(responseBytes, context, isCompressed, contentType);
return true;
}
private void WriteBytes(byte[] bytes, HttpContext context,
bool isCompressed, string contentType)
{
HttpResponse response = context.Response;
response.AppendHeader("Content-Length", bytes.Length.ToString());
response.ContentType = contentType;
if (isCompressed)
response.AppendHeader("Content-Encoding", "gzip");
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
context.Response.Cache.SetMaxAge(CACHE_DURATION);
context.Response.Cache.AppendCacheExtension(
"must-revalidate, proxy-revalidate");
response.OutputStream.Write(bytes, 0, bytes.Length);
response.Flush();
}
private bool CanGZip(HttpRequest request)
{
string acceptEncoding = request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(acceptEncoding) &&
(acceptEncoding.Contains("gzip")
|| acceptEncoding.Contains("deflate")))
return true;
return false;
}
private string GetCacheKey(string setName, string version,
bool isCompressed)
{
return "HttpCombiner." + setName + "." + version + "." + isCompressed;
}
public bool IsReusable
{
get { return true; }
}
}
``` | OK, I've debugged your code.
BOM marks appear in the source stream when the files are being read from the disk:
```
byte[] bytes = File.ReadAllBytes(physicalPath);
// TODO: Convert unicode files to specified encoding. For now, assuming
// files are either ASCII or UTF8
```
If you read the files properly, you can get rid of the marks. | The  characters are the [UTF BOM markers](http://en.wikipedia.org/wiki/Byte-order_mark). |  characters appended to the beginning of each file | [
"",
"c#",
"asp.net",
"encoding",
"httphandler",
"byte-order-mark",
""
] |
Ok so I realize that this is a pretty vague question, but bear with me.
I have experienced this problem on numerous occasions with different and unrelated queries. The query below takes many minutes to execute:
```
SELECT <Fields>
FROM <Multiple Tables Joined>
LEFT JOIN (SELECT <Fields> FROM <Multiple Tables Joined> ) ON <Condition>
```
However, by just adding the join hint it query the executes in just seconds:
```
SELECT <Fields>
FROM <Multiple Tables Joined>
LEFT HASH JOIN (SELECT <Fields> FROM <Multiple Tables Joined> ) ON <Condition>
```
The strange thing is the type of JOIN specified in the hint is not really what improves the performance. It appears to be because the hint causes the optimizer to execute the sub query in isolation and then join. I see the same performance improvement if I create a table-valued function (not an inline one) for the sub-query. e.g.
```
SELECT <Fields>
FROM <Multiple Tables Joined>
LEFT JOIN dbo.MySubQueryFunction() ON <Condition>
```
Anybody have any ideas why the optimizer is so dumb in this case? | If any of those tables are table variables, the optimizer uses a bad estimate of 0 rows and usually chooses nested loop as the join technique.
It does this due to a lack of statistics on the tables involved. | Optimizer is an algorithm. It is not dumb or smart, it works the way it is programmed.
`Hash join` implies building a hash table on a smaller row source, that's why the inner query must be executed first.
In first case optimizer might have chosen a `nested loop`. It pushed the join condition into the inner query and executed the inner query on each iteration with an additional predicate. It might not find an appropriate index for this predicate, and a `full table scan` did take place on each iteration.
It's hard to say why this happens unless you post your exact query and how many rows are in your tables.
With a table function it's impossible to push a join condition into the inner query, that's why it's being executed only once. | Why does a SQL join choose a sub-optimal query plan? | [
"",
"sql",
"sql-server",
""
] |
Is there a way to disable a tab in a [TabControl](https://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol(v=vs.110).aspx)? | The [TabPage](https://msdn.microsoft.com/en-us/library/system.windows.forms.tabpage(v=vs.110).aspx) class hides the Enabled property. That was intentional as there is an awkward UI design problem with it. The basic issue is that disabling the page does not also disable the tab. And if try to work around that by disabling the tab with the Selecting event then it does not work when the TabControl has only one page.
If these usability problems do not concern you then keep in mind that the property still works, it is merely hidden from IntelliSense. If the FUD is uncomfortable then you can simply do this:
```
public static void EnableTab(TabPage page, bool enable) {
foreach (Control ctl in page.Controls) ctl.Enabled = enable;
}
``` | Cast your TabPage to a Control, then set the Enabled property to false.
```
((Control)this.tabPage).Enabled = false;
```
Therefore, the tabpage's header will still be enabled but its contents will be disabled. | How can I disable a tab inside a TabControl? | [
"",
"c#",
"winforms",
"tabcontrol",
""
] |
Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:
```
verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
``` | Sequences have a method `index(value)` which returns index of first occurrence - in your case this would be `verts.index(value)`.
You can run it on `verts[::-1]` to find out the last index. Here, this would be `len(verts) - 1 - verts[::-1].index(value)` | Perhaps the two most efficient ways to find the *last* index:
```
def rindex(lst, value):
lst.reverse()
i = lst.index(value)
lst.reverse()
return len(lst) - i - 1
```
```
def rindex(lst, value):
return len(lst) - operator.indexOf(reversed(lst), value) - 1
```
Both take only O(1) extra space and the *two* in-place reversals of the first solution are much faster than creating a reverse copy. Let's compare it with the other solutions posted previously:
```
def rindex(lst, value):
return len(lst) - lst[::-1].index(value) - 1
def rindex(lst, value):
return len(lst) - next(i for i, val in enumerate(reversed(lst)) if val == value) - 1
```
Benchmark results, my solutions are the red and green ones:
[](https://i.stack.imgur.com/ZRMc6.png)
This is for searching a number in a list of a million numbers. The x-axis is for the location of the searched element: 0% means it's at the start of the list, 100% means it's at the end of the list. All solutions are fastest at location 100%, with the two `reversed` solutions taking pretty much no time for that, the double-reverse solution taking a little time, and the reverse-copy taking a lot of time.
A closer look at the right end:
[](https://i.stack.imgur.com/ANmnz.png)
At location 100%, the reverse-copy solution and the double-reverse solution spend all their time on the reversals (`index()` is instant), so we see that the two in-place reversals are about seven times as fast as creating the reverse copy.
The above was with `lst = list(range(1_000_000, 2_000_001))`, which pretty much creates the int objects sequentially in memory, which is extremely cache-friendly. Let's do it again after shuffling the list with `random.shuffle(lst)` (probably less realistic, but interesting):
[](https://i.stack.imgur.com/xxsNh.png)
[](https://i.stack.imgur.com/rznaG.png)
All got a lot slower, as expected. The reverse-copy solution suffers the most, at 100% it now takes about 32 times (!) as long as the double-reverse solution. And the `enumerate`-solution is now second-fastest only after location 98%.
Overall I like the `operator.indexOf` solution best, as it's the fastest one for the last half or quarter of all locations, which are perhaps the more interesting locations if you're actually doing `rindex` for something. And it's only a bit slower than the double-reverse solution in earlier locations.
All benchmarks done with CPython 3.9.0 64-bit on Windows 10 Pro 1903 64-bit. | Finding first and last index of some value in a list in Python | [
"",
"python",
"list",
"search",
""
] |
I'm trying to create a small Javascript "framework" that I can use in my greasemonkey scripts. I only need **very** basic functions, so this is why I choose not to use mooTools or DOMAssistant. Besides, I'm not going to be silly and put DOMAssitant in a 20KB Greasemonkey script! I just want a small, neat snippet of code.
I have a small problem with the below code. I think its because I am returning an array in $() so I get .setStyle is not a function error message.
```
var fmini = {
$ : function(a) {
var i=0,obj,d;
var e = [];
while (obj = arguments[i++]) {
d = document.getElementById(obj);
d.setStyle = fmini.setStyle;
d.each = fmini.each;
e.push(d);
}
return e;
},
setStyle : function(style, value) {
if (typeof this.style.cssText !== 'undefined') {
var styleToSet = this.style.cssText;
if (typeof style === 'object') {
for (var i in style)
if (typeof i === 'string') styleToSet += ';' + i + ':' + style[i];
}
else styleToSet += ';' + style + ':' + value;
this.style.cssText = styleToSet;
}
return this;
},
each : function (functionCall) {
for (var i=0, il=this.length; i < il; i++)
functionCall.call(this[i]);
return this;
},
}
window.$ = fmini.$;
```
I would like this to work when I do
```
$('bob','amy').setStyle({
'border' : '5px solid #ff0000',
'background-color' : '#ccc'
});
``` | Write your methods to operate on the *set* of nodes returned from `$`. That way both `$('bob').setStyle()` *and* `$('bob', 'amy').setStyle()` will work. I see you have a generic `forEach` or `each` method which is a good start.
```
var fmini = {
$: function() {
var i=0, obj;
var e = [];
e.setStyle = fmini.setStyle;
e.each = fmini.each;
while (obj = arguments[i++]) {
e.push(document.getElementById(obj));
}
return e;
},
setStyle : function(style, value) {
return this.each(function() {
if (typeof this.style.cssText !== 'undefined') {
var styleToSet = this.style.cssText;
if (typeof style === 'object') {
for (var i in style)
if (typeof i === 'string') styleToSet += ';' + i + ':' + style[i];
}
else styleToSet += ';' + style + ':' + value;
this.style.cssText = styleToSet;
}
})
}
}
```
Incidentally this is something `jQuery` was the first to do/popularze. | Like you had suspected the return of $ in this case is an array of the elements, you have to extend array with setStyle or add the extension when the array is populated before you pass the array back. Then you shouldn't get an error saying .setStyle is not a function. However you will have to also make sure you handle your object context binding when you are chaining like this otherwise `this` is referring to the current scope and not an element in your array. | Light Javascript framework | [
"",
"frameworks",
"javascript",
"javascript-framework",
""
] |
```
<?php
session_start();
include("connect.php");
$timeout = 60 * 30;
$fingerprint = md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
if(isset($_POST['userName']))
{
$user = mysql_real_escape_string($_POST['userName']);
$password = mysql_real_escape_string($_POST['password']);
$matchingUser = mysql_query("SELECT * FROM `users` WHERE username='$user' AND password=MD5('$password') LIMIT 1");
if (mysql_num_rows($matchingUser))
{
if($matchingUser['inactive'] == 1)//Checks if the inactive field of the user is set to one
{
$error = "Your e-mail Id has not been verified. Check your mail to verify your e-mail Id. However you'll be logged in to site with less privileges.";
$_SESSION['inactive'] = true;
}
$_SESSION['user'] = $user;
$_SESSION['lastActive'] = time();
$_SESSION['fingerprint'] = $fingerprint;
}
else
{
$error = "Invalid user id";
}
}
if ((isset($_SESSION['lastActive']) && $_SESSION['lastActive']<(time()-$timeout)) || (isset($_SESSION['fingerprint']) && $_SESSION['fingerprint']!=$fingerprint)
|| isset($_GET['logout'])
)
{
setcookie(session_name(), '', time()-3600, '/');
session_destroy();
}
else
{
session_regenerate_id();
$_SESSION['lastActive'] = time();
$_SESSION['fingerprint'] = $fingerprint;
}
?>
```
This is just modified version of <http://en.wikibooks.org/wiki/PHP_Programming/User_login_systems>
What does the `setcookie(session_name(), '', time()-3600, '/');` do here?
Here's a bug:
I use this login form:
```
<?php
if(!isset($_SESSION['user']))
{
if(isset($error)) echo $error;
echo '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">
<label>Username: </label>
<input type="text" name="userName" value="';if(isset($_POST['userName'])) echo $_POST["userName"]; echo '" /><br />
<label>Password: </label>
<input type="password" name="password" />
<input type="submit" value="Login" class="button" />
<ul class="sidemenu">
<li><a href="register.php">Register</a></li>
<li><a href="forgotPassword.php">Forgot Password</a></li>
</ul>
</form>';
}
else
{
echo '<ul class="sidemenu">
<li>' . $_SESSION['user'] . '</li>
<li><a href="' . $_SERVER["PHP_SELF"] . '?logout=true">Logout</a></li>
</ul>';
}
?>
```
The bug is that when I logout, the page remains the same, i.e. the login form does not show up but the same logout and user are shown. When I refresh the page, it gets normal. | When you log out, first, you are *queuing* the destruction of the cookie (it will occur after the response is sent), then immediately after, rendering your page. The browser has no chance to delete the cookie before rendering, and your `$_SESSION` variables are still alive.
PHP docs say about `session_destroy`:
> session\_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
A solution is to, instead of destroying the session and the cookie, simply unset the variables which would cause authentication:
```
unset($_SESSION['user']);
unset($_SESSION['lastActive']);
unset($_SESSION['fingerprint']);
```
Just a note: I would suggest splitting your code up into functions. This would make it much more organized and readable (and reusable if you do things right). | Some security notes:
```
if($matchingUser['inactive'] == 1)
```
is better written as
```
if(!$matchingUser['inactive'])
```
Because if the database schema changes (e.g. it's now an integer to indicate a certain type of activity (which is bad design, in my opinion: an enumeration would do better)) your code would have issues.
Of course, this is a double negative, which may be less readable. Better would be:
```
if($matchingUser['isactive'])
```
Or even:
```
if($matchingUser->isActive())
```
assuming you create a User class, etc. etc.
Just in case, use or `require` or `require_once` where necessary (preferably the latter if `connect.php` contains function declarations).
Store the user's ID in the session variable instead of the username. There is a possibility you will allow a user to change his name later on, and the session data would be invalid (at least `['user']` would, anyway). It's also faster to find a database record by ID (primary key, unique) than it is to by username (maybe indexed, string).
Kicking me after 30 minutes is really annoying. You're not the only site I go to, and I may revisit later after doing some work (if I get called in to do something, for example, or take a lunch break).
Use `htmlspecialchars` to help prevent XSS.
No need to use `$_SERVER['PHP_SELF']` here:
```
<a href="' . $_SERVER["PHP_SELF"] . '?logout=true">
```
Simply write without it:
```
<a href="?logout=true">
```
When the user POSTs something, make sure to redirect them (TODO: note how). Otherwise, the user's back button may cause a re-POST of the data (which probably isn't what you want!). | Is this code secure? | [
"",
"php",
"security",
"session",
"authentication",
"session-variables",
""
] |
I've set up a SOAP WebServiceProvider in JAX-WS, but I'm having trouble figuring out how to get the raw XML from a SOAPMessage (or any Node) object. Here's a sample of the code I've got right now, and where I'm trying to grab the XML:
```
@WebServiceProvider(wsdlLocation="SoapService.wsdl")
@ServiceMode(value=Service.Mode.MESSAGE)
public class SoapProvider implements Provider<SOAPMessage>
{
public SOAPMessage invoke(SOAPMessage msg)
{
// How do I get the raw XML here?
}
}
```
Is there a simple way to get the XML of the original request? If there's a way to get the raw XML by setting up a different type of Provider (such as Source), I'd be willing to do that, too. | It turns out that one can get the raw XML by using Provider<Source>, in this way:
```
import java.io.ByteArrayOutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceProvider;
@ServiceMode(value=Service.Mode.PAYLOAD)
@WebServiceProvider()
public class SoapProvider implements Provider<Source>
{
public Source invoke(Source msg)
{
StreamResult sr = new StreamResult();
ByteArrayOutputStream out = new ByteArrayOutputStream();
sr.setOutputStream(out);
try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(msg, sr);
// Use out to your heart's desire.
}
catch (TransformerException e) {
e.printStackTrace();
}
return msg;
}
}
```
I've ended up not needing this solution, so I haven't actually tried this code myself - it might need some tweaking to get right. But I know this is the right path to go down to get the raw XML from a web service.
(I'm not sure how to make this work if you absolutely must have a SOAPMessage object, but then again, if you're going to be handling the raw XML anyways, why would you use a higher-level object?) | You could try in this way.
```
SOAPMessage msg = messageContext.getMessage();
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
String strMsg = new String(out.toByteArray());
``` | Getting Raw XML From SOAPMessage in Java | [
"",
"java",
"soap",
"jax-ws",
""
] |
<http://en.wikipedia.org/wiki/Upsert>
[Insert Update stored proc on SQL Server](https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server)
Is there some clever way to do this in SQLite that I have not thought of?
Basically I want to update three out of four columns if the record exists. If it does not exist, I want to INSERT the record with the default (NULL) value for the fourth column.
The ID is a primary key, so there will only ever be one record to UPSERT.
(I am trying to avoid the overhead of SELECT in order to determine if I need to UPDATE or INSERT obviously)
Suggestions?
---
I cannot confirm that syntax on the SQLite site for TABLE CREATE.
I have not built a demo to test it, but it doesn't seem to be supported.
If it was, I have three columns so it would actually look like:
```
CREATE TABLE table1(
id INTEGER PRIMARY KEY ON CONFLICT REPLACE,
Blob1 BLOB ON CONFLICT REPLACE,
Blob2 BLOB ON CONFLICT REPLACE,
Blob3 BLOB
);
```
but the first two blobs will not cause a conflict, only the ID would
So I assume Blob1 and Blob2 would not be replaced (as desired)
---
UPDATEs in SQLite when binding data are a complete transaction, meaning
Each sent row to be updated requires: Prepare/Bind/Step/Finalize statements unlike the INSERT which allows the use of the reset function
The life of a statement object goes something like this:
1. Create the object using sqlite3\_prepare\_v2()
2. Bind values to host parameters using sqlite3\_bind\_ interfaces.
3. Run the SQL by calling sqlite3\_step()
4. Reset the statement using sqlite3\_reset() then go back to step 2 and repeat.
5. Destroy the statement object using sqlite3\_finalize().
UPDATE I am guessing is slow compared to INSERT, but how does it compare to SELECT using the Primary key?
Perhaps I should use the select to read the 4th column (Blob3) and then use REPLACE to write a new record blending the original 4th Column with the new data for the first 3 columns? | Assuming three columns in the table: ID, NAME, ROLE
---
**BAD:** This will insert or replace all columns with new values for ID=1:
```
INSERT OR REPLACE INTO Employee (id, name, role)
VALUES (1, 'John Foo', 'CEO');
```
---
**BAD:** This will insert or replace 2 of the columns... the NAME column will be set to NULL or the default value:
```
INSERT OR REPLACE INTO Employee (id, role)
VALUES (1, 'code monkey');
```
---
**GOOD**: Use SQLite On conflict clause
[UPSERT support in SQLite!](https://www.sqlite.org/draft/lang_UPSERT.html) UPSERT syntax was added to SQLite with version 3.24.0!
UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL.
[](https://i.stack.imgur.com/h475O.gif)
**GOOD but tedious:** This will update 2 of the columns.
When ID=1 exists, the NAME will be unaffected.
When ID=1 does not exist, the name will be the default (NULL).
```
INSERT OR REPLACE INTO Employee (id, role, name)
VALUES ( 1,
'code monkey',
(SELECT name FROM Employee WHERE id = 1)
);
```
This will update 2 of the columns.
When ID=1 exists, the ROLE will be unaffected.
When ID=1 does not exist, the role will be set to 'Benchwarmer' instead of the default value.
```
INSERT OR REPLACE INTO Employee (id, name, role)
VALUES ( 1,
'Susan Bar',
COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer')
);
``` | INSERT OR REPLACE is *NOT* equivalent to "UPSERT".
Say I have the table Employee with the fields id, name, and role:
```
INSERT OR REPLACE INTO Employee ("id", "name", "role") VALUES (1, "John Foo", "CEO")
INSERT OR REPLACE INTO Employee ("id", "role") VALUES (1, "code monkey")
```
Boom, you've lost the name of the employee number 1. SQLite has replaced it with a default value.
The expected output of an UPSERT would be to change the role and to keep the name. | UPSERT *not* INSERT or REPLACE | [
"",
"sql",
"sqlite",
"upsert",
""
] |
I wanna make use of the Ternary Operator with an object.
```
if($msg == 'hello'){
$o->setHello('hello');
else
$o->setHello('bye');
```
How could I do that?
Thanks | Try this:
```
($msg == 'hello') ? $o->setHello('hello') : $o->setHello('bye');
``` | ```
$o->setHello($msg == 'hello' ? 'hello' : 'bye');
``` | Object and Ternary Operator PHP | [
"",
"php",
"object",
""
] |
Im porting a project from php to java. The project is a web-app based on php and ajax techniques with a javascript front-end. What java-frameworks would you use for something like this? | Does the result have to be written in Java, or does it just have to run on the JVM? In the latter case, you might want to consider [Grails](http://grails.org/), which uses Groovy, a Java-based dynamic language that compiles to Java byte code and has full access to the Java standard API. | How well do you know Java?
Why are you porting it?
I can't really tell based on your description, but there are lots of [Java web frameworks](http://java-source.net/open-source/web-frameworks) out there. Pick one. I prefer Spring.
I fear that you're about to be very disappointed. I anticipate a lot of questions like "Why can't I do X in Java? It's easy in PHP!" | Porting from PHP to Java - framework recommendations? | [
"",
"java",
"frameworks",
""
] |
So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?
I don't see a way by using the for each and for range techniques. | ```
for x in thousand[400:500]:
pass
```
If you are working with an iterable instead of a list, you should use [itertools](http://docs.python.org/library/itertools):
```
import itertools
for x in itertools.islice(thousand, 400, 500):
pass
```
If you need to loop over `thousand[500]`, then use 501 as the latter index. This will work even if `thousand[501]` is not a valid index. | ```
for element in allElements[400:501]:
# do something
```
These are [slices](http://docs.python.org/reference/expressions.html#id8) and generate a sublist of the whole list. They are one of the main elements of Python. | Is there a way to loop through a sub section of a list in Python | [
"",
"python",
"loops",
"list",
""
] |
I've singled out a failure on my program that prevents me from assigning a value to the variable `addAntonymAnswer1`. I've tried running `cin.clear()` before the statement to get the thing read my `yes/no` answer, but the code just won't respond.
The program bit that's failing is located inside `void dictionaryMenu(vector <WordInfo> &wordInfoVector)` and reads
```
cin.clear();
cout<<">";
cin>>addAntonymAnswer1;
// cin reading STUCK, why!?
```
to get to that point of the program the user has to choose to add a word, and then add a synonym.
The input for running the program is:
```
dictionary.txt
1 cute
2 hello
3 ugly
4 easy
5 difficult
6 tired
7 beautiful
synonyms
1 7
7 1
3 2
antonyms
1 3
3 1 7
4 5
5 4
7 3
```
---
```
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
class WordInfo{
public:
WordInfo(){}
WordInfo(string newWord){
word=newWord;
}
~WordInfo() { }
int id() const {return myId;}
void readWords(istream &in)
{
in>>myId>>word;
}
vector <int> & getSynonyms () {
return mySynonyms;
}
vector <int> & getAntonyms() {
return myAntonyms;
}
string getWord() {
return word;
}
void dictionaryMenu (vector <WordInfo> &wordInfoVector){
cout<<endl<<"Would you like to add a word?"<<endl;
cout<<"(yes/no)"<<endl;
cout<<">";
string addWordAnswer;
cin>>addWordAnswer;
if (addWordAnswer=="yes")
// case if the guy wants to add a word
{
cout<<endl;
cout<<"Please, write the word "<<endl;
string newWord;
cout<<">";
cin>>newWord;
cout<<endl;
WordInfo newWordInfo (newWord);
int newWordId = wordInfoVector.size() +1;
newWordInfo.myId=newWordId;
cout<<"The id of "<<newWordInfo.word<<" is "<<newWordInfo.myId<<endl<<endl;
wordInfoVector.push_back(newWordInfo);
cout<<"Would you like to define which words on the existing dictionary are" <<endl
<<"synonyms of "<<newWordInfo.word<<"?"<<endl;
cout<<"(yes/no)"<<endl;
string addSynonymAnswer, addAntonymAnswer1, addAntonymAnswer2;
cout<<">";
cin>>addSynonymAnswer;
if (addSynonymAnswer=="yes")
{
cout<<endl;
cout<<"Please write on a single line the ids for the synonyms of "
<<newWordInfo.word<<endl<<"starting with its id, which is "<<newWordInfo.myId<<endl<<endl;
cout<<"For example, to define that the synonym of the word 'cute', which has an id 1, is"
<<"'beautiful', which has an id 7, you should write: 1 7"<<endl<<endl;
cout<<"In the case of "<<newWordInfo.word<<" you should start with "<<newWordInfo.myId<<endl;
cin.clear();
string lineOfSyns;
cout<<">";
cin>>lineOfSyns;
newWordInfo.pushSynonyms(lineOfSyns, wordInfoVector);
cin.clear();
cout<<"Would you like to define which words on the existing dictionary are" <<endl
<<"antonyms of "<<newWordInfo.word<<"?"<<endl;
//##HERE THE CIN READING OF addAntonymAnswer1 FAILS, WHY?
cin.clear();
cout<<">";
cin>>addAntonymAnswer1;
// cin reading STUCK, why!?
if (addAntonymAnswer1=="yes"){ }
else if (addAntonymAnswer1=="no"){
// END DICTIONARY MENU
}
}
else if (addSynonymAnswer=="no"){
cout<<"Would you like to define which words on the existing dictionary are" <<endl
<<"antonyms of "<<newWordInfo.word<<"?"<<endl;
cout<<">";
cin>>addAntonymAnswer2;
if (addAntonymAnswer2=="yes"){ }
else if (addAntonymAnswer2=="no"){
// END DICTIONARY MENU
}
}
} // if addWordAnswer == "no"
else if (addWordAnswer=="no"){
// ######RETURN TO MAIN MENU############
}
}
void pushSynonyms (string synline, vector<WordInfo> &wordInfoVector){
stringstream synstream(synline);
vector<int> synsAux;
// synsAux tiene la línea de sinónimos
int num;
while (synstream >> num) {synsAux.push_back(num);}
int wordInfoVectorIndex;
int synsAuxCopyIndex;
if (synsAux.size()>=2){ // takes away the runtime Error
for (wordInfoVectorIndex=0; wordInfoVectorIndex <wordInfoVector.size(); wordInfoVectorIndex++)
{
if (synsAux[0]==wordInfoVector[wordInfoVectorIndex].id()){
// this is the line that's generating a Runtime Error, Why?
for (synsAuxCopyIndex=1; synsAuxCopyIndex<synsAux.size(); synsAuxCopyIndex++){
// won't run yet
wordInfoVector[wordInfoVectorIndex].mySynonyms.push_back(synsAux[synsAuxCopyIndex]);
}
}
}
}// end if size()>=2
} // end pushSynonyms
void pushAntonyms (string antline, vector <WordInfo> &wordInfoVector)
{
stringstream antstream(antline);
vector<int> antsAux;
int num;
while (antstream >> num) antsAux.push_back(num);
int wordInfoVectorIndex;
int antsAuxCopyIndex;
if (antsAux.size()>=2){ // takes away the runtime Error
for (wordInfoVectorIndex=0; wordInfoVectorIndex <wordInfoVector.size(); wordInfoVectorIndex++)
{
if (antsAux[0]==wordInfoVector[wordInfoVectorIndex].id()){
// this is the line that's generating a Runtime Error, Why?
for (antsAuxCopyIndex=1; antsAuxCopyIndex<antsAux.size(); antsAuxCopyIndex++){
// won't run yet
wordInfoVector[wordInfoVectorIndex].myAntonyms.push_back(antsAux[antsAuxCopyIndex]);
}
}
}
}// end if size()>=2
}
//--dictionary output function
void printWords (ostream &out)
{
out<<myId<< " "<<word;
}
//--equals operator for String
bool operator == (const string &aString)const
{
return word ==aString;
}
//--less than operator
bool operator <(const WordInfo &otherWordInfo) const
{ return word<otherWordInfo.word;}
//--more than operator
bool operator > (const WordInfo &otherWordInfo)const
{return word>otherWordInfo.word;}
public:
vector<int> mySynonyms;
vector <int> myAntonyms;
string word;
int myId;
};
//--Definition of input operator for WordInfo
istream & operator >>(istream &in, WordInfo &word)
{
word.readWords(in);
}
//--Definition of output operator
ostream & operator <<(ostream &out, WordInfo &word)
{
word.printWords(out);
}
int main() {
string wordFile;
cout<<"enter name of dictionary file: "<<endl;
getline (cin,wordFile);
ifstream inStream (wordFile.data());
if(!inStream.is_open())
{
cerr<<"cannot open "<<wordFile<<endl;
exit(1);
}
vector <WordInfo> wordInfoVector;
WordInfo aword;
while (inStream >>aword && (!(aword=="synonyms")))
{
wordInfoVector.push_back(aword);
}
inStream.clear();
vector <int> intVector;
string synLine;
while (getline(inStream, synLine)&&(synLine!=("antonyms"))){
aword.pushSynonyms(synLine, wordInfoVector);
}
int theIndex;
string antLine;
while (getline(inStream,antLine)){
aword.pushAntonyms(antLine, wordInfoVector);
}
cout<<endl<<"the words on the dictionary are: "<<endl;
int h=0;
while (h<wordInfoVector.size()){
cout<<wordInfoVector[h]<<endl;
h++;
}
aword.dictionaryMenu(wordInfoVector);
system("PAUSE");
return 0;
}
``` | `cin.clear()` doesn't clear the standard input. What it does is clearing error bits, like `eofbit`, `failbit` and others, and sets the stream into a good state. Maybe you expected it to clear out anything in it? If the user typed
```
yes no
```
Just before, and you
```
cin >> someStringVariable;
```
It will read up to `no` and the stream will still contain
```
no
```
The call to `clear` then clears any error bits being active. Then, your
```
cin>>addAntonymAnswer1;
```
Will read the `no` that wasn't eaten by the previous read, and the action immediately returns, not waiting for new input. What you should do is doing a `clear` followed by an ignore, up to the next newline. You tell it the amount of characters it should ignore maximally. That amount should be the highest number possible:
```
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
```
Doing that will make the stream empty, and a following read will wait for you to type something in.
---
Another problem arises if you have got a `cin >>` followed by a `getline`: The cin will leave any whitespace (also newlines) after its read token, but `getline` will stop reading after it hits such a newline. I see you have put `clear` after nearly everything. So i want to show you when you need it and when not. You don't need it when you sequence multiple `cin >>`. Assume you have in your buffer: "foo\nbar\n". Then you do the following reads
```
cin >> a; // 1
cin >> b; // 2
```
After the first, your buffer will contain "\nbar\n". That is, the newline is still in. The second `cin>>` will first skip all whitespace and newlines, so that it can cope with `\n` being at the front of `bar`. Now, you can also sequence multiple `getline` calls:
```
getline(cin, a);
getline(cin, b);
```
Getline will throw away the `\n` that it reads at the line end, but won't ignore newlines or whitespace at the begin. So, after the first getline, the buffer contains "bar\n". The second getline will correctly read "bar\n" too. Now, let's consider the case where you need the clear/ignore:
```
cin >> a;
getline(cin, b);
```
The first will leave the stream as "\nbar\n". The getline then will see immediately the `\n` at the begin, and will think it read an empty line. Thus, it will immediately continue and not wait for anything, leaving the stream as "bar\n". So, if you have a `getline` after a `cin>>` you should first execute the clear/ignore sequence, to clear out the newline. But between `getline` or `cin>>`'s, you should not do it. | It is "stuck" because it is waiting for input. cin is attached to the standard input handle for the program, you have to type something and hit enter. | Why is this cin reading jammed? | [
"",
"c++",
"cin",
""
] |
This is a double question: The correct answer will go to "How you do it in PHP" explaining if there is any advantage goes also counts if possible.
I'm just curious because I really don't know and I see it a lot in webpages.
Edit: I don't know the technical name, but for example here on Stackoverflow:
"`http://stackoverflow.com/posts/edit/522452`" is what I mean as *"folders"* (a term previously used in the title of the question). | If you're referring to `/posts/edit/522452`-style URLs as opposed to `/posts.asp?action=edit&postid=522452`-style URLs (or whatever it translates to on the back end), this is typically done through a URL rewriter, such as [`mod_rewrite`](http://httpd.apache.org/docs/2.0/misc/rewriteguide.html). A rule for that URL might look like this:
```
RewriteRule ^/posts/(\w+)/(\d+) /posts.asp?action=\1&postid=\2
```
The two primary advantages to this kind of URL are that:
1. "Folder"-type URLs are easier for people to type and to remember.
2. The page "looks like" a page to HTTP proxies. Traditionally, proxies don't cache pages with parameters, as they don't represent separate content and change too frequently (think search results). Using "folder-style" URLs allows them to be cached normally.
In PHP, you can then access these options via `$_GET['action']` and `$_GET['postid']`, exactly as if the browser had asked for the rewritten form. | To use such URLs you have to do three steps:
1. Tell you webserver, that those requests should redirected to your PHP script. With Apache you can use the [mod\_rewrite module](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) to do so:
```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php [L]
```
This directives redirect every request, that does not match a file in the filesystem, to `index.php`.
2. Get your script to parse those URLs:
```
$_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
var_dump($segments);
```
This is probably the easiest way to parse the URL path and get each path segment.
3. Use this URLs in your output. (trivial) | How do I do URL rewriting in php? | [
"",
"php",
"html",
"url-rewriting",
""
] |
I am making a C++ program.
One of my biggest annoyances with C++ is its supposed platform independence.
You all probably know that it is pretty much impossible to compile a Linux C++ program in Windows and a Windows one to Linux without a deluge of cryptic errors and platform specific include files.
Of course you can always switch to some emulation like Cygwin and wine, but I ask you, is there really no other way? | The language itself is cross-platform but most libraries are not, but there are three things that you should keep in mind if you want to go completely cross-platform when programming in C++.
Firstly, you need to start using some kind of cross-platform build system, like [SCons](http://www.scons.org/). Secondly, you need to make sure that all of the libraries that you are using are built to be cross-platform.
And a minor third point, I would recommend using a compiler that exists on all of your target platforms, [gcc](http://gcc.gnu.org/) comes in mind here (C++ is a rather complex beast and all compilers have their own specific quirks).
I have some further suggestions regarding graphical user interfaces for you. There are several of these available to use, the three most notable are:
* [GTK+](http://www.gtk.org/)
* [QT](http://qt.nokia.com/)
* [wxWidgets](http://www.wxwidgets.org/)
[GTK+](http://www.gtk.org/) and [QT](http://qt.nokia.com/) are two API's that come with their own widget sets (buttons, lists, etc.), whilst [wxWidgets](http://www.wxwidgets.org/) is more of a wrapper API to the currently running platforms native widget set. This means that the two former might look a bit differently compared to the rest of the system whilst the latter one will look just like a native program.
And if you're into games programming there are equally many API's to choose from, all of them cross-platform as well. The two most fully featured that I know of are:
* [SDL](http://www.libsdl.org/)
* [SFML](http://www.sfml-dev.org/)
Both of which contains everything from graphics to input and audio routines, either through plugins or built-in.
Also, if you feel that the standard library in C++ is a bit lacking, check out [Boost](http://www.boost.org/) for some general purpose cross-platform sweetness.
Good Luck. | C++ is cross platform. The problem you seem to have is that you are using platform dependent libraries.
I assume you are really talking about UI componenets- in which case I suggest using something like GTK+, Qt, or wxWindows- each of which have UI components that can be compiled for different systems.
The only solution is for you to find and use platform independent libraries.
And, on a side note, neither cygwin or Wine are emulation- they are 100% native implementations of the same functionality found their respective systems. | How do I write a C++ program that will easily compile in Linux and Windows? | [
"",
"c++",
"c",
"windows",
"linux",
"platform",
""
] |
We have a scenario where in if an entity exists between the source and target, we are supposed to merge data in the target i.e. copy values from foundation columns where the target column is blank.
We are using WCF servcie calls and we have the entity objects.
If i have an entity lets say `Staff`, staff conatins the basic properties for name, etc and we have a list for `StaffAddress`, `StaffEmail`, and `StaffPhone`.
So I just wanted to know is there a way using LINQ or any other mechanism - I can find out the list of property on the `Staff` object which are null or blank ?
One rudimentary way is to of course manually check one property by one which is blank ? | Here's a quick and dirty way to do it with LINQ
```
public static IEnumerable<string> FindBlankFields(Staff staff)
{
return staff.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic)
.Where(p => p.CanRead)
.Select(p => new { Property = p, Value = p.GetValue(staff, null) })
.Where(a => a.Value == null || String.IsNullOrEmpty(a.Value.ToString()))
.Select(a => a.Property.Name);
}
``` | You could get all the properties through reflection, and then call GetValue on each PropertyInfo instance. Where it is null, you would return the PropertyInfo:
```
static IEnumerable<PropertyInfo> GetNullProperties(object obj)
{
// Get the properties and return only the ones where GetValue
// does not return null.
return
from pi in obj.GetType().GetProperties(
BindingFlags.Instance | BindingFlags.Public)
where pi.GetValue(obj, null) != null
select pi;
}
```
Mind you, this will return only public properties on the type, not non public properties. | Finding blank fields in an object - C# | [
"",
"c#",
""
] |
I would like to get all the instances of an object of a certain class.
For example:
```
class Foo {
}
$a = new Foo();
$b = new Foo();
$instances = get_instances_of_class('Foo');
```
`$instances` should be either `array($a, $b)` or `array($b, $a)` (order does not matter).
A plus is if the function would return instances which have a superclass of the requested class, though this isn't necessary.
One method I can think of is using a static class member variable which holds an array of instances. In the class's constructor and destructor, I would add or remove `$this` from the array. This is rather troublesome and error-prone if I have to do it on many classes. | If you derive all your objects from a TrackableObject class, this class could be set up to handle such things (just be sure you call `parent::__construct()` and `parent::__destruct()` when overloading those in subclasses.
```
class TrackableObject
{
protected static $_instances = array();
public function __construct()
{
self::$_instances[] = $this;
}
public function __destruct()
{
unset(self::$_instances[array_search($this, self::$_instances, true)]);
}
/**
* @param $includeSubclasses Optionally include subclasses in returned set
* @returns array array of objects
*/
public static function getInstances($includeSubclasses = false)
{
$return = array();
foreach(self::$_instances as $instance) {
if ($instance instanceof get_class($this)) {
if ($includeSubclasses || (get_class($instance) === get_class($this)) {
$return[] = $instance;
}
}
}
return $return;
}
}
```
The major issue with this is that no object would be automatically picked up by garbage collection (as a reference to it still exists within `TrackableObject::$_instances`), so `__destruct()` would need to be called manually to destroy said object. (Circular Reference Garbage Collection was added in PHP 5.3 and may present additional garbage collection opportunities) | Here's a possible solution:
```
function get_instances_of_class($class) {
$instances = array();
foreach ($GLOBALS as $value) {
if (is_a($value, $class) || is_subclass_of($value, $class)) {
array_push($instances, $value);
}
}
return $instances;
}
```
**Edit**: Updated the code to check if the `$class` is a superclass.
**Edit 2**: Made a slightly messier recursive function that checks each object's variables instead of just the top-level objects:
```
function get_instances_of_class($class, $vars=null) {
if ($vars == null) {
$vars = $GLOBALS;
}
$instances = array();
foreach ($vars as $value) {
if (is_a($value, $class)) {
array_push($instances, $value);
}
$object_vars = get_object_vars($value);
if ($object_vars) {
$instances = array_merge($instances, get_instances_of_class($class, $object_vars));
}
}
return $instances;
}
```
I'm not sure if it can go into infinite recursion with certain objects, so beware... | Get all instances of a class in PHP | [
"",
"php",
"class",
"dynamic",
""
] |
Are any of the .NET generic collections marked as IXmlSerializable? I've tried List<T> and Collection<T> but neither work out of the box.
Before I roll my own collection<T>, list<T>, or dictionary<T> class, I thought I'd check to see whether Microsoft had included something that does this already. It seems like basic functionality.
EDIT: By "rolling my own" I mean creating a class that inherits from a generic collection class and also implements IXmlSerializable. Here's one example: <http://www.codeproject.com/KB/XML/IXmlSerializable.aspx>. And here's another example: <http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx>.
I'm using the DataContractSerializer within a method whose signature looks like this:
```
public static Stream GetXmlStream(IXmlSerializable item)
```
The problem is that while there are many classes in the .NET framework that are serializable, not all of them have explicitly implement the IXmlSerializable interface. | As far as I know, there aren't any. You could take a look at the attached link, though. I think you'll find it useful.
[Serialize and deserialize objects as Xml using generic types in C# 2.0](https://web.archive.org/web/20200204000600/http://geekswithblogs.net:80/paulwhitblog/archive/2007/07/20/114076.aspx) | There is no requirement to implement IXmlSerializable to **be** xml serializable.
```
public class Foo
{
public List<string> Names { get; set; }
}
```
will xml serialize just fine producing something like:
```
<?xml version="1.0" encoding="utf-16"?>
<Foo
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Names>
<string>a</string>
<string>b</string>
<string>c</string>
</Names>
</Foo>
```
whereas
```
public class Foo<T>
{
public List<T> Names { get; set; }
}
```
will produce
```
<?xml version="1.0" encoding="utf-16"?>
<FooOfString
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Names>
<string>a</string>
<string>b</string>
<string>c</string>
</Names>
</FooOfString>
``` | What generic collections in C# are IXmlSerializable? | [
"",
"c#",
"generics",
"serialization",
"collections",
""
] |
How do I do a Case WHEN in Linq to SQL (vb.net please).
In SQL it would be like this:
```
SELECT
CASE
WHEN condition THEN trueresult
[...n]
[ELSE elseresult]
END
```
How would I do this in Linq to SQL? | Check This Out
```
var data = from d in db.tb select new {
CaseResult = (
d.Col1 == “Case1” ? "Case 1 Rised" :
d.Col1 == “Case2” ? "Case 2 Rised" :
"Unknown Case")
};
```
Please Note that [ ? Symbol = then] , [ : Symbol = Or]. | ```
var data = from d in db.tb select new {
CaseResult = If (d.Col1 = “Case1”, "Case 1 Rised", If (d.Col1 = “Case2”, "Case 2 Rised", "Unknown Case"))
};
``` | Linq to SQL Case WHEN in VB.NET? | [
"",
"sql",
"linq",
"linq-to-sql",
"t-sql",
""
] |
I've been evaluating various smart pointer implementations (wow, there are a LOT out there) and it seems to me that most of them can be categorized into two broad classifications:
1) This category uses inheritance on the objects referenced so that they have reference counts and usually up() and down() (or their equivalents) implemented. IE, to use the smart pointer, the objects you're pointing at must inherit from some class the ref implementation provides.
2) This category uses a secondary object to hold the reference counts. For example, instead of pointing the smart pointer right at an object, it actually points at this meta data object... Who has a reference count and up() and down() implementations (and who usually provides a mechanism for the pointer to get at the actual object being pointed to, so that the smart pointer can properly implement operator ->()).
Now, 1 has the downside that it forces all of the objects you'd like to reference count to inherit from a common ancestor, and this means that you cannot use this to reference count objects that you don't have control over the source code to.
2 has the problem that since the count is stored in another object, if you ever have a situation that a pointer to an existing reference counted object is being converted into a reference, you probably have a bug (I.E., since the count is not in the actual object, there is no way for the new reference to get the count... ref to ref copy construction or assignment is fine, because they can share the count object, but if you ever have to convert from a pointer, you're totally hosed)...
Now, as I understand it, boost::shared\_pointer uses mechanism 2, or something like it... That said, I can't quite make up my mind which is worse! I have only ever used mechanism 1, in production code... Does anyone have experience with both styles? Or perhaps there is another way thats better than both of these? | > "What is the best way to implement smart pointers in C++"
1. **Don't!** Use an existing, well tested smart pointer, such as boost::shared\_ptr or std::tr1::shared\_ptr (std::unique\_ptr and std::shared\_ptr with C++ 11)
2. If you have to, then remember to:
1. use safe-bool idiom
2. provide an operator->
3. provide the strong exception guarantee
4. document the exception requirements your class makes on the deleter
5. use copy-modify-swap where possible to implement the strong exception guarantee
6. document whether you handle multithreading correctly
7. write extensive unit tests
8. implement conversion-to-base in such a way that it will delete on the derived pointer type (policied smart pointers / dynamic deleter smart pointers)
9. support getting access to raw pointer
10. consider cost/benifit of providing weak pointers to break cycles
11. provide appropriate casting operators for your smart pointers
12. make your constructor templated to handle constructing base pointer from derived.
And don't forget anything I may have forgotten in the above incomplete list. | Just to supply a different view to the ubiquitous Boost answer (even though it is the right answer for *many* uses), take a look at [Loki](http://loki-lib.sourceforge.net/index.php?n=Main.Idioms)'s implementation of smart pointers. For a discourse on the design philosophy, the original creator of Loki wrote the book [Modern C++ Design](http://en.wikipedia.org/wiki/Modern_C%2B%2B_Design). | What is the best way to implement smart pointers in C++? | [
"",
"c++",
"smart-pointers",
"c++03",
"raii",
"reference-counting",
""
] |
Just got a review comment that my static import of the method was not a good idea. The static import was of a method from a DA class, which has mostly static methods. So in middle of the business logic I had a da activity that apparently seemed to belong to the current class:
```
import static some.package.DA.*;
class BusinessObject {
void someMethod() {
....
save(this);
}
}
```
The reviewer was not keen that I change the code and I didn't but I do kind of agree with him. One reason given for not static-importing was it was confusing where the method was defined, it wasn't in the current class and not in any superclass so it too some time to identify its definition (the web based review system does not have clickable links like IDE :-) I don't really think this matters, static-imports are still quite new and soon we will all get used to locating them.
But the other reason, the one I agree with, is that an unqualified method call seems to belong to current object and should not jump contexts. But if it really did belong, it would make sense to extend that super class.
So, when *does* it make sense to static import methods? When have you done it? Did/do you like the way the unqualified calls look?
EDIT: The popular opinion seems to be that static-import methods if nobody is going to confuse them as methods of the current class. For example methods from java.lang.Math and java.awt.Color. But if abs and getAlpha are not ambiguous I don't see why readEmployee is. As in lot of programming choices, I think this too is a personal preference thing. | This is from Sun's guide when they released the feature (emphasis in original):
> So when should you use static import? **Very sparingly!** Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). ... If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually.
(<https://docs.oracle.com/javase/8/docs/technotes/guides/language/static-import.html>)
There are two parts I want to call out specifically:
* Use static imports **only** when you were tempted to "abuse inheritance". In this case, would you have been tempted to have BusinessObject `extend some.package.DA`? If so, static imports may be a cleaner way of handling this. If you never would have dreamed of extending `some.package.DA`, then this is probably a poor use of static imports. Don't use it just to save a few characters when typing.
* **Import individual members.** Say `import static some.package.DA.save` instead of `DA.*`. That will make it much easier to find where this imported method is coming from.
Personally, I have used this language feature *very* rarely, and almost always only with constants or enums, never with methods. The trade-off, for me, is almost never worth it. | Another reasonable use for static imports is with JUnit 4. In earlier versions of JUnit methods like `assertEquals` and `fail` were inherited since the test class extended `junit.framework.TestCase`.
```
// old way
import junit.framework.TestCase;
public class MyTestClass extends TestCase {
public void myMethodTest() {
assertEquals("foo", "bar");
}
}
```
In JUnit 4, test classes no longer need to extend `TestCase` and can instead use annotations. You can then statically import the assert methods from `org.junit.Assert`:
```
// new way
import static org.junit.Assert.assertEquals;
public class MyTestClass {
@Test public void myMethodTest() {
assertEquals("foo", "bar");
// instead of
Assert.assertEquals("foo", "bar");
}
}
```
JUnit [documents](http://junit.sourceforge.net/doc/cookbook/cookbook.htm) using it this way. | What is a good use case for static import of methods? | [
"",
"java",
"static-import",
""
] |
I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code.
Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?
From reading the [Jython site](http://jython.sourceforge.net/docs/differences.html), most of the problems seem too obscure to bother me.
I did notice that:
* thread safety is an issue
* Unicode support seems to be quite different, which may be a problem for me
* mysqldb doesn't work and needs to be replaced with zxJDBC
Anything else?
Related question: [What are some strategies to write python code that works in CPython, Jython and IronPython](https://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i) | I'm starting this as a wiki collected from the other answers and my experience. Feel free to edit and add stuff, but please try to stick to practical advice rather than a list of broken things. Here's an [old list of differences](https://jython.sourceforge.net/archive/21/docs/differences.html) from the Jython site.
## Resource management
Jython does not use reference counting, and so resources are released as they
are garbage collected, which is much later then you'd see in the equivalent
CPython program
* `open('file').read()` doesn't automatically close the file.
Better use the `with open('file') as fp` idiom.
* The \_\_ del \_\_ method is invoked very late in Jython code, not immediately
after the last reference to the object is deleted.
## MySQL Integration
`mysqldb` is a c module, and therefore will not work in jython. Instead, you
should use `com.ziclix.python.sql.zxJDBC`, which comes bundled with Jython.
Replace the following MySQLdb code:
```
connection = MySQLdb.connect(host, user, passwd, db, use_unicode=True, chatset='utf8')
```
With:
```
url = "jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull" % (host, db)
connections = zxJDBC.connect(url, user, passwd, "com.mysql.jdbc.Driver")
```
You'll also need to replace all `_mysql_exception` with `zxJDBC`.
Finally, you'll need to replace the query placeholders from `%s` to `?`.
## Unicode
* You can't express illegal unicode characters in Jython. Trying something
like `unichr(0xd800)` would cause an exception, and having a literal `u'\ud800'`
in your code will just wreak havoc.
## Missing things
* C modules are not available, of course.
+ So no [NumPy](https://numpy.org/) or [SciPy](https://scipy.org/).
* os.spawn\* functions are not implemented. Instead use subprocess.call.
## Performance
* For most workloads, Jython will be much slower than CPython. Reports are
anything between 3 to 50 times slower.
## Community
The Jython project is still alive, but is not fast-moving. The
[dev mailing list](https://sourceforge.net/p/jython/mailman/jython-dev/)
has about 20 messages a month, and there seem to be only about 2 developers
commiting code lately. | First off, I have to say the Jython implementation is very good. Most things "just work".
Here are a few things that I have encountered:
* C modules are not available, of course.
* open('file').read() doesn't automatically close the file. This has to do with the difference in the garbage collector. This can cause issues with too many open files. It's better to use the "with open('file') as fp" idiom.
* Setting the current working directory (using os.setcwd()) works for Python code, but not for Java code. It emulates the current working directory for everything file-related but can only do so for Jython.
* XML parsing will try to validate an external DTD if it's available. This can cause massive slowdowns in XML handling code because the parser will download the DTD over the network. I [reported this issue](http://bugs.jython.org/issue1268), but so far it remains unfixed.
* The \_\_ del \_\_ method is invoked very late in Jython code, not immediately after the last reference to the object is deleted.
There is an [old list of differences](http://jython.sourceforge.net/archive/21/docs/differences.html), but a recent list is not available. | Migrating from CPython to Jython | [
"",
"python",
"migration",
"jython",
"cpython",
""
] |
This is what I need to do:
```
object foo = GetFoo();
Type t = typeof(BarType);
(foo as t).FunctionThatExistsInBarType();
```
Can something like this be done? | No, you cannot. C# does not implement [duck typing](http://en.wikipedia.org/wiki/Duck_typing).
You must implement an interface and cast to it.
(However there are attempts to do it. Look at [Duck Typing Project](http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx) for an example.) | You can use the [Convert.ChangeType](http://msdn.microsoft.com/en-us/library/dtb69x08.aspx) method.
```
object foo = GetFoo();
Type t = typeof(string);
string bar = (string)Convert.ChangeType(foo, t);
``` | Is possible to cast a variable to a type stored in another variable? | [
"",
"c#",
"casting",
""
] |
I have a list of items
* John ID
* Matt ID
* John ID
* Scott ID
* Matt ID
* John ID
* Lucas ID
I want to shove them back into a list like so which also means I want to sort by the highest number of duplicates.
* John ID 3
* Matt ID 2
* Scott ID 1
* Lucas ID 1
Let me know how I can do this with LINQ and C#.
Thanks All
**EDIT 2 Showing Code:**
```
List<game> inventory = new List<game>();
drinkingforDataContext db = new drinkingforDataContext();
foreach (string item in tbTitle.Text.Split(' '))
{
List<game> getItems = (from dfg in db.drinkingfor_Games
where dfg.game_Name.Contains(tbTitle.Text)
select new game
{
gameName = dfg.game_Name,
gameID = Boomers.Utilities.Guids.Encoder.EncodeURLs(dfg.uid)
}).ToList<game>();
for (int i = 0; i < getItems.Count(); i++)
{
inventory.Add(getItems[i]);
}
}
var items = (from xx in inventory
group xx by xx into g
let count = g.Count()
orderby count descending
select new
{
Count = count,
gameName = g.Key.gameName,
gameID = g.Key.gameID
});
lvRelatedGames.DataSource = items;
lvRelatedGames.DataBind();
```
This query displays these results:
* 1 hello world times
* 1 hello world times
* 1 Hello World.
* 1 hello world times
* 1 hello world times
* 1 hello world times
* 1 Hello World.
* 1 hello world times
It gives me the count and name, but it doesn't give me the ID of the game....
It should display:
* 6 hello world times 234234
* 2 Hello World. 23432432 | You can use "group by" + "orderby". See [LINQ 101](http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx) for details
```
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
group x by x into g
let count = g.Count()
orderby count descending
select new {Value = g.Key, Count = count};
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
```
**In response to [this post](https://stackoverflow.com/questions/454601/how-to-count-duplicates-in-list-with-linq#454652) (now deleted):**
If you have a list of some custom objects then you need to use [custom comparer](http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#comparer) or group by specific property.
Also query can't display result. Show us complete code to get a better help.
**Based on your latest update:**
You have this line of code:
```
group xx by xx into g
```
Since xx is a custom object system doesn't know how to compare one item against another.
As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:
Note that I use **Foo.Name** as a key - i.e. objects will be grouped based on value of **Name** property.
There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.
```
//Using extension methods
var q = list.GroupBy(x => x.Name)
.Select(x => new {Count = x.Count(),
Name = x.Key,
ID = x.First().ID})
.OrderByDescending(x => x.Count);
//Using LINQ
var q = from x in list
group x by x.Name into g
let count = g.Count()
orderby count descending
select new {Name = g.Key, Count = count, ID = g.First().ID};
foreach (var x in q)
{
Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}
``` | Slightly shorter version using methods chain:
```
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
.Select(g => new {Value = g.Key, Count = g.Count()})
.OrderByDescending(x=>x.Count);
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
``` | How to count duplicates based on a property in a list of objects with LINQ | [
"",
"c#",
"linq",
""
] |
I need to find out the CPU utilization of a service DLL. I have looked in existing samples and we can find CPU utilization for processes.
I think DLL will be loaded by services.exe. So is it possible to find out CPU utilization by DLL.
I am working in C++ on the Windows platform. | Make a copy of svchost.exe and call it dbgsrvc.exe; then, go into the service entry in the registry (HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog for example), and change the ImagePath to use dbgsrvc instead of services. That way, you've isolated your service into its own process so you can get perf counters on it. | Try this:
1. Use Perfmon to log all counters for the process object.
2. Before or after your test, run `tasklist /svc` from a command console. Look through the output for the svchost.exe that's hosting your service. Note the PID of this process.
3. After the test, use Perfmon to load your log file, the add the process measurements for the process in step 2. | CPU Utilization of Service DLL? | [
"",
"c++",
"windows",
"cpu",
"utilization",
""
] |
I want to distribute a command-line application written in Java on Windows.
My application is distributed as a zip file, which has a lib directory entry which has the .jar files needed for invoking my main class. Currently, for Unix environments, I have a shell script which invokes the java command with a CLASSPATH created by appending all files in lib directory.
How do I write a .BAT file with similar functionality? What is the equivalent of find Unix command in Windows world? | You want to use the for loop in Batch script
```
@echo off
setLocal EnableDelayedExpansion
set CLASSPATH="
for /R ./lib %%a in (*.jar) do (
set CLASSPATH=!CLASSPATH!;%%a
)
set CLASSPATH=!CLASSPATH!"
echo !CLASSPATH!
```
This really helped me when I was looking for a batch script to iterate through all the files in a directory, it's about deleting files but it's very useful.
[One-line batch script to delete empty directories](http://blogs.msdn.com/oldnewthing/archive/2008/04/17/8399914.aspx)
To be honest, use Jon's answer though, far better if all the files are in one directory, this might help you out at another time though. | Why would you use find? Presumably you know all the libraries your jar file needs ahead of time, so why not just list them?
Alternatively, you could always use `-Djava.ext.dirs=lib` and let it pick up everything that way. | BAT file to create Java CLASSPATH | [
"",
"java",
"windows",
"command-line",
"batch-file",
""
] |
I am using in my code at the moment a [ReentrantReadWriteLock](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html) to synchronize access over a tree-like structure. This structure is large, and read by many threads at once with occasional modifications to small parts of it - so it seems to fit the read-write idiom well. I understand that with this particular class, one cannot elevate a read lock to a write lock, so as per the Javadocs one must release the read lock before obtaining the write lock. I've used this pattern successfully in non-reentrant contexts before.
What I'm finding however is that I cannot reliably acquire the write lock without blocking forever. Since the read lock is reentrant and I am actually using it as such, the simple code
```
lock.getReadLock().unlock();
lock.getWriteLock().lock()
```
can block if I have acquired the readlock reentrantly. Each call to unlock just reduces the hold count, and the lock is only actually released when the hold count hits zero.
**EDIT** to clarify this, as I don't think I explained it too well initially - I am aware that there is no built-in lock escalation in this class, and that I have to simply release the read lock and obtain the write lock. My problem is/was that regardless of what other threads are doing, calling `getReadLock().unlock()` may not actually release *this* thread's hold on the lock if it acquired it reentrantly, in which case the call to `getWriteLock().lock()` will block forever as this thread still has a hold on the read lock and thus blocks itself.
For example, this code snippet will never reach the println statement, even when run singlethreaded with no other threads accessing the lock:
```
final ReadWriteLock lock = new ReentrantReadWriteLock();
lock.getReadLock().lock();
// In real code we would go call other methods that end up calling back and
// thus locking again
lock.getReadLock().lock();
// Now we do some stuff and realise we need to write so try to escalate the
// lock as per the Javadocs and the above description
lock.getReadLock().unlock(); // Does not actually release the lock
lock.getWriteLock().lock(); // Blocks as some thread (this one!) holds read lock
System.out.println("Will never get here");
```
So I ask, is there a nice idiom to handle this situation? Specifically, when a thread that holds a read lock (possibly reentrantly) discovers that it needs to do some writing, and thus wants to "suspend" its own read lock in order to pick up the write lock (blocking as required on other threads to release their holds on the read lock), and then "pick up" its hold on the read lock in the same state afterwards?
Since this ReadWriteLock implementation was specifically designed to be reentrant, surely there is some sensible way to elevate a read lock to a write lock when the locks may be acquired reentrantly? This is the critical part that means the naive approach does not work. | I have made a little progress on this. By declaring the lock variable explicitly as a `ReentrantReadWriteLock` instead of simply a `ReadWriteLock` (less than ideal, but probably a necessary evil in this case) I can call the [`getReadHoldCount()`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html#getReadHoldCount()) method. This lets me obtain the number of holds for the current thread, and thus I can release the readlock this many times (and reacquire it the same number afterwards). So this works, as shown by a quick-and-dirty test:
```
final int holdCount = lock.getReadHoldCount();
for (int i = 0; i < holdCount; i++) {
lock.readLock().unlock();
}
lock.writeLock().lock();
try {
// Perform modifications
} finally {
// Downgrade by reacquiring read lock before releasing write lock
for (int i = 0; i < holdCount; i++) {
lock.readLock().lock();
}
lock.writeLock().unlock();
}
```
Still, is this going to be the best I can do? It doesn't feel very elegant, and I'm still hoping that there's a way to handle this in a less "manual" fashion. | This is an old question, but here's both a solution to the problem, and some background information.
As others have pointed out, a classic [readers-writer lock](http://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock) (like the JDK [ReentrantReadWriteLock](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html)) inherently does not support upgrading a read lock to a write lock, because doing so is susceptible to deadlock.
If you need to safely acquire a write lock without first releasing a read lock, there is a however a better alternative: take a look at a *read-write-**update*** lock instead.
I've written a ReentrantReadWrite\_Update\_Lock, and released it as open source under an Apache 2.0 license [here](https://github.com/npgall/concurrent-locks). I also posted details of the approach to the JSR166 [concurrency-interest mailing list](http://cs.oswego.edu/pipermail/concurrency-interest/2013-July/011621.html), and the approach survived some back and forth scrutiny by members on that list.
The approach is pretty simple, and as I mentioned on concurrency-interest, the idea is not entirely new as it was discussed on the Linux kernel mailing list at least as far back as the year 2000. Also the .Net platform's [ReaderWriterLockSlim](http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx) supports lock upgrade also. So effectively this concept had simply not been implemented on Java (AFAICT) until now.
The idea is to provide an *update* lock in addition to the *read* lock and the *write* lock. An update lock is an intermediate type of lock between a read lock and a write lock. Like the write lock, only one thread can acquire an update lock at a time. But like a read lock, it allows read access to the thread which holds it, and concurrently to other threads which hold regular read locks. The key feature is that the update lock can be upgraded from its read-only status, to a write lock, and this is not susceptible to deadlock because only one thread can hold an update lock and be in a position to upgrade at a time.
This supports lock upgrade, and furthermore it is more efficient than a conventional readers-writer lock in applications with *read-before-write* access patterns, because it blocks reading threads for shorter periods of time.
Example usage is provided on the [site](https://github.com/npgall/concurrent-locks). The library has 100% test coverage and is in Maven central. | Java ReentrantReadWriteLocks - how to safely acquire write lock when in a read lock? | [
"",
"java",
"concurrency",
"reentrantreadwritelock",
""
] |
I've got a ComboBox in WPF that I've mucked around with quite a lot (it has a custom template and a custom item template). I've got it to the point now where it is working pretty much how I want it, except that when I type into the ComboBox it is doing the filtering for me, but only filters assuming what I type starts the name of the item in the ComboBox.
For example if I have an item in the ComboBox called "Windows Media Player" it will only find it if I start typing "Windows Media..." and it won't find it if I start typing "Media Play...". Is there any way around this? Can I set a property somewhere to tell it to search in the whole string rather than just using StartsWith()?
If not, what would be the best way to go about making it do this by myself? Is there some way to take the original control and basically just change the call to StartsWith() to a call to Contains(), or would I have to go far more low-level? | Check out the following article in CodeProject:
[A Reusable WPF Autocomplete TextBox](http://www.codeproject.com/KB/WPF/autocomplete_textbox.aspx) | The combobox now supports autocomplete, just make sure in the xaml for the combobox put
```
IsEditable="True"
``` | Autocomplete for ComboBox in WPF anywhere in text (not just beginning) | [
"",
"c#",
".net",
"wpf",
"combobox",
""
] |
i'm developing a simple C# Editor for one of my university courses and I need to send a .cs file to Compiler and collect errors (if they exist) and show them in my app. In other words i want to add a C# Compiler to my Editor. Is there anything like this for the debugger? | If you use the CodeDomProvider
```
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
// the compilation part
// change the parameters as you see fit
CompilerParameters cp = CreateCompilerParameters();
var options = new System.Collections.Generic.Dictionary<string, string>();
if (/* you want to use the 3.5 compiler*/)
{
options.Add("CompilerVersion", "v3.5");
}
var compiler = new CSharpCodeProvider(options);
CompilerResults cr = compiler.CompileAssemblyFromFile(cp,filename);
if (cr.Errors.HasErrors)
{
foreach (CompilerError err in cr.Errors)
{
// do something with the error/warning
}
}
``` | Use the `System.Diagnostics.Process` class to start a generic process and collect the I/O from standard input/output.
For this specific scenario, I suggest you look at `Microsoft.CSharp.CSharpCodeProvider` class. It'll do the task for you. | Access to Compiler's errors and warnings | [
"",
"c#",
""
] |
I've already looked at [this question](https://stackoverflow.com/questions/88904/error-creating-window-handle), and I've already checked out the suggestions that were made there. My program creates and destroys a lot of UI controls (a *lot* of UI controls), and anything that makes controls hang around after they're "destroyed" will cause this problem. (Fun fact: if you don't set a `ToolStrip` control's `Visible` property to false before you destroy its container, it doesn't get disposed, because it's still registered with Windows to receive theme-change events; it only unregisters itself when it's not visible, and it apparently doesn't have any way of knowing that this is happening when its container is being destroyed.)
The thing is, it's actually possible that my application really is running out of window handles. The program's got a single form that has nested tab controls. Each parent tab has 12 or 13 child tabs, and a child tab can have 30 or 40 controls on it. It's quite possible for the user to have 15 parent tabs open at any given time, and that's getting into the territory of 5000+ live controls in the application. And I know that many of my controls use more than one window handle.
(And before you say "well, it looks like you've designed the UI wrong," let me disabuse of that: the whole reason the application exists in the first place is that the users have an enormous space of data that they need to be able to navigate to quickly. The tabs-within-tabs thing actually works really well for them.)
My understanding is that there's a hard limit of 10,000 window handles per application. If that's actually true (I understand a lot of things to be true that aren't), then I'm going to have to manage my app's use of them. I can, for instance, throw away the contents of the least recently used tab when I start running low on window handles.
But how do I tell that I've started running low on window handles? And is this really the right approach to the problem?
(This is but one of the many reasons that I'd like to rebuild this UI in WPF.) | I've fixed this problem, which I've described in detail in [this answer](https://stackoverflow.com/questions/143206/how-do-you-obtain-current-window-handle-count-and-window-handle-limit-in-net/534991#534991). I answered it there instead of here mostly because I got mad(der) at Raymond Chen when I read the other responses to the question.
The short answer:
1. Maintain an [LRU cache](http://csharp-lru-cache.googlecode.com) of tab pages that gets updated whenever the user visits one.
2. Count the window handles in use before creating a new tab page.
3. If too many window handles are in use, dispose the contents of least-recently-visited tab pages until the number of window handles in use gets down to a safe level. | The best approach is to reduce the number of handles rather than to react to reaching the process limit. This will provide better performance and (in my opinion) will be more reliable.
Are you familiar with how most grid controls work? A grid can have a very large number of cells, but the grid control doesn't create an editbox (control) for each cell. There is just one editbox and it is moved around as needed; if a cell is a combo box (drop down list), then one combo box is created and moved around; etc. This means you need to draw something that looks like the desired control, but you only need one (each) of the controls in actual use.
Similarly, some tab controls use a single window/control, rather than creating one window for each tab.
I would suggest considering techniques like these to reduce your control count. | What to do about "Error creating window handle" errors in a C# application? | [
"",
"c#",
"controls",
"user-interface",
"window-handles",
""
] |
I would like to know what the best practice for populating a business object hierarchy (parent/child/grandchild) structure is from a single database call.
I can think of a couple ways to accomplish it off the top of my head such as:
left-joining all the relations in my sql statement then use looping and logic to fill the business objects
**or**
use several select statements and 1 datareader and use its NextResult() method to iterate through each result set and fill the corresponding BO's
Just wondering what the best practice for this is
I am using DAAB and c# for my DAL
Thanks! | There is no universal recipe. It depends on database schema, database size and number of records your application reads in typical scenario. You have two processes here:
* fetching data from database
* populating business objects
Fetching data from database is several magnitudes slower than creating objects in memory. Best way would be to construct select statements for fastest data access.
Queries can be constructed in three ways:
* one large query that fetches everything in single execution - you'll get most complex SQL, and probably the fastest execution (depends on DB schema)
* master/detail approach - simple queries. lots of traffic to database. This is acceptable only if you fetch small number of records, otherwise it is very slow.
* hybrid: one query for each layer of hierarchy. Consider this approach if previous two methods are to slow. This approach requires more complex logic for populating business objects.
You should decide which solution is acceptable. Some key points to consider:
* which SQL is easier to create and maintain - one large that fetches everything in single read or several smaller.
* when you choose on previous point, you should measure performance and make final decision | I used to use multiple returned datasets, but the overhead, and the everchanging API's for it, finally let me to return to just using joins to return it all in one gulp.
I keep an eye on the resultset sizes, but in the context of any app I've run into, it's not been an issue. I've not regretted doing so, overall, but YMMV.
Multiple result sets can get especially squirrelly if the parent-level selection clauses involve child-level selection rules.
This way handles all cases; splitting it up works sometimes, but you will end up needing single-set queries in some cases; and it's nice to have just one pattern - especially if you sometimes are stuck with refactoring from one to the other.
Finally you end up with fewer hits on the database, and transaction management is simpler. | Loading Business Object Hierarchy with One Database Call | [
"",
"c#",
"database",
"data-access-layer",
"business-objects",
""
] |
I've been thrown into an ASP.NET project and I've got a page which contains a control that is fetched via AJAX.
The Page\_Load function of the control does a little bit of logic necessary to get the correct values from the Query string.
The problem is that the Page\_Load function isn't called in IE.
If I put a breakpoint in, I can load the page in FF and watch it stop, but in IE: no deal.
I'm pretty (read: COMPLETELY) new to ASP.NET, but I'm a pretty experienced PHP developer.
So I'm thinking it's probably some funk with the way that IE does the AJAX callback to get the control.
Has anyone got any ideas?
Cheers | It seems like it was a caching issue, solved by doing something like this:
```
protected override void OnLoad(EventArgs e)
{
Response.Cache.SetNoStore();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now);
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetAllowResponseInBrowserHistory(false);
base.OnLoad(e);
}
``` | If it's the caching, you should turn it off by using the OutputCache directive:
```
<%@ OutputCache Duration="0" VaryByParam="None" %>
``` | Page_Load called in Firefox, but not IE | [
"",
"c#",
"asp.net",
"internet-explorer",
"pageload",
""
] |
I need a timer to execute callbacks with relatively low resolution. What's the best way to implement such C++ timer class in Linux? Are there any libraries I could use? | If you're writing within a framework (Glib, Qt, Wx, ...), you'll already have an event loop with timed callback functionalities. I'll assume that's not the case.
If you're writing your own event loop, you can use the `gettimeofday`/`select` pair (`struct timeval`, microsecond precision) or the `clock_gettime`/`nanosleep` pair (`struct timespec`, nanosecond precision) for your own event dispatcher. Even though latter interface is higher resolution, scheduling is never that accurate anyways, so take whatever fits best.
```
#include <algorithm>
#include <functional>
#include <vector>
#include <errno.h>
#include <sys/time.h>
#include <unistd.h>
using namespace std;
class scheduler {
public:
scheduler();
int events();
void addEvent(const struct timeval, int (*)(void *), void *);
int dispatchUntil(const struct timeval &);
bool waitUntil(const struct timeval * = NULL);
int loopUntil(const struct timeval * = NULL);
private:
static bool tv_le(const struct timeval &, const struct timeval &);
struct event {
struct timeval when;
int (*callback)(void *);
void *data;
};
static struct _cmp
: public binary_function<bool, const struct event &, const struct event &>
{
bool operator()(const struct event &a, const struct event &b) {
return !tv_le(a.when, b.when);
}
} cmp;
vector<struct event> heap;
};
bool scheduler::tv_le(const struct timeval &a, const struct timeval &b) {
return a.tv_sec < b.tv_sec ||
a.tv_sec == b.tv_sec && a.tv_usec <= b.tv_usec;
}
scheduler::scheduler() : heap() {}
int scheduler::events() {
return heap.size();
}
void scheduler::addEvent(const struct timeval when, int (*callback)(void *), void *data) {
struct event ev = {when, callback, data};
heap.push_back(ev);
push_heap(heap.begin(), heap.end(), cmp);
}
int scheduler::dispatchUntil(const struct timeval &tv) {
int count = 0;
while (heap.size() > 0 && tv_le(heap.front().when, tv)) {
struct event ev = heap.front();
pop_heap(heap.begin(), heap.end(), cmp);
heap.pop_back();
ev.callback(ev.data);
count++;
}
return count;
}
bool scheduler::waitUntil(const struct timeval *tv) {
if (heap.size() > 0 && (!tv || tv_le(heap.front().when, *tv)))
tv = &heap.front().when;
if (!tv)
return false;
struct timeval tv2;
do {
gettimeofday(&tv2, NULL);
if (tv_le(*tv, tv2))
break;
tv2.tv_sec -= tv->tv_sec;
if ((tv2.tv_usec -= tv->tv_usec) < 0) {
tv2.tv_sec--;
tv2.tv_usec += 1000000;
}
} while (select(0, NULL, NULL, NULL, &tv2) < 0 && errno == EINTR);
return heap.size() > 0 && tv_le(*tv, heap.front().when);
}
int scheduler::loopUntil(const struct timeval *tv) {
int counter = 0;
while (waitUntil(tv))
counter += dispatchUntil(heap.front().when);
return counter;
}
```
Warning: I love C. I never write C++. I'm just pretending to know the language.
Disclaimer: written just now and totally untested. The basic idea is to keep events in a priority queue, wait until the first one, run it, and repeat. | Use the boost::asio library. It has both synchronous and asynchronous timers which call a callback.
<http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/tutorial.html> | timer class in linux | [
"",
"c++",
"linux",
"timer",
""
] |
How do I access the index while iterating over a sequence with a `for` loop?
```
xs = [8, 23, 45]
for x in xs:
print("item #{} = {}".format(index, x))
```
Desired output:
```
item #1 = 8
item #2 = 23
item #3 = 45
``` | Use the built-in function [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate "enumerate"):
```
for idx, x in enumerate(xs):
print(idx, x)
```
It is *[non-pythonic](https://stackoverflow.com/questions/25011078/what-does-pythonic-mean)* to manually index via `for i in range(len(xs)): x = xs[i]` or manually manage an additional state variable.
Check out [PEP 279](https://www.python.org/dev/peps/pep-0279/ "PEP 279") for more. | > # Using a for loop, how do I access the loop index, from 1 to 5 in this case?
Use `enumerate` to get the index with the element as you iterate:
```
for index, item in enumerate(items):
print(index, item)
```
And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:
```
count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(items, start=1):
print(count, item)
```
# Unidiomatic control flow
What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:
> ```
> index = 0 # Python's indexing starts at zero
> for item in items: # Python's for loops are a "for each" loop
> print(index, item)
> index += 1
> ```
Or in languages that do not have a for-each loop:
> ```
> index = 0
> while index < len(items):
> print(index, items[index])
> index += 1
> ```
or sometimes more commonly (but unidiomatically) found in Python:
> ```
> for index in range(len(items)):
> print(index, items[index])
> ```
# Use the Enumerate Function
Python's [`enumerate` function](https://docs.python.org/2/library/functions.html#enumerate) reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an `enumerate` object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:
```
for index, item in enumerate(items, start=0): # default is zero
print(index, item)
```
This code sample is fairly well the [canonical](http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html#index-item-2-enumerate) example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.
## Getting a count
Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with `1` and the final number will be your count.
```
count = 0 # in case items is empty
for count, item in enumerate(items, start=1): # default is zero
print(item)
print('there were {0} items printed'.format(count))
```
The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.
---
## Breaking it down - a step by step explanation
To break these examples down, say we have a list of items that we want to iterate over with an index:
```
items = ['a', 'b', 'c', 'd', 'e']
```
Now we pass this iterable to enumerate, creating an enumerate object:
```
enumerate_object = enumerate(items) # the enumerate object
```
We can pull the first item out of this iterable that we would get in a loop with the `next` function:
```
iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)
```
And we see we get a tuple of `0`, the first index, and `'a'`, the first item:
```
(0, 'a')
```
we can use what is referred to as "[sequence unpacking](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences)" to extract the elements from this two-tuple:
```
index, item = iteration
# 0, 'a' = (0, 'a') # essentially this.
```
and when we inspect `index`, we find it refers to the first index, 0, and `item` refers to the first item, `'a'`.
```
>>> print(index)
0
>>> print(item)
a
```
# Conclusion
* Python indexes start at zero
* To get these indexes from an iterable as you iterate over it, use the enumerate function
* Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:
So do this:
```
for index, item in enumerate(items, start=0): # Python indexes start at zero
print(index, item)
``` | How to access the index value in a 'for' loop? | [
"",
"python",
"loops",
"list",
""
] |
Given an operation contract such as:
```
[OperationContract]
void Operation(string param1, string param2, int param3);
```
This could be redesigned to:
```
[MessageContract]
public class OperationRequest
{
[MessageBodyMember]
public string Param1 { get; set; }
[MessageBodyMember]
public string Param2 { get; set; }
[MessageBodyMember]
public int Param3 { get; set; }
}
[MessageContract]
public class OperationResponse
{
}
[OperationContract]
OperationResponse Operation(OperationRequest request);
```
One thing I like about the MessageContract is that I get a little more explicit control over the format of the SOAP message.
Similarly, I could write nearly the same code, but use a DataContract:
```
[DataContract]
public class OperationRequest
{
[DataMember]
public string Param1 { get; set; }
[DataMember]
public string Param2 { get; set; }
[DataMember]
public int Param3 { get; set; }
}
[DataContract]
public class OperationResponse
{
}
[OperationContract]
OperationResponse Operation(OperationRequest request);
```
One thing I like about the DataContract is that I can define IsRequired, Order, and Name.
Today I expect the only consumer will be a WCF client. However, I want to design contract first and adhere to SOA practices as much as possible. Rather than have WCF dictate my SOAP, WSDL, and XSD, I want the XML to define the WCF layer, but use WCF to generate this so as not to add any custom message processing to WCF. I want to follow the most common SOA XML conventions which I believe is probably all tags beginning in lowercase - am I right? And I want to be as version tolerant as possible.
Is it wise to always create Request and Response messages like this? Which of the three formats promotes the best SOA practices? Should I go one step further and define both a DataContract and a MessageContract whereby the MessageContract only contains the DataContract? Or should I only ever use DataContracts if I am truly exposing a new type (i.e. do not create message types as containers)?
A loaded set of questions I know, but I am trying to get to the heart of it, and I am not sure separating the questions provides sufficient context to get the answer I am looking for. | `XML` usually tends to be camelCased. `WSDL` and `XML` Schema use camelCasing for both elements and attributes, for example check out the [syntax](http://www.w3schools.com/wsdl/wsdl_syntax.asp) and [schema](http://www.w3schools.com/Schema/schema_howto.asp).
Why `SOAP` was defined differently, I do not know, but it uses PascalCasing for elements and camelCasing for attributes, check [here](http://www.w3schools.com/soap/soap_header.asp).
Similary, most of the `WS*` specs (maybe all) use PascalCasing for elements and attributes, see [here](http://ws-standards.com/). XML Schema is agnostic about the conventions of the types it defines for XML.
[Thomas Erl](http://www.thomaserl.com/) writes many important books on [`SOA`](http://www.soabooks.com/) including "Service-Oriented Architecture". In Chapters *13* and *15* he provides a number of examples of the XML of the various parts of typical transactions. It defines types and object members in XML Schema using PascalCasing which nicely matches the normal patterns of C# for class and property naming. Thus `WCF` defaults already closely match the standards.
Regarding actual message naming, some conventions use camelCasing and others use PascalCasing, so my preference is to match the primary language needs, which in the `WCF` case is PascalCasing. And `WCF` defaults match some examples of how the request and response message should be written, [some examples here](http://www.w3schools.com/soap/soap_example.asp).
So the only outstanding question is now the basic question of how much to standardize around the use of `OperationContract`, `DataContract`, and/or `MessageContract`.
Defining DataContract only when a you have a complex type (in `XSD` parlance) makes sense, and I tend to think YAGNI (You Ain't Gonna Need It) as pointed out by Terry is the correct choice, but *Erl* seems to suggest a much more process intensive version so I am still not sure the best approach to use as my default choice (the main part of the question). | its always a best practice not to have multiple parameter in a operation contract, always have a type that wraps all the required parameters, this will help out in the long run. Your existing clients won't break when you add a new optional parameter.
I work in a business integration team where we integrate with other companies fairly regularly, (AT&T, Cox, Exxon ...) and have never seen a web service call that took more than a single parameter. | What is best-practice when designing SOA WCF web-services? | [
"",
"c#",
"wcf",
"web-services",
"datacontract",
""
] |
I'm in the process of learning Java and my first project is a calculator, however I've run into a snag. I'm trying to get my calculator to let me enter a number then click an operator (+, -, x, /), enter another number then hit an operator again and have the display update and be able to keep this going.
Example, I would like to be able to hit the following and have it display the total each time I hit an operator after the first:
> a + b / c - d =
The code I have seems (to me) like it should work but it doesn't. What am I doing wrong?
The following is the code I'm using when you hit an operator. By default wait is set to false. After running through the class once, value1 is stored and wait is set to true and that works fine. From there it doesn't seem to work quite right:
```
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
// Set display as string
String s = display.getText();
if (!wait) {
// Convert first input string to double
try {
value1 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
dec = false;
} else {
// Convert second input string to double
try {
value2 = Double.valueOf(s.trim()).doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
// Determine operation to be performed
if (operator == "add") {
value1 = Operators.add(value1, value2);
} else if (operator == "subtract") {
value1 = Operators.subtract(value1, value2);
} else if (operator == "multiply") {
value1 = Operators.multiply(value1, value2);
} else if (operator == "divide") {
value1 = Operators.divide(value1, value2);
}
// Convert final value to string and display
display.setText(Double.toString(value1));
dec = false;
}
// Determine operator hit
if (input.equals("+")) {
operator = "add";
} else if (input.equals("-")) {
operator = "subtract";
} else if (input.equals("x")) {
operator = "multiply";
} else if (input.equals("/")) {
operator = "divide";
}
// Set wait
wait = true;
}
}
```
EDIT: Updated code to fix some confusion and update the if statement. Even after this the same problem still exists. Also, the full source is available [here](http://www.chriskankiewicz.com/documents/java/development/Calculator/src/Calculator.java) | After searching high and low I finally determined that the problem didn't lie within the code I provided. I had had a "wait = false;" in my NumberListener class that was screwing up the execution. To solve this I created 2 separate wait variables and all is working fine so far.
Thanks for the help and the tips guys, +1 to all of you for trying. | A few suggestions.
First, I would suggest when using a `boolean` as a conditional for an `if` statement, avoid comparison with `true` and `false` -- there are only two states for `boolean` anyway. Also, since there are only two states, rather than using `else if (false)`, an `else` will suffice:
```
if (condition == true)
{
// when condition is true
}
else if (condition == false)
{
// when condition is false
}
```
can be rewritten as:
```
if (condition)
{
// when condition is true
}
else
{
// when condition is false
}
```
Second, rather than comparing the string literals `"add"`, `"subtract"` and such, try to use constants (`final` variables), or [`enum`](http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html)s. Doing a `String` comparison such as `(operator == "add")` is performing a check to see whether the string literal `"add"` and the `operator` variable are both *refering* to the same object, not whether the *values* are the same. So under certain circumstances, you may have the `operator` set to `"add"` but the comparison may not be `true` because the string literal is refering to a separate object. A simple workaround would be:
```
final String operatorAdd = "add";
// ...
if (input.equals("+"))
operator = operatorAdd;
// ...
if (operator == operatorAdd)
// ...
```
Now, both the assignment of `operator` and the comparison of `operator` both are referecing the constant `operatorAdd`, so the comparison can use a `==` rather than a `equals()` method.
Third, as this seems like the type of calculator which doesn't really require two operands (i.e. `operand1 + operand2`), but rather a single operand which is acting upon a stored value (i.e. `operand + currentValue`), it probably would be easier to have some variable that holds the current value, and another variable that holds the operator, and a method which will act according to the current operator and operand. (More or less an idea of an [accumulator machine](http://en.wikipedia.org/wiki/Accumulator_(computing)), or 1-operand computer.)
The basic method of operation will be:
1. Set the `currentValue`.
2. Set the operator.
3. Set the `operand`.
4. Perform the calculation.
5. Set the `currentValue` to the result of the calculation.
6. Set the operator to blank state.
Each step should check that the previous step took place -- be sure that an operation is specified (`operator` is set to a valid operator), then the next value entered becomes the `operand`. A calculator is like a [state machine](http://en.wikipedia.org/wiki/Finite_state_machine), where going from one step to another must be performed in a certain order, or else it will not proceed to the next step.
So, the calculator may be like this (pseudocode!):
```
// Initialize calculator (Step 1)
currentValue = 0;
operand = 0;
operator = operatorNone;
loop
{
operand = getOperand(); // Step 2
operator = getOperator(); // Step 3
// Step 4 and 5
if (operator == operatorAdd)
currentValue += operand;
if (operator == operatorSubtract)
currentValue -= operand;
// ...
// Step 6
operator = operatorNone;
}
```
Although the above code uses a single loop and doesn't work like a event-based GUI model, but it should outline the steps that it takes to run a calculator. | First Java program (calculator) problems | [
"",
"java",
"class",
"operators",
"calculator",
""
] |
```
Checkbox[,] checkArray = new Checkbox[2, 3]{{checkbox24,checkboxPref1,null}, {checkbox23,checkboxPref2,null}};
```
I am getting error . How do I initialize it? | OK, I think I see what's happening here. You're trying to initialize an array at a class level using this syntax, and one of the checkboxes is also a class level variable? Am I correct?
You can't do that. You can only use static variables at that point. You need to move the init code into the constructor. At the class level do this:
```
CheckBox[,] checkArray;
```
Then in your constructor:
```
public Form1()
{
InitializeComponent();
checkArray = new CheckBox[2, 3] { { checkbox24,checkboxPref1,null}, {checkbox23,checkboxPref2,null}};
}
``` | int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
Does for me....
Tony | Initialize multidimensional array | [
"",
"c#",
"arrays",
"initialization",
""
] |
What’s the best way to remove comments from a PHP file?
I want to do something similar to strip-whitespace() - but it shouldn't remove the line breaks as well.
For example,
I want this:
```
<?PHP
// something
if ($whatsit) {
do_something(); # we do something here
echo '<html>Some embedded HTML</html>';
}
/* another long
comment
*/
some_more_code();
?>
```
to become:
```
<?PHP
if ($whatsit) {
do_something();
echo '<html>Some embedded HTML</html>';
}
some_more_code();
?>
```
(Although if the empty lines remain where comments are removed, that wouldn't be OK.)
It may not be possible, because of the requirement to preserve embedded HTML - that’s what’s tripped up the things that have come up on Google. | I'd use [tokenizer](http://www.php.net/manual/en/book.tokenizer.php). Here's my solution. It should work on both PHP 4 and 5:
```
$fileStr = file_get_contents('path/to/file');
$newStr = '';
$commentTokens = array(T_COMMENT);
if (defined('T_DOC_COMMENT')) {
$commentTokens[] = T_DOC_COMMENT; // PHP 5
}
if (defined('T_ML_COMMENT')) {
$commentTokens[] = T_ML_COMMENT; // PHP 4
}
$tokens = token_get_all($fileStr);
foreach ($tokens as $token) {
if (is_array($token)) {
if (in_array($token[0], $commentTokens)) {
continue;
}
$token = $token[1];
}
$newStr .= $token;
}
echo $newStr;
``` | Use `php -w <sourcefile>` to generate a file stripped of comments and whitespace, and then use a beautifier like [PHP\_Beautifier](http://pear.php.net/package/PHP_Beautifier) to reformat for readability. | Best way to automatically remove comments from PHP code | [
"",
"php",
"comments",
"strip",
""
] |
I need to submit data from a web application to console application. The current plan calls for the web app to submit data to the database and the console app to poll the database then act on the data when it is inserted. Should I change the console app to include an http handler that the web app can submit data so it doesn't have to poll the database? Is there a better way to communicate data between these two applications? The console app never has to send data to the web app.
**Update**
This is a .NET 2.0 console application so WCF doesn't seem like a viable option. The data payload is fairly small (a few 9 digit ID fields, less than 150 bytes total), and will be sent with a rate of about 10 per minute. There is no firewall between these two applications. | Using the simplest technologies, your Console App could connect to the database in a loop controlled by a Timer or a BackgroundWorker. You would need a way to know what records are new and which aren't. If you can delete the records from that table when you poll them, it means each time you do it, you'll get only new records. If you can't delete them, use a TimeStamp field in that table and each time you poll you select the records with that time stamp greater than the maximum time stamp of the previous batch. If you need to mark those records as processed, then you can set that flag and forget about the timestamp. | I'm not sure of your requirements, or setup but [WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) could be an option.
[edit]
To expand, you could host a wcf service in the console app, and have the asp.net site call it. For that matter, remoting (or any other form) could work as well. This way you wouldn't have to have the console app pool the database when not necessary. | Submitting data from a web application to C# console application | [
"",
"c#",
"web-applications",
"console-application",
""
] |
I've been working on my issue for 30 hours. Each time I fix one thing a new error arises. All I want to do is take a DataTables from memory and simply update an Access .MDB file. Here is my code:
```
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
namespace LCR_ShepherdStaffupdater_1._0
{
public class DatabaseHandling
{
static DataTable datatableB = new DataTable();
static DataTable datatableA = new DataTable();
public static DataSet datasetA = new DataSet();
public static DataSet datasetB = new DataSet();
static OleDbDataAdapter adapterA = new OleDbDataAdapter();
static OleDbDataAdapter adapterB = new OleDbDataAdapter();
static string connectionstringA = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Settings.getfilelocationA();
static string connectionstringB = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Settings.getfilelocationB();
static OleDbConnection dataconnectionB = new OleDbConnection(connectionstringB);
static OleDbConnection dataconnectionA = new OleDbConnection(connectionstringA);
static DataTable tableListA;
static DataTable tableListB;
static public void addTableA(string table, bool addtoDataSet)
{
dataconnectionA.Open();
datatableA = new DataTable(table);
try
{
OleDbCommand commandselectA = new OleDbCommand("SELECT * FROM [" + table + "]", dataconnectionA);
adapterA.SelectCommand = commandselectA;
adapterA.Fill(datatableA);
}
catch
{
Logging.updateLog("Error: Tried to get " + table + " from DataSetA. Table doesn't exist!", true, false, false);
}
if (addtoDataSet == true)
{
datasetA.Tables.Add(datatableA);
Logging.updateLog("Added DataTableA: " + datatableA.TableName.ToString() + " Successfully!", false, false, false);
}
dataconnectionA.Close();
}
static public void addTableB(string table, bool addtoDataSet)
{
dataconnectionB.Open();
datatableB = new DataTable(table);
try
{
OleDbCommand commandselectB = new OleDbCommand("SELECT * FROM [" + table + "]", dataconnectionB);
adapterB.SelectCommand = commandselectB;
adapterB.Fill(datatableB);
}
catch
{
Logging.updateLog("Error: Tried to get " + table + " from DataSetB. Table doesn't exist!", true, false, false);
}
if (addtoDataSet == true)
{
datasetB.Tables.Add(datatableB);
Logging.updateLog("Added DataTableB: " + datatableB.TableName.ToString() + " Successfully!", false, false, false);
}
dataconnectionB.Close();
}
static public string[] getTablesA(string connectionString)
{
dataconnectionA.Open();
tableListA = dataconnectionA.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
string[] stringTableListA = new string[tableListA.Rows.Count];
for (int i = 0; i < tableListA.Rows.Count; i++)
{
stringTableListA[i] = tableListA.Rows[i].ItemArray[2].ToString();
}
dataconnectionA.Close();
return stringTableListA;
}
static public string[] getTablesB(string connectionString)
{
dataconnectionB.Open();
tableListB = dataconnectionB.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
string[] stringTableListB = new string[tableListB.Rows.Count];
for (int i = 0; i < tableListB.Rows.Count; i++)
{
stringTableListB[i] = tableListB.Rows[i].ItemArray[2].ToString();
}
dataconnectionB.Close();
return stringTableListB;
}
static public void createDataSet()
{
string[] tempA = getTablesA(connectionstringA);
string[] tempB = getTablesB(connectionstringB);
int percentage = 0;
int maximum = (tempA.Length + tempB.Length);
Logging.updateNotice("Loading Tables...");
Logging.updateLog("Started Loading File A", false, false, true);
for (int i = 0; i < tempA.Length ; i++)
{
if (!datasetA.Tables.Contains(tempA[i]))
{
addTableA(tempA[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
else
{
datasetA.Tables.Remove(tempA[i]);
addTableA(tempA[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
}
Logging.updateLog("Finished loading File A", false, false, true);
Logging.updateLog("Started loading File B", false, false, true);
for (int i = 0; i < tempB.Length ; i++)
{
if (!datasetB.Tables.Contains(tempB[i]))
{
addTableB(tempB[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
else
{
datasetB.Tables.Remove(tempB[i]);
addTableB(tempB[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
}
Logging.updateLog("Finished loading File B", false, false, true);
Logging.updateLog("Both files loaded into memory successfully", false, true, false);
}
static public DataTable getDataTableA()
{
datatableA = datasetA.Tables[Settings.textA];
return datatableA;
}
static public DataTable getDataTableB()
{
datatableB = datasetB.Tables[Settings.textB];
return datatableB;
}
static public DataSet getDataSetA()
{
return datasetA;
}
static public DataSet getDataSetB()
{
return datasetB;
}
static public void InitiateCopyProcessA()
{
DataSet tablesA;
tablesA = DatabaseHandling.getDataSetA();
foreach (DataTable table in tablesA.Tables)
{
OverwriteTable(table, table.TableName);
Logging.updateLog("Copied " + table.TableName + " successfully.", false, true, false);
}
}
static void OverwriteTable(DataTable sourceTable, string tableName)
{
using (var destConn = new OleDbConnection(connectionstringA))
using (var destCmd = new OleDbCommand(tableName, destConn) { CommandType = CommandType.TableDirect })
using (var destDA = new OleDbDataAdapter(destCmd))
{
// Since we're using a single table, we can have the CommandBuilder
// generate the appropriate INSERT and DELETE SQL statements
using (var destCmdB = new OleDbCommandBuilder(destDA))
{
destCmdB.QuotePrefix = "["; // quote reserved column names
destCmdB.QuoteSuffix = "]";
destDA.DeleteCommand = destCmdB.GetDeleteCommand();
destDA.InsertCommand = destCmdB.GetInsertCommand();
// Get rows from destination, and delete them
var destTable = new DataTable();
destDA.Fill(destTable);
foreach (DataRow dr in destTable.Rows)
{
dr.Delete();
}
destDA.Update(destTable); // !!! Run-time error: Syntax error in FROM clause. !!!
// Set rows from source as Added, so the DataAdapter will insert them
foreach (DataRow dr in sourceTable.Rows)
{
dr.SetAdded();
}
destDA.Update(sourceTable);
}
}
}
}
}
```
**EDIT:**
OKAY THANK YOU! But like-wise a new problem arose. Same source code, but as I was copying tables to the .MDB file, 10 or so tables had already been copied then I get this run-time error:
**Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.**
On this command **destDA.DeleteCommand = destCmdB.GetDeleteCommand();**
This should be my last problem and my project will be complete. | ```
destCmdB.QuotePrefix = "["; // quote reserved column names
destCmdB.QuotePrefix = "]";
```
QuotePrefix twice? Perhaps that could be an issue. | > Dynamic SQL generation for the
> DeleteCommand is not supported against
> a SelectCommand that does not return
> any key column information.
You need a primary key...
In your Access table you need to designate a column that contains an unique value. The primary key is used to identify an individual row. Usually you create an "ID" column that is defined as autonumber. | Why am I getting this error when trying to update an Access Database file (.mdb) with a Datatable: | [
"",
"c#",
"ms-access",
"datatable",
"dataset",
"oledbcommand",
""
] |
I was wondering, If I have, let's say 6 javascripts includes on a page and 4-5 css includes as well on the same page, does it actually makes it optimal for the page to load if I do create one file or perhaps two and append them all together instead of having bunch of them? | Yes. It will get better performance with fewer files.
There are a few reasons for this and I'm sure others will chime in as I won't list them all.
1. There is overhead in the requests in addition to the size of the file, such as the request its self, the headers, cookies (if sent) and so on. Even in many caching scenarios the browser will send a request to see if the file has been modified or not. Of course proper headers/server configuration can help with this.
2. Browsers by default have a limited number of simultaneous connections that it will open at a time to a given domain. I believe IE has 2 and firefox does 4 (I could mistaken on the numbers). Anyway the point is, if you have 10 images, 5 js files and 2 css files, thats 17 items that needs to be downloaded and only a few will be done at the same time, the rest are just queued.
I know these are vague and simplistic explanations, but I hope it gets you on the right track. | One of your goals is to reduce http requests, so yes. The tool called yslow can grade your application to help you see what you can do to get a better user experience.
<http://developer.yahoo.com/yslow/> | javascript and css loadings | [
"",
"javascript",
"css",
"performance",
"browser",
""
] |
Today I was thinking about a Python project I wrote about a year back where I used `logging` pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (`hotshot` indicated it was one of my biggest bottlenecks).
I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and **target only the code objects that are causing bottlenecks**. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:
```
[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
```
Of course, **you'd want to use it sparingly and probably with per-function granularity** -- only for code objects that have shown `logging` to be a bottleneck. Anybody know of anything like this?
**Note:** There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named `debug` may have to be wrapped with an `if not isinstance(log, Logger)`. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-) | What about using [logging.disable](http://docs.python.org/library/logging.html?highlight=logging#logging.disable "logging.disable")?
I've also found I had to use [logging.isEnabledFor](http://docs.python.org/library/logging.html?highlight=logging#logging.Logger.isEnabledFor) if the logging message is expensive to create. | Use [pypreprocessor](http://code.google.com/p/pypreprocessor/)
Which can also be found on [PYPI (Python Package Index)](http://pypi.python.org/pypi/pypreprocessor) and be fetched using pip.
Here's a basic usage example:
```
from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define nologging
#ifdef nologging
...logging code you'd usually comment out manually...
#endif
```
Essentially, the preprocessor comments out code the way you were doing it manually before. It just does it on the fly conditionally depending on what you define.
You can also remove all of the preprocessor directives and commented out code from the postprocessed code by adding 'pypreprocessor.removeMeta = True' between the import and
parse() statements.
The bytecode output (.pyc) file will contain the optimized output.
*SideNote: pypreprocessor is compatible with python2x and python3k.*
*Disclaimer: I'm the author of pypreprocessor.* | How can I strip Python logging calls without commenting them out? | [
"",
"python",
"optimization",
"logging",
"bytecode",
""
] |
I have a Console application hosting a WCF service:
*Updated this code to run off the app.config file instead of initialising it programatically*
```
Uri baseAddress = new Uri("http://localhost:8000/ChatServer/Service");
ServiceHost myHost = new ServiceHost(typeof(ClientServerChat.ChatServer), baseAddress);
myHost.AddServiceEndpoint(typeof(IChat), new WSHttpBinding(), "ChatService");
ServiceMetadataBehavior mb = new ServiceMetadataBehavior();
ServiceBehaviorAttribute attrib = (ServiceBehaviorAttribute)myHost.Description.Behaviors[0];
attrib.IncludeExceptionDetailInFaults = true;
mb.HttpGetEnabled = true;
myHost.Description.Behaviors.Add(mb);
myHost.Open();
```
The Console app compiles and runs. svcutil runs perfectly.
*Svcutil runs against the new service code perfectly and generates the Client code and the ouput file*
*I'm calling svcutil via the Visual Studio Command Prompt like so: svcutil.exe <http://localhost:8000/ChatServer/Service>*
It generates this output.config:
```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IChat" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false"
transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8000/ChatServer/Service/ChatService"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IChat"
contract="IChat" name="WSHttpBinding_IChat">
<identity>
<userPrincipalName value="Bedroom-PC\Roberto" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
```
Along with the bundled client code (which is in the same directory as the output file, I should add) I should be able to call the service with this:
```
ChatClient client = new ChatClient();
```
*The new output from svcutil (both code and config) still throws this exception.*
But it throws an exception saying:
"Could not find default endpoint element that references contract 'IChat' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element."
Interestingly, Visual Studio 2008 will crash when adding the same Service reference to a Client project.
*VS2008 still crashes with the updated code.*
It will find the service, get all the operations and what not. When I click Add, it crashes.
Any one have a clue whats going on??
Thanks in advance
Roberto | I fixed it.
I copy and pasted the system.serviceModel section from output.config into app.config after the the userSettings section and commented out the entire output.config.
I also specified the name of the endpoint when inistializing ChatClient("name").
It seems to be working. | Have you tried using the configuration file setup rather than doing it programmatically? Then at least you'll know if it's a general settings problem or something to do with your code. You could then roll out the code bits one by one; mex, then endpoint and see which kills it. | VS2008 Crashes when adding a WCF service | [
"",
"c#",
"visual-studio",
"wcf",
""
] |
Consider the following code:
```
def CalcSomething(a):
if CalcSomething._cache.has_key(a):
return CalcSomething._cache[a]
CalcSomething._cache[a] = ReallyCalc(a)
return CalcSomething._cache[a]
CalcSomething._cache = { }
```
This is the easiest way I can think of for simulating a 'local static' variable in python.
What bothers me is that CalcSomething.\_cache is mentioned outside the function's definition, but the alternative would be something like that:
```
if not hasattr(CalcSomething, "_cache"):
setattr(CalcSomething, "_cache", { } )
```
inside the function's definition, which is really cumbersome.
Is there a more elegant way?
[EDIT]
Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy:
```
def ParseString(s):
return ParseString._parser.parse(s)
# Create a Parser object once, which will be used for all parsings.
# Assuming a Parser object is heave on resources, for the sake of this example.
ParseString._parser = Parser()
``` | Turn it into a callable object (since that's what it really is.)
```
class CalcSomething(object):
def __init__(self):
self._cache = {}
def __call__(self, a):
if a not in self._cache:
self._cache[a] = self.reallyCalc(a)
return self._cache[a]
def reallyCalc(self, a):
return # a real answer
calcSomething = CalcSomething()
```
Now you can use `calcSomething` as if it were a function. But it remains tidy and self-contained. | Turn it into a decorator.
```
def static_var(var_name, initial_value):
def _set_var(obj):
setattr(obj, var_name, initial_value)
return obj
return _set_var
@static_var("_cache", {})
def CalcSomething(a):
...
``` | Simulating a 'local static' variable in python | [
"",
"python",
""
] |
I've installed XAMPP Apache server and put my website into htdocs. I've started Apache server. On my website I've got files with extension PHP and with extension PHP5.The difference is that when I type in into browser localhost/file.php - I see a parsed website.
But when I type localhost/file.php5 (i have this file on server), than browser asks me if I want to download or open this file. And if I choose open than I see PHP code of file.php5!
I've looked into configuration, so:
1. I dont have htaccess file
2. PHPINFO() shows PHP 5
3. c:\xampp\apache\conf\extra\httpd-xampp is included into configuration and has this on the beginning:
AddType application/x-httpd-php-source .phps
AddType application/x-httpd-php .php .php5 .php4 .php3 .phtml .phpt
I've tried also to put:
```
AddHandler php5-script .php5
AddType text/html .php5
```
Into httpd.conf, but it does not work for me (no changes).
Could you please help me fixing it? I would like to have php5 and php extension files to be opened with php5 parser. | XAMPP passes by default files with the following extensions to PHP: .php **.php5** .php4 .php3 .phtml .phpt (this was tested with XAMPP Lite 1.6.8).
My suggestion would be to remove the "AddType text/html .php5" line from the XAMPP configuration. Alternatively, use a clean install of XAMPP and look at the differences (with something like [WinMerge](http://winmerge.org/)). | 1. Follow the path `c:/xampp/apache/conf/extra/httpd-xammp`
Open `httpd-xammp`
2. Find the area of the text that resembles this:
```
<FilesMatch "\.php$">
SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch "\.phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
```
3. replace the top line of the code with the following:
```
<FilesMatch "\.php$|\.php5$|\.php4$|\.php3$|\.phtml$|\.phpt$">
```
4. so the text resembles the following:
```
<FilesMatch "\.php$|\.php5$|\.php4$|\.php3$|\.phtml$|\.phpt$">
SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch "\.phps$">
SetHandler application/x-httpd-php-source
</FilesMatch>
```
That worked for me.
Good luck.. | Extension PHP5 does not parse in XAMPP | [
"",
"php",
"apache",
"xampp",
""
] |
I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.
For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.
In a language like Perl, I could `unshift()` the apple back onto the tree, and then let the loop expression re-pick the apple:
```
while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
```
Or else I can also use `redo`, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.
```
while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
```
What would be the most **pythonic** solution for this kind of problem? | Why bother with unshifting when the else clause should always occur?
```
for apple in tree:
if (apple.weight + basket.weight) > 10:
send(basket)
basket.clear()
basket.add(apple)
```
Anyway, I'm fairly certain that Python doesn't have the sort of behavior you're looking for. | > I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.
Here's a simple solution:
```
class MyIterator(object): # undo-able iterator wrapper
def __init__(self, iterable):
super(MyIterator, self).__init__()
self.iterator = iter(iterable)
self.stack = []
def __iter__(self):
return self
def next(self):
if self.stack:
return self.stack.pop()
return self.iterator.next() # Raises StopIteration eventually
def undo(self, item):
self.stack.append(item)
```
```
for i in MyIterator(xrange(5)): print i
0
1
2
3
4
```
```
rng = MyIterator(xrange(5))
rng.next()
0
rng.next()
1
rng.undo(1)
rng.next()
1
``` | Pythonic equivalent of unshift or redo? | [
"",
"python",
"redo",
""
] |
The architecture of one of our products is a typical 3-tier solution:
* C# client
* WCF web service
* SQL Server database
The client requests information from the web service. The web service hits the database for the information and returns it to the client.
Here's the problem. Some of these queries can take a long, long time, and we don't know up-front which ones will be slow. We know some that are often slower than others, but even the simplest requests can be slow given enough data. Sometimes uses query or run reports on large amounts of data. The queries can be optimized only so far before the sheer volume of data slows them down.
If a query in the database hits the maximum query timeout in SQL server, the database query terminates, and the web service returns an error to the client. This is understood. We can handle these errors.
The client is waiting for the web service call to complete. If the database call takes a long time, the client may timeout on its call to the web service. The client gives up, but the database request continues processing. At this point, the client is out-of-synch with the database. The database call may or may not succeed. There may have been an error. The client will never know. In some cases, we don't want our users initiating another request that may result in an invalid state given the completion of the previous request.
I'm curious to see how others have handled this problem. **What strategies have you used to prevent web service timeouts from affecting database calls?**
The best ideas I can come up with involve making an actual database layer somewhere-- inside the web service, attached to a message queue-- something. Offloading every single query to another process seems excessive. (Then again, we don't always know if a given request will be fast or slow.)
It would be great if we could separate the act of making an HTTP request from the act of initiating and running a database process. I've seen this done with a custom server at a previous company, but it was using straight socket communication, and I'd rather avoid replacing the web service with some custom application.
Note that given the amount of data we deal with, we are all over query optimization. Query optimization, indexes, etc., only takes you so far when the volume of data is high. Sometimes things just take a long time. | One of the solutions we've used lately is to break apart huge database processes into separate parallel operations. Each operation is much smaller and designed to be as efficient as possible. The clients initiate the operations, spawn a few threads, and do whatever they can in parallel.
For example, we've broken apart some huge proceses into a series of steps like Start, Process 1 Chunk of Work, Finish, and Gather Report Data. The Process Work steps can run in parallel, but they can't start until the Start step completes. The Finish step needs to wait for all Process Work steps to complete.
Since the client is controlling the process, the client can report progress on exactly which step it is on. | I've encountered similiar problems in the past, and used one of the following 3 methods to resolve it:
1. Add all long running queries to a queue, and process these sequentially.
In my case these were all complicated reports which where then emailed to the client, or which were stored in permanent 'temporary' tables, for viewing by clients after they had been notified.
2. We called a webservice using a JQuery call, which then called a javascript postback method when it was complete.
This worked well when we didn't want to make the page load synchronise with what the web service was doing.
However it did mean that that piece of functionality was not available until the long running process was complete.
3. The most complicated one.
We popped up another window which displayed a progress bar, which also polled the server periodically.
This used a session variable to determine how far along to show the progress bar.
After the progress bar was initiated, a new thread was started which updated the same session variable periodically.
Once the session variable value was set to 100, the popup window closed itself.
The clients loved this method.
Anyway I hope one of those is of some help to you. | Handling Web Service Timeouts While Performing Long-Running Database Tasks | [
"",
"c#",
"sql-server",
"web-services",
"architecture",
"timeout",
""
] |
We currently have a quite complex business application that contains a huge lot of JavaScript code for making the user interface & interaction feel as close to working with a traditional desktop application as possible (since that's what our users want). Over the years, this Javascript code has grown and grown, making it hard to manage & maintain and making it ever more likely that adding new functionallity will break some existing one. Needless to say, lots of this code also isn't state of the art anymore.
Thus, we have some ongoing discussion whether the client-side part of the application should be written anew in either Flex or Silverlight, or written anew with some state of the art JavaScript framework like jQuery, or whether we should simply carry on with what we have and gradually try to replace the worst bits of the existing code. What makes this even harder to decide is that writing the UI anew will probable cost us 6-12 person months.
I'd like to hear your thoughts on that issue (maybe some of you have already had to make a similar decission).
EDIT: To answer some of the questions that came up with the answers: The back-end code is written in C#, the target audience are (usually) non-technical users from the companies we sell the software to (not the general public, but not strictly internal users either), the software 'only' has to run in desktop browsers but not necessarily on mobile devices, and the client app is a full-blown UI. | In all honesty, I would refactor the old JavaScript code and not rewrite the application. Since you are asking about which platform to put it in, I would guess that your team isn't an expert in any of them (not slamming the team, it's just a simple fact that you have to consider when making a decision). This will work against you as you'll have double duty rewriting and learning how to do things on the new platform.
By keeping it in JavaScript, you can slowly introduce a framework if you choose and do it iteratively (Replace on section of code, test it, release it, and fix any bugs). This will allow you to do it at a slower pace and get feedback along the way. That way too, if the project is canceled part way through, you aren't out all the work, because the updated code is being used by the end users. Remember the waterfall model, which is essentially what a full swap out of will be almost never works.
As much as I hate to admit this, as it is always the most fun for developers, shifting platforms, and replacing an entire system at once rarely works. There are countless examples of this, Netscape for one. [Here is the post from Spolsky on it.](http://www.joelonsoftware.com/articles/fog0000000027.html) (I would also recommend the book [Dreaming in Code](https://rads.stackoverflow.com/amzn/click/com/1400082463). It is an excellent example of a software project that failed and how and why). Remember to rewrite a system from scratch you are essentially going to have to go through every line of code and figure what it does and why. At first you think you can skip it, but eventually it comes down to this. Like you said, your code is old, and that means there are most likely hacks in it to get something done. Some of these you can ignore, and others will be, "I didn't know the system needed it to do that." | This decision is usually less about the technology, and more about your skill sets and comfort zones.
If you have guys that eat and breathe Javascript, but know nothing about .net or Flash/Flex then there's nothing wrong with sticking with Javascript and leaning on a library like jQuery or Prototype.
If you have skills in either of the others then you might get a quicker result using Silverlight or Flex, as you get quite a lot of functionality "for free" with both of them. | JavaScript/CSS vs. Silverlight vs. Flex | [
"",
"javascript",
"apache-flex",
"silverlight",
"web-applications",
"user-interface",
""
] |
I want to make an advanced installer for my C# application. |I want my application continue its installation after the pre-requisites been installed.
My scenario is:
* myApplication requires .net Framework 2
* it redirects the user to the Microsoft website.
* the user installs the framework.
* the installation requires to restart the PC.
STOPPED INSTALLATION
After this step (after restarting) I want myApplication to continue the installation (go to the last stage of the installation)
Any suggestion on how I do this ?!?! | I would suggest taking a look at the nullsoft install system. Use the Modern UI theme and the DotNET macro (<http://nsis.sourceforge.net/DotNET>). That's everything that you are looking for prebuilt, for free, and you can be up and running with very little effort.
I've had experience releasing applications with this route and it works very well. | Things like InstallShield, or one of the other installer creation tools would be able to handle the pre-requisite side of things for you. If you want to roll your own, then you could check for the framework, perform the various steps you mentioned to install it, then add you setup application to the [RunOnce](http://support.microsoft.com/kb/137367) registry key so it starts again on startup.
Looking at something that would handle all the pre-requisites etc for you would be my choice though :-) | Advanced installation regarding to C# | [
"",
"c#",
""
] |
I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however [I did find an easy implementation in C](http://cppgm.blogspot.com/2008/01/data-encryption-standard.html). (I do not know C, I know a little C++, but not that well, pointer still get me now and then.)
So I tried simply converting the code from C to Java, which did work out about halfway, however I'm having a problem with the last part, especially with the example using:
```
printf("%c",M);
```
Which, from what Google told me, seems to be converting numbers(Integer) to ASCII-Characters, but I'm not really sure. My Code seems to be working until that last part, so I would be thankful for anyone that can give me fix/hint.
My Code:
```
import java.util.Scanner;
public class DES {
/**
* @param args
*/
public static void main(String[] args) {
Scanner eingabe = new Scanner(System.in);
int p, q, key2, fn, encryption_key, temp1 , temp2 ,
t, s =0 , privatekey1=1, b=0 , passwort_s=0, klartext;
int[] Cipher = new int [100];
String passwort;
System.out.println("Enter the value of p and q");
p = eingabe.nextInt();
q = eingabe.nextInt();
System.out.println(p);
System.out.println(q);
key2= p*q;
fn=(p-1)*(q-1);
System.out.println("Enter Enryption key e: ");
encryption_key = eingabe.nextInt();
do {
s=(privatekey1*encryption_key)%fn;
privatekey1++;
} while (s!=1);
privatekey1=privatekey1-1;
System.out.println("Public Key : "+ encryption_key + ","+ key2 );
System.out.println("Private Key: "+ privatekey1 + "," +key2 );
System.out.println("Enter Message: ");
passwort= eingabe.next();
for ( temp2 = 0; temp2 < passwort.length(); temp2++)
{
t = passwort.charAt(temp2);
passwort_s=1;
for(temp1 =0 ; temp1< encryption_key ; temp1++){
passwort_s= passwort_s*t%key2;
}
passwort_s= passwort_s%key2;
System.out.println(passwort_s);
}
System.out.println("Enter cipher Text: ");
for(temp1=0;temp1< passwort.length(); temp1++ )
{
Cipher[temp1]= eingabe.nextInt();
}
System.out.println("Plainttext: ");
for(temp2 =0; temp2 < passwort.length(); temp2++);
{
klartext=1;
for(temp1 =0; temp1 < privatekey1; temp1 ++){
klartext=klartext*Cipher[temp2]%key2;
}
klartext=klartext%key2;
System.out.println(klartext);
}
}
}
```
How can I convert the
```
printf("%c",M);
```
to Java, and is this then a full DES implementation? | Its late and I'm tired but this isn't a DES implementation, is it?
It looks more like [RSA](http://en.wikipedia.org/wiki/RSA#Key_Generation).
Yeah the link on your post is an asymmetrical cryptosystem. DES is symmetrical. | Or, more concisely:
```
output.print((char)M);
```
This assumes M is a numeric value representing an ASCII character from 0-127 (or an ISO 8859-1 character from 0-255, or a Unicode character from 0-65535).
It also assumes output is a PrintWriter or PrintStream, one of which is System.out (a FileOutputStream is easily wrapped by a PrintOutputStream, or PrintWriter(new OutputStreamWriter)). | How can I translate printf("%c",M); from C to Java for my DES implementation? | [
"",
"java",
"c",
"cryptography",
"des",
""
] |
I've spent the last 4 years in C# so I'm interested in current best practices and common design patterns in C++. Consider the following partial example:
```
class World
{
public:
void Add(Object *object);
void Remove(Object *object);
void Update();
}
class Fire : Object
{
public:
virtual void Update()
{
if(age > burnTime)
{
world.Remove(this);
delete this;
}
}
}
```
Here we have a world responsible for managing a set of objects and updating them regularly. Fire is an an object that might be added to the world under many different circumstances but typically by another object already in the world. Fire is the only object that knows when it has burned out so currently I have it deleting itself. The object that created the fire is likely no longer in existence or relevant.
Is this a sensible thing to do or is there a better design that would help clean up these objects? | The problem with this is that you're really creating an implicit coupling between the object and the World class.
If I try to call Update() outside the World class, what happens? I might end up with the object being deleted, and I don't know why. It seems the responsibilities are badly mixed up. This is going to cause problems the moment you use the Fire class in a new situation you hadn't thought of when you wrote this code. What happens if the object should be deleted from more than one place? Perhaps it should be removed both from the world, the current map, and the player's inventory? Your Update function will remove it from the world, and then delete the object, and the next time the map or the inventory tries to access the object, Bad Things Happen.
In general, I'd say it is very unintuitive for an Update() function to delete the object it is updating. I'd also say it's unintuitive for an object to delete itself.
The object should more likely have some kind of way to fire an event saying that it has finished burning, and anyone interested can now act on that. For example by removing it from the world. For deleting it, think in terms of ownership.
Who owns the object? The world? That means the world alone gets to decide when the object dies. That's fine as long as the world's reference to the object is going to outlast an other references to it.
Do you think the object own itself? What does that even mean? The object should be deleted when the object no longer exists? Doesn't make sense.
But if there is no clearly defined single owner, implement shared ownership, for example using a smart pointer implementing reference counting, such as `boost::shared_ptr`
But having a member function on the object itself, which is hardcoded to remove the object from *one* specific list, whether or not it exists there, and whether or not it also exists in any other list, and also delete the object itself regardless of which references to it exist, is a bad idea. | You have made `Update` a virtual function, suggesting that derived classes may override the implementation of `Update`. This introduces two big risks.
1.) An overridden implementation may remember to do a `World.Remove`, but may forget the `delete this`. The memory is leaked.
2.) The overridden implementation calls the base-class `Update`, which does a `delete this`, but then proceeds with more work, but with an invalid this-pointer.
Consider this example:
```
class WizardsFire: public Fire
{
public:
virtual void Update()
{
Fire::Update(); // May delete the this-object!
RegenerateMana(this.ManaCost); // this is now invaild! GPF!
}
}
``` | Should objects delete themselves in C++? | [
"",
"c++",
"oop",
"memory-management",
"resource-cleanup",
"self-destruction",
""
] |
Spring has a very handy convenience class called [PropertyPlaceholderConfigurer](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html), which takes a standard .properties file and injects values from it into your bean.xml config.
Does anyone know of a class which does exactly the same thing, and integrates with Spring in the same way, but accepts XML files for the config. Specifically, I'm thinking of Apache digester-style config files. It would be easy enough to do this, I'm just wondering if anyone already has.
Suggestions? | I just tested this, and it should just work.
PropertiesPlaceholderConfigurer contains a setPropertiesPersister method, so you can use your own subclass of [PropertiesPersister](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/util/PropertiesPersister.html). The default PropertiesPersister already supports properties in XML format.
Just to show you the fully working code:
JUnit 4.4 test case:
```
package org.nkl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(locations = { "classpath:/org/nkl/test-config.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class PropertyTest {
@Autowired
private Bean bean;
@Test
public void testPropertyPlaceholderConfigurer() {
assertNotNull(bean);
assertEquals("fred", bean.getName());
}
}
```
The spring config file `test-config.xml`
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<context:property-placeholder
location="classpath:/org/nkl/properties.xml" />
<bean id="bean" class="org.nkl.Bean">
<property name="name" value="${org.nkl.name}" />
</bean>
</beans>
```
The XML properties file `properties.xml` - see [here](http://www.ibm.com/developerworks/java/library/j-tiger02254.html) for description of usage.
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="org.nkl.name">fred</entry>
</properties>
```
And finally the bean:
```
package org.nkl;
public class Bean {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
```
Hope this helps... | Found out that Spring Modules provide [integration between Spring and Commons Configuration](http://www.springbyexample.org/twiki/bin/view/Example/SpringModulesWithCommonsConfiguration), which has a hierarchial XML configuration style. This ties straight into PropertyPlaceholderConfigurer, which is exactly what I wanted. | Is there a PropertyPlaceholderConfigurer-like class for use with Spring that accepts XML? | [
"",
"java",
"xml",
"spring",
"properties",
""
] |
I'm currently looking into using XSLT 2.0, but I cannot find any open-source java implementations ([Saxon-B](http://en.wikipedia.org/wiki/Saxon_XSLT) seems to fit the bill, but isn't schema-aware).
Am I missing something? | The only one is Saxon-HE:
[Saxon-HE](http://sourceforge.net/projects/saxon/files/Saxon-HE/)
The W3C hosts an online version of it for testing:
[W3C Jigsaw XSLT 2.0 Service](http://www.w3.org/2005/08/online_xslt/)
And there is JSFiddle like version as well:
[xsltransform.net](http://xsltransform.net/)
And the Frameless project hosts a JavaScript version of it:
[XSLT Fiddle](http://fiddle.frameless.io/)
There's also an App Engine project which uses it:
[XSLT App Engine Test Harness](https://xslttest.appspot.com/)
Other than that, there's an incomplete Xerces extension which implements XPath 2.0:
[Xerces XPath 2.0 Extension](http://sourceforge.net/projects/xsltproc/)
An Eclipse extension which implements XPath 2.0:
[WTP XPath2.0 Processor](http://wiki.eclipse.org/PsychoPathXPathProcessor)
An incomplete Xalan-J branch which partially implements XSLT 2.0:
> Some prototype work for XSLT 2.0
> support in the Xalan-J Interpretive processor went on in 2003, but then
> trailed off. That prototype work is still available on the xslt20 branch
> <http://svn.apache.org/repos/asf/xalan/java/branches/xslt20/>, but since
> then nobdy has stepped forward to carry on that initial prototyping, and
> the Xalan PMC hasn't put in place any plans for XSLT 2.0 support.
As well as a server-side implementation of [Saxon-CE](http://www.saxonica.com/ce/index.xml) which can run on [Nashorn/Avatar.js](https://avatar-js.java.net/):
[xslty](https://www.npmjs.org/package/xslty)
**References**
* [Running Node.js on Java 8 Nashorn with Avatar.js on Windows "no avatar-js in java.library.path"](https://stackoverflow.com/questions/23130587/running-node-js-on-java-8-nashorn-with-avatar-js-on-windows-no-avatar-js-in-jav)
* [Re: Xalan-J XSLT 2.0 status](http://mail-archives.apache.org/mod_mbox/xml-xalan-dev/200608.mbox/<OF9710600B.492097BF-ON852571D3.00577829-852571D3.0057BE5E@ca.ibm.com>)
* [org.eclipse.wst.xml.xpath2.processor.sdk.feature](http://git.eclipse.org/c/sourceediting/webtools.sourceediting.xpath.git/tree/features/org.eclipse.wst.xml.xpath2.processor.sdk.feature/feature.properties)
* [Nashorn - The Combined Power of Java and JavaScript in JDK 8](http://www.infoq.com/articles/nashorn)
* [Nodyn Completion of the Node.js API](http://nodyn.io/compatibility.html)
* [Saxonica Product Feature Matrix](http://www.saxonica.com/html/products/feature-matrix-9-6.html) | Yes, I'm answering my own question from 2.5 years ago:
I haven't tried it yet, but I just stumbled upon [Eclipse PsychoPath](http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.wst.xml.xpath2.processor.doc.user/html/index.html), which is (according to the docs) a XPath 2.0 XML Schema Aware processor that passes 96% of the XPath 2.0 test suite (version 1.1M1). | Open-source java XSLT 2.0 implementation? | [
"",
"java",
"xml",
"open-source",
"xslt-2.0",
"xslt",
""
] |
I recently discovered metaclasses in python.
Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.
But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:
* a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages).
* a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)
* a meta-meta-metaclass is a *pattern factory*, which corresponds to the GOF pattern groupings, e.g. Creational, Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.
* a meta-meta-meta-metaclass (as far as I could go), is a *pattern factory factory*, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.
I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.
Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?
I'd very much like to research it further. | The class system in Smalltalk is an interesting one to study. In Smalltalk, everything is an object and every object has a class. This doesn't imply that the hierarchy goes to infinity. If I remember correctly, it goes something like:
5 -> Integer -> Integer class -> Metaclass -> Metaclass class -> Metaclass -> ... (it loops)
Where '->' denotes "is an instance of". | This reminds me of the eternal quest some people seem to be on to make a "generic implementation of a pattern." Like a factory that can create any object ([including another factory](http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12)), or a general-purpose dependency injection framework that is far more complex to manage than simply writing code that actually *does* something.
I had to deal with people intent on abstraction to the point of navel-gazing when I was managing the Zend Framework project. I turned down a bunch of proposals to create components that didn't do anything, they were just magical implementations of GoF patterns, as though the pattern were a goal in itself, instead of a means to a goal.
There's a point of diminishing returns for abstraction. Some abstraction is great, but eventually you need to write code that does something useful.
Otherwise it's just [turtles all the way down](http://en.wikipedia.org/wiki/Turtles_all_the_way_down). | Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages? | [
"",
"python",
"metaprogramming",
"design-patterns",
"factory",
"metaclass",
""
] |
We are currently using the log4net appender (web.config snippet):
```
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
```
Looking for experience using other appenders. | We use `SmtpAppender` for ERROR and FATAL levels to "mail home" exception reports. Also `ConsoleAppender` when running a Windows Service in a console.
For `FileAppender` we set `<staticLogFileName value="false" />` to avoid an ever-increasing delay when rolling over to a new file and the folder contains lots of files. | My former company actually found that [NLog](http://www.nlog-project.org/) was faster. | .NET: Looking for best performing appender of log4net | [
"",
"c#",
".net",
"asp.net",
"log4net",
""
] |
So, I am working with .NET. I have an XSL file, XslTransform object in C# that reads in the XSL file and transforms a piece of XML data (manufactured in-house) into HTML.
I notice that my final output has **<** and **>** automatically encoded into **<** and **>**. Is there any ways I can prevent that from happening? Sometimes I need to bold or italicize my text but it's been unintentionally sanitized. | Your xsl file should have:
* an output of html
* omit namespaces for all used in the xslt
i.e.
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
exclude-result-prefixes="xsl msxsl">
<xsl:output method="html" indent="no" omit-xml-declaration="yes"/>
<!-- lots -->
</xsl:stylesheet>
```
And you should ideally use the overloads that accept either a `TextWriter` or a `Stream` (not `XmlWriter`) - i.e. something like:
```
StringBuilder sb = new StringBuilder();
using (XmlReader reader = XmlReader.Create(source)
using (TextWriter writer = new StringWriter(sb))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("Foo.xslt"); // in reality, you'd want to cache this
xslt.Transform(reader, options.XsltOptions, writer);
}
string html = sb.ToString();
```
In the xslt, if you really want standalone `<` / `>` (i.e. you want it to be malformed for some reason), then you need to disable output escaping:
```
<xsl:text disable-output-escaping="yes">
Your malformed text here
</xsl:text>
```
However, in general it is *correct* to escape the characters. | I have used this in the past to transform XMl documents into HTML strings which is what you need.
```
public static string TransformXMLDocFromFileHTMLString(string orgXML, string transformFilePath)
{
System.Xml.XmlDocument orgDoc = new System.Xml.XmlDocument();
orgDoc.LoadXml(orgXML);
XmlNode transNode = orgDoc.SelectSingleNode("/");
System.Text.StringBuilder sb = new System.Text.StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
XmlWriter writer = XmlWriter.Create(sb, settings);
System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();
trans.Load(transformFilePath);
trans.Transform(transNode, writer);
return sb.ToString();
}
``` | What's the property way to transform with XSL without HTML encoding my final output? | [
"",
"c#",
"asp.net",
"xml",
"xslt",
""
] |
I am a noob when it comes to python. I have a python script which gives me output like this:
```
[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[download] Destination: myvideo.flv
[download] 9.9% of 10.09M at 3.30M/s ETA 00:02
```
The last line keeps getting updated with new values of progress. I want to change this. Instead of updating I want a new line to be printed each time. How can i do this? I think the part concerned is this bit:
```
def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
"""Report download progress."""
self.to_stdout(u'\r[download] %s of %s at %s ETA %s' %
(percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
```
If more code needs to be seen please let me know so that I can show you what is needed to solve this.
Thank you very much for any help. | If I understand your request properly, you should be able to change that function to this:
```
def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
"""Report download progress."""
print u'[download] %s of %s at %s ETA %s' % (percent_str, data_len_str, speed_str, eta_str)
```
That will print the output on a new line each time. | I'm thinking you may just need to change:
```
skip_eol=True
```
to:
```
skip_eol=False
```
and get rid of the "`\r`" to see what happens. I think you'll be pleasantly surprised :-) | Python Script: Print new line each time to shell rather than update existing line | [
"",
"python",
"shell",
""
] |
I want to create a sort of light/thick box that only acts on a single DIV within a page.
When mine fires off the first div(phantom\_back) acts as I want it but the second, phantom\_top sets its self after phantom\_back regardless of its z-index and positioning.
What am I doing wrong?
Here is what I have so far:
```
<html>
<head>
<script type="text/javascript">
<!--//
function phantom_back(image)
{
document.getElementById('phantom_back').style.zIndex = 100;
document.getElementById('phantom_back').style.height = '100%';
document.getElementById('phantom_back').style.width = '100%';
phantom_top();
}
function phantom_top(image)
{
document.getElementById('phantom_top').style.zIndex = 102;
document.getElementById('phantom_top').style.height = 600;
document.getElementById('phantom_top').style.width = 600;
document.getElementById('phantom_top').style.top = 0;
document.getElementById('phantom_top').style.left = 0;
}
//-->
</script>
</head>
<body>
<a href="#" onclick="phantom_back()">Change</a>
<div style="height: 700px; width: 700px; border: 2px black solid; margin:0 auto; background-color: red;" id="overlord">
<div style="height: 10px; width: 10px; position: relative; z-index: -1; background-color: #000000; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: 0.5;" id="phantom_back"></div>
<div style="height: 10px; width: 10px; position: relative; z-index: -3; margin: 0 auto; background-color: green;" id="phantom_top">asdf</div>
</div>
</body>
</html>
```
I was wandering why none of the tutorials I've been able to find offer something like this. | So, I got it. I set an absolute positioning on phantom\_back and instead of trying to restack them I just set the visibility. When I tried to set the z-index it would fall apart on me.
```
<html>
<head>
<script type="text/javascript">
<!--//
function phantom_back(image)
{
document.getElementById('phantom_back').style.height = 700;
document.getElementById('phantom_back').style.width = 700;
document.getElementById('phantom_back').style.zIndex = 50;
phantom_top();
}
function phantom_top()
{
document.getElementById('phantom_top').style.height = 600;
document.getElementById('phantom_top').style.width = 600;
document.getElementById('phantom_top').style.visibility = "visible";
}
//-->
</script>
</head>
<body>
<a href="#" onclick="phantom_back()">Change</a>
<div style="height: 700px; width: 700px; border: 2px black solid; margin:0 auto; background-color: red;" id="overlord">
<div style="height: 10px; width: 10px; position: absolute; z-index: -1; background-color: #000000; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: 0.5;" id="phantom_back"></div>
<div style="margin: 0 auto; text-align: center; height: 10px; width: 10px; position: relative; z-index: 102; top: 10px; background-color: white; visibility: hidden;" id="phantom_top"><br /><br /><img src="load.gif"></div>
</div>
</body>
</html>
``` | phantom\_top is set to position:relative not absolute therefore it's currently not overlapping phantom\_back. | javascript, css, z-index, div stacking | [
"",
"javascript",
"css",
"html",
"z-index",
""
] |
I'm trying to write a branchless function to return the MAX or MIN of two integers without resorting to if (or ?:). Using [the usual technique](https://stackoverflow.com/questions/227383/how-do-i-programmatically-return-the-max-of-two-integers-without) I can do this easily enough for a given word size:
```
inline int32 imax( int32 a, int32 b )
{
// signed for arithmetic shift
int32 mask = a - b;
// mask < 0 means MSB is 1.
return a + ( ( b - a ) & ( mask >> 31 ) );
}
```
Now, assuming [arguendo](http://en.wikipedia.org/wiki/For_arguing) that I really am writing the kind of application on the kind of in-order processor where this is necessary, my question is whether there is a way to use C++ templates to generalize this to all sizes of int.
The **>>31** step only works for int32s, of course, and while I could copy out overloads on the function for int8, int16, and int64, it seems like I should use a template function instead. But how do I get the size of a template argument in *bits*?
Is there a better way to do it than this? Can I force the mask T to be signed? If T is unsigned the mask-shift step won't work (because it'll be a logical rather than arithmetic shift).
```
template< typename T >
inline T imax( T a, T b )
{
// how can I force this T to be signed?
T mask = a - b;
// I hope the compiler turns the math below into an immediate constant!
mask = mask >> ( (sizeof(T) * 8) - 1 );
return a + ( ( b - a ) & mask );
}
```
And, having done the above, can I prevent it from being used for anything but an integer type (eg, no floats or classes)? | **EDIT:** This answer is from before C++11. Since then, C++11 and later has offered `make_signed<T>` and much more as part of the standard library
---
Generally, looks good, but for 100% portability, replace that 8 with `CHAR_BIT` (or `numeric_limits<char>::max()`) since it isn't guaranteed that characters are 8-bit.
Any good compiler will be smart enough to merge all of the math constants at compile time.
You can force it to be signed by using a type traits library. which would usually look something like (assuming your numeric\_traits library is called numeric\_traits):
```
typename numeric_traits<T>::signed_type x;
```
An example of a manually rolled numeric\_traits header could look like this: <http://rafb.net/p/Re7kq478.html> (there is plenty of room for additions, but you get the idea).
or better yet, use boost:
```
typename boost::make_signed<T>::type x;
```
EDIT: IIRC, signed right shifts don't **have to be** arithmetic. It is common, and certainly the case with every compiler I've used. But I believe that the standard leaves it up the compiler whether right shifts are arithmetic or not on signed types. In my copy of the draft standard, the following is written:
> The value of E1 >> E2 is E1
> rightshifted E2 bit positions. If E1
> has an unsigned type or if E1 has a
> signed type and a nonnegative value,
> the value of the result is the
> integral part of the quotient of E1
> divided by the quantity 2 raised to
> the power E2. **If E1 has a signed type
> and a negative value, the resulting
> value is implementation defined**.
But as I said, it will work on every compiler I've seen :-p. | ## tl;dr
To achieve your goals, you're best off just writing this:
```
template<typename T> T max(T a, T b) { return (a > b) ? a : b; }
```
## Long version
I implemented both the "naive" implementation of `max()` as well as your branchless implementation. Both of them were not templated, and I instead used int32 just to keep things simple, and as far as I can tell, not only did Visual Studio 2017 make the naive implementation branchless, it also produced fewer instructions.
Here is the relevant [Godbolt](https://godbolt.org/z/ersx_a) (and please, check the implementation to make sure I did it right). Note that I'm compiling with /O2 optimizations.
Admittedly, my assembly-fu isn't all that great, so while `NaiveMax()` had 5 fewer instructions and no apparent branching (and inlining I'm honestly not sure what's happening) I wanted to run a test case to definitively show whether the naive implementation was faster or not.
So I built a test. Here's the code I ran. Visual Studio 2017 (15.8.7) with "default" Release compiler options.
```
#include <iostream>
#include <chrono>
using int32 = long;
using uint32 = unsigned long;
constexpr int32 NaiveMax(int32 a, int32 b)
{
return (a > b) ? a : b;
}
constexpr int32 FastMax(int32 a, int32 b)
{
int32 mask = a - b;
mask = mask >> ((sizeof(int32) * 8) - 1);
return a + ((b - a) & mask);
}
int main()
{
int32 resInts[1000] = {};
int32 lotsOfInts[1'000];
for (uint32 i = 0; i < 1000; i++)
{
lotsOfInts[i] = rand();
}
auto naiveTime = [&]() -> auto
{
auto start = std::chrono::high_resolution_clock::now();
for (uint32 i = 1; i < 1'000'000; i++)
{
const auto index = i % 1000;
const auto lastIndex = (i - 1) % 1000;
resInts[lastIndex] = NaiveMax(lotsOfInts[lastIndex], lotsOfInts[index]);
}
auto finish = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
}();
auto fastTime = [&]() -> auto
{
auto start = std::chrono::high_resolution_clock::now();
for (uint32 i = 1; i < 1'000'000; i++)
{
const auto index = i % 1000;
const auto lastIndex = (i - 1) % 1000;
resInts[lastIndex] = FastMax(lotsOfInts[lastIndex], lotsOfInts[index]);
}
auto finish = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
}();
std::cout << "Naive Time: " << naiveTime << std::endl;
std::cout << "Fast Time: " << fastTime << std::endl;
getchar();
return 0;
}
```
And here's the output I get on my machine:
```
Naive Time: 2330174
Fast Time: 2492246
```
I've run it several times getting similar results. Just to be safe, I also changed the order in which I conduct the tests, just in case it's the result of a core ramping up in speed, skewing the results. In all cases, I get similar results to the above.
Of course, depending on your compiler or platform, these numbers may all be different. It's worth testing yourself.
## The Answer
In brief, it would seem that the best way to write a branchless templated `max()` function is *probably* to keep it simple:
```
template<typename T> T max(T a, T b) { return (a > b) ? a : b; }
```
There are additional upsides to the naive method:
1. It works for unsigned types.
2. It even works for floating types.
3. It expresses exactly what you intend, rather than needing to comment up your code describing what the bit-twiddling is doing.
4. It is a well known and recognizable pattern, so most compilers will know exactly how to optimize it, making it more portable. (This is a gut hunch of mine, only backed up by personal experience of compilers surprising me a lot. I'll be willing to admit I'm wrong here.) | Templatized branchless int max/min function | [
"",
"c++",
"performance",
"templates",
"bit-manipulation",
"branchless",
""
] |
I used windows installer (msi project) and actually I have the msi file after installation it throws a shortcuts to the desktop.
My problem is when i double-click on the shortcut for my application, it displays somthing like the installation then it runs my application. I don't want the installtion windows to appear where my application doesn't need to throw any file or to install something before running all pre-requests are installed through the msi file. I want that when the end-user clicks on the shortcut, it runs the application directly ...
I hope I explained my problem well.
One additional note i'm using VS 2005, C#
What if i want to remove this action where it always happens. everytime i double click on the exe file it appears this window . my application is not so complicated to so.
EDIT: where can i find the log file ?!?
please help.
thnx indavence | One of the "*features*" of the MSI installation system is that it can automatically repair some things when your application is run.
A good way to see this in action is to have two versions of Microsoft Office installed side-by-side. After running MS Word 2007, an invocation of MS Word 2003 will start with MsiExec popping up to fix a few things before the application starts.
Almost certainly, what you're seeing is this kind of repair - check the log file and find out what is being fixed, then alter your installation project so things aren't broken on first install.
Hope this helps. | That quick installer operations you saw is very often issue. I think it appears only on first run and never again. Never mind. Maybe Windows Installer service makes some registration, etc. | Unwanted MSI appearance after installation | [
"",
"c#",
"visual-studio-2005",
"installation",
"windows-installer",
"vdproj",
""
] |
My particular problem:
I have a string which specifies an aribitrary type in a configuration class
`Config.numberType = "System.Foo";`
where `Foo` is a type like `Decimal` or `Double`
I use `Type.GetType(Config.numberType)` to return the corresponding type.
How do I get from that type to being able to use, `System.Foo.TryParse()` ?
**Some further related queries**
* `TryParse()` can be accessed from `System.Foo.TryParse()` as well as `foo.TryParse()`. Does this mean `foo` is some kind of class in C#? This seems weird to me that `int`, `double` etc are actually not just modifier keywords.
* How can you declare variables under these circumstances? - `var` is not universally usable it seems i.e. only in local scope etc. | As many have said - there isn't a direct route. I expect one close option is `TypeConverter`:
```
Type type = typeof(double);
string text = "123.45";
object value = TypeDescriptor.GetConverter(type)
.ConvertFromInvariantString(text);
```
Of course, you may need `try`/`catch` to handle exceptions. Such is life. | > How do I get from that type to being
> able to use, System.Foo.TryParse() ?
You'll need to use reflection to look up and then invoke the static `TryParse()` method. Not all types implement this method - so you'll have to decide how to handle it if it's missing. You could also use [`System.Convert`](http://msdn.microsoft.com/en-us/library/system.convert.aspx) to convert a string to an arbitrary type, assuming the string is actually a valid representation of a value for that type *and* there's a conversion implemented for it.
> TryParse() can be accessed from
> System.Foo.TryParse() as well as
> foo.TryParse(). Does this mean foo is
> some kind of class in C#?
`int`, `double`, etc. are [aliases](https://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care) for `System.Int32`, `System.Double`, etc. - they're part of the C# language, which would be uncomfortably verbose without them.
> How can you declare variables under
> these circumstances?
Without knowing the type at compile-time, you'll be forced to declare and work with your data as `object` / `System.Object`. C# 4.0 will introduce actual dynamic types that will take care of some of the tedious reflection work for you, but for now you're stuck doing it by hand. Note that if you [use `System.Convert`](https://stackoverflow.com/questions/476589/how-do-i-get-from-a-type-to-the-tryparse-method#476654) in a method [with a parametrized type argument and return](https://stackoverflow.com/questions/170665/helper-functions-for-safe-conversion-from-strings#170731), or `TryParse()` using a technique such as that [linked to by Sebastian Sedlak](https://stackoverflow.com/questions/476589/how-do-i-get-from-a-type-to-the-tryparse-method#476607), you can easily achieve the ability to write client code that works with static types... So long as they match or can be converted to from the types you're parsing. | How do I get from a type to the TryParse method? | [
"",
"c#",
"parsing",
"types",
""
] |
How do I traverse a list in reverse order in Python? So I can start from `collection[len(collection)-1]` and end in `collection[0]`.
I also want to be able to access the loop index. | Use the built-in [`reversed()`](https://docs.python.org/library/functions.html#reversed) function:
```
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
```
To also access the original index, use [`enumerate()`](https://docs.python.org/library/functions.html#enumerate) on your list before passing it to `reversed()`:
```
>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
```
Since `enumerate()` returns a generator and generators can't be reversed, you need to convert it to a `list` first. | You can do:
```
for item in my_list[::-1]:
print item
```
(Or whatever you want to do in the for loop.)
The `[::-1]` slice reverses the list in the for loop (but won't actually modify your list "permanently"). | Traverse a list in reverse order in Python | [
"",
"python",
"loops",
"reverse",
""
] |
Is there a way to use DecimalFormat (or some other standard formatter) to format numbers like this:
> 1,000,000 => 1.00M
>
> 1,234,567 => 1.23M
>
> 1,234,567,890 => 1234.57M
Basically dividing some number by 1 million, keeping 2 decimal places, and slapping an 'M' on the end. I've thought about creating a new subclass of NumberFormat but it looks trickier than I imagined.
I'm writing an API that has a format method that looks like this:
```
public String format(double value, Unit unit); // Unit is an enum
```
Internally, I'm mapping Unit objects to NumberFormatters. The implementation is something like this:
```
public String format(double value, Unit unit)
{
NumberFormatter formatter = formatters.get(unit);
return formatter.format(value);
}
```
Note that because of this, I can't expect the client to divide by 1 million, and I can't just use String.format() without wrapping it in a NumberFormatter. | ```
String.format("%.2fM", theNumber/ 1000000.0);
```
For more information see the [String.format javadocs](http://java.sun.com/javase/6/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)). | Note that if you have a `BigDecimal`, you can use the `movePointLeft` method:
```
new DecimalFormat("#.00").format(value.movePointLeft(6));
``` | Java: Format number in millions | [
"",
"java",
"formatting",
"numeric",
"numericupdown",
""
] |
With reference to the following thread:
[Java App : Unable to read iso-8859-1 encoded file correctly](https://stackoverflow.com/questions/498636/java-app-unable-to-read-iso-8859-1-encoded-file-correctly)
What is the best way to programatically determine the correct charset encoding of an inputstream/file ?
I have tried using the following:
```
File in = new File(args[0]);
InputStreamReader r = new InputStreamReader(new FileInputStream(in));
System.out.println(r.getEncoding());
```
But on a file which I know to be encoded with ISO8859\_1 the above code yields ASCII, which is not correct, and does not allow me to correctly render the content of the file back to the console. | I have used this library, similar to jchardet for detecting encoding in Java:
<https://github.com/albfernandez/juniversalchardet> | You cannot determine the encoding of a arbitrary byte stream. This is the nature of encodings. A encoding means a mapping between a byte value and its representation. So every encoding "could" be the right.
The [getEncoding()](http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#getEncoding%28%29) method will return the encoding which was set up (read the [JavaDoc](http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#getEncoding%28%29)) for the stream. It will not guess the encoding for you.
Some streams tell you which encoding was used to create them: XML, HTML. But not an arbitrary byte stream.
Anyway, you could try to guess an encoding on your own if you have to. Every language has a common frequency for every char. In English the char e appears very often but ê will appear very very seldom. In a ISO-8859-1 stream there are usually no 0x00 chars. But a UTF-16 stream has a lot of them.
Or: you could ask the user. I've already seen applications which present you a snippet of the file in different encodings and ask you to select the "correct" one. | Java : How to determine the correct charset encoding of a stream | [
"",
"java",
"file",
"encoding",
"stream",
"character-encoding",
""
] |
here is the code
```
<php?
$id1 =1;
$id2 = "module 1 loaded";
echo "$var1=$id1","$var2=$id2";
?>
```
i know this is not correct way how can i pass these two varables to flash | ```
<?php
echo http_build_query( array(
'var1' => 1
,'var2' => 'module 1 loaded'
));
``` | If you want to create a script which outputs data which can be loaded with [LoadVariables](http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary425.html) or [LoadVars](http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary427.html) you need something like this
```
//set up your values
$vars=array();
$vars['foo']='bar';
$vars['xyz']='123';
//output
header ("Content-Type: application/x-www-urlformencoded");
$sep="";
foreach($vars as $name=>$val)
{
echo $sep.$name."=".urlencode($val);
$sep="&";
}
```
If your version of PHP supports it, [http\_build\_query](http://php.net/http_build_query) makes this even easier:
```
$vars=array();
$vars['foo']='bar';
$vars['xyz']='123';
header ("Content-Type: application/x-www-urlformencoded");
echo http_build_query($vars);
``` | passing multiple values to flash through php | [
"",
"php",
"flash",
""
] |
We are computing something whose runtime is bound by matrix operations. (Some details below if interested.) This experience prompted the following question:
Do folk have experience with the performance of Java libraries for matrix math (e.g., multiply, inverse, etc.)? For example:
* [JAMA](http://math.nist.gov/javanumerics/jama/)
* [COLT](http://acs.lbl.gov/~hoschek/colt/)
* [Apache commons math](http://commons.apache.org/math/)
I searched and found nothing.
---
Details of our speed comparison:
We are using Intel FORTRAN (ifort (IFORT) 10.1 20070913). We have reimplemented it in Java (1.6) using Apache commons math 1.2 matrix ops, and it agrees to all of its digits of accuracy. (We have reasons for wanting it in Java.) (Java doubles, Fortran real\*8). Fortran: 6 minutes, Java 33 minutes, same machine. jvisualm profiling shows much time spent in RealMatrixImpl.{getEntry,isValidCoordinate} (which appear to be gone in unreleased Apache commons math 2.0, but 2.0 is no faster). Fortran is using Atlas BLAS routines (dpotrf, etc.).
Obviously this could depend on our code in each language, but we believe most of the time is in equivalent matrix operations.
In several other computations that do not involve libraries, Java has not been much slower, and sometimes much faster. | Just to add my 2 cents. I've compared some of these libraries. I attempted to matrix multiply a 3000 by 3000 matrix of doubles with itself. The results are as follows.
Using multithreaded ATLAS with C/C++, Octave, Python and R, the time taken was around 4 seconds.
Using Jama with Java, the time taken was 50 seconds.
Using Colt and Parallel Colt with Java, the time taken was 150 seconds!
Using JBLAS with Java, the time taken was again around 4 seconds as JBLAS uses multithreaded ATLAS.
So for me it was clear that the Java libraries didn't perform too well. However if someone has to code in Java, then the best option is JBLAS. Jama, Colt and Parallel Colt are not fast. | I'm the author of Java Matrix Benchmark ([JMatBench](http://lessthanoptimal.github.io/Java-Matrix-Benchmark/)) and I'll give my thoughts on this discussion.
There are significant difference between Java libraries and while there is no clear winner across the whole range of operations, there are a few clear leaders as can be seen in the [latest performance results](http://lessthanoptimal.github.io/Java-Matrix-Benchmark/runtime/2013_10_Corei7v2600/) (October 2013).
If you are working with "large" matrices and can use native libraries, then the clear winner (about 3.5x faster) is [MTJ](https://github.com/fommil/matrix-toolkits-java/) with [system optimised netlib](https://github.com/fommil/netlib-java/). If you need a pure Java solution then [MTJ](https://github.com/fommil/matrix-toolkits-java/), [OjAlgo](http://ojalgo.org/), [EJML](http://ejml.org/) and [Parallel Colt](https://sites.google.com/site/piotrwendykier/software/parallelcolt) are good choices. For small matrices EJML is the clear winner.
The libraries I did not mention showed significant performance issues or were missing key features. | Performance of Java matrix math libraries? | [
"",
"java",
"math",
"matrix",
"performance",
""
] |
**Background**
I am working on a phonetic converter program which converts english text into equivalant regional language text. Regional languages will have more characters than english letters and regional language fonts uses almost all positions (1-255) in a font.
My program supports different fonts and I have created a font class which will have methods gives access to the characters. This class will have 255 methods each representing each character. All these are marked as *virtual* so that a new font can override necessary character methods.
The methods in this font class are trivial. All methods are single line. Example would be
```
string StandardFont::consonant1(){
return "a";
}
string StandardFont::consonant2(){
return "b";
}
..
```
**Questions**
1. Will 255 virtual functions in a single class make any performance issues? I know about *vtable* stuff, but I am not sure how much impact it has in this scenario.
2. Can anyone suggest an alternate design for this class? Main design goal is to allow derived classes to override necessary methods. I have thought about adding the characters into containers like *map* or *vector* and providing method to get the character. But since I will have 255 items and this class is used frequently, I think each time I have to loop the container to get the character, which is again an issue.
Any thought? | I suggest you use a standard encoding of non-ASCII (regional) characters.
A standard encoding is called "unicode", for example <http://www.joelonsoftware.com/articles/Unicode.html>
Anyway: to answer your questions ...
> Will 255 virtual functions in a single class make any performance issues?
In a word: no, it won't.
> But since I will have 255 items and this class is used frequently, I think each time I have to loop the container to get the character, which is again an issue.
With a vector or a fixed-length array whose length is 256, you wouldn't need to loop ... instead you could index directly, for example:
```
const char* translations[256] = {
"a",
"bee",
"c!",
...etc...
};
const char* translate(char c)
{
//use the character as an index into the array
int index = c;
//use the translation array (using indexing, not looping)
const char* result = translations[index];
return result;
}
``` | 255 virtual functions will not generally cause performance issues (except that each instance of your class will have a large VTable which will very marginally affect caching).
However, 255 virtual functions will generally cause a maintenance nightmare.
If I understand your description correctly, then what you need is:
1) Create a class representing a character in a regional language, probably with methods to return the image or whatever you need.
2) Create is a hierarchy of classes that represent character sets.
3) Every instance of a character set will maintain a mapping from positions to instances of the character class.
4) Have a function that gets the index and returns the object.
One benefit of this design is that you can have multiple character sets using some of the same glyphs (e.g., for numbers).
All that being said, why are you not using Unicode and 16 bit characters? | Class design suggestions - C++ | [
"",
"c++",
"virtual-functions",
""
] |
I'm writing some Scala code which uses the [Apache POI](http://en.wikipedia.org/wiki/Apache_POI) API. I would like to iterate over the rows contained in the `java.util.Iterator` that I get from the Sheet class. I would like to use the iterator in a `for each` style loop, so I have been trying to convert it to a native Scala collection but will no luck.
I have looked at the Scala wrapper classes/traits, but I can not see how to use them correctly. How do I iterate over a Java collection in Scala without using the verbose `while(hasNext()) getNext()` style of loop?
Here's the code I wrote based on the correct answer:
```
class IteratorWrapper[A](iter:java.util.Iterator[A])
{
def foreach(f: A => Unit): Unit = {
while(iter.hasNext){
f(iter.next)
}
}
}
object SpreadsheetParser extends Application
{
implicit def iteratorToWrapper[T](iter:java.util.Iterator[T]):IteratorWrapper[T] = new IteratorWrapper[T](iter)
override def main(args:Array[String]):Unit =
{
val ios = new FileInputStream("assets/data.xls")
val workbook = new HSSFWorkbook(ios)
var sheet = workbook.getSheetAt(0)
var rows = sheet.rowIterator()
for (val row <- rows){
println(row)
}
}
}
``` | There is a wrapper class (`scala.collection.jcl.MutableIterator.Wrapper`). So if you define
```
implicit def javaIteratorToScalaIterator[A](it : java.util.Iterator[A]) = new Wrapper(it)
```
then it will act as a sub class of the Scala iterator so you can do `foreach`. | As of Scala 2.8, all you have to do is to import the JavaConversions object, which already declares the appropriate conversions.
```
import scala.collection.JavaConversions._
```
This won't work in previous versions though. | Iterating over Java collections in Scala | [
"",
"java",
"scala",
"collections",
"scala-java-interop",
""
] |
From the [`isset()` docs](http://php.net/isset):
```
isset() will return FALSE if testing a variable that has been set to NULL.
```
Basically, `isset()` doesn't check for whether the variable is set at all, but whether it's set to anything but `NULL`.
Given that, what's the best way to actually check for the existence of a variable? I tried something like:
```
if(isset($v) || @is_null($v))
```
(the `@` is necessary to avoid the warning when `$v` is not set) but `is_null()` has a similar problem to `isset()`: it returns `TRUE` on unset variables! It also appears that:
```
@($v === NULL)
```
works exactly like `@is_null($v)`, so that's out, too.
How are we supposed to reliably check for the existence of a variable in PHP?
---
Edit: there is clearly a difference in PHP between variables that are not set, and variables that are set to `NULL`:
```
<?php
$a = array('b' => NULL);
var_dump($a);
```
PHP shows that `$a['b']` exists, and has a `NULL` value. If you add:
```
var_dump(isset($a['b']));
var_dump(isset($a['c']));
```
you can see the ambiguity I'm talking about with the `isset()` function. Here's the output of all three of these `var_dump()s`:
```
array(1) {
["b"]=>
NULL
}
bool(false)
bool(false)
```
---
Further edit: two things.
One, a use case. An array being turned into the data of an SQL `UPDATE` statement, where the array's keys are the table's columns, and the array's values are the values to be applied to each column. Any of the table's columns can hold a `NULL` value, signified by passing a `NULL` value in the array. You *need* a way to differentiate between an array key not existing, and an array's value being set to `NULL`; that's the difference between not updating the column's value and updating the column's value to `NULL`.
Second, [Zoredache's answer](https://stackoverflow.com/questions/418066/best-way-to-test-for-a-variables-existence-in-php-isset-is-clearly-broken#418162), `array_key_exists()` works correctly, for my above use case and for any global variables:
```
<?php
$a = NULL;
var_dump(array_key_exists('a', $GLOBALS));
var_dump(array_key_exists('b', $GLOBALS));
```
outputs:
```
bool(true)
bool(false)
```
Since that properly handles just about everywhere I can see there being any ambiguity between variables that don't exist and variables that are set to `NULL`, **I'm calling `array_key_exists()` the official easiest way in PHP to truly check for the existence of a variable**.
(Only other case I can think of is for class properties, for which there's `property_exists()`, which, according to [its docs](http://php.net/property_exists), works similarly to `array_key_exists()` in that it properly distinguishes between not being set and being set to `NULL`.) | If the variable you are checking would be in the global scope you could do:
```
array_key_exists('v', $GLOBALS)
``` | Attempting to give an overview of the various discussions and answers:
**There is no single answer to the question which can replace all the ways `isset` can be used.** Some use cases are addressed by other functions, while others do not stand up to scrutiny, or have dubious value beyond code golf. Far from being "broken" or "inconsistent", other use cases demonstrate why `isset`'s reaction to `null` is the logical behaviour.
# Real use cases (with solutions)
## 1. Array keys
Arrays can be treated like collections of variables, with `unset` and `isset` treating them as though they were. However, since they can be iterated, counted, etc, a missing value is not the same as one whose value is `null`.
The answer in this case, is to **use [`array_key_exists()`](http://php.net/array_key_exists) instead of `isset()`**.
Since this is takes the array to check as a function argument, PHP will still raise "notices" if the array itself doesn't exist. In some cases, it can validly be argued that each dimension should have been initialised first, so the notice is doing its job. For other cases, a "recursive" `array_key_exists` function, which checked each dimension of the array in turn, would avoid this, but would basically be the same as `@array_key_exists`. It is also somewhat tangential to the handling of `null` values.
## 2. Object properties
In the traditional theory of "Object-Oriented Programming", encapsulation and polymorphism are key properties of objects; in a class-based OOP implementation like PHP's, the encapsulated properties are declared as part of the class definition, and given access levels (`public`, `protected`, or `private`).
However, PHP also allows you to dynamically add properties to an object, like you would keys to an array, and some people use class-less objects (technically, instances of the built in `stdClass`, which has no methods or private functionality) in a similar way to associative arrays. This leads to situations where a function may want to know if a particular property has been added to the object given to it.
As with array keys, **a solution for checking object properties is included in the language, called, reasonably enough, [`property_exists`](http://php.net/property_exists)**.
# Non-justifiable use cases, with discussion
## 3. `register_globals`, and other pollution of the global namespace
The `register_globals` feature added variables to the global scope whose names were determined by aspects of the HTTP request (GET and POST parameters, and cookies). This can lead to buggy and insecure code, which is why it has been disabled by default since [PHP 4.2, released Aug 2000](http://www.php.net/releases/4_2_0.php) and removed completely in [PHP 5.4, released Mar 2012](http://www.php.net/releases/5_4_0.php). However, it's possible that some systems are still running with this feature enabled or emulated. It's also possible to "pollute" the global namespace in other ways, using the `global` keyword, or `$GLOBALS` array.
Firstly, `register_globals` itself is unlikely to unexpectedly produce a `null` variable, since the GET, POST, and cookie values will always be strings (with `''` still returning `true` from `isset`), and variables in the session should be entirely under the programmer's control.
Secondly, pollution of a variable with the value `null` is only an issue if this over-writes some previous initialization. "Over-writing" an uninitialized variable with `null` would only be problematic if code somewhere else was distinguishing between the two states, so on its own this possibility is an argument *against* making such a distinction.
## 4. `get_defined_vars` and `compact`
A few rarely-used functions in PHP, such as [`get_defined_vars`](http://php.net/get_defined_vars) and [`compact`](http://php.net/compact), allow you to treat variable names as though they were keys in an array. For global variables, [the super-global array `$GLOBALS`](http://php.net/manual/en/reserved.variables.globals.php) allows similar access, and is more common. These methods of access will behave differently if a variable is not defined in the relevant scope.
Once you've decided to treat a set of variables as an array using one of these mechanisms, you can do all the same operations on it as on any normal array. Consequently, see 1.
Functionality that existed only to predict how these functions are about to behave (e.g. "will there be a key 'foo' in the array returned by `get_defined_vars`?") is superfluous, since you can simply run the function and find out with no ill effects.
## 4a. Variable variables (`$$foo`)
While not quite the same as functions which turn a set of variables into an associative array, most cases using ["variable variables"](http://php.net/manual/en/language.variables.variable.php) ("assign to a variable named based on this other variable") can and should be changed to use an associative array instead.
A variable name, fundamentally, is the label given to a value by the programmer; if you're determining it at run-time, it's not really a label but a key in some key-value store. More practically, by not using an array, you are losing the ability to count, iterate, etc; it can also become impossible to have a variable "outside" the key-value store, since it might be over-written by `$$foo`.
Once changed to use an associative array, the code will be amenable to solution 1. Indirect object property access (e.g. `$foo->$property_name`) can be addressed with solution 2.
## 5. `isset` is so much easier to type than `array_key_exists`
I'm not sure this is really relevant, but yes, PHP's function names can be pretty long-winded and inconsistent sometimes. Apparently, pre-historic versions of PHP used a function name's length as a hash key, so Rasmus deliberately made up function names like `htmlspecialchars` so they would have an unusual number of characters...
Still, at least we're not writing Java, eh? ;)
## 6. Uninitialized variables have a type
The [manual page on variable basics](http://php.net/manual/en/language.variables.basics.php) includes this statement:
> Uninitialized variables have a default value of their type depending on the context in which they are used
I'm not sure whether there is some notion in the Zend Engine of "uninitialized but known type" or whether this is reading too much into the statement.
What is clear is that it makes no practical difference to their behaviour, since the behaviours described on that page for uninitialized variables are identical to the behaviour of a variable whose value is `null`. To pick one example, both `$a` and `$b` in this code will end up as the integer `42`:
```
unset($a);
$a += 42;
$b = null;
$b += 42;
```
(The first will raise a notice about an undeclared variable, in an attempt to make you write better code, but it won't make any difference to how the code actually runs.)
## 99. Detecting if a function has run
*(Keeping this one last, as it's much longer than the others. Maybe I'll edit it down later...)*
Consider the following code:
```
$test_value = 'hello';
foreach ( $list_of_things as $thing ) {
if ( some_test($thing, $test_value) ) {
$result = some_function($thing);
}
}
if ( isset($result) ) {
echo 'The test passed at least once!';
}
```
If `some_function` can return `null`, there's a possibility that the `echo` won't be reached even though `some_test` returned `true`. The programmer's intention was to detect when `$result` had never been set, but PHP does not allow them to do so.
However, there are other problems with this approach, which become clear if you add an outer loop:
```
foreach ( $list_of_tests as $test_value ) {
// something's missing here...
foreach ( $list_of_things as $thing ) {
if ( some_test($thing, $test_value) ) {
$result = some_function($thing);
}
}
if ( isset($result) ) {
echo 'The test passed at least once!';
}
}
```
Because `$result` is never initialized explicitly, it will take on a value when the very first test passes, making it impossible to tell whether subsequent tests passed or not. **This is actually an extremely common bug when variables aren't initialised properly.**
To fix this, we need to do something on the line where I've commented that something's missing. The most obvious solution is to set `$result` to a "terminal value" that `some_function` can never return; if this is `null`, then the rest of the code will work fine. If there is no natural candidate for a terminal value because `some_function` has an extremely unpredictable return type (which is probably a bad sign in itself), then an additional boolean value, e.g. `$found`, could be used instead.
### Thought experiment one: the `very_null` constant
PHP could theoretically provide a special constant - as well as `null` - for use as a terminal value here; presumably, it would be illegal to return this from a function, or it would be coerced to `null`, and the same would probably apply to passing it in as a function argument. That would make this very specific case slightly simpler, but as soon as you decided to re-factor the code - for instance, to put the inner loop into a separate function - it would become useless. If the constant could be passed between functions, you could not guarantee that `some_function` would not return it, so it would no longer be useful as a universal terminal value.
The argument for detecting uninitialised variables in this case boils down to the argument for that special constant: if you replace the comment with `unset($result)`, and treat that differently from `$result = null`, you are introducing a "value" for `$result` that cannot be passed around, and can only be detected by specific built-in functions.
### Thought experiment two: assignment counter
Another way of thinking about what the last `if` is asking is "has anything made an assignment to `$result`?" Rather than considering it to be a special value of `$result`, you could maybe think of this as "metadata" *about* the variable, a bit like Perl's "variable tainting". So rather than `isset` you might call it `has_been_assigned_to`, and rather than `unset`, `reset_assignment_state`.
But if so, why stop at a boolean? What if you want to know *how many times* the test passed; you could simply extend your metadata to an integer and have `get_assignment_count` and `reset_assignment_count`...
Obviously, adding such a feature would have a trade-off in complexity and performance of the language, so it would need to be carefully weighed against its expected usefulness. As with a `very_null` constant, it would be useful only in very narrow circumstances, and would be similarly resistant to re-factoring.
The hopefully-obvious question is why the PHP runtime engine should assume in advance that you want to keep track of such things, rather than leaving you to do it explicitly, using normal code. | Best way to test for a variable's existence in PHP; isset() is clearly broken | [
"",
"php",
"variables",
"isset",
""
] |
On [this question](https://stackoverflow.com/questions/438192/using-declaration-with-enum), there's [an answer](https://stackoverflow.com/questions/438192/using-declaration-with-enum#439055) that states:
> You can use typedef to make Colour enumeration type accessible without specifying it's "full name".
>
> ```
> typedef Sample::Colour Colour;
> Colour c = Colour::BLUE;
> ```
That sounds correct to me, but someone down-voted it and left this comment:
> Using the scope resolution operator :: on enums (as in "Colour::BLUE") is a compiler-specific extension, not standard C++
Is that true? I believe I've used that on both MSVC and GCC, though I'm not certain of it. | I tried the following code:
```
enum test
{
t1, t2, t3
};
void main()
{
test t = test::t1;
}
```
Visual C++ 9 compiled it with the following warning:
> warning C4482: nonstandard extension
> used: enum 'test' used in qualified
> name
Doesn't look like it's standard. | **That is not standard.**
In C++11, you will be able to make scoped enums with an [enum class](http://en.wikipedia.org/wiki/C%2B%2B0x#Strongly_typed_enumerations) declaration.
With pre-C++11 compilers, to scope an enum, you will need to define the enum inside a struct or namespace. | Scope resolution operator on enums a compiler-specific extension? | [
"",
"c++",
"standards",
""
] |
Yesterday I read some code of a colleague and came across this:
```
class a_class
{
public:
a_class() {...}
int some_method(int some_param) {...}
int value_1;
int value_2;
float value_3;
std::vector<some_other_class*> even_more_values;
/* and so on */
}
a_class a_instances[10];
void some_function()
{
do_stuff();
do_more_stuff();
memset(a_instances, 0, 10 * sizeof(a_class)); // <===== WTF?
}
```
Is that legal (the WTF line, not the public attributes)? To me it smells really, really bad...
The code ran fine when compiled with VC8, but it throws an "unexpected exception" when compiled with VC9 when calling `a_instances[0].event_more_values.push_back(whatever)`, but when accessing any of the other members. Any insights?
EDIT: Changed the memset from `memset(&a_instances...` to `memset(a_instances...`. Thanks for pointing it out Eduard.
EDIT2: Removed the ctor's return type. Thanks litb.
Conclusion: Thanks folks, you confirmed my suspicion. | This is a widely accepted method for initialization for C structs.
In C++ it doesn't work ofcourse because you can't assume anything about `vector`s internal structure. Zeroing it out is very likely to leave it in an illegal state which is why your program crashes. | He uses memset on a non-POD class type. It's invalid, because C++ only allows it for the simplest cases: Where a class doesn't have a user declared constructor, destructor, no virtual functions and several more restrictions. An array of objects of it won't change that fact.
If he removes the vector he is fine with using memset on it though. One note though. Even if it isn't C++, it might still be valid for his compiler - because if the Standard says something has undefined behavior, implementations can do everything they want - including blessing such behavior and saying what happens. In his case, what happens is probably that you apply memset on it, and it would silently clear out any members of the vector. Possible pointers in it, that would point to the allocated memory, will now just contain zero, without it knowing that.
You can recommend him to clear it out using something like this:
```
...
for(size_t i=0; i < 10; i++)
objects[i].clear();
```
And write clear using something like:
```
void clear() {
a_object o;
o.swap(*this);
}
```
Swapping would just swap the vector of o with the one of \*this, and clear out the other variables. Swapping a vector is especially cheap. He of course needs to write a swap function then, that swaps the vector (`even_more_values.swap(that.even_more_values)`) and the other variables. | Erase all members of a class | [
"",
"c++",
""
] |
i have a log file which contains hundreds/thousands of seperate XML messages and need to find a way to extract a complete xml message depending on the parameters given (values of nodes).
My biggest problem is that even though i program a fair amount i have had very little contact with XML or the XML libraries of the languages i use and didnt think that a simple text parsing would be an elegant solution!
I am going to attempt this in C# or VB.net any help would be much appreciated and any attempt at a solution even better!
thanks in advance! | A very basic approach would be to:
1. Parse the file. You can extract each Xml message and treat it as one complete document.
2. Based on the parameters query the xml and determine if it's a match.
This solution is not the greatest, I would wager it will perform poorly as you'll be loading quite a lot, although only testing would know. This approach has a benefit in that the file doesn't have to be valid Xml. So if your parsing a file being written to, you'd be able to use this method. (I'm assuming your logger is just appending xml to the file and not treating this as one large dom).
If the file is not being written too, and depending on the size you could wrap the contents of the file in an Xml node. Again this assumes the only thing written to the file is Xml. If your logging additional info then you'll have to go with the first solution.
As for parsing the Xml you have various options such as Linq to Xml, or XPath. | EDIT: The answer below assumes that the whole log file is a valid XML document. Ignore if that's not the case.
XPath is probably your answer here - assuming you can afford to load the whole log file in one go, it should be fairly easy to use [XmlNode.SelectSingleNode](http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectsinglenode.aspx) or [XNode.XPathSelectElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.xpathselectelement.aspx).
Alternatively, if you're using LINQ to XML you could construct a LINQ query - that may well be more readable if you're not familiar with XPath.
If you want to learn XPath, I've usually found the [W3Schools](http://w3schools.com/xpath/) tutorial pretty good. | Extract a specific XML message from a log file | [
"",
"c#",
"xml",
"vb.net",
""
] |
Okay so I have a scenario similar to the below code, I have a parent class that implements IComparable and a child class.
```
class Parent : IComparable<Parent>
class Child : Parent
Child a = new Child();
Child b = new Child();
a.CompareTo(b);
```
Now the above works fine, i can compare two of the child objects to each other no problem
```
List<Child> l = new List<Child>();
l.Add(b);
l.Add(a);
l.Sort();
```
The above fails though with an InvalidOperationException. Can someone please explain why this sort isn't working when the child class does implement the IComparable interface, or at least it seems to me that it does.
Okay here is my CompareTo implementation for my actual parent class
```
public int CompareTo(IDType other)
{
return this.Name.ToString().CompareTo(other.ToString());
}
``` | Your type implements `IComparable<Parent>` rather than `IComparable<Child>`. As the [MSDN docs for Sort](http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx) say, it will throw InvalidOperationException if "the default comparer Comparer(T).Default cannot find an implementation of the IComparable(T) generic interface or the IComparable interface for type T." And indeed it can't, where T is Child. If you try making it a `List<Parent>` you may well find it's fine.
EDIT: Alternatively (and preferably, IMO) implement `IComparable<Child>`. At the moment it's not at all clear that a child can sensibly be compared with another child. Implementing `IComparable<Child>` - even if that implementation just defers to the base implementation - advertises the comparability. | I gave this a try and ran into the same error. My guess is that because you've got a `List<Child>` it's looking for someone that implements `IComparable<Child>`, not `IComparable<Parent>`.
If you change the collection to `List<Parent>`, things seem to work. Alternatively, have Child implement `IComparable<Child>` (and it can just delegate to Parent's implementation). | I have a problem with IComparable and the collection sort method | [
"",
"c#",
".net",
"generics",
"inheritance",
""
] |
Does anyone know if there is some parameter available for programmatic search on yahoo allowing to restrict results so only links to files of specific type will be returned (like PDF for example)?
It's possible to do that in GUI, but how to make it happen through API?
I'd very much appreciate a sample code in Python, but any other solutions might be helpful as well. | Thank you.
I found myself that something like this works OK (file type is the first argument, and query is the second):
format = sys.argv[1]
query = " ".join(sys.argv[2:])
srch = create\_search("Web", app\_id, query=query, format=format) | Yes, there is:
<http://developer.yahoo.com/search/boss/boss_guide/Web_Search.html#id356163> | how to search for specific file type with yahoo search API? | [
"",
"python",
"yahoo-api",
"yahoo-search",
""
] |
I'm writing a Windows Service for communication with a Serial Mag-stripe reader and a relay board (access control system).
I run into problems where the code stops working (i get IOExceptions) after another program has "interrupted" the process by opening the same serial port as my service.
Part of the code is as follows:
```
public partial class Service : ServiceBase
{
Thread threadDoorOpener;
public Service()
{
threadDoorOpener = new Thread(DoorOpener);
}
public void DoorOpener()
{
while (true)
{
SerialPort serialPort = new SerialPort();
Thread.Sleep(1000);
string[] ports = SerialPort.GetPortNames();
serialPort.PortName = "COM1";
serialPort.BaudRate = 9600;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
serialPort.Parity = Parity.None;
if (serialPort.IsOpen) serialPort.Close();
serialPort.Open();
serialPort.DtrEnable = true;
Thread.Sleep(1000);
serialPort.Close();
}
}
public void DoStart()
{
threadDoorOpener.Start();
}
public void DoStop()
{
threadDoorOpener.Abort();
}
protected override void OnStart(string[] args)
{
DoStart();
}
protected override void OnStop()
{
DoStop();
}
}
```
My sample program successfully starts the work-thread, and the opening/closing and raising of DTR causes my Mag-stripe reader to power up (wait 1sec), shut down (wait 1 sec) and so on.
If I launch HyperTerminal and connects to the same COM port, HyperTerminal tells me the port is currently in use. If i repeatedly press ENTER in HyperTerminal, to try to reopen
the port it will succeed after a few retries.
This has the effect of causing IOExceptions in my work-thread, which is expected. However, even if I close down HyperTerminal, i still get the same IOException in my work-thread. The only cure is actually to restart the computer.
Other programs (which is not using .NET libraries for port-access) seem to work normally at this point.
Any ideas as to what is causing this? | @thomask
Yes, Hyperterminal does in fact enable fAbortOnError in SetCommState's DCB, which explains for most of the IOExceptions thrown by the SerialPort object. Some PCs / handhelds also have UARTs that have the abort on error flag turned on by default - so it's imperative that a serial port's init routine clears it (which Microsoft neglected to do). I wrote a long article recently to explain this in greater detail (see [this](http://zachsaw.blogspot.com/2010/07/net-serialport-woes.html) if you're interested). | You can't close someone elses connection to a port, the following code will never work:
```
if (serialPort.IsOpen) serialPort.Close();
```
Because your object didn't open the port you can't close it.
Also you should close and dispose the serial port even after exceptions occur
```
try
{
//do serial port stuff
}
finally
{
if(serialPort != null)
{
if(serialPort.IsOpen)
{
serialPort.Close();
}
serialPort.Dispose();
}
}
```
If you want the process to be interruptible then you should Check if the port is open and then back off for a period and then try again, something like.
```
while(serialPort.IsOpen)
{
Thread.Sleep(200);
}
``` | How to do robust SerialPort programming with .NET / C#? | [
"",
"c#",
".net",
"serial-port",
""
] |
I have a string looks like
aeroport aimé
I know it is French, and I want to convert this string back to readable format.
Any suggestions? | Heh. It's simple cryptanalysis task. You should collect statistics of letter usage in your string. It can be by single letter, two- or better tree-letter groups. Than you should collect the same statistics on big amount of text of same thematic. Then you should arrange tree-gramms of Franch and your fancy text by usage and decode your cryptogram. Of course it'll be wrong at first, but than you can apply dictionary to determine failure ratio and apply some kind of genetics algorithm to find best mach.
And by the way. If originally text was UTF-8, but was 'forced' to be an one byte code page text, you should operate in bytes - not in symbols. | That is not French, the French word for "airport" is "aéroport".
If you want to convert the string to a readable format, you have to know what encoding the original string was in, not what language. "aeroport aimé" is a legal UTF8 string.
Where are you seeing this string? On a Windows command prompt? That shows funny characters like "├⌐" for high-ASCII characters. The command prompt uses CP437, not UTF8, if you have the UTF8 string "aimé" it will display as "aim├⌐" in CP437.
If that is your situation, try writing the string to a file and opening the file in Notepad. If that looks right your string is correct, the application displaying it is wrong. | How to convert an unreadable string back to UTF-8 bytes in c# | [
"",
"c#",
"string",
"utf-8",
""
] |
I've been looking at strategy pattern implementation examples and it seems to me like they are very similar to c# delegates. The only difference I see is that strategy pattern implementations don't need to explicitly declare a delegate.
But other than that, they both seem to point to functions that need a specific signature and they can both be used to determine what to execute at run time.
Is there a more obvious difference that I am missing?
I guess a related question would be, IF they are similar, what's the advantage of using one over the other? | Put simply, you can use delegates to implement strategy pattern.
Strategy pattern is a pattern. Delegates are a language feature. You use the language feature to implement the pattern. They reside in two separate categories of concepts altogether, but are related in their interaction with each other.
In other words, strategy pattern is the blueprint, the C# delegates are the bricks. You can't build the (strategy pattern) house without either. (You could build it with other kinds of bricks also, but nothing in the language feature of delegates inherently describes strategy pattern). | Design Patterns are language agnostic, high-level solutions to commonly-encountered problems.
Delegates can be used in a platform-specific *implementation* of the strategy pattern for .NET, but aren't the only way of implementing such a solution.
An alternative solution is to define an interface like:
```
public interface IStrategy
{
void DoStuff(...)
}
```
Strategies would then be represented by classes implementing this interface, rather than by a delegate.
Delegates may be an okay implementation if you expect your strategies to be very simple. For anything reasonably complex, implementing strategies as interfaces gives you a lot more options when it comes to keeping track of state, organizing things into multiple methods, sharing code between implementations, etc. | in c# what is the difference between strategy pattern and delegates? | [
"",
"c#",
"delegates",
"strategy-pattern",
""
] |
I have a PHP script which executes a shell command:
```
$handle = popen('python last', 'r');
$read = fread($handle, 4096);
print_r($read);
pclose($handle);
```
I echo the output of the shell output. When I run this in the command I get something like this:
```
[root@localhost tester]# python last
[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[last] ZVZX-W3vo9I: URL: x
[download] Destination: here.flv
[download] 0.0% of 10.09M at ---b/s ETA --:--
[download] 0.0% of 10.09M at 22.24k/s ETA 07:44
[download] 0.0% of 10.09M at 66.52k/s ETA 02:35
[download] 0.1% of 10.09M at 154.49k/s ETA 01:06
[download] 0.1% of 10.09M at 162.45k/s ETA 01:03
```
However, when I run that same command from PHP I get this output:
```
[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[last] ZVZX-W3vo9I: URL: x
[download] Destination: here.flv
```
As you can see the bottom bit is missing which is the bit I need!! The problem before was that the percentages were being updated on the same line but now I have changed my Python script so that it creates a new line. But this made difference! :(
This question is related [to this one](https://stackoverflow.com/questions/524286/ajax-progress-reading-output-from-the-shell).
Thank you for any help.
## Update
Needed to redirect output "2>&1". Arul got lucky :P since I missed the deadline to pick the one true answer which belonged to Pax! | You read only the first 4,096 bytes from the pipe, you'll need to place the `fread`/`print`\_r in a loop and check for the end-of-file using the `feof` function.
```
$handle = popen('python last', 'r');
while(!feof($handle))
{
print_r(fread($handle, 4096));
}
pclose($handle);
``` | The first step is to see where the output is going. The first thing I would do is choose a slightly smaller file so that you're not waiting around for seven minutes for each test.
Step 1/ See where things are being written in the shell. Execute the command `python last >/tmp/stdout 2>/tmp/stderr` then look at those two files. Ideally, everything will be written to stdout but that may not be the case. This gives you the baseline behavior of the script.
Step 2/ Do the same thing when run from PHP by using `$handle = popen('python last >/tmp/stdout 2>/tmp/stderr', 'r');`. Your PHP script probably won't get anything returned in this case but the files should still be populated. This will catch any changed behavior when running in a non-terminal environment.
If some of the output goes to stderr, then the solution should be as simple as `$handle = popen('python last 2>&1', 'r');`
Additionally, the doco for PHP states (my bolding):
`Returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite().`
So I'm not sure you should even be using `fread()`, although it's shown in one of the examples. Still, I think line-based input maps more to what you're trying to achieve.
Irrespective of all this, you should read the output in a loop to ensure you can get the output when it's more than 4K, something like:
```
$handle = popen ('python last 2>&1', 'r');
if ($handle) {
while(! feof ($handle)) {
$read = fgets ($handle);
echo $read;
}
pclose ($handle);
}
```
Another thing to look out for, if you're output is going to a browser and it takes too long, the browser itself may time out since it thinks the server-side connection has disappeared. If you find a small file working and your 10M/1minute file not working, this may be the case. You can try `flush()` but not all browsers will honor this. | Shell output not being fully retrieved by PHP! | [
"",
"php",
"linux",
"shell",
"command-line",
""
] |
I'm playing around with gmock and noticed it contains this line:
```
#include <tuple>
```
I would have expected `tuple.h`.
When is it okay to exclude the extension, and does it give the directive a different meaning? | The C++ standard headers do not have a ".h" suffix. I believe the reason is that there were many, different pre-standard implementations that the standard would break. So instead of requiring that vendors change their existing "iostream.h" (for example) header to be standards compliant (which would break their existing user's code), the standards committee decided that they'd drop the suffix (which, I believe no then existing implementation had already done).
That way, existing non-standard programs would continue to work using the vendor's non-standard libraries. When the user wanted to make their programs standards-compliant, one of the steps they would take is to change the "`#include`" directive to drop the ".h" suffix.
So
```
#include <iostream> // include the standard library version
#include <iostream.h> // include a vendor specific version (which by
// now might well be the same)
```
As other answers have mentioned, writers of non-standard libraries may choose either naming convention, but I'd think they would want to continue using ".h" or ".hpp" (as Boost has done) for a couple of reasons:
1. If and when the library gets standardized, the standard version won't automatically override the previous, non-standard one (causing broken user code in all likelihood).
2. It seems to be a convention (more or less) that headers without a suffix are standard libraries, and those with a suffix (other than the C compatibility headers) are non-standard.
Note that a similar problem happened when the committee went to add hash maps to the STL - they found that there are already many (different) `hash_map` implementations that exist, so instead of coming up with a standard one that breaks a lot of stuff out there today, they call the standard implementation "`unordered_map`". Namespaces were supposed to help prevent this type of jumping through hoops, but it didn't seem to work well enough (or be used well enough) to allow them to use the more natural name without breaking a lot of code.
Note that for the 'C' headers, C++ allows you to include either a `<cxxxxxx>` or `<xxxxxx.h>` variant. The ones that start with 'c' and have no ".h" suffix put their declarations in the `std` namespace (and possibly also in the global namespace); the ones with the ".h" suffix put the names in the global namespace (and possibly also in the `std` namespace). | If the file is named `tuple` then you need to `#include <tuple>`
if it's named `tuple.h` then you need to `#include <tuple.h>`
It's as simple as that. You are not omitting any extension. | When can you omit the file extension in an #include directive? | [
"",
"c++",
"include",
"c-preprocessor",
"standards",
""
] |
I have a C# class library and a startup project (a console app). The class library includes a service reference to a web service. When I try to run the project, I get an InvalidOperationException because the startup project isn't reading the class library's app.config, and it's ignoring the service reference. To get it working, I'm forced to add the same service reference to the startup project. Is there any way I can avoid this? Can I make the startup project recognize the class library's service reference and app.config without having to copy it to the startup project?
I've tried adding a link to the app.config from the class library, but that doesn't work. The class library isn't very portable if it requires anyone who uses it to add that service reference to the startup project. | Think about what you are trying to do - you have two assemblies that you are building:
```
Library
ConsoleApp
```
Both of these assemblies have configuration files - I would imagine they look something like this:
```
Library
app.config
ConsoleApp
ConsoleApp.exe.config
```
When you run `ConsoleApp` it has no way of reading from or knowing aboout `app.config` from your `Library` assembly. The only configuration file that it knows or cares about is `ConsoleApp.exe.config`. Now it is possible to have configuration files reference each other but this is not the proper solution for what you are trying to do.
Since your `Library` assembly has no entry point, it will never be loaded into an AppDomain. Since it will never be loaded into an AppDomain its application configuration file will never be used.
What you ought to do is reference `Library` in `ConsoleApp` via a project reference. Then move all the relevant configuration data from `app.config` into `ConsoleApp.exe.config` as this is the configuration file that will be used by your application.
This will allow you to have to two things you need to invoke methods on your web service
1. The code in `Library` that can send and receive SOAP messages.
2. The configuration metadata that is required by `Library` to function. | An alternative to using a service reference in the class library and then copying the config would be to use build events that call svcutil.exe. The thing I like about this is that you don't have to make "update service reference" when the service changes. It will be updated automatically.
In the class library, use a build event that only generates the proxy code:
```
svcutil.exe net.tcp://localhost:3315/MyService/mex /noConfig
```
In the application, use a build event that generates the config. You can use the /mergeConfig option to merge it into an existing app.config.
```
svcutil.exe net.tcp://localhost:3315/MyService/mex
/config:App.config /mergeConfig
```
If you don't want to get a build error if the service is not running, put this in your project file and you will get a warning instead of an error:
```
<Target
Name="PreBuildEvent"
Condition="'$(PreBuildEvent)'!=''"
DependsOnTargets="$(PreBuildEventDependsOn)">
<Exec WorkingDirectory="$(OutDir)"
Command="$(PreBuildEvent)"
ContinueOnError="true" />
</Target>
``` | Including a service reference from a class library | [
"",
"c#",
"app-config",
"service-reference",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.