Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called `AddressList`, containing simple nodes called `ListNode`). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: `public AddressList reverse()`
ListNode:
```
public class ListNode{
public String data;
public ListNode next;
}
```
Right now my `reverse` function just calls a helper function that takes an argument to allow recursion.
```
public AddressList reverse(){
return new AddressList(this.reverse(this.head));
}
```
With my helper function having the signature of `private ListNode reverse(ListNode current)`.
At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in C that recursively reversed and converted it to Java code by hand, and it worked, but I had no understanding of it.
Edit: Nevermind, I figured it out in the meantime.
```
private AddressList reverse(ListNode current, AddressList reversedList){
if(current == null)
return reversedList;
reversedList.addToFront(current.getData());
return this.reverse(current.getNext(), reversedList);
}
```
While I'm here, does anyone see any problems with this route? | There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):
1. What is the reverse of null (the empty list)? null.
2. What is the reverse of a one element list? the element.
3. What is the reverse of an n element list? the reverse of the rest of the list followed by the first element.
---
```
public ListNode Reverse(ListNode list)
{
if (list == null) return null; // first question
if (list.next == null) return list; // second question
// third question - in Lisp this is easy, but we don't have cons
// so we grab the second element (which will be the last after we reverse it)
ListNode secondElem = list.next;
// bug fix - need to unlink list from the rest or you will get a cycle
list.next = null;
// then we reverse everything from the second element on
ListNode reverseRest = Reverse(secondElem);
// then we join the two lists
secondElem.next = list;
return reverseRest;
}
``` | I was asked this question at an interview and was annoyed that I fumbled with it since I was a little nervous.
This should reverse a singly linked list, called with reverse(head,NULL);
so if this were your list:
```
1->2->3->4->5->null
it would become:
5->4->3->2->1->null
```
```
//Takes as parameters a node in a linked list, and p, the previous node in that list
//returns the head of the new list
Node reverse(Node n,Node p){
if(n==null) return null;
if(n.next==null){ //if this is the end of the list, then this is the new head
n.next=p;
return n;
}
Node r=reverse(n.next,n); //call reverse for the next node,
//using yourself as the previous node
n.next=p; //Set your next node to be the previous node
return r; //Return the head of the new list
}
```
edit: ive done like 6 edits on this, showing that it's still a little tricky for me lol | Reversing a linked list in Java, recursively | [
"",
"java",
"data-structures",
"recursion",
"linked-list",
""
] |
I'm generating a coupon based on dynamic input and a cropped image, and I'm displaying the coupon using ntml and css right now, the problem is, printing this has become an issue because of how backgrounds disappear when printing and other problems, so I think the best solution would be to be able to generate an image based on the html, or set up some kind of template that takes in strings and an image, and generates an image using the image fed in as a background and puts the coupon information on top.
Is there anything that does this already?
This is for an ASP.NET 3.5 C# website!
Thanks in advance.
edit: It'd be great if the output could be based on the HTML input, as the coupon is designed by manipulating the DOM using jQuery and dragging stuff around, it all works fine, it's just when it comes to the printing (to paper) it has z-indexing issues. | What you can do is create an aspx page that changes the response type to be in the format you want and then put the image into the stream. I created a barcode generator that does a similar thing. Excluding all the formalities of generating the image, you'll Page\_Load will look something like this:
```
Bitmap FinalBitmap = new Bitmap();
MemoryStream msStream = new MemoryStream();
strInputParameter == Request.Params("MagicParm").ToString()
// Magic code goes here to generate your bitmap image.
FinalBitmap.Save(msStream, ImageFormat.Png);
Response.Clear();
Response.ContentType = "image/png";
msStream.WriteTo(Response.OutputStream);
if ((FinalBitmap != null)) FinalBitmap.Dispose();
```
and that's it! Then all you have to do in your image is set the URL to be something like RenderImage.aspx?MagicParm=WooHoo or whatever you need. That way you can have it render whatever you want to specify. | You can render html to a bitmap using the WebBrowser control in either a winforms or console application.
An example of this can be found here: <http://www.wincustomize.com/articles.aspx?aid=136426&c=1>
The above example can be modified to run in ASP.Net by creating a new STAThread and performing an Application.Run on it to start a new message loop. | Render HTML as an Image | [
"",
"c#",
"asp.net",
"image",
""
] |
Javascript client side application.
Trying to eliminate memory leaks leads to ugly (to say the least) code.
I am trying to clean up in window.unload instead on messing up all the code trying to avoid them.
We use mostly `element.onevent=function(){..};` pattern, that results in closure (mostly wanted) and memory leak.
We do not use javascript frameworks.
Are there any ideas on how to clean up properly on exit?
Has anyone do the same or are you trying to avoid them? | The best solution is for you to roll out your own method that manages event handling. Therefore, when attaching an event handler, your method can keep track of all the added events. On unload, it can unregister all the handlers.
I know you said you don't use libraries, but you can use their code as inspiration. Ext-js does that when you use Ext.EventMgr.addListener.
Here's a simple EvtMgr obj that you can use to get started. It's very simplistic, I can't write it all for you here. Feel free to ask questions about things that you'd like and don't know how to do. Also note that I wouldn't use the element.onclick method since you can only add a single handler. I'm doing it that way because you said that's how you do it.
```
var EvtMgr = (function(){
var listenerMap = {};
// Public interface
return {
addListener: function (evtName, node, handler) {
node["on" + evtName] = handler;
var eventList = listenerMap[evtName];
if (!eventList) {
eventList = listenerMap[evtName] = [];
}
eventList.push(node);
},
removeAllListeners: function() {
for (var evtName in listenerMap) {
var nodeList = listenerMap[evtName];
for (var i=0, node; node = nodeList[i]; i++) {
node["on" + evtName] = null;
}
}
}
}
})();
```
Also, beware that handlers with closures is not the only way to create leaks. See my comment on this question [[Javascript memory leaks after unloading a web page](https://stackoverflow.com/questions/1077840/javascript-memory-leaks-after-unloading-a-web-page/1886359#1886359)](https://stackoverflow.com/questions/1077840/javascript-memory-leaks-after-unloading-a-web-page/1886359#1886359)
Also, I don't understand why some people are afraid of libraries. jquery is tiny, ext core is too. They can be dangerous if you use them without understanding js. But if your js skills are solid, you save a lot of work by reusing their code. I get under the hood of ext-js every single day when I need to understand how somethings is done. This was how I gave you these few lines of code.
Another think to think about when managing memory leaks is to make sure you remove handlers when removing elements from the DOM (node.innerHTML or any other way). If you do that, you should remove handlers from the nodes you've removed from the DOM. There's some work to get that working but it should be part of your strategy. | A solution for avoiding memory leaks with events is delegation. In a nutshell, you attach your event handler to a parent object instead of the children. Because of propagation, a click on a child will also register as a click on the parent, triggering your handler. By checking the target attribute of the event, you can then decide what to do with it.
Since the handler is attached to the parent, you can add or remove children without worrying about leaks.
A more thorough explanation can be found here: <http://www.robertnyman.com/2008/05/04/event-delegation-with-javascript/>
A demo here: <http://www.robertnyman.com/test/event-delegation/event-delegation.html> | Javascript memory leak cleanup in window.unload | [
"",
"javascript",
"ajax",
"web-applications",
"memory-leaks",
""
] |
I am reorganizing my source files into a single solution with a single project, due to various reasons:
* a paranoic configured antivirus software;
* [Advices on partitioning code through .NET assemblies](http://codebetter.com/blogs/patricksmacchia/archive/2008/12/08/advices-on-partitioning-code-through-net-assemblies.aspx)
* [Control component dependencies to gain clean architecture](http://www.theserverside.net/tt/articles/showarticle.tss?id=ControllingDependencies)
* [Benefit from the C# and VB.NET compilers perf](http://codebetter.com/blogs/patricksmacchia/archive/2007/06/20/benefit-from-the-c-and-vb-net-compilers-perf.aspx)
This leaves me with many namespaces, which are splitted across multiple files. So far, I am using this convention: given the namespace `Company.Project.A`, the files are named `A.f1.cs`, `A.f2.cs` and so on, and the `Company.Project.B` namespace is splitted across `B.f1.cs`, `B.f2.cs`, etc.
Given the single project restriction, are there any better ways to organize multiple files in multiple namespaces? | Yes - use folders.
If you create a folder within a project, new classes within that folder will automatically use the folder name as the basis for the namespace.
For instance, if you have a project with a default namespace of "Company.Project" and a folder "Foo" containing "Bar.cs" you'll end up with:
```
using System; // Etc
namespace Company.Project.Foo
{
class Bar
{
}
}
``` | So the solution is right here. It's Folders. But it's sometimes tricky. First of all it's kind of a good idea to have one file per class. If you will pack several classes into one file - you'll have problems with finding them with time.
Second thing about folders - if you will click on a folder and choose for example "Add -> New Item", this item will be put into selected folder. But watch out! If you will move files between folders, namespaces are not updated.
It's common source of messing project. Just after a while you can end up with a project where you have neat organized folder and files, but not reflecting namespaces. So for example, if you have class MyClass in folder MyFolder make sure, your namespace for this class is something like MyApp.MyFolder and not some old rubbish.
So If you will not pack classes into one file and watch if classes namespaces reflect folder hierarchy - you're on the good road to make you project very easy to read and navigate. | C# single project organization | [
"",
"c#",
"visual-studio-2008",
"projects-and-solutions",
"project-organization",
""
] |
Does anyone know a good tool that can be run on a page (for asp.net, for example) to help to minimize the footprint size of the page?
The page will have typical items: HTML, Javascript, etc.
I've heard of Javascript crunchers in the past, that will make the size of the code as compact as possible (and obfuscate it, I suppose).
The goal is to help optimize the page size (make it as small as possible for speed, without changing anything).
Is this possible? | You could configure your web server to compress the page on the fly (and possibly cache the compressed version) for any client that indicates it can take a gzip or zip (or other) encoding, which is pretty much all of them. | Well, its not a automatic cleaner-upper, but I like [YSlow](http://developer.yahoo.com/yslow/) for optimizing pages. And the [YUI Compressor](http://developer.yahoo.com/yui/compressor/) can minify your javascript.
If you're really interested in javascript, the keyword is "minify".
Also, look at this question just posted: [HTML and stuff](https://stackoverflow.com/questions/299636/good-tool-to-minimize-html-footprint)
Hope that helps! | Good tool to minimize HTML footprint? | [
"",
"asp.net",
"javascript",
"html",
"optimization",
"footprint",
""
] |
How do you open a path in explorer by code in c++. I googled and couldn't find any thing but systems commands to do this, however, i dont want it to block or show the console window. | You probably are looking for the [`ShellExecute()`](http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx) function in `shellapi.h`. It is called with an "action verb", a path, and optional parameters. In your case this will want either "open" or "explore" as follows:
```
ShellExecuteA(NULL, "open", "C:\\", NULL, NULL, SW_SHOWDEFAULT);
```
This will open an unattached explorer window at C:. ShellExecute() will give basically the same action as typing in a command at the Run dialog. It will also handle URLs, so the following will open up the user's default browser:
```
ShellExecuteA(NULL, "open", "http://www.google.com", NULL, NULL, SW_SHOWDEFAULT);
```
Although make sure to pay attention to the note in the documentation that ShellExecute relies on COM (Although your code doesn't have to worry about any COM objects itself).
```
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)
``` | This does not show the command window, just opens the directory.
```
system("explorer C:\\");
``` | Open in Explorer | [
"",
"c++",
"windows",
"explorer",
""
] |
Please don't say EHCache or OSCache, etc. Assume for purposes of this question that I want to implement my own using just the SDK (learning by doing). Given that the cache will be used in a multithreaded environment, which datastructures would you use? I've already implemented one using [LinkedHashMap](http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html) and [Collections#synchronizedMap](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)), but I'm curious if any of the new concurrent collections would be better candidates.
UPDATE: I was just reading through [Yegge's latest](http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html) when I found this nugget:
> If you need constant-time access and want to maintain the insertion order, you can't do better than a LinkedHashMap, a truly wonderful data structure. The only way it could possibly be more wonderful is if there were a concurrent version. But alas.
I was thinking almost exactly the same thing before I went with the `LinkedHashMap` + `Collections#synchronizedMap` implementation I mentioned above. Nice to know I hadn't just overlooked something.
Based on the answers so far, it sounds like my best bet for a highly concurrent LRU would be to extend [ConcurrentHashMap](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html) using some of the same logic that `LinkedHashMap` uses. | If I were doing this again from scratch today, I'd use Guava's [`CacheBuilder`](http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/cache/CacheBuilder.html). | I like lots of these suggestions, but for now I think I'll stick with `LinkedHashMap` + `Collections.synchronizedMap`. If I do revisit this in the future, I'll probably work on extending `ConcurrentHashMap` in the same way `LinkedHashMap` extends `HashMap`.
UPDATE:
By request, here's the gist of my current implementation.
```
private class LruCache<A, B> extends LinkedHashMap<A, B> {
private final int maxEntries;
public LruCache(final int maxEntries) {
super(maxEntries + 1, 1.0f, true);
this.maxEntries = maxEntries;
}
/**
* Returns <tt>true</tt> if this <code>LruCache</code> has more entries than the maximum specified when it was
* created.
*
* <p>
* This method <em>does not</em> modify the underlying <code>Map</code>; it relies on the implementation of
* <code>LinkedHashMap</code> to do that, but that behavior is documented in the JavaDoc for
* <code>LinkedHashMap</code>.
* </p>
*
* @param eldest
* the <code>Entry</code> in question; this implementation doesn't care what it is, since the
* implementation is only dependent on the size of the cache
* @return <tt>true</tt> if the oldest
* @see java.util.LinkedHashMap#removeEldestEntry(Map.Entry)
*/
@Override
protected boolean removeEldestEntry(final Map.Entry<A, B> eldest) {
return super.size() > maxEntries;
}
}
Map<String, String> example = Collections.synchronizedMap(new LruCache<String, String>(CACHE_SIZE));
``` | How would you implement an LRU cache in Java? | [
"",
"java",
"caching",
"data-structures",
"lru",
""
] |
by default is a class:
1. private ?
2. internal ?
3. sealed ? | internal
see:
<http://msdn.microsoft.com/en-us/library/ms173121.aspx> | The default for non-nested types is internal.
The default for nested types is private.
In both cases the default (for classes) is unsealed.
The general rule for all members is that if you don't specify an access modifier, it's as private as it can be. The single exception for this is properties which can make one part (i.e. the getter or the setter) more private than the overall property by specifying an access modifier, e.g.
```
public string Foo { get; private set; }
``` | Default Class Accessibility in C# | [
"",
"c#",
"oop",
""
] |
I'm using a hosting service which allows me to backup my SQL 2008 database and download the BAK file via a web interface only--and I have access to the database via Management Studio. I can execute the backup command from Management Studio,but I don't have rights to the path where the backups are located. Is there any way via SQL or script to pull down a full copy of the database--can I generate the script required to recreate the database using code? It's only a few thousand records.
Thanks. | If you have access via Management Studio, why don't you copy the hosted db on to your local machine (Tasks > Copy DB)?
Once it's been restored to the local system, you can do whatever you want. | Free [SqlBackupAndFTP](http://SqlBackupAndFTP.com) allows to do remote backups using scripting | How to automate SQL backup on a shared hosted server? | [
"",
"sql",
"sql-server",
"backup",
""
] |
How can I delete all the tables in a web page? The tables don't have any ids associated with them. | Very simple version:
```
var tables = document.getElementsByTagName("TABLE");
for (var i=tables.length-1; i>=0;i-=1)
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
``` | Danger! getElementsByTagName returns a ‘live’ NodeList. In Joel's code, removing element 0 moves the items in the list down so that when you remove element 1, you've missed one.
Possible alternatives: if you know you're always going to be removing every element, you can use a while-loop:
```
var tables= document.getElementsByTagName('table');
while (tables.length>0)
tables[0].parentNode.removeChild(tables[0]);
```
Or, if you might or might not remove, but iteration order is unimportant, go through the list backwards:
```
var tables= document.getElementsByTagName('table');
for (var i= tables.length; i-->0;)
tables[i].parentNode.removeChild(tables[i]);
```
If you might-or-might-not remove *and* you need to iterate forwards, you're in the tedious position of having to copy the list:
```
function toArray(l) {
var a= [];
for (var i= 0; i<l.length; i++)
a[i]= l[i];
return a;
}
var tables= toArray(document.getElementsByTagName('table'));
for (var i= 0; i<tables.length; i++)
...
``` | How to delete all tables in HTML with JavaScript? | [
"",
"javascript",
"html",
"html-table",
""
] |
How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.):
```
while True:
# doing amazing pythonic embedded stuff
# ...
# periodically do a non-blocking check to see if
# we are being told to do something else
x = keyboard.read(1000, timeout = 0)
if len(x):
# ok, some key got pressed
# do something
```
What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required. | The standard approach is to use the [select](https://docs.python.org/2/library/select.html) module.
However, this doesn't work on Windows. For that, you can use the [msvcrt](https://docs.python.org/2/library/msvcrt.html#console-i-o) module's keyboard polling.
Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device. | A solution using the curses module. Printing a numeric value corresponding to each key pressed:
```
import curses
def main(stdscr):
# do not wait for input when calling getch
stdscr.nodelay(1)
while True:
# get keyboard input, returns -1 if none available
c = stdscr.getch()
if c != -1:
# print numeric value
stdscr.addstr(str(c) + ' ')
stdscr.refresh()
# return curser to start position
stdscr.move(0, 0)
if __name__ == '__main__':
curses.wrapper(main)
``` | Polling the keyboard (detect a keypress) in python | [
"",
"python",
"console",
"keyboard",
"blocking",
"nonblocking",
""
] |
I've seen this in a few [places](https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript#221357)
```
function fn() {
return +new Date;
}
```
And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.
Can anyone explain? | That's the `+` unary operator. It's equivalent to:
```
function(){ return Number(new Date); }
```
See <http://xkr.us/articles/javascript/unary-add> and [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus). | JavaScript is loosely typed, so it performs type coercion/conversion in certain circumstances:
<http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html>
<http://www.jibbering.com/faq/faq_notes/type_convert.html>
Other examples:
```
>>> +new Date()
1224589625406
>>> +"3"
3
>>> +true
1
>>> 3 == "3"
true
``` | What does the plus sign do in '+new Date' | [
"",
"javascript",
"syntax",
""
] |
Consider the "double-check idiom for lazy initialization of instance fields":
> ```
> // Item 71 in Effective Java copied from this interview with Bloch.
> private volatile FieldType field;
> FieldType getField() {
> FieldType result = field;
> if (result == null) { // First check (no locking)
> synchronized(this) {
> result = field;
> if (result == null) // Second check (with locking)
> field = result = computeFieldValue();
> }
> }
> return result;
> }
> ```
I want to be able to reset the field in a safe way (force it to load again from the database, in my case). I assume that we could do this by having a reset method:
> ```
> void reset() {
> field = null;
> }
> ```
Is this the standard way of doing resetting the field? Is it safe? Any pitfalls? I'm asking because Bloch gave the following warning about double-checked lazy-loading: "The idiom is very fast but also complicated and delicate, so don't be tempted to modify it in any way. Just copy and paste -- normally not a good idea, but appropriate here."
Thanks in advance,
Playa from the Himalayas. | Yes, this is thread safe.
The synchronized block is to prevent multiple threads from unnecessarily calling `computeFieldValue()`. Since `field` is volatile, the accesses in `reset` and `getField` are all well-ordered.
If the first check is non-null, `getField` is done; `result` is returned.
Otherwise, a lock is acquired, excluding any other thread that might set the field to non-null, but permitting any thread to set `field` to null. If any thread does set `field` to null, nothing should have changed; that's the condition that got the thread into the synchronized block. If another thread had already acquired the lock after the current thread's check, and set the field to a non-null value, the second check will detect that. | I think this should be safe, but only because you're storing the field in a local variable. After this is done, there's no way for the local variable reference to magically change to null, even if another thread is resetting field's value half-way through. | Resetting a field lazy-loaded with the double-check idiom | [
"",
"java",
"thread-safety",
"locking",
"double-checked-locking",
""
] |
I am writing a .NET library that for various reasons cannot be registered in the GAC.
This dll (let's call it SDK.dll) depends on other DLLs in order to be loaded.
When writing a program that uses this SDK.dll, I noticed that my program failed loading the dll with a FileNotFoundException thrown. This happens because although I was able to find the referenced SDK.dll, the CLR failed to load its dependencies.
The only way I found to solve the problem is to "Copy Local" the SDK.dll and all its dependencies (something I can't do because of deployment problems), or compiling my program into the same directory as SDK.dll
Is there a way to tell SDK.dll where to look for it's dependencies regardless of its location? Maybe a SDK.dll.config file can help? | You can handle this at runtime by subscribing to this event:
```
AppDomain.CurrentDomain.AssemblyResolve
```
It's fired when the runtime fails to resolve an assembly. In your event handler method, write your logic to find the assembly and load it using Assembly.LoadFrom(). It would look something like this:
```
public SDKClass()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(FindAssembly);
}
private Assembly FindAssembly(object sender, ResolveEventArgs args)
{
string assemblyPath = "c:\PathToAssembly";
string assemblyName = args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
string assemblyFullName = Path.Combine(assemblyPath, assemblyName);
Assembly theAssembly = Assembly.Load(assemblyFullName);
return theAssembly;
}
``` | to register your assembly in GAC it must have be signed with a [strong name](http://msdn.microsoft.com/en-us/library/szdke3d6.aspx).
If it depends on other assemblies, those should be in GAC to.
BeowulfOF | Assembly binding problems in .NET | [
"",
"c#",
".net",
"app-config",
"assembly.load",
""
] |
I have to choose a server pages technology for a few server components that are written in Java and hosted by Tomcat, like Lucene search service and a flex BlazeDS graphic component.
Not sure whether to use JSP or PHP.
On one hand JSP can integrate with the components Java API easily while PHP will require another way of integration like XML or a bridge that might introduce a performance overhead.
On the other hand PHP seem to be faster to develop and, not sure but, more used and supported lately. | JSP all the way in this situation. Firstly you can choose from myriad different frameworks - Struts and Tiles, Spring, Hibernate, etc, to aid in development.
Secondly the speed of development is not that much slower, if at all. In addition many of the frameworks enforce decent MVC coding practices.
I wouldn't recommend coding pure servlets and JSP these days however, given the frameworks, unless you are coding something very specific.
Other alternatives could be investigating JRuby or JPython for development in Ruby or Python - although I don't know how easy this would be as I haven't done it myself. | Given your situation, I would choose for JSP.
PHP-applications might be slightly faster to develop, but only if your not used to Java. Intergrating existing components wirtten in Java, are easily intergrated with JSP.
PHP is supported more by web-hosting companies, if you're looking for cheap low requirements hosting. JSP is widely supported for dedicated hosting. Every propper linux/unix distribution does Java+Tomcat out of the box. | JSP or PHP for Java server components? | [
"",
"php",
"jsp",
""
] |
I'm used to passing around string like this in my C++ applications:
```
void foo(const std::string& input)
{
std::cout << input.size() << std::endl;
}
void bar()
{
foo("stackoverflow");
}
```
Now I have a case where I want the string to be NULL:
```
void baz()
{
foo("stackoverflow");
foo(NULL); // very bad with foo implementation above
}
```
I could change `foo` to:
```
void foo(const std::string* input)
{
// TODO: support NULL input
std::cout << input->size() << std::endl;
}
```
But to pass a string literal or copy a `char*` to that implementation of `foo` I need to write something like this:
```
void bar()
{
string input("hi"); // annoying temporary
foo(&input);
foo(NULL); // will work as long as foo handles NULL properly
}
```
I started thinking about inheriting from `std::string` and adding a `null` property, but I'm not so sure it's a good idea. Maybe it is better to simply use a `const char*` string for parameters that can be NULL, but what if I want to save a copy of the string (or NULL) without having to manage its memory myself? (See [What are some of the drawbacks to using C-style strings?](https://stackoverflow.com/questions/312570/what-are-some-of-the-drawbacks-to-using-c-style-strings) etc.)
Any clever solution around? | If you want the type to be null, then make it a pointer. Pass string pointers around instead of references, since this is precisely what pointers can do, and references cant. References always point to the same valid object. Pointers can be set to null, or be reseated to point to another object. Thus, if you need the things pointers can do, use pointers.
Alternatively, use boost::optional, which allows a more type-safe way to specify "this variable may or may not contain a value".
Or, of course, change the semantics so you either use empty strings instead of null, pass a separate bool parameter specifying whether the string is available or not, or refactor so you don't need this in the first place. | Function overloading to the rescue...
```
void foo( const std::string& input )
{
std::cout << input << std::endl;
// do more things ...
}
void foo( const char* input )
{
if ( input != NULL ) foo( std::string(input) );
}
```
This will accept both c-style char arrays and std::strings, and will incur extra overhead on the stack if you pass in a string literal or a char array, but allows you to keep your implementation in one place and keep your nice syntax. | C++ string that can be NULL | [
"",
"c++",
"string",
"null",
""
] |
I was wondering if there was a way to bind an ArrayList (or any kind of List, for that matter) to a PreparedStatement which will eventually be used to access an Oracle database. I found:
[PreparedStatement IN clause alternatives?](https://stackoverflow.com/questions/178479/alternatives-for-java-sql-preparedstatement-in-clause-issue)
And that seems similar to my issue, but this question is more specific: I'd like to bind an ArrayList to a PreparedStatement to be used in Oracle, if it is possible, how is this accomplished? | You can't bind a List to a single parameter in a prepared statement.
Generate SQL with the a parameter marker for each element in the list, for example:
```
SELECT NAME FROM ITEM WHERE ID IN (?, ?, ?, ?)
```
Even though you'll generate a new statement for each query, I'd still recommend using a `PreparedStatement`. If your list contains `String` instances, you'll get the necessary escaping to protect from SQL injection.
But even if it's a safe type, like `Integer` objects, some drivers or middleware can cache `PreparedStatements`, and return a cached instance if the same form is requested. Of course, some testing would be necessary. If your lists vary widely in size, you'll have many different statements, and a poorly-implemented cache might not be prepared to handle so many. | You can't bind it directly. There is a way to pass an array as a parameter. I have no idea what you want to do with it on the database side so this may not help you.
Basically, you have to create a nested table type in the database; build a Java object based on that type, containing the data from your array; and pass that as the parameter.
If you created these objects in the database:
```
CREATE OR REPLACE TYPE my_nested_table IS TABLE OF VARCHAR2(20);
CREATE TABLE my_table (a my_nested_table) NESTED TABLE a STORE AS my_table_a;
```
Then you can write Java code like this:
```
String[] insertvalues = { "a", "b", "c" };
PreparedStatement p = conn.prepareStatement("INSERT INTO my_table VALUES( ? )");
ARRAY insertParameter = new ARRAY( a_desc, conn, insertvalues );
p.setArray( 1, insertParameter );
p.execute();
```
The results in Oracle look like this:
```
dev> select * from my_table;
A
--------------------------------------------------------------------------------
MY_NESTED_TABLE('a', 'b', 'c')
``` | How do I bind an ArrayList to a PreparedStatement in Oracle? | [
"",
"java",
"oracle",
"jdbc",
"arraylist",
"prepared-statement",
""
] |
I've just started to use linq to sql and have run into a problem with inserting a record with an auto incrementing field.
I have created a new instance of a company object defined by linq. it has initialised an auto incrementing field 'companyID' to 0.
InsertOnSubmit() fails with the following invalidOperationException.
> Incorrect autosync specification for
> member 'companyID'
the column attribute IsDbGenerated is true for the companyID property.
I am using sql server 2000.
Edit: Auto-sync is set to OnIsert. The dataype is BigInt in TSQL, long in c#.
Does anyone know why this error is occuring and how it can be resolved?
thanks | Found the answer. It was to do with primary keys. In the linq designer the primary keys were setup as they should be. In the database the relevant fields were not set as primary keys. I fixed the keys in the databse and this resolved the problem. | What is the data-type? int? (int both TSQL and in C#?)
What auto-sync setting do you have? For a primary key, it should be "OnInsert" | Linq to sql error with identitiy increment field | [
"",
".net",
"sql",
"linq",
"auto-increment",
""
] |
If I have several classes with functions that I need but want to store separately for organisation, can I extend a class to have both?
i.e. `class a extends b extends c`
edit: I know how to extend classes one at a time, but I'm looking for a method to instantly extend a class using multiple base classes - AFAIK you can't do this in PHP but there should be ways around it without resorting to `class c extends b`, `class b extends a` | # EDIT: 2020 PHP 5.4+ and 7+
As of PHP 5.4.0 there are "[Traits](https://www.php.net/manual/en/language.oop5.traits.php)" - you can use more traits in one class, so the final deciding point would be whether you want **really an inheritance** or you **just** need **some "feature"(trait)**. Trait is, vaguely said, an already implemented interface that is meant to be just `use`d.
---
Currently accepted answer by @Franck will work but it is not in fact multiple inheritance but a child instance of class defined out of scope, also there is the `\_\_call()` shorthand - consider using just `$this->childInstance->method(args)` anywhere you need ExternalClass class method in "extended" class.
## Exact answer
No you can't, respectively, not really, as [manual of `extends` keyword](http://php.net/manual/en/keyword.extends.php) says:
> An extended class is always dependent on a single base class, that is,
> multiple inheritance is not supported.
## Real answer
However as @adam suggested correctly this does NOT forbids you to use multiple hierarchal inheritance.
You CAN extend one class, with another and another with another and so on...
So pretty simple example on this would be:
```
class firstInheritance{}
class secondInheritance extends firstInheritance{}
class someFinalClass extends secondInheritance{}
//...and so on...
```
## Important note
As you might have noticed, **you can only do multiple(2+) intehritance by hierarchy if you have control over all classes included in the process** - that means, you can't apply this solution e.g. with built-in classes or with classes you simply can't edit - if you want to do that, you are left with the @Franck solution - child instances.
...And finally example with some output:
```
class A{
function a_hi(){
echo "I am a of A".PHP_EOL."<br>".PHP_EOL;
}
}
class B extends A{
function b_hi(){
echo "I am b of B".PHP_EOL."<br>".PHP_EOL;
}
}
class C extends B{
function c_hi(){
echo "I am c of C".PHP_EOL."<br>".PHP_EOL;
}
}
$myTestInstance = new C();
$myTestInstance->a_hi();
$myTestInstance->b_hi();
$myTestInstance->c_hi();
```
Which outputs
```
I am a of A
I am b of B
I am c of C
``` | If you really want to fake multiple inheritance in PHP 5.3, you can use the magic function \_\_call().
This is ugly though it works from class A user's point of view :
```
class B {
public function method_from_b($s) {
echo $s;
}
}
class C {
public function method_from_c($s) {
echo $s;
}
}
class A extends B
{
private $c;
public function __construct()
{
$this->c = new C;
}
// fake "extends C" using magic function
public function __call($method, $args)
{
$this->c->$method($args[0]);
}
}
$a = new A;
$a->method_from_b("abc");
$a->method_from_c("def");
```
Prints "abcdef" | Can I extend a class using more than 1 class in PHP? | [
"",
"php",
"class",
"oop",
"extends",
""
] |
Assuming the following hypothetical inheritance hierarchy:
```
public interface IA
{
int ID { get; set; }
}
public interface IB : IA
{
string Name { get; set; }
}
```
Using reflection and making the following call:
```
typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)
```
will only yield the properties of interface `IB`, which is "`Name`".
If we were to do a similar test on the following code,
```
public abstract class A
{
public int ID { get; set; }
}
public class B : A
{
public string Name { get; set; }
}
```
the call `typeof(B).GetProperties(BindingFlags.Public | BindingFlags.Instance)` will return an array of `PropertyInfo` objects for "`ID`" and "`Name`".
Is there an easy way to find all the properties in the inheritance hierarchy for interfaces as in the first example? | I've tweaked @Marc Gravel's example code into a useful extension method encapsulates both classes and interfaces. It also add's the interface properties first which I believe is the expected behaviour.
```
public static PropertyInfo[] GetPublicProperties(this Type type)
{
if (type.IsInterface)
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetInterfaces())
{
if (considered.Contains(subInterface)) continue;
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = subType.GetProperties(
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.Instance);
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
return type.GetProperties(BindingFlags.FlattenHierarchy
| BindingFlags.Public | BindingFlags.Instance);
}
``` | `Type.GetInterfaces` returns the flattened hierarchy, so there is no need for a recursive descent.
The entire method can be written much more concisely using LINQ:
```
public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
{
if (!type.IsInterface)
return type.GetProperties();
return (new Type[] { type })
.Concat(type.GetInterfaces())
.SelectMany(i => i.GetProperties());
}
``` | GetProperties() to return all properties for an interface inheritance hierarchy | [
"",
"c#",
".net",
"reflection",
""
] |
I can see some options available:
1) Use PEAR's POP3 class --> tried it, having some weird weird issues like FF choking to death on their sample code!!!
2) Use PHPClasses ([here](http://www.phpclasses.org/)) --> seems to be the viable option at the time, still working on it
3) Write my own or use one of the snippets available
The target is currently Gmail, but I would like this to work on my ISP mail too (not necessarily same code of course).
What do you use? Pointers to working snippets would be much appreciated. | I use the PHPClasses version. Works fine for me - I've been working on an AJAX mail client (personal project, learning exercise really). I also found that the sample code they provided was quite good so you should be able to get something working with it. | The native PHP IMAP functions support POP3 mailboxes, and will probably be faster than anything written purely in PHP. There are generally some useful comments and examples in the PHP manual, for example on the [imap\_open](https://www.php.net/imap_open) page. | retrieve email using PHP and pop3 - what is your technique? | [
"",
"php",
"pop3",
""
] |
I have a site that I've developed that makes decent use of Javascript, and minimal use of AJAX for a few things. The site worked fine on the iPhone until I added the [function to create an HttpRequest handle](http://www.w3schools.com/Ajax/ajax_server.asp) at which point all Javascript on the iPhone now silently fails. So, I have a few questions.
(1) It seems that AJAX does not work at all on the iPhone. IS this true? If not, how can I modify the HttpRequest create function to accomodate the iPhone?
(2) If AJAX is indeed impossible on the iPhone, is there a way I can modify the function given so that it will fail gracefully on the iPhone, and other scripts on the page will still function?
(3) If this is not true, what do I need to do server side (and is this even possible?) do detect the iPhone, so that I can remove the AJAX code entirely when an iPhone requests the page?
What would *also* work quite nicely is the ability to use CSS to detect the iPhone as a display device, and act accordingly, similar to what you use with Opera Show. Of course, this wouldn't fix the AJAX issue, but it would be neat. ^\_^
Thanks for answers. Several of my customers access the site regularly from the iPhone, and I want my pages to work as much as they possibly can, so I'm willing to modify my code for it, even though I don't have one to test on. | Of course the iPhone supports ajax, check out <http://developer.apple.com/webapps/> for a BUNCH of resources for developing iPhone webapps. I would recommend using a framework (such as [jQuery](http://www.jquery.com/), or [iUI](http://code.google.com/p/iui/) (for ui)) rather than rolling your own ajax functionality, it will already address a lot of the browser quirks and be optimised. | One useful resource for troubleshooting JavaScript errors like this on the device is the debug console. It should report any parsing errors and can also be used to log messages and exceptions. You can turn it on from Settings > Safari > Developer (scroll to the bottom). | AJAX on the iPhone? | [
"",
"javascript",
"iphone",
"ajax",
""
] |
What is the best way to find the total number of words in a text file in Java? I'm thinking Perl is the best on finding things such as this. If this is true then calling a Perl function from within Java would be the best? What would you have done in condition such as this? Any better ideas? | Congratulations you have stumbled upon one of the biggest linguistic problems! What is a word? It is said that a word is the only word that actually means what it is. There is an entire field of linguistics devoted to words/units of meaning - Morphology.
I assume that you question pertains to counting words in English. However, creating a language-neutral word counter/parser is next to impossible due to linguistic differences. For example, one might think that just processing the groups of characters separated by white space is sufficient. However, if you look at the following example in Japanese, you will see that that approach does not work:
これは日本語の例文です。
This example contains 3 distinct words and none of them are separated by spaces. Typically, Japanese word boundaries are parsed using a dictionary-based approach and there are a number of commercial libraries available for this. Are we lucky to have spaces in English! I believe that Indic languages, Chinese and Korean also have similar problems.
If this solution is going to actually be deployed in any ways that multi-lingual input is possible, it will be important to be able to plug in different word counting methods depending upon the language being parsed.
I think the first answer was a good answer because it uses Java's knowledge of Unicode whitespace values as delimiters. It tokenizes by matching using the following regex: `\p{javaWhitespace}+` | ```
int count = 0;
Scanner sc = new Scanner(new File("my-text-file.txt"));
while (sc.hasNext()) {
++count;
sc.next();
}
``` | What's the best way to determine the total number of words of a file in Java? | [
"",
"java",
"perl",
"file",
"word-count",
""
] |
What does the "class" part of a template statement do?
Example:
```
template <class T>
class Something
{
public:
Something(const T &something);
}
```
And what else can go there? I usually only see "class". | The `class` keyword means the same thing as the `typename` keyword for the most part. They both indicates that T is a type.
The only difference between the keywords `class` and `typename` is that `class` can be used to provide class template template arguments to a template, whereas `typename` can't. Consider:
```
template<template <class T> class U> // must be "class"
std::string to_string(const U<char>& u)
{
return std::string(u.begin(),u.end());
}
```
The only other thing you can put in place of the `class` or `typename` keywords is an integral type. For example:
```
template<std::size_t max>
class Foo{...};
...
Foo<10> f;
```
For a concrete example of this, take a look at `std::bitset<N>` in the standard library. | To define a template parameter, you need either to tell the compiler the parameter is a type, or a value.
## In the begining...
If I remember correctly, the C++ committee was reluctant to add a new keyword to the C++ language, and so, they decided to authorize the following notations:
```
template<int I>
int getTwice()
{
return I * 2 ;
}
template<class T>
std::string getType(const T & t)
{
return typeid(t).name() ;
}
void doSomething()
{
std::cout << "25 : " << getTwice<25>() << std::endl ;
std::cout << "5 : " << getTwice<5>() << std::endl ;
std::cout << "type(25) : " << getType(25) << std::endl ;
std::cout << "type(25.5) : " << getType(25.5) << std::endl ;
std::cout << "type(abc) : " << getType("abc") << std::endl ;
}
```
Which outputs, in g++:
```
25 : 50
5 : 10
type(25) : i
type(25.5) : d
type(abc) : A4_c
```
The first notation was a template over a value. So, we have the type of the value in the template declaration:
```
// "I" is the value, and "int" is the type of the value
template <int I>
```
The second notation was a template over a unknown type, and the fact that type was not "known" was marked by a "class" keyword. So, in this context, "class" meant "type".
```
// "T" is a type... And "class" is the "this-is-a-type" keyword
template <class T>
```
You'll note that with the second notation, despite the class keyword, T could be... a int, or another build-in type. But then, better to have this curiosity than add a new keyword, don't you agree?...
## Oops...
Everything was good and Ok until someone wrote the following code:
```
template<class T> // T could be any STL container, for example a vector<char>
void printContainerData(const T & t)
{
std::cout << "aVector:" ;
for(T::const_iterator it = t.begin(), itEnd = t.end(); it != itEnd; ++it)
{
std::cout << " " << (*it) ;
}
std::cout << std::endl ;
}
```
Where T::const\_iterator is a type, of course... But then, it could be a static member of a class of type T, and thus, a value. The compiler could be quite confused.
## In the end...
The solution was to tell the compiler that T::const\_iterator was **really** a type... Which would lead with this kind of notation:
```
for(class T::const_iterator it = t.begin(), // etc.
```
But this was thought not possible/correct (class is about classes declarations, no?). So, dragging their feet, they decided a keyword **was** indeed needed to tell the compiler the symbol was a type, and not a value.
"type" was not considered, I guess, because making it a keyword would break a lot of code. So typename was used instead. With typename, we can write:
```
for(typename T::const_iterator it = t.begin(), // etc.
```
And for consistency's sake, we are supposed to use:
```
template <typename T>
```
When T is supposed to be a type, and not a value.
But for compatibility reasons, the old notation:
```
template <class T>
```
is still authorized.
## And what about??
[eben](https://stackoverflow.com/questions/348730/why-is-there-class-in-template-class-x#348740) proposed an answer above, an answer I wanted to comment, because it is quite interesting:
```
template<template <class T> class U> // must be "class"
std::string to_string(const U<char>& u)
{
return std::string(u.begin(),u.end());
}
```
I will comment only its "meaning" (this code can't be used with STL containers on my g++ compiler, but this was not the point, I guess): One moment, it puts a constraint over U saying: "U is a class templated over the type T. This is the part:
```
template <class T> class U
```
Which can be also written:
```
template <typename T> class U
```
Because U is really and only a class (and not a built-in type), while T is a type, any type.
And the next line, it says that U is specialized over char:
```
std::string to_string(const U<char>& u)
```
So, this "generic code" will only work for U if U is declared as:
```
template<typename T>
class U
{
// Etc.
} ;
```
And U is instanciated over a char:
```
U<char> u ;
// etc.
to_string(u)
```
But one thing was forgotten: The notation proposed by Eben can be written two ways:
```
template<template <class T> class U>
std::string to_string(const U<char>& u)
template<template <typename T> class U>
std::string to_string(const U<char>& u)
```
The second "class" keyword is not a "type" keyword per se. It's a type that is a templated class over T. Thus the confusing notation.
Another way of writting Eben's code, removing the constraints above, would be something like:
```
template<typename U>
std::string to_string(const U & u)
{
return std::string(u.begin(),u.end());
}
```
And let the compiler do its magic:
```
std::list<char> myList ;
// etc.
std::cout << to_string(myList) << std:endl ;
```
(Eben's code didn't work with STL containers templated on "char" on my g++ compiler, for example...) | Why is there "class" in "template <class x>"? | [
"",
"c++",
"templates",
"syntax",
""
] |
I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the [standard](http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html), even as [documented](http://msdn.microsoft.com/en-us/library/aa768859(VS.85).aspx) on the MSDN site.
My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript?
* Call the add method differently based on the value of the user agent?
* Wrap the select object in a class that provides the proper method signature?
* Use a javascript library which does this for you (specify which library)? | You can use a try-catch block for doing this :
```
try
{
//Standards compliant
list.add(optionTag, null);
}
catch (err)
{
//IE
list.add(optionTag);
}
``` | Adding a new Option type works at least IE6 and up
```
function addOption(selectID, display, value)
{
var obj = document.getElementById(selectID);
obj.options[obj.options.length] = new Option(display, value);
}
```
Additionally tested in Firefox 2, 3, Opera 8, 9.5, and Safari 4 successfully. IE4 failed :( | Browser Neutral Way to add options to a select element in javascript | [
"",
"javascript",
""
] |
I need to take production data with real customer info (names, address, phone numbers, etc) and move it into a dev environment, but I'd like to remove any semblance of *real* customer info.
Some of the answers to [this question](https://stackoverflow.com/questions/157600/data-generators-for-sql-server) can help me generating NEW test data, but then how do I replace those columns in my production data, but keep the other relevant columns?
Let's say I had a table with 10000 fake names. Should I do a cross-join with a SQL update? Or do something like
```
UPDATE table
SET lastname = (SELECT TOP 1 name FROM samplenames ORDER By NEWID())
``` | Anonymizing data can be tricky and if not done correctly can lead you to trouble, like what happened to [AOL when they released search data a while back](http://en.wikipedia.org/wiki/AOL_search_data_scandal). I would attempt to create test data from scratch at all costs before I tried to convert existing customer data. Things may lead you to be able to figure out who the data belonged to using things such as behavioral analysis and other data points that you might not consider sensitive. I would rather be safe than sorry. | This is easier than it sounds if you understand the database. One thing that is necessary is to understand the places where personal info is not normalized. For instance, the customer master file will have a name and address, but the order file will also have a name and address that might be different.
My basic process:
1. ID the data (i.e. the columns), and the tables which contain those columns.
2. ID the "master" tables for those columns, and also the non-normailzed instances of those columns.
3. Adjust the master files. Rather than trying to randomize them, (or make them phony), connect them to the key of the file. For customer 123, set the name to name123, the address to 123 123rd St, 123town, CA, USA, phone 1231231231. This has the added bonus of making debugging very easy!
4. Change the non-normal instances by either updating from the master file *or* by doing the same kind of de-personalization
It doesn't look pretty, but it works. | Anonymizing customer data for development or testing | [
"",
"sql",
"data-scrubbing",
""
] |
I have a string. I need to replace all instances of a given array of strings from this original string - how would I do that?
Currently I am using...
```
var inputString = "this is my original string.";
var replacement = "";
var pattern = string.Join("|", arrayOfStringsToRemove);
Regex.Replace(inputString, pattern, replacement);
```
This works fine, but unfortunately it breaks down when someone tries to remove a character that has a special meaning in the regex.
How should I do this? Is there a better way? | Build the pattern using Regex.Escape:
```
StringBuilder pattern = new StringBuilder();
foreach (string s in arrayOfStringsToRemove)
{
pattern.Append("(");
pattern.Append(Regex.Escape(s));
pattern.Append(")|");
}
Regex.Replace(inputString, pattern.ToString(0, pattern.Length - 1), // remove trailing |
replacement);
``` | Look at [Regex.Escape](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx) | Remove characters using Regex | [
"",
"c#",
"regex",
"string",
""
] |
I have a table called ApprovalTasks... Approvals has a status column
I also have a view called ApprovalsView
When I try a straight update :
```
update ApprovalTasks set Status = 2 where ApprovalTaskID = 48
```
I'm getting this error message:
```
Msg 2601, Level 14, State 1, Line 1
Cannot insert duplicate key row in object 'dbo.ApprovalsView' with unique index 'IX_ApprovalTaskID'.
The statement has been terminated.
```
Any idea why this is happening?
Here is the create table script:
```
USE [CSPMOSSApplication]
GO
/****** Object: Table [dbo].[ApprovalTasks] Script Date: 12/11/2008 12:41:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApprovalTasks](
[ApprovalTaskID] [int] IDENTITY(1,1) NOT NULL,
[ApproverID] [int] NOT NULL,
[DueDate] [datetime] NULL,
[Status] [smallint] NOT NULL,
[ApprovedRejectedDate] [datetime] NULL,
[Reason] [nvarchar](1024) COLLATE Finnish_Swedish_CI_AS NULL,
[OrganizationID] [int] NOT NULL,
[TicketID] [int] NOT NULL,
[Link] [nchar](255) COLLATE Finnish_Swedish_CI_AS NULL,
[GlobalApproverID] [int] NULL,
CONSTRAINT [PK_Approval_Tasks] PRIMARY KEY CLUSTERED
(
[ApprovalTaskID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
USE [CSPMOSSApplication]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_ApprovalTaskStatuses] FOREIGN KEY([Status])
REFERENCES [dbo].[ApprovalTaskStatuses] ([ApprovalTaskStatusID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_ApprovalTaskStatuses]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_Organizations] FOREIGN KEY([OrganizationID])
REFERENCES [dbo].[Organizations] ([OrganizationID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_Organizations]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_Tickets] FOREIGN KEY([TicketID])
REFERENCES [dbo].[Tickets] ([TicketID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_Tickets]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_Users] FOREIGN KEY([ApproverID])
REFERENCES [dbo].[Users] ([UserID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_Users]
```
PK\_Approval\_Tasks(Clustered)
```
USE [CSPMOSSApplication]
GO
/****** Object: Index [PK_Approval_Tasks] Script Date: 12/11/2008 12:45:50 ******/
ALTER TABLE [dbo].[ApprovalTasks] ADD CONSTRAINT [PK_Approval_Tasks] PRIMARY KEY CLUSTERED
(
[ApprovalTaskID] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
```
IX\_ApprovalTaskID(Clsutered)
```
SE [CSPMOSSApplication]
GO
SET ARITHABORT ON
GO
SET CONCAT_NULL_YIELDS_NULL ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
SET ANSI_PADDING ON
GO
SET ANSI_WARNINGS ON
GO
SET NUMERIC_ROUNDABORT OFF
GO
/****** Object: Index [IX_ApprovalTaskID] Script Date: 12/11/2008 12:47:27 ******/
CREATE UNIQUE CLUSTERED INDEX [IX_ApprovalTaskID] ON [dbo].[ApprovalsView]
(
[ApprovalTaskID] ASC
)WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
```
Create View Script
```
USE [CSPMOSSApplication]
GO
-- =============================================
-- Script Template
-- =============================================
-- [ApprovalTasks]: add columns Link, GlobalApproverID
IF NOT EXISTS(SELECT 1 FROM sysobjects,syscolumns WHERE sysobjects.id = syscolumns.id
AND sysobjects.name = 'ApprovalTasks' AND syscolumns.name = 'Link')
BEGIN
ALTER TABLE ApprovalTasks ADD [Link] [nchar] (255) COLLATE Finnish_Swedish_CI_AS NULL
PRINT 'Column ApprovalTasks.Link was added.'
END
IF NOT EXISTS(SELECT 1 FROM sysobjects,syscolumns WHERE sysobjects.id = syscolumns.id
AND sysobjects.name = 'ApprovalTasks' AND syscolumns.name = 'GlobalApproverID')
BEGIN
ALTER TABLE ApprovalTasks ADD [GlobalApproverID] [int] NULL
PRINT 'Column ApprovalTasks.GlobalApproverID was added.'
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_GlobalApproverID] FOREIGN KEY([GlobalApproverID])
REFERENCES [dbo].[Users] ([UserID])
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_GlobalApproverID]
END
-- [ApprovalsView]
IF EXISTS (SELECT * FROM sys.fulltext_indexes fti WHERE fti.object_id = OBJECT_ID(N'[dbo].[ApprovalsView]'))
BEGIN
DROP FULLTEXT INDEX ON [dbo].[ApprovalsView]
PRINT 'FULLTEXT INDEX on [ApprovalsView] was dropped.'
END
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ApprovalsView]') AND name = N'IX_ApprovalTaskID')
BEGIN
DROP INDEX IX_ApprovalTaskID ON [dbo].[ApprovalsView] WITH ( ONLINE = OFF )
PRINT 'INDEX IX_ApprovalTaskID was dropped.'
END
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[ApprovalsView]'))
DROP VIEW [dbo].[ApprovalsView]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[ApprovalsView]
WITH SCHEMABINDING
AS
SELECT at.ApprovalTaskID,
at.ApproverID,
at.DueDate,
at.Status,
ats.ApprovalTaskStatusTranslationKey AS StatusText,
at.ApprovedRejectedDate,
at.Reason,
at.OrganizationID,
ord.Name AS OrderName,
ord.TotalPrice,
ord.SubmitDate,
ord.OrdererID,
usr.FirstName AS OrdererFirstName,
usr.LastName AS OrdererLastName,
ordi.Items_Name AS ItemName,
ordi.Items_Description AS ItemDescription,
ordi.OtherInformation AS ItemInformation,
oir.RecipientFullName,
CONVERT(nvarchar(250), oir.DeliveryAddress) As DeliveryAddress,
ti.Description
FROM dbo.ApprovalTasks at
INNER JOIN
dbo.ApprovalTaskStatuses ats ON ats.ApprovalTaskStatusID = at.Status
INNER JOIN
dbo.Orders_Items_Recipients oir ON oir.TicketID = at.TicketID
INNER JOIN
dbo.Orders_Items ordi ON ordi.Orders_ItemsID = oir.Orders_ItemsID
INNER JOIN
dbo.Orders ord ON ordi.OrderID = ord.OrderID
INNER JOIN
dbo.Users usr ON ord.OrdererID = usr.UserID
INNER JOIN
dbo.Tickets ti ON ti.TicketID = at.TicketID
GO
CREATE UNIQUE CLUSTERED INDEX [IX_ApprovalTaskID] ON [dbo].[ApprovalsView]
(
[ApprovalTaskID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
CREATE FULLTEXT INDEX ON [dbo].[ApprovalsView](
[DeliveryAddress] LANGUAGE [Neutral],
[ItemDescription] LANGUAGE [Neutral],
[ItemInformation] LANGUAGE [Neutral],
[ItemName] LANGUAGE [Neutral],
[OrdererFirstName] LANGUAGE [Neutral],
[OrdererLastName] LANGUAGE [Neutral],
[OrderName] LANGUAGE [Neutral],
[Reason] LANGUAGE [Neutral],
[RecipientFullName] LANGUAGE [Neutral])
KEY INDEX [IX_ApprovalTaskID] ON [ApprovalSearchCatalog]
WITH CHANGE_TRACKING AUTO
GO
ALTER FULLTEXT CATALOG [ApprovalSearchCatalog] rebuild
PRINT 'Catalog [ApprovalSearchCatalog] task to rebuild fulltext index was sent.'
-- STORED PROCEDURES
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReceiveApprovalTasksFromQueue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ReceiveApprovalTasksFromQueue]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Petr Klozik
-- Create date: 19.11.2008
-- Description: Gets approvals which DueDate is over ReferenceDate (now)
-- =============================================
CREATE Procedure [dbo].[ReceiveApprovalTasksFromQueue]
@Limit int
As
BEGIN
SET NOCOUNT ON;
If Not @Limit Is Null Set RowCount @Limit
-- Status: WaitingForApproval = 1
Select Tasks.ApprovalTaskID
From ApprovalTasks Tasks
Where Status = 1 And DueDate < GetDate()
END
'
GO
GRANT EXECUTE ON [dbo].[ReceiveApprovalTasksFromQueue] TO [OMT_IntegrationRole]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateApprovalTaskInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateApprovalTaskInfo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Klozik Petr
-- Create date: 2008-11-25
-- Description: Updates Approval task info to DB
-- =============================================
CREATE PROCEDURE [dbo].[UpdateApprovalTaskInfo]
@ApprovalTaskID int,
@DueDate datetime,
@ApprovalRejectDate datetime,
@Reason nvarchar(1024),
@Status int,
@GlobalApproverID int
AS
BEGIN
SET NOCOUNT ON;
Update ApprovalTasks
Set DueDate = @DueDate,
ApprovedRejectedDate = @ApprovalRejectDate,
Reason = @Reason,
Status = @Status,
GlobalApproverID = @GlobalApproverID
Where ApprovalTaskID = @ApprovalTaskID
END
'
GO
GRANT EXECUTE ON [dbo].[UpdateApprovalTaskInfo] TO [OMT_IntegrationRole]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetUserById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetUserById]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Klozik Petr
-- Create date: 2008-12-04
-- Description: Gets user row by the specified ID.
-- =============================================
CREATE PROCEDURE [dbo].[GetUserById]
(
@UserID int
)
AS
BEGIN
SELECT
UserID,
RTRIM(SID) [SID],
RTRIM(OMTGUID) [OMTGUID],
RTRIM(UserAccount) [UserAccount],
RTRIM(Email) [Email],
RTRIM(FirstName) [FirstName],
RTRIM(LastName) [LastName],
RTRIM(Country) [Country],
RTRIM(City) [City],
RTRIM(PostalNumber) [PostalNumber],
RTRIM(StreetAddress) [StreetAddress],
RTRIM(PhoneNumber) PhoneNumber,
Modified,
Deleted,
Uploaded,
UploadCode,
UploadStatus,
RTRIM(Users.ADUserAccount) AS ADUserAccount
FROM
[dbo].[Users]
WHERE
UserID = @UserID
END
'
GO
GRANT EXECUTE ON [dbo].[GetUserById] TO [OMT_IntegrationRole]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetApprovalTaskInfoById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetApprovalTaskInfoById]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Petr Klozik
-- Create date: 19.11.2008
-- Description: Gets approvals which DueDate is over ReferenceDate (now)
-- =============================================
CREATE Procedure [dbo].[GetApprovalTaskInfoById]
@ApprovalTaskID int
As
BEGIN
SET NOCOUNT ON;
Declare @OrganizationID int
Declare @CurrentApproverID int
Declare @NewApproverID int
Declare @NewOrganizationID int
Select @OrganizationID = OrganizationID, @CurrentApproverID = ApproverID
From ApprovalTasks
Where ApprovalTaskID = @ApprovalTaskID
Set @NewApproverID = (
Select Top 1 o.GlobalApproverID
From Organizations o
Inner Join OrganizationDescendants od On od.OrganizationID = o.OrganizationID
Where od.DescendantID = @OrganizationID
And Not(o.GlobalApproverID Is Null)
Order By o.OrganizationLevel Desc
)
If Not(@NewApproverID Is Null)
Begin
Set @NewOrganizationID = (
Select OrganizationID
from Organizations
Where GlobalApproverID = @NewApproverID)
End
Select Tasks.*, Tickets.Description AS TicketDescription,
Tickets.RequestorID, Tickets.OrdererID,
@NewApproverID AS OrgGlobalApproverID,
@NewOrganizationID AS OrgGlobalApproverOrganizationID
From ApprovalTasks Tasks
inner join Tickets Tickets on Tasks.TicketID = Tickets.TicketID
Where ApprovalTaskID = @ApprovalTaskID
END
'
GO
GRANT EXECUTE ON [dbo].[GetApprovalTaskInfoById] TO [OMT_IntegrationRole]
GO
``` | look at the definition of the index IX\_ApprovalTaskID
Is it possible there is a unique key constraint on ApprovalTaskID, StatusID which would mean there is another row in the table with Status = 2 & ApprovalTaskID = 48
I agree with user Learning, it looks like there's a FOR UPDATE trigger on ApprovalTasks that is inserting an ApprovalTaskID into ApprovalView
Try running `DISABLE TRIGGER ALL ON ApprovalTasks` and re-run the update | Lucky guess: any update triggers defined?
2nd lucky guess: ApprovalsView is an [indexed view](http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx) whose index is violated after updating the ApprovalTask table. | Very strange SQL update issue | [
"",
"sql",
"sql-update",
""
] |
I write a Text Editor with Java , and I want to add Undo function to it
but without UndoManager Class , I need to use a Data Structure like Stack or LinkedList but the Stack class in Java use Object parameters e.g : push(Object o) , Not Push(String s)
I need some hints or links .
Thanks | Assuming you are using Java 5, Stack is a generic class. You can instantiate it according to the objects it should hold.
You can then use:
```
Stack<String> stack = new Stack<String>();
String string = "someString";
stack.push(string);
```
Also note that in the case you are using Java 1.4 or below, you can still push String objects into the stack. Only that you will need to explicitly downcast them when you pop() them out, like so:
```
Stack stack = new Stack();
String string = "someString";
stack.push(string);
String popString = (String) stack.pop(); // pop() returns an Object which needs to be downcasted
``` | The "data structure", which in fact is a pattern, is called [Memento](http://en.wikipedia.org/wiki/Memento_pattern). It is helpful when you need to store multiple states and have the option of going back to a previous state. For efficient data storage of the states depends on what kind of a text editor you are doing, if can do some formatting, then take a look at the [Flyweight](http://en.wikipedia.org/wiki/Flyweight_pattern) pattern. | I need some help in Undo function in Java | [
"",
"java",
"class",
"function",
"stack",
"undo",
""
] |
This is my code:
```
import datetime
today = datetime.date.today()
print(today)
```
This prints: `2008-11-22` which is exactly what I want.
But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:
```
import datetime
mylist = [datetime.date.today()]
print(mylist)
```
This prints `[datetime.date(2008, 11, 22)]`. How can I get just a simple date like `2008-11-22`? | ## The WHY: dates are objects
In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.
Any object in Python has TWO string representations:
* The regular representation that is used by `print` can be get using the `str()` function. It is most of the time the most common human readable format and is used to ease display. So `str(datetime.datetime(2008, 11, 22, 19, 53, 42))` gives you `'2008-11-22 19:53:42'`.
* The alternative representation that is used to represent the object nature (as a data). It can be get using the `repr()` function and is handy to know what kind of data your manipulating while you are developing or debugging. `repr(datetime.datetime(2008, 11, 22, 19, 53, 42))` gives you `'datetime.datetime(2008, 11, 22, 19, 53, 42)'`.
What happened is that when you have printed the date using `print`, it used `str()` so you could see a nice date string. But when you have printed `mylist`, you have printed a list of objects and Python tried to represent the set of data, using `repr()`.
## The How: what do you want to do with that?
Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.
When you want to display them, just use `str()`. In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using `str(date)`.
One last thing. When you tried to print the dates, you printed `mylist`. If you want to print a date, you must print the date objects, not their container (the list).
E.G, you want to print all the date in a list :
```
for date in mylist :
print str(date)
```
Note that ***in that specific case***, you can even omit `str()` because print will use it for you. But it should not become a habit :-)
## Practical case, using your code
```
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
```
## Advanced date formatting
Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the `strftime()` method.
`strftime()` expects a string pattern explaining how you want to format your date.
E.G :
```
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
```
All the letter after a `"%"` represent a format for something:
* `%d` is the day number (2 digits, prefixed with leading zero's if necessary)
* `%m` is the month number (2 digits, prefixed with leading zero's if necessary)
* `%b` is the month abbreviation (3 letters)
* `%B` is the month name in full (letters)
* `%y` is the year number abbreviated (last 2 digits)
* `%Y` is the year number full (4 digits)
etc.
[Have a look at the official documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), or [McCutchen's quick reference](https://strftime.org) you can't know them all.
Since [PEP3101](https://www.python.org/dev/peps/pep-3101/), every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in
strftime. So you can do the same as above like this:
```
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
```
The advantage of this form is that you can also convert other objects at the same time.
With the introduction of [Formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals) (since Python 3.6, 2016-12-23) this can be written as
```
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
```
## Localization
Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-) | ```
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
```
**Edit:**
After [Cees' suggestion](https://stackoverflow.com/a/20066760/7487335), I have started using time as well:
```
import time
print time.strftime("%Y-%m-%d %H:%M")
``` | How to print a date in a regular format? | [
"",
"python",
"datetime",
"date",
""
] |
We are in the process of upgrading our projects from C# 2.0 / VS2005 to C# 3.0 / VS2008. As part of the upgrade, we are adding some items to our coding standards document.
How would (or did) you change your coding standards document when upgrading from C# 2.0 / VS2005 to C# 3.0 / VS2008? | You could/should give advice about:
* When to use query expressions vs dot notation
* Any restrictions on the use of lambda expressions (e.g. "don't modify captured variables). (This could also apply to anonymous methods in C# 2 of course.)
* When to write extension methods
* When to use implicitly typed variables (`var`)
The last two of these cause some controversy, particularly `var`.
If your conventions give any design guidelines, I'd suggest that you also advise programmers to consider using delegates for specialisation where previously they might have used inheritance or interfaces. A good example of this is sorting - it's easier (and more readable) to use a projection to specify a sort order than to write an implementation of `IComparer<T>`. | The updgrade coincided with a new project, so when we moved we started using tools like StyleCop and FxCop which altered our coding standards. Also it handily enforces them too :o) | How has your coding standards document changed when you upgraded to C# 3.0 / VS2008? | [
"",
"c#",
"visual-studio-2008",
"visual-studio-2005",
"coding-style",
"upgrade",
""
] |
I have written a [toolbar](http://osirisdevelopment.com/BatteryBar) that runs on the taskbar. Unfortunately, after it is installed, the user has to enable it manually. Is there a way to tell explorer to open (or close) a given toolbar?
I would like for the installer, NSIS, to turn on the toolbar when the installation is complete (I realize that a plugin would be necessary).
I also want to know if it's possible to automatically enable a toolbar for all users, for example in a corporate environment where multiple users would share a PC. | * [This CodeProject comment does it by simulating key presses](http://www.codeproject.com/KB/atl/rbdeskband.aspx?display=PrintAll&select=1659628#xx1659628xx)
* Vista+ has API to do this, with [ShowDeskBand](http://msdn.microsoft.com/en-us/library/bb774485(VS.85).aspx) and [HideDeskBand](http://msdn.microsoft.com/en-us/library/bb774482(VS.85).aspx)
* Edit: This code can now Add a deskband object (from Pinvoke.net, and [these](http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/c1f93cbf-f5c5-41ec-a57c-c451bd18f444) [two](http://social.msdn.microsoft.com/forums/en-US/ieextensiondevelopment/thread/edbfa343-d6aa-43fc-9155-c5f806a65481/) MSDN forum questions):
```
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("4CF504B0-DE96-11D0-8B3F-00A0C911E8E5")]
public interface IBandSite
{
[PreserveSig]
uint AddBand([In, MarshalAs(UnmanagedType.IUnknown)] Object pUnkSite);
[PreserveSig]
void RemoveBand(uint dwBandID);
}
private uint AddDeskbandToTray(Guid Deskband)
{
Guid IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
Guid ITrayBand = new Guid("{F60AD0A0-E5E1-45cb-B51A-E15B9F8B2934}");
Type TrayBandSiteService = Type.GetTypeFromCLSID(ITrayBand, true);
IBandSite BandSite = Activator.CreateInstance(TrayBandSiteService) as IBandSite;
object DeskbandObject = CoCreateInstance(Deskband, null, CLSCTX.CLSCTX_INPROC_SERVER, IUnknown);
return BandSite.AddBand(DeskbandObject);
}
```
And, an example use:
```
Guid address_toolbar_guid = new Guid("{01E04581-4EEE-11D0-BFE9-00AA005B4383}");
uint band_id = AddDeskbandToTray(address_toolbar_guid);
```
It would make sense that a similar call to RemoveBand would also do the trick, but as of yet, I can't get that code to work. Another issue: the added deskband closes when the application that added it closes. | You might want to [check out this article](http://blogs.msdn.com/oldnewthing/archive/2009/02/02/9388941.aspx). It looks like you can only do this ("officially" anyway) in Vista using the [ITrayDeskBand interface](http://msdn.microsoft.com/en-us/library/bb774484%28VS.85%29.aspx). | How can I programatically tell Windows taskbar to open (or close) a given toolbar? | [
"",
"c#",
"installation",
"toolbar",
"taskbar",
"deskband",
""
] |
Open source implementation will be preferred. | Obviously, it isn't an easy task, PDF formatting is much richer than HTML's one (plus you must extract images and link them, etc.).
Simple text extraction is much simpler (although not trivial...).
I see in the sidebar of your question a similar question: [Converting PDF to HTML with Python](https://stackoverflow.com/questions/276434/converting-pdf-to-html-with-python "Converting PDF to HTML with Python") which points to a library (poppler, which is apparently written in C++, perhaps can be accessed with JNI/JNA) and to a related question which offers even more answers. | Only ones I know of have to be paid for.
[BFO](http://bfo.co.uk/)
[JPedal](http://www.jpedal.org/) | Is there any java library for converting document from pdf to html? | [
"",
"java",
"html",
"pdf",
""
] |
How does an application perform a proximity search? For example, a user types in a postal code, then the application lists all the businesses within 20 miles ordered by proximity.
I want to build something like that in PHP and MySQL. Is this approach correct?
1. Get the addresses for locations I'm interested in and store in my database
2. Geocode all the addresses with Google's geocoding service
3. Write a database query that includes Haversine formula to do the proximity search and ordering
Is this OK? In step 3, I'm going to calculate the proximity for every query. Is it better to have a PROXIMITY table that lists the distance between every business and a few reference locations? | If there are enough records for speed to matter, here's a way to index them ahead of time.
Define a grid of bins about 20 miles on a side. Store the bin number with each store's record. At search time, compute the numbers of all bins that intersect a 20-mile radius from your search point. Then retrieve all stores in any of those bins, and proceed as before. | We use this to do many thousands of points. It is important if you are performing this in SQL to have an index on the Latitude and Longitude column. We tried doing this in SQL 2008 with spatial indexes but we really didn't see the performance increase we expected. Though if you want to calculate within a certain distance from a ZIP you need to think about if you are going to use the ZIP centroid or a polygon representation of the ZIP code.
[Haversine forumla](http://en.wikipedia.org/wiki/Haversine_formula) is a good place to start.
We have not had performance problems calculating the distance on the fly, we do calculate it ahead of time for some applications where we know the points ahead of time and there are going to be millions of records.
```
SELECT
[DistanceRadius]=
69.09 *
DEGREES(
ACOS(
SIN( RADIANS(latitude) )*SIN( RADIANS(@ziplat) )
+
COS( RADIANS(latitude) )*COS( RADIANS(@ziplat) )
*
COS( RADIANS(longitude - (@ziplon)) )
)
)
,*
FROM
table
) sub
WHERE
sub.DistanceRadius < @radius
``` | Proximity Search | [
"",
"php",
"mysql",
"proximity",
""
] |
I need the perfect algorithm or C# function to calculate the difference (distance) between 2 decimal numbers.
For example the difference between:
**100** and **25** is **75**
**100** and **-25** is **125**
**-100** and **-115** is **15**
**-500** and **100** is **600**
Is there a C# function or a very elegant algorithm to calculate this or I have to go and handle every case separately with *if*s.
If there is such a function or algorithm, which one is it? | You can do it like this
```
public decimal FindDifference(decimal nr1, decimal nr2)
{
return Math.Abs(nr1 - nr2);
}
``` | ```
result = Math.Abs(value1 - value2);
``` | Difference between 2 numbers | [
"",
"c#",
"algorithm",
"math",
"numbers",
""
] |
With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log allocations.
Any ideas? I'm looking for the simplest possible solution. Recompiling the library is not an option. | [`malloc_hook(3)`](http://linux.die.net/man/3/malloc_hook) allows you to globally interpose your own `malloc` function. (There's `__realloc_hook` `__free_hook` etc. as well, I've just left them out for simplicity.)
```
#include <stdio.h>
#include <malloc.h>
static void *(*old_malloc_hook)(size_t, const void *);
static void *new_malloc_hook(size_t size, const void *caller) {
void *mem;
__malloc_hook = old_malloc_hook;
mem = malloc(size);
fprintf(stderr, "%p: malloc(%zu) = %p\n", caller, size, mem);
__malloc_hook = new_malloc_hook;
return mem;
}
static void init_my_hooks(void) {
old_malloc_hook = __malloc_hook;
__malloc_hook = new_malloc_hook;
}
void (*__malloc_initialize_hook)(void) = init_my_hooks;
```
```
$ cat >mem.c <<'EOF'
(the code above)
EOF
$ cc -fPIC -shared -o mem.so mem.c
$ LD_PRELOAD=./mem.so ls
0x7ffc14931adc: malloc(5) = 0xb40010
0x7ffc1492c6b0: malloc(120) = 0xb40030
0x7ffc1497f61a: malloc(12) = 0xb40010
0x7ffc1492be38: malloc(776) = 0xb400b0
…
```
`printf` might call `malloc`, which is why we undo the hook temporarily. Be careful of this if when you hook `malloc` in any way. | You can trace calls to malloc/free with ltrace:
```
#include <stdlib.h>
int main (void)
{
void *ptr = malloc(10);
free(ptr);
return 0;
}
$ g++ test.cpp -o test
$ ltrace -e malloc,free ./test
malloc(10) = 0x804a008
free(0x804a008) = <void>
+++ exited (status 0) +++
```
To trace new/delete calls without recompiling you will probably need to use something like LD\_PRELOAD to override the calls with your own versions, this is precisely what [LeakTracer](http://www.andreasen.org/LeakTracer/) does which might do what you want. | Outputting to stderr whenever malloc/free is called | [
"",
"c++",
"linux",
"memory",
"malloc",
"valgrind",
""
] |
This function exists on OS X and allows you to pass custom local to the function. setlocale is not thread-safe, and passing locale as parameter is.
If there is no equivalent, any way of locale-independent printf, or printf just for doubles (%g) will be ok. | There are locale-independent double to string convertion routines at <http://www.netlib.org/fp/>. String to double conversion is available too. The API is not very nice, but the code works. | You might try [`uselocale`](http://refspecs.freestandards.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/baselib-uselocale-3.html), which sets the thread locale (rather than the process locale) before calling `printf`. | How to get equivalent of printf_l on Linux? | [
"",
"c++",
"thread-safety",
"locale",
"printf",
""
] |
Would anyone happen to know how to convert type `LPTSTR` to `char *` in C++? | Depends if it is Unicode or not it appears. LPTSTR is char\* if not Unicode, or w\_char\* if so.
[Discussed better here](http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/1b994ff3-da28-46a8-90ef-6c7fab8dcd21/) (accepted answer worth reading) | Here are a lot of ways to do this. MFC or ATL's CString, ATL macros, or Win32 API.
```
LPTSTR szString = _T("Testing");
char* pBuffer;
```
You can use ATL macros to convert:
```
USES_CONVERSION;
pBuffer = T2A(szString);
```
CString:
```
CStringA cstrText(szString);
```
or the Win32 API `WideCharToMultiByte` if `UNICODE` is defined. | Convert lptstr to char* | [
"",
"c++",
"char",
"lptstr",
""
] |
I want to make a simple server application where people can connect using a browser-based client (which I will make later) to watch streaming video. And I want to use C#.
What do I need to capture video or rapid images through a webcam and send them over the network? | If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.
If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the [DirectShow.Net](http://directshownet.sourceforge.net/) library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.
In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.
Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - [*Programming Microsoft DirectShow*](https://rads.stackoverflow.com/amzn/click/com/0735618216) - was out of print and going for around $350 for a used copy! | The usual API for this is DirectShow.
You can use P/Invoke to import the C++ APIs, but I think there are already a few projects out there that have done this.
<http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/>
<http://www.codeproject.com/KB/directx/DirXVidStrm.aspx>
To get the streaming part, you probably want to use DirectShow to apply a compression codec to reduce lag, then you can get a Stream and transmit it. You could consider using multicast to reduce network load. | How can I stream webcam video with C#? | [
"",
"c#",
"video",
"streaming",
"webcam",
""
] |
Can anyone explain to me what this means?
"Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention." | When calling a function, the compiler has to push some arguments on the stack, or put them in some registers. The function body will change some memory location (or a register) to contain the return value. Then it will return to a block of code at a location stored 'somewhere' on the stack.
The calling convention specifies the concrete details: e.g. first push the return address, then push arguments (input or output) on the stack from left to right, then execute the function, pop the arguments off again, then pop the return address and jump to that location.
If the caller does this differently than the function expects, things can go wrong (return location is not at the expected stack position).
ESP is typically the register containing the address of the current stack frame. This register is used in combination with indexes to obtain arguments in the function body. When returning, the stack top is typically reset to ESP, and the processor jumps to the location at e.g. ESP+1.
Things that may cause this to happen:
* someone wrote over the values of the stack and changed the return location (e.g. buffer overflow)
* the caller had a different calling convention than the callee | Possibility #1 is your object got Aliased wrong. That means the compiler mistakenly casted an object incorrectly, most commonly as an optimization.
Possibility #2 your using a reference to an object that isn't valid.
Possibility #3 something totally unrelated broke your stack, likely a buffer overflow.
Without code sample It's hard to predict beyond these possibilities, but they cover 90% of what might be happening. | C++ Visual Studio Runtime Error | [
"",
"c++",
"visual-studio",
"debugging",
""
] |
After trying to setup my site for Google Webmaster Tools I found that my Custom ASP.NET 404 page was not returning the 404 status code. It displayed the correct custom page and told the browser that everything is OK. This is consider a soft 404 or false 404. Google doesn't like this. So I found many articles on the issue but the solution I want didn't seem to work.
The solution I want to work is adding the following two lines to the code behind Page\_Load method of the custom 404 page.
```
Response.Status = "404 Not Found";
Response.StatusCode = 404;
```
This doesn't work. The page still returns 200 OK. I found however that if I hard code the following code into the design code it will work properly.
```
<asp:Content ID="ContentMain" ContentPlaceHolderID="ContentPlaceHolderMaster" runat="server">
<%
Response.Status = "404 Not Found";
Response.StatusCode = 404;
%>
... Much more code ...
</asp:content>
```
The page is using a master page. And I am configuring custom error pages in my web.config. I would really rather use the code behind option but I can't seem to make it work without putting a the hack inline code in the design / layout. | **Solution:**
The problem, it turned out, was the use of the master page. I got it to work by setting the status code later in the pages lifecycle, obviously the rendering of the master page was resetting it, so I overrode the render method and set it after the render was complete.
```
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
Response.StatusCode = 404;
}
```
More work could be done to find out exactly when the master page is setting the status, but I'll leave that to you.
---
**Original Post:**
I was able to get a test web app to work fine, well it at least displayed the custom error page and returned a 404 status code. I can't tell you what is wrong with your app, but I can tell you what I did:
1) Edited the web.config for custom errors:
> ```
> <customErrors mode="On">
> <error statusCode="404" redirect="404.aspx"/>
> </customErrors>
> ```
2) Added a 404.aspx page and set the status code to 404.
> ```
> public partial class _04 : System.Web.UI.Page
> {
> protected void Page_Load(object sender, EventArgs e)
> {
> Response.StatusCode = 404;
> }
> }
> ```
Thats about it, if I go to any page extension that is processed by Asp.Net and does not exist, my fiddler log clearly shows a 404, here is the header:
> ```
> HTTP/1.1 404 Not Found
> Server: Microsoft-IIS/5.1
> Date: Sun, 07 Dec 2008 06:04:13 GMT
> X-Powered-By: ASP.NET
> X-AspNet-Version: 2.0.50727
> Cache-Control: private
> Content-Type: text/html; charset=utf-8
> Content-Length: 533
> ```
Now if I go to a page that is not processed by Asp.Net, like a htm file, the custom page does not show and the 404 that is configured by IIS is displayed.
Here is a post that goes into some more details that may be of use to you and your problem, my test does do a redirect to the new page so the url of the requested file is pretty much lost (except its in the query string).
[Google 404 and .NET Custom Error Pages](https://stackoverflow.com/questions/152307/google-404-and-net-custom-error-pages)
**Header Spy Response:**
```
HTTP/1.1 404 Not Found
Date: Sun, 07 Dec 2008 06:21:20 GMT
``` | I had a similar problem I want to show a custom page as a 404 (which is ASPX) and it worked fine on localhost but as soon as a remote visitor connected they would get the generic IIS 404.
The solution to this was to add
```
Response.TrySkipIisCustomErrors = true;
```
Before changing the Response.StatusCode.
Found via Rick Strahl <http://www.west-wind.com/weblog/posts/745738.aspx> | ASP.NET Custom 404 Returning 200 OK Instead of 404 Not Found | [
"",
"c#",
"asp.net",
"master-pages",
"http-status-code-404",
"custom-errors",
""
] |
I'm working on a Zend Framework (1.7) project with a structure loosely based on the structure of the quickstart application - front controller, action controllers, views & models that use Zend\_Db\_Table to get to the database. One of my main models relies on some expensive joins to pull up its primary listing, so I'm looking into using Zend\_Paginator to reduce the number of rows brought back from the database. My problem is that Zend\_Paginator only comes with 4 adaptors, none of which really seem to be a good fit for me.
* **Array** : Building the array to feed to ZP would involve fetching all the records which is what I'm trying to avoid
* **Iterator** : A dumb iterator would present the same problems as an array and a smart one feels like it would be a poor fit for the Model
* **DbSelect** : Getting a DbSelect object up to the Controller would uncomfortably tie the Controller to the inner workings of my DB (not to mention producing raw result rows rather than encapsulated objects)
* **DbTableSelect** : same as DbSelect
* **Null Adapter** : pass all the details back and forth manually.
Passing the paginator into the model feels like it, too, would violate the MVC separation. Is the problem that I've built my model incorrectly, that I'm being to dogmatic about maintaining MVC separation or am I missing a clean, elegant way of sticking all the moving parts together? | You can provide an interface on your models that accepts `$current_page` and `$per_page` parameters and returns the current page's data set as well as a paginator object.
This way all your pagination code is contained within the model and you are free to use the Db adapters without feeling like you've broken the concept.
Plus, the controller really shouldn't be setting up the pager anyways since you are correct in it being tied to the data (and models are for data, not just database connections).
```
class Model
{
//...
/**
* @return array Array in the form: array( 'paginator' => obj, 'resultset' => obj )
*/
public function getAll( $where = array(), $current_page = null, $per_page = null );
//...
}
``` | There is now a setFilter method for Zend\_Paginator that allows you to load the data from the row object to any model object you want:
```
class Model_UserDataMapper {
public function getUsers($select, $page) {
$pager = Zend_Paginator::factory($select);
$pager->setItemCountPerPage(10)
>setCurrentPageNumber($page)
->setFilter(new Zend_Filter_Callback(array($this,'getUserObjects')));
}
public function getUserObjects($rows) {
$users = array();
foreach($rows as $row) {
$user = new Model_User($row->toArray());
$users[] = $user;
}
return $users;
}
}
``` | Zend_Paginator blurring MVC lines | [
"",
"php",
"model-view-controller",
"zend-framework",
"zend-paginator",
""
] |
Is there any real reason **not** to make a member function virtual in C++? Of course, there's always the performance argument, but that doesn't seem to stick in most situations since the overhead of virtual functions is fairly low.
On the other hand, I've been bitten a couple of times with forgetting to make a function virtual that *should* be virtual. And that seems to be a bigger argument than the performance one. So is there any reason not to make member functions virtual by default? | One way to read your questions is "Why doesn't C++ make every function virtual by default, unless the programmer overrides that default." Without consulting my copy of "Design and Evolution of C++": this would add extra storage to every class unless every member function is made non-virtual. Seems to me this would have required more effort in the compiler implementation, and slowed down the adoption of C++ by providing fodder to the performance obsessed (I count myself in that group.)
Another way to read your questions is "Why do C++ programmers do not make every function virtual unless they have very good reasons not to?" The performance excuse is probably the reason. Depending on your application and domain, this might be a good reason or not. For example, part of my team works in market data ticker plants. At 100,000+ messages/second on a single stream, the virtual function overhead would be unacceptable. Other parts of my team work in complex trading infrastructure. Making most functions virtual is probably a good idea in that context, as the extra flexibility beats the micro-optimization. | Stroustrup, the designer of the language, [says](http://www.research.att.com/%7Ebs/bs_faq2.html#virtual):
> Because many classes are not designed to be used as base classes. For example, see [class complex](http://www.research.att.com/%7Ebs/bs_faq2.html#data-in-class).
>
> Also, objects of a class with a virtual function require space needed by the virtual function call mechanism - typically one word per object. This overhead can be significant, and can get in the way of layout compatibility with data from other languages (e.g. C and Fortran).
>
> See The Design and Evolution of C++ for more design rationale. | Is there any reason not to make a member function virtual? | [
"",
"c++",
"oop",
"virtual-functions",
""
] |
I'm having an extremely weird problem with a PHP script of mine.
I'm uploading a couple of files and having PHP put them all in one folder.
I've have trouble with random files being sent and random ones not being sent. So I debugged it and I got a very weird result from the $\_FILES[] array.
I tried it with 3 files.
`$_FILES["addFile"]["name"]` Holds the names of the 3 files.
You'd expect `$_FILES["addFile"]["tmp_name"]` to hold the 3 temporary names that PHP uses to copy the files, but it doesn't. It holds just one name. The other 2 are empty strings, which generate an error whilst uploading(which I supress from being displayed)
This is very odd. I've tried mulitple situations and it just keeps on happening.
This must be something in my settings or perhaps even my code.
Here's my code:
```
$i = 0;
if (!empty($_FILES['addFile'])) {
foreach($_FILES['addFile'] as $addFile) {
$fileToCopy = $_FILES["addFile"]["tmp_name"][$i];
$fileName = $_FILES["addFile"]["name"][$i];
$i++;
if(!empty($fileToCopy)){
$copyTo = $baseDir."/".$fileName;
@copy($fileToCopy, $copyTo) or die("cannot copy ".$fileToCopy." to ".$copyTo);
}
}
exit(0);
}
```
Since the tmp\_name is empty, the if-value will be false so it's gonna skip the die() function.
Does anybody know what might be causing this?
further info: I'm using Windows XP, running WAMP server. Never had this problem before and I can acces all maps from which I've tried to upload. Security settings of windows can't be the issue I think. | Relevent, but probably not going to help: but move\_uploaded\_file is a (slightly) better way to handle uploaded files than copy.
Are any of the files large? PHP has limits on the filesize and the time it can take to upload them ...
Better to send you here than attempt to write up what it says:
<https://www.php.net/manual/en/features.file-upload.common-pitfalls.php> | I'm sorry but it seams to me that you are trying to upload all 3 files with the same variable name? Is this right?
But this will not work because they will overwrite each other.
I think the better an cleaner way it would be to use something like
```
$i = 0;
foreach($_FILES['addFile'.$i] as $addFile) {
if(!empty($addFiles) {
move_uploaded_file($addFile['temp_name'], 'YOUR DIRECTORY');
}
$i++;
}
``` | PHP file uploading trouble | [
"",
"php",
"file-upload",
""
] |
I am currently developing a (somewhat large) site for a magazine, the site mainly consists of sections like : news (for various categories), members, and some 'other stuff' (like shoutbox, polls, previous covers, photo galleries that can be tagged, and ad banners system).
Now, since most part of the site is a typical blog style (single-post page), I'm thinking of using Wordpress as the main engine because of its powerful backend with a good (easy to use ?) WYSIWYG editor, nice page organization, media handling, and lots of other features. Naturally that leaves me with the 'other stuff'. (banner management, photo tags management, etc.)
The easiest way (well, I think) was to set up another CMS (let's call it CMS2), to handle all those things that would be impossible or probably difficult to integrate into WP admin, and then trying to cope everything in the frontend, WP style.
My questions :
1. Is it good (normal) for a site to have two (or more) CMS behind it ?
2. What could possibly go wrong ? (or perhaps, is there anything I should know beforehand with this kind of approach ?)
3. The other alternative would be to look for another good, single way to handle everything. But the main problem now is to find a CMS powerful and flexible enough for those. What framework / CMS is the most appropriate for this (according to you) ?
4. Other alternative ?
Many thanks in advance. | Honestly I think it's a pretty bad idea, at least on the background of my own experience.
The main disadvantages:
* doubles the amount of knowledge an admin/editor has to have/develop
* doubles the amount of security risks
* doubles the amount of updating/patching the CMS installations
* lowers the probability of finding a replacement for you
* it makes SEO related tasks more difficult
* it makes development more difficult if features of the two sites are supposed to interact
* it makes interaction between features of the two sites difficult or impossible (due to the restrictions of the CMS)
What would that second CMS be anyways?
If it is a site with the dimensions you described, why not using a real CMS?
Both Drupal and Joomla can handle all of the requirements you describe!
Take some time to evaluate, which one to choose and go for one CMS! | I think its too complicated and that problems are likely to arise around the fact there are two systems. Its also not great from a usability perspective.
You should look at some of the beefier CMS options. Drupal has a lot of plugins and functionality available, be suprised if it can't do what you need. Joomla is also worth a look, as is CMS Made Simple (CMSMS). | setting up two CMS for one site, best practice | [
"",
"php",
"architecture",
"content-management-system",
""
] |
I have a template class like below.
```
template<int S> class A
{
private:
char string[S];
public:
A()
{
for(int i =0; i<S; i++)
{
.
.
}
}
int MaxLength()
{
return S;
}
};
```
If i instantiate the above class with different values of S, will the compiler create different instances of A() and MaxLenth() function? Or will it create one instance and pass the S as some sort of argument?
How will it behave if i move the definition of A and Maxlength to a different cpp file. | The template will be instantiated for each different values of S.
If you move the method implementations to a different file, you'll need to #include that file. (Boost for instance uses the `.ipp` convention for such source files that need to be #included).
If you want to minimise the amount of code that is generated with the template instantiation (and hence needs to be made available in the `.ipp` file) you should try to factor it out by removing the dependency on S. So for example you could derive from a (private) base class which provides member functions with S as a parameter. | Actually this is fully up to the compiler. It's only required to generate *correct* code for its inputs. In order to do so it must follow the C++ standard as that explains what *is* correct. In this case it says that the compiler must at one step in the process instantiate templates with different arguments as different types, these types may later be represented by the same code, or not, it's fully up to the compiler.
It's most probable that the compiler would inline at least MaxLength() but possibly also your ctor. Otherwise it may very well generate a single instance of your ctor and pass/have it retrieve S from elsewhere. The only way to know for sure is to examine the output of the compiler.
So in order to know for sure I decided to list what VS2005 does in a release build. The file I have compiled looks like this:
```
template <int S>
class A
{
char s_[S];
public:
A()
{
for(int i = 0; i < S; ++i)
{
s_[i] = 'A';
}
}
int MaxLength() const
{
return S;
}
};
extern void useA(A<5> &a, int n); // to fool the optimizer
extern void useA(A<25> &a, int n);
void test()
{
A<5> a5;
useA(a5, a5.MaxLength());
A<25> a25;
useA(a25, a25.MaxLength());
}
```
The assembler output is the following:
```
?test@@YAXXZ PROC ; test, COMDAT
[snip]
; 25 : A<5> a5;
mov eax, 1094795585 ; 41414141H
mov DWORD PTR _a5$[esp+40], eax
mov BYTE PTR _a5$[esp+44], al
; 26 : useA(a5, a5.MaxLength());
lea eax, DWORD PTR _a5$[esp+40]
push 5
push eax
call ?useA@@YAXAAV?$A@$04@@H@Z ; useA
```
As you can see both the ctor and the call to MaxLength() are inlined. And as you may now guess it does the same with the A<25> type:
```
; 28 : A<25> a25;
mov eax, 1094795585 ; 41414141H
; 29 : useA(a25, a25.MaxLength());
lea ecx, DWORD PTR _a25$[esp+48]
push 25 ; 00000019H
push ecx
mov DWORD PTR _a25$[esp+56], eax
mov DWORD PTR _a25$[esp+60], eax
mov DWORD PTR _a25$[esp+64], eax
mov DWORD PTR _a25$[esp+68], eax
mov DWORD PTR _a25$[esp+72], eax
mov DWORD PTR _a25$[esp+76], eax
mov BYTE PTR _a25$[esp+80], al
call ?useA@@YAXAAV?$A@$0BJ@@@H@Z ; useA
```
It's very interesting to see the clever ways the compiler optimizes the for-loop. For all those premature optimizers out there using memset(), I would say fool on you.
> How will it behave if i move the definition of A and Maxlength to a different cpp file.
It will probably not compile (unless you only use A in that cpp-file). | c++ template instantiation | [
"",
"c++",
"templates",
""
] |
I need to create a request for a web page delivered to our web sites, but I need to be able to set the host header information too. I have tried this using HttpWebRequest, but the Header information is read only (Or at least the Host part of it is). I need to do this because we want to perform the initial request for a page before the user can. We have 10 web server which are load balanced, so we need to request the file from each of the web servers.
I have tried the following:
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.1.5/filename.htm");
request.Headers.Set("Host", "www.mywebsite.com");
WebResponse response = request.GetResponse();
```
Obviously this does not work, as I can't update the header, and I don't know if this is indeed the right way to do it. | I have managed to find out a more long winded route by using sockets. I found the answer in the MSDN page for IPEndPoint:
```
string getString = "GET /path/mypage.htm HTTP/1.1\r\nHost: www.mysite.mobi\r\nConnection: Close\r\n\r\n";
Encoding ASCII = Encoding.ASCII;
Byte[] byteGetString = ASCII.GetBytes(getString);
Byte[] receiveByte = new Byte[256];
Socket socket = null;
String strPage = null;
try
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("10.23.1.93"), 80);
socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ip);
}
catch (SocketException ex)
{
Console.WriteLine("Source:" + ex.Source);
Console.WriteLine("Message:" + ex.Message);
}
socket.Send(byteGetString, byteGetString.Length, 0);
Int32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0);
strPage = strPage + ASCII.GetString(receiveByte, 0, bytes);
while (bytes > 0)
{
bytes = socket.Receive(receiveByte, receiveByte.Length, 0);
strPage = strPage + ASCII.GetString(receiveByte, 0, bytes);
}
socket.Close();
``` | Although this is a very late answer, maybe someone can get benefit of it
```
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://192.168.1.1"));
request.Headers.GetType().InvokeMember("ChangeInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, request.Headers, new object[] {"Host","www.mysite.com"});
```
Reflection is your friend :) | Request Web Page in c# spoofing the Host | [
"",
"c#",
"http",
"http-headers",
""
] |
How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP? | By using
```
$_SERVER['REQUEST_METHOD']
```
### Example
```
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
```
For more details please see the [documentation for the $\_SERVER variable](http://php.net/manual/en/reserved.variables.server.php). | REST in PHP can be done pretty simple. Create <http://example.com/test.php> (outlined below). Use this for REST calls, e.g. <http://example.com/test.php/testing/123/hello>. This works with Apache and Lighttpd out of the box, and no rewrite rules are needed.
```
<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
switch ($method) {
case 'PUT':
do_something_with_put($request);
break;
case 'POST':
do_something_with_post($request);
break;
case 'GET':
do_something_with_get($request);
break;
default:
handle_error($request);
break;
}
``` | Detecting request type in PHP (GET, POST, PUT or DELETE) | [
"",
"php",
"http",
"request",
""
] |
I need a byte buffer class in Java for single-threaded use. I should be able to insert data at the back of the buffer and read data at the front, with an amortized cost of O(1). The buffer should resize when it's full, rather than throw an exception or something.
I could write one myself, but I'd be very surprised if this didn't exist yet in a standard Java package, and if it doesn't, I'd expect it to exist in some well-tested public library.
What would you recommend? | Not sure if it is "the best", but you have a nice example of [Circular Byte buffer here](http://ostermiller.org/utils/CircularBuffer.html).
Those [Java Utilities - OstermillerUtils](http://ostermiller.org/utils/) classes are under [GPL license](http://ostermiller.org/utils/licenseFAQ.html).
> This Circular Byte Buffer implements the circular buffer producer/consumer model for bytes. Filling and emptying the buffer is done with standard Java InputStreams and OutputStreams.
>
> Using this class is a simpler alternative to using a PipedInputStream and a PipedOutputStream.
> PipedInputStreams and PipedOutputStreams don't support the mark operation, don't allow you to control buffer sizes that they use, and have a more complicated API that requires a instantiating two classes and connecting them. | I wonder if this one works well
<https://svn.apache.org/repos/asf/etch/releases/release-1.0.0/util/src/main/java/etch/util/CircularByteBuffer.java>
We will probably try this one since it is apache license. | What is the best resizable circular byte buffer available in Java? | [
"",
"java",
"buffer",
"byte",
""
] |
Why does this test program result in a `java.lang.IllegalMonitorStateException`?
```
public class test {
static Integer foo = new Integer(1);
public static void main(String[] args) {
synchronized(foo) {
foo++;
foo.notifyAll();
}
System.err.println("Success");
}
}
```
Result:
```
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at test.main(test.java:6)
``` | You have noted correctly that `notifyAll` must be called from a synchronized block.
However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked `notifyAll` on. In fact, the new, incremented `foo` instance is still confined to the stack, and no other threads could possibly be blocked on a `wait` call.
You could implement your own, mutable counter on which synchronization is performed. Depending on your application, you might also find that [AtomicInteger](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html) meets your needs. | You should also be leery of locking or notifying on objects like String and Integer that can be interned by the JVM (to prevent creating a lot of objects that represent the integer 1 or the string ""). | Why does notifyAll() raise IllegalMonitorStateException when synchronized on Integer? | [
"",
"java",
"synchronization",
"notify",
"illegalmonitorstateexcep",
""
] |
I have written a small java application for which I need to obtain performance metrics such as memory usage, running time etc., Is there any simple to use performance measurement tool available? | [Yourkit](http://yourkit.com/) is pretty good (free 30 day trial). Eclipse also has built in [TPTP tools](http://www.eclipse.org/tptp/). | [Apache JMeter](http://jakarta.apache.org/jmeter/) has a ton of features, for benchmarking http requests, JDBC calls, web services, JMS, mail, regular Java requests, etc. | Java benchmarking tool | [
"",
"java",
"performance",
"benchmarking",
""
] |
I'm trying to do the following in python:
In a file called foo.py:
```
# simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
```
And then in a file called bar.py:
import foo
```
d = foo.data
d.fn(1,2,3)
```
However, I get the following error:
> TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)
This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.
So the question is:
***How can I store a function in a class object without the function becoming bound to that class?*** | ```
data.fn = staticmethod(myFunction)
```
should do the trick. | What you can do is:
```
d = foo.data()
d.fn = myFunction
d.fn(1,2,3)
```
Which may not be exactly what you want, but does work. | storing unbound python functions in a class object | [
"",
"python",
"function",
""
] |
I have to include many header files, which are in different sub-directories. Is there a way in Visual Studio (I am using 2005 edition) to set one include path that Visual Studio will search also the sub-directories for header files? | Setting the folder search paths in the Visual Studio settings to fix an include issue is generally not really a good idea from a design point of view. Your code will be less portable to different machines with different directory lay-outs.
My suggestion would be to settle on an organisation of your code so that the relative paths of the sub-directories (relative to your including code) are fixed:
* Add the "base folder" to the project (*project properties -> Configuration Properties -> C/C++ -> Additional Include Directories, "additional include directories"*)
* Add the subdirectories to the #include statements , i.e. `#include "subdirectory/somefile.h"`.
This has the added bonus of being able to see which folder in your Solution contains the file - that is often useful information when you're trying to find your way around or trying to figure out what a file is for. | We haven't found a way of setting a recursive folder search in Visual Studio (though Xcode has no problem setting and using them). What we do is list all the directories in a file, and specify the file in the C/C++ Command Line additional options:
@"IncludeFolders.rsp"
We rarely find problems using recursive search, though an accidental inclusion of ``/'' did slow things down a bit once. | How to include sub-directories in Visual Studio? | [
"",
"c++",
"visual-studio",
"visual-studio-2005",
"include",
""
] |
How do Window's programmers profile their native C++ code?
On Unix/Linux you have gprof *[thanks Evan]* & valgrind (I personally used this one, although it's not a real profiler), and recently I'm on Mac and Solaris, which means I moved to dTrace. Now when I've had the need to profile on Windows in the past, like at my previous job, I used Intel's vtune, which is great, however it's commercial, and I don't have a license for private use, so I'm left wondering what's the standard (free is better) tool windows programmers commonly use?
Thanks in advance | You should give [Xperf](http://blogs.msdn.com/pigscanfly/archive/2008/02/09/xperf-a-new-tool-in-the-windows-sdk.aspx) a try - it's a new system wide performance tool that can drill down to a particular application and what exactly it's doing inside itself as well as what's it's asking of the OS.
It's freely available on the [Windows SDK for Windows Server 2008 and .NET Framework 3.5 ISO](http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en):
> 1. Install the SDK by downloading the [ISO image](http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en), or using the Web based
> installer.
> 2. Find the xperf MSI in the SDK's "bin" directory. It will be named
> xperf\_x86.msi, xperf\_x64.msi, or
> xperf\_ia64.msi, depending on the
> architecture for which you install the
> SDK.
> 3. You can then install the xperf tools from the MSI directly, or copy
> the xperf MSI file to another location
> and install it from there. For
> example, you could keep the MSI files
> on a USB key.
[Source: Pigs Can Fly blog on MSDN.com](http://blogs.msdn.com/pigscanfly/archive/2008/02/09/xperf-a-new-tool-in-the-windows-sdk.aspx)
Just verified that the xperf msi will not install except on windows Vista or Windows 2007.
-Adam | I got [AMD Code Analyst](http://www.amd.com/codeanalyst/). It's free, and you don't need an AMD CPU ;)
It's a little basic compared to something like Intel's VTune, but the price is right. | What tools do you use to profile (native)C++ on Windows? | [
"",
"c++",
"windows",
"profiling",
""
] |
If i do jQuery(expr).change( function), then I can get an event function to fire when the user makes a change to the value.
Is it possible to get this to fire if it's changed programatically, ie if I call jQuery(expr).val("moo").
or if some Plain old JavaScript changes it's value?
Thanks for any help. | After you've changed the value, you can fire the event yourself, and thus calling all the 'onchange' handlers.
```
jQuery('#element').change();
``` | Changing the value directly in JS doesn't hook into anything which jQuery can listen for to trigger the change event. Like Sander says, you can fire the event handler yourself. If you don't have control over other code modifying these values and that isn't an option, you're kind of out of luck. The only other option which might work would be to have an observer watch the value on an interval using `setTimeout`, which is really messy and probably not a good idea. | JQuery detecting Programatic change event | [
"",
"javascript",
"jquery",
""
] |
I am looking at depency injection, I can see the benefits but I am having problems with the syntax it creates. I have this example
```
public class BusinessProducts
{
IDataContext _dx;
BusinessProducts(IDataContext dx)
{
_dx = dx;
}
public List<Product> GetProducts()
{
return dx.GetProducts();
}
}
```
The problem is that I don't want to write
```
BusinessProducts bp = new BusinessProducts(dataContextImplementation);
```
I would continue to write
```
BusinessProducts bp = new BusinessProducts();
```
because I feel the first alternative just feels unatural. I dont want to know what the BusinessProduct "depends" on to get the products, also I feel it makes my code more unreadable.
Is there any alternatives to this approach as I would like to keep my original syntax for creating objects but I would like to still be able to fake the dependencies when unit testing or is it this dependecy injection frameworks can do for me?
I am coding in c# but alternatives from other languages is welcome | I use a factory for my context and inject it, providing a suitable default if the provided factory is null. I do this for two reasons. First, I use the data context as a unit of work scoped object so I need to be able to create them when needed, not keep one around. Second, I'm primarily using DI to increase testability, with decoupling only a secondary consideration.
So my business products class would look like:
```
public class BusinessProducts
{
private IDataContextFactory DataContextFactory { get; set; } // my interface
public BusinessProducts() : this(null) {}
public BusinessProducts( IDataContextFactory factory )
{
this.DataContext = factory ?? new BusinessProductsDataContextFactory();
}
public void DoSomething()
{
using (DataContext dc = this.DataContextFactory().CreateDataContext())
{
...
}
}
```
An alternative to this would be to make the factory property publicly settable and inject an alternate factory by setting the property. Either way if you want to keep the null constructor, you'll need to provide a default. | You can create a factory. DI containers are best for wirings that happen at setup-time - not at runtime (As this looks to be a case of). Factories can be implemented in different ways, depending on how pluggable it needs to be, and how many places you need to use it. | dependency injection alternatives | [
"",
"c#",
"dependency-injection",
""
] |
Related to this question:
[URL characters replacement in JSP with UrlRewrite](https://stackoverflow.com/questions/353207/url-characters-replacement-in-jsp-with-urlrewrite)
I want to have masked URLs in this JSP Java EE web project.
For example if I had this:
```
http://mysite.com/products.jsp?id=42&name=Programming_Book
```
I would like to turn that URL into something more User/Google friendly like:
```
http://mysite.com/product-Programming-Book
```
I've been fighting with UrlRewrite, forwarding and RequestDispatcher to accomplish what I want, but I'm kind of lost. I should probably have a filter for all http requests, re format them, and forward the page.
Can anyone give some directions? Tips?
Thanks a lot.
**UPDATE:** Servlets did it. Thanks Yuval for your orientation.
I had been using UrlRewrite, as you can see at the first sentence of the question I also asked a question about that. But I couldn't manage to get UrlRewrite work the way I wanted. Servlets did the job. | It's been a while since I mucked about with JSPs, but if memory serves you can add URL patterns to your web.xml (or one of those XML config files) and have the servlet engine automatically route the request to a valid URL with your choice of paramters. I can look up the details if you like.
In your case, map `http://mysite.com/product-Programming-Book` to the URL
`http://mysite.com/products.jsp?id=42&name=Programming_Book` and the user no longer sees the real URL. Also, you can use this more user-friendly URL within your application, as a logical name for that page.
Yuval =8-) | You could use a `URLRewrite filter`. It's like how mod\_rewrite is for Apache's HTTP web server.
<http://tuckey.org/urlrewrite/>
"Redirect one url
```
<rule>
<from>^/some/old/page\.html$</from>
<to type="redirect">/very/new/page.html</to>
</rule>
```
Tiny/Freindly url
```
<rule>
<from>^/zebra$</from>
<to type="redirect">/big/ugly/url/1,23,56,23132.html</to>
</rule>
```
" | Mask urls in JSP | [
"",
"java",
"jsp",
"url",
"jakarta-ee",
""
] |
I'm working with some old PHP code that has a lot of the following:
```
$someVar =& new SomeClass();
```
Did the **new** operator ever return a value, um, not by reference? (That feels strange to type. I feel like I'm losing my mind.) | It was one of those sort of optimization techniques taught in a lot of older books on OOP in PHP 4.
Basically, the initial object created in memory is one the application can't access unless you return the instance by reference. Otherwise you get a copy of the object - the only catch is that the original exists without a symbol. Kinda dumb.
But ya, object creating and passing and references in PHP 4 is a monumental mess. | Thats PHP4 code.
From the documentation: (now removed)
> "new" does not return a reference by
> default, instead it returns a copy.
~~[1]: <http://no.php.net/manual/en/language.oop.newref.php>~~ | PHP new operator returning reference | [
"",
"php",
"reference",
""
] |
Is there a way in SWT to get a monospaced font simply, that works across various operating systems?
For example. this works on Linux, but not Windows:
```
Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);
```
or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.
I tried getting the system font from Display, but that wasn't monospaced. | According to the section on [Font Configuration Files](http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html) in the JDK documentation of [Internationalization Support](http://java.sun.com/javase/6/docs/technotes/guides/intl/)-related APIs, the concept of **Logical Font**s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files:
> The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.
So in your case, I'd try
`Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);`
to get a handle to the physical monospaced font of the current platform your code is running on.
**Edit**: It seems that SWT doesn't know anything about logical fonts ([Bug 48055](https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055) on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font... | I spent a while bashing my head against this one until I realised that obviously eclipse must have access to a monospace font for use in its text fields, console etc. A little digging turned up:
```
Font terminalFont = JFaceResources.getFont(JFaceResources.TEXT_FONT);
```
Which works if all you're interested in is getting hold of some monospace font.
**Edit:** Or based on @ctron's comment:
```
Font font = JFaceResources.getTextFont();
```
**Edit:** Caveat (based on @Lii's comment): this will get you the configured Text Font, which can be overriden by the user and may not be a monospace font. However, it will be consistent with, e.g., the font used in the editor and console which is *probably* what you want. | SWT - OS agnostic way to get monospaced font | [
"",
"java",
"fonts",
"swt",
""
] |
I'd like them to be easy to bundle, with few dependencies and easy to use. | Do you want to highlight Java code or use a Java lib to highlight some other code?
I use these two: <https://jhighlight.dev.java.net/> (server-side) for xml and <http://code.google.com/p/syntaxhighlighter/> (js lib) for other stuff. The latter has something called 'brushes' which are "pluggable" .js for several langauges. If you are doing simple highlighting, I recommend the ,js approach. | <http://sourceforge.net/projects/jintilla/>
<http://syntax.jedit.org/> | What code highlighting libs are there for Java? | [
"",
"java",
"syntax-highlighting",
"codehighlighter",
""
] |
My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look
[Image](http://img114.imageshack.us/img114/9683/frameow2.jpg)
Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?
I also would like to set the size of those buttons so they are not so huge (`BorderLayout` is being used for the buttons and TextField) | If you want the two checkerboards to stay the same size, then you'll need to have them each contained in their own `JPanel`. Set each of those parent JPanel's to have a layout type of `GridBagLayout`. Set the preferedSize for each checkerboard component and then add them to their respective containers. GridBagLayout should by default lay each board out in the center of the parent JPanel. So as the window is resized, the JPanel parent area will get larger or smaller, but the checkerboard components inside will remain the same size.
Alternatively, you could have your blue squares scale to the right size as the window is resized by having each checkboard square be a `JPanel` with a `BorderLayout` layout manager and adding the `JLabel` (with a blue background color) to its `BorderLayout.CENTER` location.
As for your buttons, try something like this:
```
JPanel theButtonPanel = new JPanel(new BorderLayout());
JButton button1 = new JButton("Fire");
JButton button2 = new JButton("Pass");
JButton button3 = new JButton("Forfiet");
JPanel innerButtonContainer = new JPanel(new Grid(1, 3, 8, 8));
innerButtonContainer.add(button1);
innerButtonContainer.add(button2);
innerButtonContainer.add(button3);
theButtonPanel.add(innterButtonContainer);
```
Lastly, consider using a design tool for your Swing user interface. Netbeans has an **excellent UI** designer built into it. Download Netbeans [here](http://www.netbeans.org/downloads/index.html). | **GridBagLayout** is what you really want to use. The GridLayout will force the same size for each component in the layout no matter what size constraints you put on them. GridBagLayout is a lot more powerful and a lot more complicated. Study up on [the API page](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/GridBagLayout.html) for it. Using `GridBagLayout`, the components won't fill the whole grid space if you don't want them to and can even stay the size that you ask it to be. To keep a component's size from changing, I would set all three available size constraints:
```
water.setPreferredSize(new Dimension(20, 20));
water.setMinimumSize(new Dimension(20, 20));
water.setMaximumSize(new Dimension(20, 20));
```
For your buttons, I would definitely use an inner panel as [Bryan](https://stackoverflow.com/questions/316454/can-you-set-a-permanent-size-for-a-jpanel-inside-of-a-jframe#316496) mentions. You could use either a GridLayout like he suggests or a FlowLayout if you don't want all the buttons to be the same size. Add all your buttons to that inner panel instead of the main one. | Can you set a permanent size for a JPanel inside of a JFrame? | [
"",
"java",
"swing",
"size",
"jlabel",
"grid-layout",
""
] |
I am working on an application which draws a simple dot grid. I would like the mouse to snap between the points on the grid, eventually to draw lines on the grid.
I have a method which takes in the current mouse location (X,Y) and calculates the nearest grid coordinate.
When I create an event and attempt to move the mouse to the new coordinate the whole system becomes jerky. The mouse doesn't snap smoothly between grid points.
I have copied a code sample below to illustrate what I am attempting to do. Does anyone have any advice they could offer me as to how I can eliminate the jumpiness within the mouse movement?
---
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GridTest
{
public partial class Form1 : Form
{
Graphics g;
const int gridsize = 20;
public Form1()
{
InitializeComponent();
g = splitContainer1.Panel2.CreateGraphics();
splitContainer1.Panel2.Invalidate();
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
Drawgrid();
}
private void Drawgrid()
{
for (int x = 0; x < splitContainer1.Panel2.ClientSize.Width; x += gridsize)
{
for (int y = 0; y < splitContainer1.Panel2.ClientSize.Height; y += gridsize)
{ g.DrawLine(Pens.Black, new Point(x, y), new Point(x + 1, y)); }
}
}
private void splitContainer1_Panel2_MouseMove(object sender, MouseEventArgs e)
{
Point newPosition = new Point();
newPosition = RoundToNearest(gridsize, e.Location);
Cursor.Position = splitContainer1.Panel2.PointToScreen(newPosition);
}
private Point RoundToNearest(int nearestRoundValue, Point currentPoint)
{
Point newPoint = new Point();
int lastDigit;
lastDigit = currentPoint.X % nearestRoundValue;
if (lastDigit >= (nearestRoundValue/2))
{ newPoint.X = currentPoint.X - lastDigit + nearestRoundValue; }
else
{ newPoint.X = currentPoint.X - lastDigit; }
lastDigit = currentPoint.Y % nearestRoundValue;
if (lastDigit >= (nearestRoundValue / 2))
{ newPoint.Y = currentPoint.Y - lastDigit + nearestRoundValue; }
else
{ newPoint.Y = currentPoint.Y - lastDigit; }
return newPoint;
}
}
}
``` | I think I understand where you're coming from. You simply need to be some delta away from the original snap point (the left mouse click) before you snap to the new point.
Here's 50 lines of code illustrating what I mean:
(Start a new VB.NET project, add a new module, copy and paste the code, add a reference, to System, System.drawing, and System.Windows.Forms)
```
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Module modSnap
Public Const strApplicationTitle As String = "Snap Demo"
Public frmSnap As SnapForm
Public ptSnap, ptStart, ptEnd As Point
Public Class SnapForm
Inherits Form
Public Sub New()
Me.Text = "Snap Demo"
Me.ClientSize = New Size(800, 600)
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.StartPosition = FormStartPosition.CenterScreen
Me.DoubleBuffered = True
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaint(e)
e.Graphics.Clear(Color.Black)
For row As Integer = 20 To 780 Step 20
For col As Integer = 20 To 580 Step 20
e.Graphics.DrawEllipse(Pens.Blue, New Rectangle(row - 2, col - 2, 4, 4))
Next
Next
e.Graphics.DrawLine(Pens.Red, ptStart, ptEnd)
End Sub
Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseDown(e)
Dim x As Integer = CInt(e.X / 20) * 20
Dim y As Integer = CInt(e.Y / 20) * 20
ptStart = New Point(x, y)
ptSnap = New Point(x, y)
Windows.Forms.Cursor.Position = Me.PointToScreen(ptSnap)
End Sub
Protected Overrides Sub OnMouseMove(ByVal e As System.Windows.Forms.MouseEventArgs)
MyBase.OnMouseMove(e)
If e.Button = Windows.Forms.MouseButtons.Left Then
Dim x As Integer = CInt(e.X / 20) * 20
Dim y As Integer = CInt(e.Y / 20) * 20
' must be some delta away from original snap point
If (x < ptSnap.X - 15 Or x > ptSnap.X + 15) Or (y < ptSnap.Y - 15 Or y > ptSnap.Y + 15) Then
ptSnap = New Point(x, y)
ptEnd = New Point(x, y)
Me.Invalidate(False)
Windows.Forms.Cursor.Position = Me.PointToScreen(ptSnap)
End If
End If
End Sub
End Class
Public Sub main()
Try
frmSnap = New SnapForm
Application.Run(frmSnap)
Catch ex As Exception
MessageBox.Show(ex.Message, strApplicationTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
frmSnap.Dispose()
End Try
End Sub
End Module
``` | Don't modify the cursor position. You don't need to.
Instead, *draw* as if it was snapped to the grid. When the user clicks somewhere, just draw the line from the nearest grid points.
For instance, if the user clicks on (197,198), but you know that the nearest point actually is (200,200), just draw a line to (200,200) instead of (197,198).
And please, don't mess with the *actual* cursor position.
---
I don't know if there's some way to hide the mouse cursor. If there is, you can hide it and draw it yourself, *without modifying the real position*. | Snap to grid mouse locking up | [
"",
"c#",
"grid",
"mouse",
"cursor-position",
"onmousemove",
""
] |
I'm using Django and Python 2.6, and I want to grow my application using a MySQL backend. Problem is that there isn't a win32 package for MySQLdb on Python 2.6.
Now I'm no hacker, but I thought I might compile it myself using MSVC++9 Express. But I run into a problem that the compiler quickly can't find `config_win.h`, which I assume is a header file for MySQL so that the MySQLdb package can know what calls it can make into MySQL.
Am I right? And if so, where do I get the header files for MySQL? | I think that the header files are shipped with MySQL, just make sure you check the appropriate options when installing (I think that sources and headers are under "developer components" in the installation dialog). | Thanks all! I found that I hadn't installed the developer components in MySQL. Once that was done the problem was solved and I easily compiled the MySQLdb for Python 2.6.
I've made the package available at [my site](http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe). | Problem compiling MySQLdb for Python 2.6 on Win32 | [
"",
"python",
"mysql",
"winapi",
""
] |
I am currently working on a web application that uses PHP and MySQL, but I do not have shell access to the server (working on that problem already...). Currently, I have source control with subversion on my local computer and I have a database on the local computer that I make all changes to. Then, once I've tested all the updates on my local computer I deploy the site manually. I use filezilla to upload the updated files and then dump my local database and import it on the deployment server.
Obviously, my current solution is not anywhere near ideal. For one major thing, I need a way to avoid copying my .svn files... Does anyone know what the best solution for this particular setup would be? I've looked into Capistrano a bit and Ant, but both of those look like it would be a problem that I do not have shell access... | You can do a subversion export (rather than checkout) to different directory from your working copy, then it will remove all the .svn stuff for you | I'm using [Weex](http://weex.sourceforge.net/) to synchronize a server via FTP. Weex is basically a non-interactive FTP client that automatically uploads and deletes files/directories on the remote server. It can be configured to not upload certain paths (like SVN directories), as well as to keep certain remote paths (like Log directories).
Unfortunately I have no solution at hand to synchronize MySQL databases as well...
Maybe you could log your database changes in "SQL patch scripts" (or use complete dumps), upload those with Weex and call a remote PHP script that executes the SQL patches afterwards. | What is a good solution for deploying a PHP/MySQL site via FTP? | [
"",
"php",
"mysql",
"deployment",
""
] |
Thanks to a library upgrade (easymock 2.2 -> 2.4), we're having tests that have started locking up. I'd like to have a time out on individual tests, all of them. The idea is to identify the locked up tests - we're currently guessing - and fix them.
Is this possible, preferably on a suite-wide level? We have 400 tests, doing this each method or even each class will be time consuming. | The [suite tag](http://code.google.com/p/testng/source/browse/trunk/src/main/org/testng/xml/XmlSuite.java) can have the time-out attribute. This time-out will be used as default for all test methods.
This default time-out can than be overridden on a per test method basis. | If the Suite level turns out to be the wrong approach (i.e. "too wide a net", because you end up marking too much methods with a timeout limit), you need to define a custom [IAnnotationTransformer](http://testng.org/doc/documentation-main.html#annotationtransformers) which, for each illegible function, will give you the opportunity to modify a @Test annotation (with, for instance the [setTimout() method](http://code.google.com/p/testng/source/browse/trunk/src/main/org/testng/annotations/ITestAnnotation.java)).
(`setTimout(0)` cancels a timeout directive) | Timing out tests in TestNG | [
"",
"java",
"multithreading",
"testng",
""
] |
I have a large number of 2D points and I want to quickly get those that lie in a certain rectangle.
Let's say a '.' is any point and 'X' is a point I want to find inside a rectangle which has 'T' as TopLeft and 'B' as BottomRight points:
```
. . . . . .
. T-----+ .
. | X X | .
. +-----B .
. . . . . .
```
I have tried a std::set with a sort functor which sorts the TopLeft point at the beginning and the BottomRight at the end of the set. When sorting by X value first, this would result in the following points being found.
```
. . . . . .
. T-----+ .
X | X X | X
. +-----B .
. . . . . .
```
This means I would have to check each found point, whether it really is inside the rectangle. Not really good.
What would be a better way to do this?
My language is C++ (Windows) and I have the STL as well as boost available.
### Update
Having read the answers so far, I noticed that I haven't accounted for all parameters of my problem: There is not one fixed rectangle.
Rectangles can be set by the user at runtime. This means sorting the set of points promises to be more efficient than a linear search through all points as suggested by Artelius before this update.
I will still give it a try, though! I don't expect the user to set a rectangle *very* frequent. So regarding the implementation effort it might show up to be a good solution for me. | You could store the points in a spatial index using quad or r-trees. Then given the rectangle you could find all the nodes of the tree that overlap it, you would then have to compare each point in this subset to see if it falls in the rectangle.
In essence, the spatial tree helps you prune the search space.
You might be able to use a simpler solution, such as partitioning the points in ranges. Say where x is from 0,10 as one range, 11,20 as another. Any solution that lets you prune the search space will help. | Please see [this question](https://stackoverflow.com/questions/132319/storing-objects-for-locating-by-xy-coordinates#132393).
[The Stony Brook Algorithm Repository](http://www.cs.sunysb.edu/~algorith/files/kd-trees.shtml) has some implementations of KDTrees in C++,
though they are not part of STL nor Boost. | Store 2D points for quick retrieval of those inside a rectangle | [
"",
"c++",
"stl",
"boost",
"spatial",
"point",
""
] |
I have the following regex expression to match html links:
```
<a\s*href=['|"](http:\/\/(.*?)\S['|"]>
```
it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?
**EDIT:** This would make it grab only up to the quotes instead of everything after the < a href btw | I don't think your regex is doing what you want.
```
<a\s*href=['|"](http:\/\/(.*?)\S['|"]>
```
This captures anything non-greedily from http:// up to the first non-space character before a quote, single quote, or pipe. For that matter, I'm not sure how it parses, as it doesn't seem to have enough close parens.
If you are trying to capture the href, you might try something like this:
```
<a .*?+href=['"](http:\/\/.*?)['"].*?>
```
This uses the .\*? (non-greedy match anything) to allow for other attributes (target, title, etc.). It matches an href that begins and ends with either a single or double quote (it does not distinguish, and allows the href to open with one and close with the other). | \S matches any character that is not a whitespace character, just like [^\s]
Written like that, you can easily exclude quotes: [^\s"']
Note that you'll likely have to give the .\*? in your regex the same treatment. The dot matches any character that is not a newline, just like [^\r\n]
Again, written like that, you can easily exclude quotes: [^\r\n'"] | excluding characters in \S regex match | [
"",
"python",
"html",
"regex",
""
] |
I'm already familiar with the standard Java package naming convention of using a domain name to create a unique package name (i.e. package `com.stackoverflow.widgets`). However, I've never seen any recommendations for how to choose package names for personal projects. I assume because this is because this is really a matter of personal taste.
So, how do you choose package names for personal projects that will never make it into production (you might be experimenting with a new framework in your spare time). Assuming you don't have a personal website whose domain you can use to create your package structure, what do (or would) you do? Do you have a logical system in place for generating new package names for hobby projects, or do you just use simple throw-away package names like `mypackage`?
Since I'm just curious to see what different people's thoughts are on this, I've made this a community wiki.
For me personally, I've never given it much thought, but I wanted to play around with [Wicket](http://wicket.apache.org/) tonight and it occurred to me that I don't have a clear idea of how I want to organize my hobby projects. A separate, distinct package naming convention for hobby projects (in my mind, at least) would serve as a good way to keep personal and work-related code clearly separate from each other.
I was thinking of a simple hierarchal naming convention, to keep the source for my personal projects in a single root folder:
* Use `myprojects` as the root folder
* Append the project name
* Add any additional subpackage names
So, my Wicket project would be in the package `myprojects.learningwicket` and unit tests would be in the package `myprojects.learningwicket.tests` (for example). | If you're just doing personal projects where nobody else will use the code, then you can make up a package name that you like. Don't make up something that starts with `com.` or `net.` or other top-level domain though, because that would imply that you own the domain name (ie. using `com.john` as your package name just because your name happens to be John is not a good idea).
If you're going to give the code to anybody else, you should use a globally unique package name, which according to Java conventions means you should register and use a domain name. | I just use my initials: fg.nameofproject.etc
It reduces typing.
It can be prefixed at any time with sf.net or com. or org. or com.google..
As the project is personal treat it special just like your freshly pressed personalized gift shirt - it will feel good. | What package naming convention do you use for personal/hobby projects in Java? | [
"",
"java",
"naming-conventions",
""
] |
I'm trying to upload an image to my site through a form, however it's much more efficient to (rather than bog down the database) just store the location of the image in the database.
I'm having trouble with my form and really don't know where to go:
```
<?=form_open('bro/submit_new');?>
//other form data
Image: <input type="file" name="image" size="20" /> <br>
<input type="submit" value="Submit" />
</form>
```
Now the form itself works fine, the problem is that it's trying to store the image into the database field 'image' (which is type TEXT). What's the easiest way to tell it to just store the file, and give the file location to store in the 'image' field? (I tell it where to upload the file via the controller).
Thanks
Edit: controller code (for this part):
```
function submit_new(){
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->db->insert('post', $_POST);
redirect('bro');
}
``` | CodeIgniter's file uploading class will do this for you. The [entry in their user guide](http://codeigniter.com/user_guide/libraries/file_uploading.html) explains as well as I could, so I'm going to point you there.
Essentially you'd just need to modify the controller that they have there to include a bit where you put the file URL in the database, which you can accomplish easily by using $this->upload->data() and extracting [full\_path] from the resulting array, and then sending it to a model which handles the database input. | use form\_open\_multipart() not form\_open() | CodeIgniter - Uploading an Image through a form, store the location of the image in database | [
"",
"php",
"mysql",
"file",
"codeigniter",
"upload",
""
] |
Ok, I'm not great in mysql, but I know an index would help me out here, however I've done some plugging and can't find one to help...
Anyone got any ideas?
```
explain
select `users_usr`.`id_usr` AS `id_usr`,
`users_usr`.`firstname_usr` AS `firstname_usr`,
`users_usr`.`lastname_usr` AS `lastname_usr`,`users_usr`.`social_usr` AS `social_usr`,`users_usr`.`address1_usr` AS `address1_usr`,
`users_usr`.`address2_usr` AS `address2_usr`,`users_usr`.`city_usr` AS `city_usr`,`users_usr`.`state_usr` AS `state_usr`,`users_usr`.`zip_usr` AS `zip_usr`,
`users_usr`.`email_usr` AS `email_usr`,`credit_acc`.`given_credit_acc` AS `given_credit_acc`,`credit_acc`.`credit_used_acc` AS `credit_used_acc`,
`credit_acc`.`date_established_acc` AS `date_established_acc`,`credit_acc`.`type_acc` AS `type_acc`,`credit_acc`.`bureau_status_acc` AS `bureau_status_acc`,
sum((`credit_balance`.`debit_acc` - `credit_balance`.`credit_acc`)) AS `balance`
from (((`users_usr`
left join `credit_acc` on((`users_usr`.`id_usr` = `credit_acc`.`uid_usr`)))
left join `cfc_cfc` on((`credit_acc`.`id_cfc` = `cfc_cfc`.`id_cfc`)))
join `credit_acc` `credit_balance` on((`credit_balance`.`credit_used_acc` = `credit_acc`.`id_acc`)))
where ((`credit_acc`.`type_acc` = _latin1'init')
and (`credit_acc`.`status_acc` = _latin1'active')
and (`credit_acc`.`linetype_acc` = _latin1'personal'))
group by `credit_balance`.`credit_used_acc` order by `users_usr`.`id_usr`
```
Gives me
```
id select_type table type possible_keys key key_len ref rows Extra
------ ----------- -------------- ------ ----------------------------------- --------------- ------- --------------------------------- ------ -------------------------------
1 SIMPLE credit_balance index credit_used_acc,cash_report_index credit_used_acc 40 (NULL) 14959 Using temporary; Using filesort
1 SIMPLE credit_acc eq_ref PRIMARY,type_acc,type_acc_2,uid_usr PRIMARY 8 cc.credit_balance.credit_used_acc 1 Using where
1 SIMPLE cfc_cfc eq_ref PRIMARY PRIMARY 4 cc.credit_acc.id_cfc 1 Using index
1 SIMPLE users_usr eq_ref PRIMARY,id_usr PRIMARY 4 cc.credit_acc.uid_usr 1
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment
---------- ---------- ----------------- ------------ ----------------------- --------- ----------- -------- ------ ------ ---------- -------
credit_acc 0 PRIMARY 1 id_acc A 14016 (NULL) (NULL) BTREE
credit_acc 1 type_acc 1 type_acc A 11 (NULL) (NULL) YES BTREE
credit_acc 1 type_acc 2 date_acc A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 type_acc 3 affiliate_aff A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 type_acc_2 1 type_acc A 11 (NULL) (NULL) YES BTREE
credit_acc 1 type_acc_2 2 date_acc A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 type_acc_2 3 complete_acc A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 type_acc_2 4 commission_refunded_acc A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 credit_used_acc 1 credit_used_acc A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 credit_used_acc 2 id_acc A 14016 (NULL) (NULL) BTREE
credit_acc 1 credit_used_acc 3 type_acc A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 uid_usr 1 uid_usr A 7008 (NULL) (NULL) YES BTREE
credit_acc 1 cash_report_index 1 credit_used_acc A 7008 (NULL) (NULL) YES BTREE
credit_acc 1 cash_report_index 2 type_acc A 14016 (NULL) (NULL) YES BTREE
credit_acc 1 cash_report_index 3 date_established_acc A 14016 (NULL) (NULL) YES BTREE
``` | Your EXPLAIN output shows that you already have indexes that *might* be useful, but the query engine has decided not to use them.
<http://dev.mysql.com/doc/refman/5.0/en/using-explain.html> says:
> **Using temporary**
>
> To resolve the query, MySQL needs to
> create a temporary table to hold the
> result. This typically happens if the
> query contains GROUP BY and ORDER BY
> clauses that list columns differently.
Your query includes:
```
GROUP BY `credit_balance`.`credit_used_acc`
ORDER BY `users_usr`.`id_usr`
```
You name different columns in these two clauses, so this means the query requires a temporary table and sorts its results on disk. Disk I/O is the arch-enemy of SQL performance. This is probably more detrimental to performance than you can make up for by applying an index.
So I'd suggest try removing the `ORDER BY` clause and see if it gets rid of the "using temporary" comment.
**edit** Okay, I've done some more tests and looked more closely at your table defs.
I think you have a lot of indexes that are redundant, and not applicable to this current query. It could be the indexes are useful to some other query, or they may just be leftovers from your experiments.
One observation is that your join to `cfc_cfc` is unnecessary but I see from your comment that you've taken it out. It doesn't seem to fix the EXPLAIN report though.
Another observation is that your `LEFT JOIN` is unnecessary; it could be an `INNER JOIN` because you have conditions in the `WHERE` clause for those columns anyway. There's no purpose for it being an outer join, and outer joins tend to be slower.
Indexes may be useful for columns you use in join conditions, or in row restrictions, or in GROUP BY or ORDER BY clauses. MySQL cannot use more than one index per table in a given query, so it makes sense to define compound indexes. But you should define the index over columns that are used in the query. If you only use columns 2 and 3 of a three-column index (i.e. not the first column in the index) then the index is ineffective.
Of course there are indexes created implicitly for all primary key and foreign key constraints, but here's the only extra index I created:
```
KEY columns_used_in_query (uid_usr, type_acc, status_acc, linetype_acc),
```
It shouldn't matter to the optimization plan if you put your conditions in the `WHERE` clause or the join condition, as long as they aren't part of the conditions for an outer join. But I do notice that all other things being equal, the optimizer seems to choose an index based on which one you define first!
I still haven't eliminated the temp table & filesort comment in the EXPLAIN report, but I think these changes will speed up the query. | Retract some of that, and start over.
Here is my interpretation of your query.
```
uu.select uu.id_usr,
uu.firstname_usr,
uu.lastname_usr,
uu.social_usr,
uu.address1_usr,
uu.address2_usr,
uu.city_usr,
uu.state_usr,
uu.zip_usr,
uu.email_usr,
ca.given_credit_acc,
ca.credit_used_acc,
ca.date_established_acc,
ca.type_acc,
ca.bureau_status_acc,
sum(cb.debit_acc - cb.credit_acc) AS `balance`
from users_usr AS uu
left join credit_acc AS ca on uu.id_usr = ca.uid_usr
join credit_acc AS cb on ca.credit_used_acc = ca.id_acc
where ca.type_acc = 'init'
and ca.status_acc = 'active'
and ca.linetype_acc = 'personal'
group by cb.credit_used_acc
order by uu.id_usr
``` | help with an index | [
"",
"sql",
"mysql",
""
] |
Why does this code:
```
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
};
int main(void)
{
B *b = new B(5);
delete b;
}
```
Result in these errors:
```
main.cpp: In function ‘int main()’:
main.cpp:13: error: no matching function for call to ‘B::B(int)’
main.cpp:8: note: candidates are: B::B()
main.cpp:8: note: B::B(const B&)
```
Shouldn't B inherit A's constructor?
(this is using gcc) | If your compiler supports C++11 standard, there is a constructor inheritance using `using` (pun intended). For more see [Wikipedia C++11 article](http://en.wikipedia.org/wiki/C%2B%2B11#Object_construction_improvement). You write:
```
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
```
This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.
Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.
---
For templated base classes, refer to this example:
```
using std::vector;
template<class T>
class my_vector : public vector<T> {
public:
using vector<T>::vector; ///Takes all vector's constructors
/* */
};
``` | Constructors are not inherited. They are called implicitly or explicitly by the child constructor.
The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.
```
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
public:
explicit B(int x) : A(x) { }
};
```
**UPDATE**: In C++11, constructors can be inherited. See Suma's answer for details. | Inheriting constructors | [
"",
"c++",
"inheritance",
"gcc",
"constructor",
""
] |
What is the C++ equivalent to `GetObject` in [JavaScript](http://en.wikipedia.org/wiki/JavaScript) and [VBScript](http://en.wikipedia.org/wiki/VBScript)?
The closest match I found to my question is:
<http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html>
However the sample use an unexisting interface and asking for the `IUnknown` returns null. Did someone have an example that works? | I figured out the issue. The object I wanted to access was
`winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv`
I mistakenly took \\ for an escapement. In C++ the correct query is :
`::CoGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\default:StdRegProv", NULL, IID_IUnknown, (void**)&pUnk);`
Thank you :) | The article you linked to is correct. You may be providing the wrong interface ID, or the display name could be wrong. You should check the return value from the `CoGetObject` call. | What is the C++ equivalent to GetObject in JavaScript and VBScript? | [
"",
"c++",
"winapi",
"com",
"vbscript",
"wsh",
""
] |
How do you tell if caps lock is on using JavaScript?
One caveat though: I did google it and the best solution I could find was to attach an `onkeypress` event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lock must be on. This feels really dirty and just... *wasteful* - surely there's a better way than this? | You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)
NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.
OLD VERSION: <https://jsbin.com/mahenes/edit?js,output>
Also, here is a modified version (can someone test on mac and confirm)
NEW VERSION: <https://jsbin.com/xiconuv/edit?js,output>
**NEW VERSION:**
```
function isCapslock(e) {
const IS_MAC = /Mac/.test(navigator.platform);
const charCode = e.charCode;
const shiftKey = e.shiftKey;
if (charCode >= 97 && charCode <= 122) {
capsLock = shiftKey;
} else if (charCode >= 65 && charCode <= 90
&& !(shiftKey && IS_MAC)) {
capsLock = !shiftKey;
}
return capsLock;
}
```
**OLD VERSION:**
```
function isCapslock(e) {
e = (e) ? e : window.event;
var charCode = false;
if (e.which) {
charCode = e.which;
} else if (e.keyCode) {
charCode = e.keyCode;
}
var shifton = false;
if (e.shiftKey) {
shifton = e.shiftKey;
} else if (e.modifiers) {
shifton = !!(e.modifiers & 4);
}
if (charCode >= 97 && charCode <= 122 && shifton) {
return true;
}
if (charCode >= 65 && charCode <= 90 && !shifton) {
return true;
}
return false;
}
```
For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...
uppercase A-Z or 'Ä', 'Ö', 'Ü',
lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'
The above keys are just sample representation. | You can use a `KeyboardEvent` to detect numerous keys including the caps lock on most recent browsers.
The [`getModifierState` function](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState) will provide the state for:
* Alt
* AltGraph
* CapsLock
* Control
* Fn (Android)
* Meta
* NumLock
* OS (Windows & Linux)
* ScrollLock
* Shift
[This demo](http://jsfiddle.net/Mottie/a6nhqvv0/) works in all major browsers including mobile ([caniuse](http://caniuse.com/#search=getModifierState)).
```
passwordField.addEventListener( 'keydown', function( event ) {
var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
console.log( caps ); // true when you press the keyboard CapsLock key
});
``` | How do you tell if caps lock is on using JavaScript? | [
"",
"javascript",
"keyboard",
"capslock",
""
] |
How are the java API thread priorities (1-10) gets translated to the OS level priorities since most OS don't have thread priority levels (in terms of number) which match this.
So keeping in mind , can there be a scenario when two or more threads with different priorities eventually get the same priority at OS level.
Please clarify, if I there is some correction in my understanding. | Indeed, some priority levels can map to the same "native" priority level. Here's the list (based on the Hotspot code in OpenJDK 6):
## Solaris
* 1 ⇒ 0
* 2 ⇒ 32
* 3 ⇒ 64
* 4 ⇒ 96
* 5 – 10 ⇒ 127
Of note is that on Solaris, you can't raise the thread priority above normal, only lower it: the priority value for 5 is the same as any of the higher values.
## Linux
* 1 – 10 ⇒ 4 – -5 (`nice` values)
Of note is that on Linux, different thread priorities in Java do map to distinct priority values at native level.
## Windows
* 1 – 2 ⇒ `THREAD_PRIORITY_LOWEST`
* 3 – 4 ⇒ `THREAD_PRIORITY_BELOW_NORMAL`
* 5 – 6 ⇒ `THREAD_PRIORITY_NORMAL`
* 7 – 8 ⇒ `THREAD_PRIORITY_ABOVE_NORMAL`
* 9 – 10 ⇒ `THREAD_PRIORITY_HIGHEST` | Your understanding is correct - Java thread priorities do not map cleanly to OS thread priorities.
As a result, if your algorithm relies in any way on the details of thread priority mapping, then it is broken, since it will vary according to so many variables. Upgrading your JRE or applying a patch/service pack to your OS could break it, for example - and of course just running on a different OS will have consequences too.
Except in very unusual cases, using only two priorities will be sufficient - Normal and Low. Most work will be done in a Normal thread. Low priority should be reserved for threads that must not be allowed to starve the threads of Normal priority, instead just gobbling up and processor power not otherwise used.
While you can get more fine-grained than this if you choose, you need to be aware that any greater detail will likely be lost on the target platform. | How are Java Thread priorities translated to an OS thread priority? | [
"",
"java",
"multithreading",
"operating-system",
""
] |
I'm porting a relatively simple console program written for Unix to the Windows platform ([Visual C++ 8.0](http://en.wikipedia.org/wiki/Visual_C++#32-bit_versions)). All the source files include "unistd.h", which doesn't exist. Removing it, I get complaints about missing prototypes for 'srandom', 'random', and 'getopt'.
I know I can replace the random functions, and I'm pretty sure I can find/hack-up a getopt implementation.
But I'm sure others have run into the same challenge.
My question is: is there a port of "unistd.h" to Windows? At least one containing those functions which do have a native Windows implementation - I don't need pipes or forking.
**EDIT**:
I know I can create my very own "unistd.h" which contains replacements for the things I need - especially in this case, since it is a limited set. But since it seems like a common problem, I was wondering if someone had done the work already for a bigger subset of the functionality.
Switching to a different compiler or environment isn't possible at work - I'm stuck with Visual Studio. | Since we can't find a version on the Internet, let's start one here.
Most ports to Windows probably only need a subset of the complete Unix file.
Here's a starting point. Please add definitions as needed.
```
#ifndef _UNISTD_H
#define _UNISTD_H 1
/* This is intended as a drop-in replacement for unistd.h on Windows.
* Please add functionality as needed.
* https://stackoverflow.com/a/826027/1202830
*/
#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */
#define srandom srand
#define random rand
/* Values for the second argument to access.
These may be OR'd together. */
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
//#define X_OK 1 /* execute permission - unsupported in windows*/
#define F_OK 0 /* Test for existence. */
#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */
#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#endif /* unistd.h */
``` | Try including the `io.h` file. It seems to be the Visual Studio's equivalent of `unistd.h`. | Is there a replacement for unistd.h for Windows (Visual C)? | [
"",
"c++",
"c",
"windows",
"portability",
"unistd.h",
""
] |
What is the best tool for Java for aspect-oriented programming?
The requirements for a tool are of course IDE support, expressiveness and proper documentation. | JBossAOP and AspectJ are two commonly used, mature frameworks for AOP. Another popular choice is Spring AOP, but it lacks some of the features of the other two.
Both JBossAOP and AspectJ have similar features, one big difference being that AspectJ relies on extensions to the Java language, whereas JBoss AOP does not.
If your AOP requirements are fairly simple, it's also worth considering a byte-code manipulation library, such as [ASM](http://asm.objectweb.org/). I've used ASM to implement simple 'around-advice' (ie, code that is injected before and after method invocations), and it proved to be a more lightweight alternative to JBossAOP. ASM is cleanly-designed and well-documented. | I would say AspectJ. The IDE part, as far as I know, is lacking, but documentation and expressiveness is among the best of the AOP frameworks I have seen. | Aspect-oriented programming in Java | [
"",
"java",
"aop",
""
] |
I have some products that belongs to the some category.
Each category can have different properties.
For example,
* category *cars* has properties *color*,
power, ...
* category *pets* have properties *weight*, *age*, ...
Number of categories is about 10-15.
Number of properties in each category is 3-15.
Number of products is very big.
Main requirement for this app is very good search. We will select category, and enter criteria for each property in this category.
Have to design database for this scenario. (SQL Server 2005) | The classic design approach would be (the star denotes the primary key column):
```
Product
ProductId*
CategoryId: FK to Category.CategroyId
Name
Category
CategoryId*
Name
Property
PropertyId*
Name
Type
CategoryProperty
CategoryId*: FK to Category.CategoryId
PropertyId*: FK to Property.PropertyId
ProductProperty
ProductId*: FK to Product.ProductId
PropertyId*: FK to Property.PropertyId
ValueAsString
```
If you can live with the fact that every property value would go to the DB as a string and type conversion info is stored in the Property table, this layout would be enough.
The query would go something like this:
```
SELECT
Product.ProductId,
Product.Name AS ProductName,
Category.CategoryId,
Category.Name AS CategoryName,
Property.PropertyId,
Property.Name AS PropertyName,
Property.Type AS PropertyType,
ProductProperty.ValueAsString
FROM
Product
INNER JOIN Category ON Category.CategoryId = Product.CategoryId
INENR JOIN CategoryProperty ON CategoryProperty.CategoryId = Category.CategoryId
INNER JOIN Property ON Property.PropertyId = CategoryProperty.PropertyId
INNER JOIN ProductProperty ON ProductProperty.PropertyId = Property.PropertyId
AND ProductProperty.ProductId = Product.ProductId
WHERE
Product.ProductId = 1
```
The more WHERE conditions you supply (conjunctively, e.g. using AND), the faster the query will be. If you have properly indexed your tables, that is.
As it is, the solution is not ideal for a full text indexing situation. An additional table that stores all the text associated with a ProductId in a more denormalized way could help here. This table would need updating through triggers that listen for changes in the ProductProperty table. | If the user of the application *has* to select a category before they can search, I would separate your products into different database tables by category. This solution is also indicated by the fact that the categories themselves have so little in common. Breaking it down by category will also make each search much faster, since time won't be wasted searching through cars when your user is looking for a pet.
Once you have the products split up in to categories, it should be easy to create the tables using the common properties of the products in each category. The user interface of your application should be dynamic (I'm thinking of a web form), in that the properties the user can choose from should change when the user selects a category.
Please note that if you have products that you want listed in multiple categories, this solution will result in duplicate data in your tables. There is a trade-off between speed and normalization when designing a database. If you *don't* have products that fit in multiple categories, then I think this will be the fastest solution (in terms of search speed). | What is best practice for this problem (different properties for different categories)? | [
"",
"sql",
"sql-server",
"database",
"database-design",
"entity-attribute-value",
""
] |
This is a somewhat bizarre question. My objectives are to understand the language design decision and to identify the possibilities of reflection in C++.
1. Why C++ language committee did not go towards implementing reflection in the language? Is reflection too difficult in a language that does not run on a virtual machine (like java)?
2. If one were to implement reflection for C++, what will be the challenges?
I guess the uses of reflection are well-known: editors can be more easily written, program code will be smaller, mocks can be generated for unit tests and so on. But it would be great if you could comment on uses of reflection too. | There are several problems with reflection in C++.
* It's a lot of work to add, and the C++ committee is fairly conservative, and don't spend time on radical new features unless they're sure it'll pay off. (A suggestion for adding a module system similar to .NET assemblies has been made, and while I think there's general consensus that it'd be nice to have, it's not their top priority at the moment, and has been pushed back until well after C++0x. The motivation for this feature is to get rid of the `#include` system, but it would also enable at least some metadata).
* You don't pay for what you don't
use. That's one of the must basic
design philosophies underlying C++.
Why should my code carry around
metadata if I may never need it?
Moreover, the addition of metadata
may inhibit the compiler from
optimizing. Why should I pay that
cost in my code if I may never need
that metadata?
* Which leads us to another big point:
C++ makes *very* few guarantees
about the compiled code. The
compiler is allowed to do pretty
much anything it likes, as long as
the resulting functionality is what
is expected. For example, your
classes aren't required to actually
*be there*. The compiler can optimize them away, inline
everything they do, and it
frequently does just that, because
even simple template code tends to
create quite a few template
instantiations. The C++ standard
library *relies* on this aggressive
optimization. Functors are only
performant if the overhead of
instantiating and destructing the
object can be optimized away.
`operator[]` on a vector is only comparable to raw
array indexing in performance
because the entire operator can be
inlined and thus removed entirely
from the compiled code. C# and Java
make a lot of guarantees about the
output of the compiler. If I define
a class in C#, then that class *will
exist* in the resulting assembly.
Even if I never use it. Even if all
calls to its member functions could
be inlined. The class has to be
there, so that reflection can find
it. Part of this is alleviated by C#
compiling to bytecode, which means
that the JIT compiler *can* remove
class definitions and inline
functions if it likes, even if the
initial C# compiler can't. In C++,
you only have one compiler, and it
has to output efficient code. If you
were allowed to inspect the metadata
of a C++ executable, you'd expect to
see every class it defined, which
means that the compiler would have
to preserve all the defined classes,
even if they're not necessary.
* And then there are templates.
Templates in C++ are nothing like
generics in other languages. Every
template instantiation creates a
*new* type. `std::vector<int>` is a completely separate class from
`std::vector<float>`. That adds up to
a lot of different types in a entire
program. What should our reflection
see? The *template* `std::vector`? But
how can it, since that's a
source-code construct, which has no
meaning at runtime? It'd have to see
the separate classes
`std::vector<int>` and
`std::vector<float>`. And
`std::vector<int>::iterator` and
`std::vector<float>::iterator`, same
for `const_iterator` and so on. And
once you step into template
metaprogramming, you quickly end up
instantiating hundreds of templates,
all of which get inlined and removed
again by the compiler. They have no
meaning, except as part of a
compile-time metaprogram. Should all
these hundreds of classes be visible
to reflection? They'd have to,
because otherwise our reflection
would be useless, if it doesn't even guarantee that the classes I defined will actually *be there*. And a side problem is that the template class doesn't exist until it is instantiated. Imagine a program which uses `std::vector<int>`. Should our reflection system be able to see `std::vector<int>::iterator`? On one hand, you'd certainly expect so. It's an important class, and it's defined in terms of `std::vector<int>`, which *does* exist in the metadata. On the other hand, if the program never actually *uses* this iterator class template, its type will never have been instantiated, and so the compiler won't have generated the class in the first place. And it's too late to create it at runtime, since it requires access to the source code.
* And finally, reflection isn't quite
as vital in C++ as it is in C#. The
reason is again, template
metaprogramming. It can't solve
everything, but for many cases where
you'd otherwise resort to
reflection, it's possible to write a
metaprogram which does the same
thing at compile-time.
`boost::type_traits` is a simple
example. You want to know about type
`T`? Check its `type_traits`. In C#,
you'd have to fish around after its
type using reflection. Reflection
would still be useful for some
things (the main use I can see,
which metaprogramming can't easily
replace, is for autogenerated
serialization code), but it would
carry some significant costs for
C++, and it's just not necessary as often as it is in other languages.
*Edit:*
In response to comments:
cdleary:
Yes, debug symbols do something similar, in that they store metadata about the types used in the executable. But they also suffer from the problems I described. If you've ever tried debugging a release build, you'll know what I mean. There are large logical gaps where you created a class in the source code, which has gotten inlined away in the final code. If you were to use reflection for anything useful, you'd need it to be more reliable and consistent. As it is, types would be vanishing and disappearing almost every time you compile. You change a tiny little detail, and the compiler decides to change which types get inlined and which ones don't, as a response. How do you extract anything useful from that, when you're not even guaranteed that the most relevant types will be represented in your metadata? The type you were looking for may have been there in the last build, but now it's gone. And tomorrow, someone will check in a small innocent change to a small innocent function, which makes the type just big enough that it won't get completely inlined, so it'll be back again. That's still useful for debug symbols, but not much more than that. I'd hate trying to generate serialization code for a class under those terms.
Evan Teran: Of course these issues *could* be resolved. But that falls back to my point #1. It'd take a lot of work, and the C++ committee has plenty of things they feel is more important. Is the benefit of getting some limited reflection (and it would be limited) in C++ really big enough to justify focusing on that at the expense of other features? Is there really a huge benefit in adding features the core language which can already (mostly) be done through libraries and preprocessors like QT's? Perhaps, but the need is a lot less urgent than if such libraries didn't exist.
For your specific suggestions though, I believe disallowing it on templates would make it completely useless. You'd be unable to use reflection on the standard library, for example. What kind of reflection wouldn't let you see a `std::vector`? Templates are a *huge* part of C++. A feature that doesn't work on templates is basically useless.
But you're right, some form of reflection could be implemented. But it'd be a major change in the language. As it is now, types are exclusively a compile-time construct. They exist for the benefit of the compiler, and nothing else. Once the code has been compiled, there *are* no classes. If you stretch yourself, you could argue that functions still exist, but really, all there is is a bunch of jump assembler instructions, and a lot of stack push/pop's. There's not much to go on, when adding such metadata.
But like I said, there is a proposal for changes to the compilation model, adding self-contained modules, storing metadata for select types, allowing other modules to reference them without having to mess with `#include`s. That's a good start, and to be honest, I'm surprised the standard committee didn't just throw the proposal out for being too big a change. So perhaps in 5-10 years? :) | Reflection requires some metadata about types to be stored somewhere that can be queried. Since C++ compiles to native machine code and undergoes heavy changes due to optimization, high level view of the application is pretty much lost in the process of compilation, consequently, it won't be possible to query them at run time. Java and .NET use a very high level representation in the binary code for virtual machines making this level of reflection possible. In some C++ implementations, however, there is something called Run Time Type Information (RTTI) which can be considered a stripped down version of reflection. | Why does C++ not have reflection? | [
"",
"c++",
"reflection",
""
] |
I was reading up about NTVDM.exe as I build a quick test console app and it crashed on a friends machine complaining about this EXE.
As I understand it all DOS cmd windows (C# console apps included) run as 16bit not 32bit.
Is this true? Does this mean all my works console app back office apps are running as 16bit rather than making the most of the 32bit available?
What about Windows services? As I believe we wrote it as a console app then made it run as a windows service?
Thanks | Any .NET app that is compiled for x86 will be 32-bit
C# console apps aren't running in "real" dos - they run in a 32-bit or 64-bit environment - depending on your OS and .NET framework. | > As I understand it all DOS cmd windows
> (C# console apps included) run as
> 16bit not 32bit.
>
> Is this true?
No, not at all.
You can run DOS applications under Windows, and they are 16-bit, but the fact that they look a bit console-like is pretty much just coincidence.
There are no 16-bit .NET applications, and whether an application is console mode or not makes no difference to whether it's 16 or 32 bit. | C# console applications all 16bit? | [
"",
"c#",
"console-application",
"16-bit",
"ntvdm.exe",
""
] |
I want to create an array with a message.
```
$myArray = array('my message');
```
But using this code, `myArray` will get overwritten if it already existed.
If I use `array_push`, it has to already exist.
```
$myArray = array(); // <-- has to be declared first.
array_push($myArray, 'my message');
```
Otherwise, it will bink.
Is there a way to make the second example above work, without first clearing `$myArray = array();`? | Check if the array exists first, and if it doesn't, create it...then add the element, knowing that the array will surely be defined before hand :
```
if (!isset($myArray)) {
$myArray = array();
}
array_push($myArray, 'my message');
``` | Here:
```
$myArray[] = 'my message';
```
$myArray have to be an array or not set. If it holds a value which is a string, integer or object that doesn't implement arrayaccess, it will fail. | php: pushing to an array that may or may not exist | [
"",
"php",
"arrays",
"declaration",
"push",
""
] |
I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance | Here's a concrete example of what *does* work, so you can compare your own situation.
Take this code and put it anywhere, in a file called `MainClass.java`. (I've assumed a directory called `src` later. Normally you'd arrange the source to match the package, of course.)
```
package archiveFolder;
public class MainClass
{
public static void main(String[] args)
{
System.out.println("I'm MainClass");
}
}
```
Then run each of these commands:
```
# Compile the source
javac -d . src/MainClass.java
# Build the jar file
jar cf archive.jar archiveFolder
# Remove the unpackaged binary, to prove it's not being used
rm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows
# Execute the class
java -cp archive.jar achiveFolder.MainClass
```
The result:
```
I'm MainClass
```
How are you building your jar file? Is the code in the appropriate package? | Does theMainClassName class have the following package line at the top:
```
package archiveFolder
```
You need the class file to be in the same directory structure as the declared package. So if you had something like:
```
org/jc/tests/TestClass.class
```
its source file would have to look like this:
```
package org.jc.tests;
public class TestClass {
public static void main(String[] args) {
System.out.printf("This is a test class!\n");
}
}
```
Then you could use the following to create the jar file and run it from the command line (assuming the current directory is at the top level, just above org):
```
$ jar -cf testJar.jar org/jc/tests/*.class
$ java -cp testJar.jar org.jc.tests.TestClass
``` | Java Command Line Trouble with Reading a Class from a Jar Archive | [
"",
"java",
"command-line",
""
] |
What is the shortest chunk of C++ you can come up with to safely clean up a `std::vector` or `std::list` of pointers? (assuming you have to call delete on the pointers?)
```
list<Foo*> foo_list;
```
I'd rather not use Boost or wrap my pointers with smart pointers. | Since we are throwing down the gauntlet here... "Shortest chunk of C++"
```
static bool deleteAll( Foo * theElement ) { delete theElement; return true; }
foo_list . remove_if ( deleteAll );
```
I think we can trust the folks who came up with STL to have efficient algorithms. Why reinvent the wheel? | For `std::list<T*>` use:
```
while(!foo.empty()) delete foo.front(), foo.pop_front();
```
For `std::vector<T*>` use:
```
while(!bar.empty()) delete bar.back(), bar.pop_back();
```
Not sure why i took `front` instead of `back` for `std::list` above. I guess it's the feeling that it's faster. But actually both are constant time :). Anyway wrap it into a function and have fun:
```
template<typename Container>
void delete_them(Container& c) { while(!c.empty()) delete c.back(), c.pop_back(); }
``` | Cleaning up an STL list/vector of pointers | [
"",
"c++",
"list",
"vector",
"stl",
""
] |
I type
```
ArrayList memberNames = new ArrayList() { "Jim", "John", "George" };
```
and Visual Studio tells me "ArrayList" cannot be found so I have to manually go to the top of the file and type
```
using System.Collections;
```
Is there a way to get Visual Studio to do this automatically?
In FlashDevelop, for instance, you press CTRL-SHIFT-1 and it automatically generates these missing references, a nice feature. | SHIFT-ALT-F10 Will activate the Smart Tag on the class, which will give you the options "using System.Collections", and "System.Collections.ArrayList". It's typically two keystrokes to add a using.
Edit: Seems I had a mangled keyboard profile. Updated the key combo to the default. Thanks to Alan for pointing it out. | `Alt` + `Shift` + `F10` brings up a pop-up menu with "using System.Collections", and "System.Collections.ArrayList".
If you want to find a keyboard shortcut, choose Tools: Options and navigate down to Environment: Keyboard. However, it can be a challenge to figure out what they've called the thing you're looking for. (The one you asked about is obviously View.ShowSmartTag, right?)
**Update:** From comments and other posts, I just learned that `Ctrl` + `.` also brings up the same menu. I guess not all the keyboard shortcuts appear in the keyboard options dialog. | Contextual code generation in Visual C# 2008? | [
"",
"c#",
".net",
"visual-studio",
""
] |
Does anyone know whether the iPhone supports or will soon support the [W3C Geolocation specification](http://dev.w3.org/geo/api/spec-source.html)?
I'm looking to build an app for mobile users, but rather than spend the time developing apps for every different platform (iPhone, Android, etc...), I'd much prefer to create a web app that makes use of the W3C Standard. | This code worked for me -- on the iPhone web browser **Safari** *and* as an added bonus it even worked with **FireFox 3.5** on my laptop! The Geolocation API Specification is part of the W3 Consortium’s standards **But be warned: it hasn’t been finalized as yet.**
[](https://i.stack.imgur.com/iHatw.jpg)
(source: [bemoko.com](http://blog.bemoko.com/wp-content/uploads/2009/06/iphone-geo-300-1-150x150.jpg)) [](https://i.stack.imgur.com/94v2x.jpg)
(source: [bemoko.com](http://blog.bemoko.com/wp-content/uploads/2009/06/iphone-geo-300-2-150x150.jpg))
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Geolocation API Demo</title>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport"/>
<script>
function successHandler(location) {
var message = document.getElementById("message"), html = [];
html.push("<img width='256' height='256' src='http://maps.google.com/maps/api/staticmap?center=", location.coords.latitude, ",", location.coords.longitude, "&markers=size:small|color:blue|", location.coords.latitude, ",", location.coords.longitude, "&zoom=14&size=256x256&sensor=false' />");
html.push("<p>Longitude: ", location.coords.longitude, "</p>");
html.push("<p>Latitude: ", location.coords.latitude, "</p>");
html.push("<p>Accuracy: ", location.coords.accuracy, " meters</p>");
message.innerHTML = html.join("");
}
function errorHandler(error) {
alert('Attempt to get location failed: ' + error.message);
}
navigator.geolocation.getCurrentPosition(successHandler, errorHandler);
</script>
</head>
<body>
<div id="message">Location unknown</div>
</body>
</html>
``` | You can now get location from Javascript APIs in the safari browser following the iPhone 3.0 release - we've created a working example @ <http://blog.bemoko.com/2009/06/17/iphone-30-geolocation-javascript-api/> | Geolocation API on the iPhone | [
"",
"javascript",
"iphone",
"geolocation",
"gps",
""
] |
I am building an ObjectQuery like this:
```
string query = "select value obj from Entities.Class as obj " +
"where obj.Property = @Value";
ObjectQuery<Class> oQuery = new ObjectQuery<Class>(query, EntityContext.Instance);
oQuery.Parameters.Add(new ObjectParameter("Value", someVariable));
```
I can now assign this object as a DataSource for a control, or iterate with a foreach loop or even force a materialization to a List, however, I can I count the number of objects that will be returned, without forcing a materialization?
Do I need to create a companion query that will execute a count() or is there a function that will do that for me somewhere?
Thank you. | `ObjectQuery<T>` implements `IQueryable<T>`, so can't you simply use the extension method:
```
int count = oQuery.Count();
```
What happens if you execute this? I would have expected the overall query to just do a Count()... (not that I've done much EF...). | The ObjectQuery<T> class implements the IEnumerable<T> interface, which supports the Count() method.
What do you get from this?
```
int count = oQuery.Count();
``` | How to count how many objects will be returned by an ObjectQuery<T>? | [
"",
"c#",
"entity-framework",
""
] |
I have snippets of Html stored in a table. *Not entire pages, no tags or the like, just basic formatting.*
I would like to be able to display that Html as text only, *no formatting*, on a given page (actually just the first 30 - 50 characters but that's the easy bit).
How do I place the "text" within that Html into a string as straight text?
So this piece of code.
```
<b>Hello World.</b><br/><p><i>Is there anyone out there?</i><p>
```
Becomes:
Hello World. Is there anyone out there? | If you are talking about tag stripping, it is relatively straight forward if you don't have to worry about things like `<script>` tags. If all you need to do is display the text without the tags you can accomplish that with a regular expression:
```
<[^>]*>
```
If you do have to worry about `<script>` tags and the like then you'll need something a bit more powerful then regular expressions because you need to track state, omething more like a Context Free Grammar (CFG). Althought you might be able to accomplish it with 'Left To Right' or non-greedy matching.
If you can use regular expressions there are many web pages out there with good info:
* <http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx>
* <http://www.google.com/search?hl=en&q=html+tag+stripping+&btnG=Search>
If you need the more complex behaviour of a CFG I would suggest using a third party tool, unfortunately I don't know of a good one to recommend. | The MIT licensed [HtmlAgilityPack](https://github.com/linezero/HtmlAgilityPack) has [in one of its samples](https://github.com/ceee/ReadSharp/blob/master/ReadSharp/HtmlUtilities.cs) a method that converts from HTML to plain text.
```
var plainText = HtmlUtilities.ConvertToPlainText(string html);
```
Feed it an HTML string like
```
<b>hello, <i>world!</i></b>
```
And you'll get a plain text result like:
```
hello world!
``` | How do you convert Html to plain text? | [
"",
"c#",
"asp.net",
"html",
""
] |
What's the difference between [`java.lang.ref.WeakReference`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/WeakReference.html) and [`java.lang.ref.SoftReference`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/SoftReference.html) ? | From [Understanding Weak References](https://web.archive.org/web/20061130103858/http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html), by Ethan Nicholas:
> **Weak references**
>
> A *weak reference*, simply put, is a
> reference that isn't strong enough to
> force an object to remain in memory.
> Weak references allow you to leverage
> the garbage collector's ability to
> determine reachability for you, so you
> don't have to do it yourself. You
> create a weak reference like this:
>
> ```
> WeakReference weakWidget = new WeakReference(widget);
> ```
>
> and then
> elsewhere in the code you can use
> `weakWidget.get()` to get the actual
> `Widget` object. Of course the weak
> reference isn't strong enough to
> prevent garbage collection, so you may
> find (if there are no strong
> references to the widget) that
> `weakWidget.get()` suddenly starts
> returning `null`.
>
> ...
>
> **Soft references**
>
> A *soft reference* is exactly like a
> weak reference, except that it is less
> eager to throw away the object to
> which it refers. An object which is
> only weakly reachable (the strongest
> references to it are `WeakReferences`)
> will be discarded at the next garbage
> collection cycle, but an object which
> is softly reachable will generally
> stick around for a while.
>
> `SoftReferences` aren't *required* to
> behave any differently than
> `WeakReferences`, but in practice softly
> reachable objects are generally
> retained as long as memory is in
> plentiful supply. This makes them an
> excellent foundation for a cache, such
> as the image cache described above,
> since you can let the garbage
> collector worry about both how
> reachable the objects are (a strongly
> reachable object will *never* be removed
> from the cache) and how badly it needs
> the memory they are consuming.
And Peter Kessler added in a comment:
> The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all. | Weak references are collected eagerly. If GC finds that an object is
weakly reachable (reachable only through weak references), it'll clear the
weak references to that object immediately. As such, they're good for
keeping a reference to an object for which your program also keeps
(strongly referenced) "associated information" somewere, like cached
reflection information about a class, or a wrapper for an object, etc.
Anything that makes no sense to keep after the object it is associated
with is GC-ed. When the weak reference gets cleared, it gets enqueued in a
reference queue that your code polls somewhere, and it discards the
associated objects as well. That is, you keep extra information about an
object, but that information is not needed once the object it refers to
goes away. Actually, in certain situations you can even subclass
WeakReference and keep the associated extra information about the object
in the fields of the WeakReference subclass. Another typical use of
WeakReference is in conjunction with Maps for keeping canonical instances.
SoftReferences on the other hand are good for caching external, recreatable resources
as the GC typically delays clearing them. It is guaranteed though that all
SoftReferences will get cleared before OutOfMemoryError is thrown, so they
theoretically can't cause an OOME[\*].
Typical use case example is keeping a parsed form of a contents from a
file. You'd implement a system where you'd load a file, parse it, and keep
a SoftReference to the root object of the parsed representation. Next time
you need the file, you'll try to retrieve it through the SoftReference. If
you can retrieve it, you spared yourself another load/parse, and if the GC
cleared it in the meantime, you reload it. That way, you utilize free
memory for performance optimization, but don't risk an OOME.
Now for the [\*]. Keeping a SoftReference can't cause an OOME in itself. If
on the other hand you mistakenly use SoftReference for a task a WeakReference is meant
to be used (namely, you keep information associated with an Object somehow
strongly referenced, and discard it when the Reference object gets
cleared), you can run into OOME as your code that polls the ReferenceQueue
and discards the associated objects might happen to not run in a timely
fashion.
So, the decision depends on usage
- if you're caching information that is expensive to construct, but
nonetheless reconstructible from other data, use soft references
- if you're keeping a reference to a canonical instance of some data, or
you want to have a reference to an object without "owning" it (thus
preventing it from being GC'd), use a weak reference. | What's the difference between SoftReference and WeakReference in Java? | [
"",
"java",
"reference",
"weak-references",
"soft-references",
""
] |
This should be easy for many of you, but for me it's just another bit of rust needing to be chipped away as I get back into basic Java coding. Using bloody associative arrays for so long in other languages have turned me nice and spoiled. :P
My problem is simple: I'm storing a set of objects, each containing a string and a number, in a list. I would like each object inserted into this list to be sorted alphabetically by its string. I would also like to be able to retrieve objects from the list by their string as well. I would like to do this as formally and/or efficiently as possible.
Is there something already available in the Java standard libraries for this? | there is a great [writeup on java collections](http://java.sun.com/docs/books/tutorial/collections/index.html) which covers most of your needs.
short advice concerning this: use a [TreeMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html)(Comparator c) with a custom Comparator.
key ist the string, value is the composite object with string and number | That sound like a [SortedMap](http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedMap.html). With the String as the key and the Number as the value. | Data Structure Brushup (Java) | [
"",
"java",
"data-structures",
""
] |
I want to test some PHP on my local machine running Windows XP Professional. I'm familiar with coding PHP for upload, but not with running a web server.
**What is the easiest way to set up a test environment?** Step-by-step instructions would be great if you can give them.
(I see WAMP recommended in [this thread](https://stackoverflow.com/questions/125022/install-php-on-xp-iis-51) - thoughts?)
## Update - a year later
A little self-promotion: after using XAMPP for a long time, I began to want things it didn't include. (Support for PDO was a big one - every time I tried to enable pdo and mysqli simultaneously, something crashed.) I eventually worked through the process of installing Apache, PHP, MySQL, and PHPMyAdmin individually, and [documented the process with screen shots on my blog.](http://sleeplessgeek.blogspot.com/2010/01/setting-up-apache-php-mysql-phpmyadmin.html)
Some of the configuration that I was able to do this way could have been done in XAMPP, but it was only because I had to set things up myself that I discovered new things (like being able to serve files out of c:\whatever instead of c:\program files\apache\htdocs).
On the whole, I'm happier with having installed these items separately. But XAMPP was a good (and easy) package to start with, and served me well while I used it. | [](https://i.stack.imgur.com/8PuYL.gif)
(source: [apachefriends.org](http://www.apachefriends.org/images/1240.jpg))
[Xampp](http://www.apachefriends.org/en/xampp.html) is the simplest. You can setup everything in a Step by Step and if you require further configuration (Virtual Server, extension) you have the normal php.ini and other file in the directory that you can edit yourself.
Here is the [Step By Step installation](http://www.apachefriends.org/en/xampp-windows.html#522) for Windows. | [XAMPP from ApacheFriends](http://www.apachefriends.org/en/xampp.html) is pretty simple to set up and use.
**note** the site appears to be down as at 15:02 UTC on 3rd Dec 2008
**note again** and it is back! | What's the easiest way to test PHP in Windows XP Professional? | [
"",
"php",
"testing",
"windows-xp",
""
] |
What is the proper way to load a `ListBox` in C# .NET 2.0 Winforms?
I thought I could just bind it to a `DataTable`. No such luck.
I thought I could bind it with a `Dictionary`. No luck.
Do I have to write an class called `KeyValuePair`, and then use `List<KeyValuePair>` just to be able to load this thing with objects? Maybe I am missing something obvious. I want my display text and values to be different values. | Simple code example. Say you have a `Person` class with 3 properties. `FirstName`, `LastName` and `Age`. Say you want to bind your listbox to a collection of `Person` objects. You want the display to show the first name, but the value to be the age. Here's how you would do it:
```
List<Person> people = new List<Person>();
people.Add(new Person { Age = 25, FirstName = "Alex", LastName = "Johnson" });
people.Add(new Person { Age = 23, FirstName = "Jack", LastName = "Jones" });
people.Add(new Person { Age = 35, FirstName = "Mike", LastName = "Williams" });
people.Add(new Person { Age = 25, FirstName = "Gill", LastName = "JAckson" });
this.listBox1.DataSource = people;
this.listBox1.DisplayMember = "FirstName";
this.listBox1.ValueMember = "Age";
```
The trick is the `DisplayMember`, and the `ValueMember`. | You can [bind a DataTable](http://www.codeproject.com/KB/database/scomlistcontrolbinding.aspx) directly...
```
listbox.ValueMember = "your_id_field";
listbox.DisplayMember = "your_display_field";
listbox.DataSource = dataTable;
``` | What is the proper way to load up a ListBox? | [
"",
"c#",
".net",
"winforms",
""
] |
In SQL server 2005 this query
```
select len(cast('the quick brown fox jumped over the lazy dog' as varchar))
```
returns 30 as length while the supplied string has more characters. This seems to be the default. Why 30, and not 32 or any other power of 2?
**[EDIT]** I am aware that I should always specifiy the length when casting to varchar but this was a quick let's-check-something query. Questions remains, why 30? | Why don't you specify the varchar length? ie:
```
SELECT CAST('the quick brown fox jumped over the lazy dog' AS VARCHAR(45))
```
As far as why 30, that's the default length in SQL Server for that type.
From [char and varchar (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms176089.aspx):
> When n is not specified in a data definition or variable declaration statement, the default length is 1. *When n is not specified when using the CAST and CONVERT functions, the default length is 30.* | On your question as to why 30 and not 32 or any other power of 2, the storage size is n + 2 bytes for varchar(n), which makes the byte storage size 32 for a string of length 30. Might be that this is what they looked at?
Then just a point of clarity on some of the comments: The default length for an unspecified length varchar field is n=1. The default string length that CAST or CONVERT returns for a conversion of this data type is 30.
Very cool question! | Why is 30 the default length for VARCHAR when using CAST? | [
"",
"sql",
"sql-server",
"casting",
""
] |
I've been looking for some guidelines on how to layout PHP code. I've found some good references, such as the following:
<http://www.dagbladet.no/development/phpcodingstandard/>
and [this question](https://stackoverflow.com/questions/5214/whats-a-good-standard-code-layout-for-a-php-application) on SO.
However, none of that quite gets to what I'm specifically wondering about, which is the integration of HTML and PHP. For example:
1. Is it OK to have a PHP file that starts out with HTML tags and only has PHP inserted where needed? Or should you just have one section of PHP code that contains everything?
2. If you have a chunk of PHP code in the middle of which is a set of `echo`'s that just output a fixed bit of HTML, is it better to break out of PHP and just put in the HTML directly?
3. Should functions all be defined in dedicated PHP files, or is it OK to define a bunch of functions at the top of a file and call them later on in that same file?
There are probably other questions I'd like to ask, but really I'm looking for someone to point me at some kind of resource online that offers guidance on the general idea of how HTML and PHP should be combined together. | There's really not a single, common standard for these things. Most languages are more restrictive than PHP in this sense.
In the later years, a lot of so-called frameworks have emerged, and amongst other things they define a set of rules for everything from naming over where to place files and to which style your code should follow. There are several frameworks around, so you can't really pick one and call it the standard. However, most frameworks have a subset of commonality. For example, most follows some variant of the [PEAR Coding Standards](http://pear.php.net/manual/en/standards.php). | Combining programming code and output data (including HTML) is IMHO a very bad idea. Most of the PHP gurus I know use a template engine such as [Smarty](http://www.smarty.net/) to help keep the two things separate. | PHP coding standards | [
"",
"php",
"coding-style",
""
] |
I have a legacy MS Access 2007 table that contains 52 fields (1 field for each week of the year) representing historical sales data (plus one field for the year actually). I would like to convert this database into a more conventional Time/Value listing.
Does anyone knows how to do that without writing queries with 52+ explicit parameters?
(if a solution exists under MS SQL Server 2005, I can also export/import the table) | [Using PIVOT and UNPIVOT](http://msdn.microsoft.com/en-us/library/ms177410%28SQL.90%29.aspx).
> `UNPIVOT` performs almost the reverse
> operation of `PIVOT`, by rotating
> columns into rows. Suppose the table
> produced in the previous example is
> stored in the database as `pvt`, and you
> want to rotate the column identifiers
> `Emp1`, `Emp2`, `Emp3`, `Emp4`, and `Emp5` into
> row values that correspond to a
> particular vendor. This means that you
> must identify two additional columns.
> The column that will contain the
> column values that you are rotating
> (`Emp1`, `Emp2`,...) will be called
> `Employee`, and the column that will
> hold the values that currently reside
> under the columns being rotated will
> be called Orders. These columns
> correspond to the *pivot\_column* and
> *value\_column*, respectively, in the
> Transact-SQL definition. Here is the
> query.
```
--Create the table and insert values as portrayed in the previous example.
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
Emp3 int, Emp4 int, Emp5 int)
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4)
INSERT INTO pvt VALUES (2,4,1,5,5,5)
INSERT INTO pvt VALUES (3,4,3,5,4,4)
INSERT INTO pvt VALUES (4,4,2,5,5,4)
INSERT INTO pvt VALUES (5,5,1,5,5,5)
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt
GO
```
> Here is a partial result set.
```
VendorID Employee Orders
1 Emp1 4
1 Emp2 3
1 Emp3 5
1 Emp4 4
1 Emp5 4
2 Emp1 4
2 Emp2 1
2 Emp3 5
2 Emp4 5
2 Emp5 5
...
``` | As mentioned above, UNPIVOT operator, if available, will do this... If this is not available, then std SQL approach is:
Union multiple select statments (One for each week) that alias the specific week's column with the same column name alias
```
Select 1 as week, Week1Val as value from Table
UNION
Select 2 as week, Week2Val as value from Table
UNION
Select 3 as week, Week3Val as value from Table
UNION
...
UNION
Select 52 as week, Week52Val as value from Table
``` | How to convert fields into rows through SQL in MS Access 2007 or MS SQL Server 2005 | [
"",
"sql",
"sql-server",
"ms-access",
"pivot",
""
] |
If I generate an exception on my own, I can include any info into the exception: a number of code line and name of source file. Something like this:
```
throw std::exception("myFile.cpp:255");
```
But what's with unhandled exceptions or with exceptions that were not generated by me? | It seems everyone is trying to improve your code to throw exceptions in your code, and no one is attempting the actual question you asked.
Which is because it can't be done. If the code that's throwing the exception is only presented in binary form (e.g. in a LIB or DLL file), then the line number is gone, and there's no way to connect the object to to a line in the source code. | A better solution is to use a custom class and a macro. :-)
```
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
class my_exception : public std::runtime_error {
std::string msg;
public:
my_exception(const std::string &arg, const char *file, int line) :
std::runtime_error(arg) {
std::ostringstream o;
o << file << ":" << line << ": " << arg;
msg = o.str();
}
~my_exception() throw() {}
const char *what() const throw() {
return msg.c_str();
}
};
#define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__);
void f() {
throw_line("Oh no!");
}
int main() {
try {
f();
}
catch (const std::runtime_error &ex) {
std::cout << ex.what() << std::endl;
}
}
``` | How to know the exact line of code where an exception has been caused? | [
"",
"c++",
"exception",
""
] |
I saw this the other day (scroll *all the way* down to see some of the clever stuff):
> <http://www.mono-project.com/docs/tools+libraries/tools/repl/>
And wondered whether something like this exists for Python.
So, is there a good Python GUI shell that can do stuff like that C# shell can do?
Edit: Here are links to screenshots from the article, showing what I'm interested in doing.
An example of the type of things I'm interested:
<http://www.mono-project.com/archived/images/7/75/GSharpPlot.png>
They are able to add hooks to produce GUI elements like the plot, or even do silly things like:
<http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png>
I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython).
Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want. | One project I'm aware of that provides similar features (inline plotting, customisable rendering) is [Reinteract](http://fishsoup.net/software/reinteract/). Another (though possibly a bit heavyweight for general usage) is [SAGE](http://www.sagemath.org/) which provides functionality for web-based [notebooks](http://www.sagenb.org).
These aren't quite shells - they're designed more as a mathematical notebook (so for instance, you can modify an earlier result and have the change propogate to later calculations), but they're close to what you're looking for, and could probably be modified to be used as such. | Have you looked at [ipython](http://ipython.scipy.org/moin/)? It's not quite as "gui". No smileys, sorry. ;-) It is a pretty good interactive shell for python though.
edit: I see you revised your question to emphasize the importance **GUI**. In that case, IPython wouldn't be a good match.
Might as well save you another blind alley: I went looking at DrPython hoping it would be similar to PLT's DrScheme, which looks comparable to example you've linked too. Unfortunately DrPython isn't all that much like DrScheme. | Is there a good Python GUI shell? | [
"",
"python",
"shell",
"user-interface",
""
] |
I need to find whether the user clicking the browser back button or Refresh button.
I need to redirect the page to Error page when he clicks the back or refresh button. How to do this.
I need to do this in javascript for my ASP.net page | First of all, giving error messages if users use Back or have to refresh a page for whatever reason, is a really bad idea. Instead, you should transparently deal with that. Think about a page not coming up fully because of problems on the transportation level - the only option the user has is to reload or go back.
To answer your question, you have to keep track of the user's navigation yourself, that means on the server side. Forget about java-script here. If the user visits a website, you can store that information in a Session associated to the user (there are several methods of keeping these unique sessions, and I won't go into details here).
If you store in your internal structures which pages the user visited lately, it is easy to determine a page being visited twice, or navigation going into the "wrong" direction.
You could easily generalize this (and making the whole thing more robust, for example against users jumping wildly between urls, or going back more than one step at once) by building a graph of "allowed" navigation and traversing it while the user is visiting websites.
The correct behaviour then if the user is doing a "wrong" navigation (like stepping back, reloading == visiting twice) is to get him back on track. Not to give an error message he can't escape! As he is not allowed to reload or go back, he has no options left. | You can't. The browser doesn't send it's own ui events to the server. All you get are http requests and one looks pretty much like another. Maybe the clicked the back button or maybe they just retyped the last url in. Tell us what problems it's causing and we can help you adapt your project to work with the http protocol a little better. | How to find whether the user clicks browser back button or Refresh button | [
"",
"javascript",
"asp.net",
"browser",
"back-button",
""
] |
I would like to replace ">" with ">" and "<" with "<" but only when they occur outside "<pre>" and "</pre>". Is this possible?
```
$newText = preg_replace('>', '>', $text);
```
I would be using the preg\_replace in PHP as above. | If you want to do this with a regex, the trick is to make your regex match the things you don't want to replace as well as the things you want to replace, and dynamically calculate the replacement depending on what was matched.
```
$new_text = preg_replace_callback('%<|>|<pre>.*?</pre>%si', compute_replacement, $text);
function compute_replacement($groups) {
if ($groups[0] == '<') {
return '<';
} elseif ($groups[1] == '>') {
return '>';
} else {
return $groups[0];
}
}
``` | This isn't really an answer because you asked for a regex, but I just wrote a really dirty function to do it:
```
<?php
$html = ' <pre>hello > <</pre>
> <
<pre></pre>';
function stringReplaceThing($str) {
$offset = 0;
$num = 0;
$preContents = array();
$length = strlen($str);
//copy string so can maintain offsets/positions in the first string after replacements are made
$str2=$str;
//get next position of <pre> tag
while (false !== ($startPos = stripos($str, '<pre>', $offset))) {
//the end of the opening <pre> tag
$startPos += 5;
//try to get closing tag
$endPos = stripos($str, '</pre>', $startPos);
if ($endPos === false) {
die('unclosed pre tag..');
}
$stringWithinPreTags = substr($str, $startPos, $endPos - $startPos);
//replace string within tags with some sort of token
if (strlen($stringWithinPreTags)) {
$token = "!!T{$num}!!";
$str2 = str_replace($stringWithinPreTags, $token, $str2);
$preContents[$token] = $stringWithinPreTags;
$num++;
}
$offset = $endPos + 5;
}
//do the actual replacement
$str2 = str_replace(array('>', '<'), array('>', '<'), $str2);
//put the contents of <pre></pre> blocks back in
$str2 = str_replace(array_keys($preContents), array_values($preContents), $str2);
return $str2;
}
print stringReplaceThing($html);
``` | Regex to replace text only when occurs outside of two strings? | [
"",
"php",
"regex",
""
] |
I have data from a table in a database (string) that contain text and price. I extract the price from the data but my problem is that sometime I can Convert it to float and sometime not.
I have noticed that :
```
Convert.ToSingle(m.Groups[1].Value);
```
It works but not always because sometime the period is the problem (it requires a comma). What can I do? I have try to replace the ".", by "," but sometime on other PC it's a period that it's required! | You have this problem because the conversion check the language of your PC. You will need to do something like :
```
Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture.NumberFormat);
```
This ways, it won't check the language of the PC. You can find more information about [InvariantCulture](http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture.aspx) from MSDN. I have something similar in a project and my conversion works. | Or ask for this specific number format explicitly:
```
System.Globalization.NumberFormatInfo nf
= new System.Globalization.NumberFormatInfo ( )
{
NumberGroupSeparator = "."
};
float f = float.Parse ( "5.34534", nf );
``` | Convert Float that has period instead of comma? | [
"",
"c#",
".net",
".net-2.0",
""
] |
Java 1.5, Linux
I do have a screen which contains different textareas and textfields.
I do have acess to the application frame, but not to the components inside the frame, because i only get an implementation of an interface.
When i try to add german umlauts i see a rectangle in the text component, because the character is not supported.
Which font or which system-propertiy i have to set to support "umlauts" under linux.
On windows the characters are shown correctly. | It sounds like a character encoding problem or font problem... Like using "windows" encoding in a Linux environment. You should check the following:
* Can you write those characters in a normal texteditor in your linux distro?
* Are those characters from input files in your java application or is it from the source, if so what OS did you use to write the source?
* If they are from a source file or resource file, have you checked that the characters is actually readable in the sourcefile in Linux?
* If you open the sourcefile in for instance vim, what encoding does it use? (It usually says in the lower part of the screen just after you opened the file)
If you tell what happens when you do this, we may have a better idea of what is wrong. :)
**UPDATE:**
The reason I wanted you to check this is that I know the so called "windows encoding" can create problems in other OS'es. You say you can write umlauts on the console but not in vi, what do you get instead, squares?
It does't matter that users isn't supposes to view the ini file, if you created the ini files manually in Linux I suppose you were able to write umlauts then. You should find out what character encoding these files and the TCP connection uses. It should be UTF-8, "Western" or "Windows" or "Latin-1" etc. may cause problems.
If everything is UTF-8, readable everywhere except in your application I would start to suspect a missing font issue. | My guess is that the desktop (KDE or Gnome) is configured to use a font which doesn't contain umlauts (kind of strange, today, but it happens). Java usually tries to use the system font as a basis to calculate the "Dialog" font (which is always available even if it is not installed; "Dialog" is a virtual font name which Java uses to say "Default sans-serif font").
* Check which fonts are installed with xlsfonts
* Check whether you can enter the umlauts in the console
* Try a different Java app
* Check $JAVA\_HOME/jre/lib/fonts (IIRC). I think you can find font mappings in there. | TextField "umlauts" are not shown on linux | [
"",
"java",
"linux",
"unix",
"unicode",
"encoding",
""
] |
I have to transform a few hundred images every day in a specific way.
I need the best freeware tool or a piece of C# code that supports batch watermarking, resizing of images and can be automated (old configuration can be reused).
What tool do you suggest? | Dave Winer of [scripting.com](http://scripting.com/) fame has been posting about his success with [ImageMagick](http://www.imagemagick.org/script/index.php). I think its free. | [IrfanView](http://www.irfanview.com/) has pretty decent batch image processing/conversion support. | Batch process images | [
"",
"c#",
"image",
"batch-processing",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.