Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
We are working on an [S60](http://en.wikipedia.org/wiki/S60_%28software_platform%29) version and this platform has a nice Python API..
However, there is nothing official about Python on Android, but since [Jython](http://en.wikipedia.org/wiki/Jython) exists, is there a way to let the snake and the robot work together?... | One way is to use [Kivy](http://kivy.org/):
> Open source Python library for rapid development of applications
> that make use of innovative user interfaces, such as multi-touch apps.
> Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms.
[Kivy Showcase a... | There is also the new [Android Scripting Environment](http://www.talkandroid.com/1225-android-scripting-environment/) (ASE/SL4A) project. It looks awesome, and it has some integration with native Android components.
Note: no longer under "active development", but some forks may be. | Is there a way to run Python on Android? | [
"",
"android",
"python",
"jython",
"ase",
"android-scripting",
""
] |
I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic... | I've had some luck with [the Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/introduction.html) | [Apache Commons Daemon](http://commons.apache.org/daemon/index.html) is a good alternative. It has [Procrun](http://commons.apache.org/daemon/procrun.html) for windows services, and [Jsvc](http://commons.apache.org/daemon/jsvc.html) for unix daemons. It uses less restrictive Apache license, and Apache Tomcat uses it as... | How to create a windows service from java app | [
"",
"java",
"windows-services",
""
] |
I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks. | The following works great for printing with the win32api from C++
```
char szPrinterName[255];
unsigned long lPrinterNameLength;
GetDefaultPrinter( szPrinterName, &lPrinterNameLength );
HDC hPrinterDC;
hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL);
```
In the future instead of googling "unmanaged" tr... | Here is how to get a list of current printers and the default one if there is one set as the default.
Also note: getting zero for the default printer name length is valid if the user has no printers or has not set one as default.
Also being able to handle long printer names should be supported so calling GetDefaultPr... | Default Printer in Unmanaged C++ | [
"",
"c++",
"windows",
"unmanaged",
"default",
"printing",
""
] |
I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | This works without having to use scrot or ImageMagick.
```
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != N... | Just for completeness:
Xlib - But it's somewhat slow when capturing the whole screen:
```
from Xlib import display, X
import Image #PIL
W,H = 200,200
dsp = display.Display()
try:
root = dsp.screen().root
raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
image = Image.fromstring("RGB", (W, H), raw.dat... | Take a screenshot via a Python script on Linux | [
"",
"python",
"linux",
"screenshot",
""
] |
I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions (
* for performance reasons - exceptions are expensive
* for usability reasons - the debugger pops up
* for design reasons - the expected is not exceptional
In other words the code:
```
public static Boolean TryStrToGuid(Str... | **Performance Benchmarks**
```
Catch exception:
10,000 good: 63,668 ticks
10,000 bad: 6,435,609 ticks
Regex Pre-Screen:
10,000 good: 637,633 ticks
10,000 bad: 717,894 ticks
COM Interop CLSIDFromString
10,000 good: 126,120 ticks
10,000 bad: 23,134 ticks
```
**COM Intertop (Fastest) A... | Once .net 4.0 is available you can use [`Guid.TryParse()`](https://msdn.microsoft.com/en-us/library/system.guid.tryparse(v=vs.110).aspx). | Test if string is a guid without throwing exceptions? | [
"",
"c#",
"string",
"parsing",
"guid",
""
] |
I need to update a `combobox` with a new value so it changes the reflected text in it. The cleanest way to do this is after the `combobox`has been initialised and with a message.
So I am trying to craft a `postmessage` to the hwnd that contains the `combobox`.
So if I want to send a message to it, changing the curren... | You want [ComboBox\_SetCurSel](http://msdn.microsoft.com/en-us/library/bb856484(VS.85).aspx):
```
ComboBox_SetCurSel(hWndCombo, n);
```
or if it's an MFC CComboBox control you can probably do:
```
m_combo.SetCurSel(2);
```
I would imagine if you're doing it manually you would also want SendMessage rather than PostM... | A concise version:
```
const int index = 0;
m_comboBox.PostMessage(CBN_SELCHANGE, index);
``` | Programmatically change combobox | [
"",
"c++",
"winapi",
"mfc",
"combobox",
"postmessage",
""
] |
What is the JavaScript to scroll to the top when a button/link/etc. is clicked? | ```
<a href="javascript:scroll(0, 0)">Top</a>
``` | If you had an anchor link at the top of the page, you could do it with anchors too.
```
<a name="top"></a>
<a href='#top">top</a>
```
It'll work in browser's with Javascript disabled, but changes the url. :( It also lets you jump to anywhere the name anchor is set. | Make the web browser scroll to the top? | [
"",
"javascript",
"scroll",
""
] |
I have a datagridview with a DataGridViewComboboxColumn column with 3 values:
"Small", "Medium", "Large"
I get back the users default which in this case is "Medium"
I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or j... | When you get into the datagridview it is probably best to get into databinding. This will take care of all of the selected index stuff you are talking about.
However, if you want to get in there by yourself,
```
DataGridView.Rows[rowindex].Cells[columnindex].Value
```
will let you get and set the value associated to... | ```
DataGridViewComboBoxColumn ColumnPage = new DataGridViewComboBoxColumn();
ColumnPage.DefaultCellStyle.NullValue = "Medium";
``` | Set selected item on a DataGridViewComboboxColumn | [
"",
"c#",
".net",
"winforms",
"datagridview",
""
] |
I installed Visual Studio 2005 ( with SP1 ) and made the default settings as what is required for C++ .
Now i open a solution and run the exe .
Under " Tools " menu item i go and Select " Attach the process " and i attach it to the exe i just ran . I put breakpoints several places in the code ( this breakpoints looks ... | Perhaps it is attaching to "the wrong kind" of code.
In the "Attach to Process" dialog, there is a setting that allows you to select the kind of code you want to debug. Try clicking "Select" button next to "Attach to" text box and checking only ~~"Managed code"~~ the relevant code type.
<http://img204.imageshack.us/i... | Are you in Debug mode? I've had this problem when I was trying to do it in Release mode. It doesn't complain, it just doesn't hit the breakpoints. | " Attach to Process " in Visual Studio 2005 | [
"",
"c++",
"visual-studio-2005",
"visual-c++-2005",
""
] |
I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions.
I want to store the old hover functions before I set new ones so I can restore them whe... | Calling an event `bind` method (such as `hover`) does not delete old event handlers, only adds your new events, so your idea of 'restoring' the old event functions wouldn't work, as it wouldn't delete your events.
You can add your own events, and then remove them without affecting any other events then use Event names... | Not sure if this will work, but you can try this:
```
function setHover(obj, mouseenter, mouseleave) {
obj.data("_mouseenter", mouseenter);
obj.data("_mouseleave", mouseleave);
obj.hover(obj.data("_mouseenter"), obj.data("_mouseleave"));
}
function removeHover(obj) {
obj.unbind("mouseenter", obj.data("_mousee... | How to read bound hover callback functions in jQuery | [
"",
"javascript",
"jquery",
"callback",
""
] |
I'm building an application in C# using WPF. How can I bind to some keys?
Also, how can I bind to the [Windows key](http://en.wikipedia.org/wiki/Windows_key)? | I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, *Save All* that can be triggered from anywhere by `Ctrl` + `Shift` + `S`.)
You find the global `UIElement` of your choice, for example, the top level window which is the parent of al... | This is a full working solution, hope it helps...
Usage:
```
_hotKey = new HotKey(Key.F9, KeyModifier.Shift | KeyModifier.Win, OnHotKeyHandler);
```
...
```
private void OnHotKeyHandler(HotKey hotKey)
{
SystemHelper.SetScreenSaverRunning();
}
```
Class:
```
using System;
using System.Collections.Generic;
usin... | How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5? | [
"",
"c#",
".net",
"wpf",
"windows",
"hotkeys",
""
] |
Is there a function in python to split a word into a list of single letters? e.g:
```
s = "Word to Split"
```
to get
```
wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
``` | ```
>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
``` | The easiest way is probably just to use `list()`, but there is at least one other option as well:
```
s = "Word to Split"
wordlist = list(s) # option 1,
wordlist = [ch for ch in s] # option 2, list comprehension.
```
They should *both* give you what you need:
```
['W','o','r','d',' ','t','o',' ',... | Is there a function in python to split a word into a list? | [
"",
"python",
"function",
"split",
""
] |
I have the following query:
```
select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;
```
What would be the difference if I replaced all calls to `count(column_name)` to `count(*)`?
This question was inspired by [How do I find duplicate values in a table in Oracle?](ht... | `count(*)` counts NULLs and `count(column)` does not
[edit] added this code so that people can run it
```
create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla v... | Another minor difference, between using \* and a specific column, is that in the column case you can add the keyword DISTINCT, and restrict the count to distinct values:
```
select column_a, count(distinct column_b)
from table
group by column_a
having count(distinct column_b) > 1;
``` | In SQL, what's the difference between count(column) and count(*)? | [
"",
"sql",
""
] |
I can create the following and reference it using
```
area[0].states[0]
area[0].cities[0]
var area = [
{
"State" : "Texas",
"Cities" : ['Austin','Dallas','San Antonio']
},
{
"State" :"Arkansas",
"Cities" : ['Little Rock','Texarkana','Hot Springs']
... | If you want to just create it that way to begin with, just say
```
area = {
"Texas": ['Austin','Dallas','San Antonio']
}
```
and so on. If you're asking how to take an existing object and convert it into this, just say
```
states = {}
for(var j=0; j<area.length; j++)
states[ area[0].State ] = area[0].Cities
... | (With help from the answers, I got this to work like I wanted. I fixed the syntax in selected answer, in the below code)
With the following select boxes
```
<select id="states" size="2"></select>
<select id="cities" size="3"></select>
```
and data in this format (either in .js file or received as JSON)
```
var area... | Javascript array with a mix of literals and arrays | [
"",
"javascript",
"jquery",
""
] |
Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own? | `TextInfo.ToTitleCase()` capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include `ToLower()`.
```
string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"
```
If CurrentCulture is u... | ```
CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");
``` | How do I capitalize first letter of first name and last name in C#? | [
"",
"c#",
"string",
"capitalize",
""
] |
How are callbacks written in PHP? | The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a [function pointer](http://en.wikipedia.org/wiki/Function_pointer), referencing a function or class method for future invocation. This has allowed some elements of fun... | With PHP 5.3, you can now do this:
```
function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
```
Finally a nice way to do it. A great addition to PHP, because callbacks are awesome. | How do I implement a callback in PHP? | [
"",
"php",
""
] |
I want to quickly test an ocx. How do I drop that ocx in a console application. I have found some tutorials in CodeProject and but are incomplete. | Sure..it's pretty easy. Here's a fun app I threw together. I'm assuming you have Visual C++.
Save to test.cpp and compile: cl.exe /EHsc test.cpp
To test with your OCX you'll need to either #import the typelib and use it's CLSID (or just hard-code the CLSID) in the CoCreateInstance call. Using #import will also help d... | Isn't an OCX an ActiveX User Control? (something that you put onto a form for the user to interact with)?
The easiest way I know of to test COM/ActiveX stuff is to use excel. (Yes I know it sounds dumb, bear with me)
1. Run Excel, create a new file if it hasn't done this for you
2. Press `Alt+F11` to launch the Visua... | Using an ocx in a console application | [
"",
"c++",
"visual-c++",
"console",
"activex",
""
] |
What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML?
Let's say I have a `Foo` that has an property `Bar[] Bars`. A `Bar` object has a key and a value. By default, this serializes to the following XML:
```
<Foo>
<Bars>
<Bar key="key0" value="value0"/>
... | I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, ... | ISerializable isn't used for xml serialization; its used for binary serialization. You would be better implementing IXmlSerializable.
But I think that the KeyedCollection serializes more like you're thinking. Except you'll never get <key0 ... /> <key1 ... /> since the elements map to classes. | What's the best way to serialize a HashTable for SOAP/XML? | [
"",
"c#",
".net",
"xml",
"serialization",
""
] |
How do you usually go about **separating your codebase and associated unit tests**? I know people who create a separate project for unit tests, which I personally find confusing and difficult to maintain. On the other hand, if you mix up code and its tests in a single project, you end up with binaries related to your u... | I definitely advocate separating your tests out to a separate project. It's the only way to go in my opinion.
Yes, as [Gary](https://stackoverflow.com/users/6369/garry-shutler) says, it also forces you to test behavior through public methods rather than playing about with the innards of your classes | As the others point out, a seperate test project (for each normal project) is a good way to do it. I usually mirror the namespaces and create a test class for each normal class with 'test' appended to the name. This is supported directly in the IDE if you have Visual Studio Team System which can automatically generate ... | C# - Excluding unit tests from the release version of your project | [
"",
"c#",
".net",
"unit-testing",
"assemblies",
"reference",
""
] |
I'd like to add a method `AddDefaultNamespace()` to the String class in Java so that I can type `"myString".AddDefaultNamespace()` instead of `DEFAULTNAMESPACE + "myString"`, to obtain something like `"MyDefaultNameSpace.myString"`. I don't want to add another derived class either (`PrefixedString` for example).
Maybe... | `String` is a final class which means it cannot be extended to work on your own implementation. | Well, actually everyone is being unimaginative. I needed to write my own version of startsWith method because I needed one that was case insensitive.
```
class MyString{
public String str;
public MyString(String str){
this.str = str;
}
// Your methods.
}
```
Then it's quite simple, you make yo... | Can I add new methods to the String class in Java? | [
"",
"java",
"string",
""
] |
In Java, you often see a META-INF folder containing some meta files. What is the purpose of this folder and what can I put there? | Generally speaking, you should not put anything into META-INF yourself. Instead, you should rely upon whatever you use to package up your JAR. This is one of the areas where I think Ant really excels: specifying JAR file manifest attributes. It's very easy to say something like:
```
<jar ...>
<manifest>
<a... | From [the official JAR File Specification](http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html) (link goes to the Java 7 version, but the text hasn't changed since at least v1.3):
> ## The META-INF directory
>
> The following files/directories in the META-INF directory are recognized and interpreted by ... | What's the purpose of META-INF? | [
"",
"java",
"meta-inf",
""
] |
Before I jump headlong into C#...
I've always felt that C, or maybe C++, was best for developing drivers on Windows. I'm not keen on the idea of developing a driver on a .NET machine.
But .NET seems to be the way MS is heading for applications development, and so I'm now wondering:
* Are people are using C# to devel... | You can not make kernel-mode device drivers in C# as the runtime can't be safely loaded into ring0 and operate as expected.
Additionally, C# doesn't create binaries suitable for loading as device drivers, particularly regarding entry points that drivers need to expose. The dependency on the runtime to jump in and anal... | This shall help you in a way: [Windows Driver Kit](http://www.microsoft.com/whdc/devtools/wdk/default.mspx) | C# driver development? | [
"",
"c#",
"kernel",
"drivers",
"device",
""
] |
I am wondering if anyone has any experience using a JQuery plugin that converts a html
```
<select>
<option> Blah </option>
</select>
```
combo box into something (probably a div) where selecting an item acts the same as clicking a link.
I guess you could probably use javascript to handle a selection event (my j... | The simple solution is to use
```
$("#mySelect").change(function() {
document.location = this.value;
});
```
This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option. | I'm not sure where you want to link to when you click the Div, but given something like this perhaps would work:
```
<select id="mySelect">
<option value="1">Option 1</option>
<option value="2">Option 2</options>
</select>
<div id="myDiv"/>
```
and the following JQuery creates a list of `<div>` elements, a goes t... | Linking combo box (JQuery preferrably) | [
"",
"javascript",
"jquery",
"html",
"drop-down-menu",
""
] |
I would like to create an application wide keyboard shortcut for a Java Swing application.
Looping over all components and adding the shortcut on each, has focus related side effects, and seems like a brute force solution.
Anyone has a cleaner solution? | Install a custom KeyEventDispatcher. The KeyboardFocusManager class is also a good place for this functionality.
[KeyEventDispatcher](http://java.sun.com/javase/6/docs/api/java/awt/KeyEventDispatcher.html) | For each window, use `JComponent.registerKeyboardAction` with a condition of `WHEN_IN_FOCUSED_WINDOW`. Alternatively use:
```
JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, command);
JComponent.getActionMap().put(command,action);
```
as described in the [registerKeyboardAction API docs](http://docs.ora... | Application wide keyboard shortcut - Java Swing | [
"",
"java",
"swing",
"shortcut",
"keystroke",
""
] |
I know there's JScript.NET, but it isn't the same as the JavaScript we know from the web.
Does anyone know if there are any JavaScript based platforms/compilers for desktop development? Most specifically Windows desktop development. | Windows 8 allows for Windows Store Apps to be written in HTML5/JavaScript. | There is [XULRunner](http://developer.mozilla.org/en/XULRunner), which let's you build GUI apps like Firefox using JavaScript and XUL. It has a lot of extension to JavaScript though, using XPCOM. They also offer [Prism](http://developer.mozilla.org/en/Prism) which let's you build web apps that work offline, sort of lik... | Can you do Desktop Development using JavaScript? | [
"",
"javascript",
"windows",
"desktop",
"platform",
""
] |
I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them? | More specifically
```
AppDomain domain = AppDomain.CreateDomain("New domain name");
//Do other things to the domain like set the security policy
string pathToDll = @"C:\myDll.dll"; //Full path to dll you want to load
Type t = typeof(TypeIWantToLoad);
TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFr... | If you're targeting 3.5, you can take advantage of the new [managed extensibility framework](http://code.msdn.microsoft.com/mef) to handle all the heavy lifting for you. | Loading DLLs into a separate AppDomain | [
"",
"c#",
".net",
"appdomain",
""
] |
How does gcc implement stack unrolling for C++ exceptions on linux? In particular, how does it know which destructors to call when unrolling a frame (i.e., what kind of information is stored and where is it stored)? | See section 6.2 of the [x86\_64 ABI](http://www.x86-64.org/documentation/abi.pdf). This details the interface but not a lot of the underlying data. This is also independent of C++ and could conceivably be used for other purposes as well.
There are primarily two sections of the ELF binary as emitted by gcc which are of... | There isn't much documentation currently available, however the basic system is that GCC translates try/catch blocks to [function calls](http://gcc.gnu.org/onlinedocs/gccint/Exception-handling-routines.html) and then [links in a library with the needed runtime support](http://codesynthesis.com/~boris/blog/2006/12/10/st... | How does gcc implement stack unrolling for C++ exceptions on linux? | [
"",
"c++",
"exception",
"gcc",
""
] |
I'm using jmockit for unit testing (with TestNG), and I'm having trouble using the Expectations class to mock out a method that takes a primitive type (boolean) as a parameter, using a matcher. Here's some sample code that illustrates the problem.
```
/******************************************************/
import sta... | So the problem appears to be in Expectations.with():
```
protected final <T> T with(Matcher<T> argumentMatcher)
{
argMatchers.add(argumentMatcher);
TypeVariable<?> typeVariable = argumentMatcher.getClass().getTypeParameters()[0];
return (T) Utilities.defaultValueForType(typeVariable.getClass(... | the issue is the combination of Expectation usage and that Matchers does not support primitive type.
The Matchers code rely on Generic which basically does not support primitive type. Typically the usage of Matchers is more for matching value; with the auto-boxing/unboxing feater in Java 5, this is usually not a probl... | Using jmockit expectations with matchers and primitive types | [
"",
"java",
"unit-testing",
"mocking",
"jmockit",
""
] |
Okay so im working on this php image upload system but for some reason internet explorer turns my basepath into the same path, but with double backslashes instead of one; ie:
```
C:\\Documents and Settings\\kasper\\Bureaublad\\24.jpg
```
This needs to become C:\Documents and Settings\kasper\Bureaublad\24.jpg. | Use the [`stripslashes`](http://us.php.net/manual/en/function.stripslashes.php) function.
That should make them all single slashes. | Note that you may be running into PHP's Magic Quotes "feature" where incoming backslashes are turned to `\\`.
See
<https://www.php.net/magic_quotes> | PHP replace double backslashes "\\" to a single backslash "\" | [
"",
"php",
"string",
"replace",
"backslash",
""
] |
When I start Tomcat (6.0.18) from Eclipse (3.4), I receive this message (first in the log):
> WARNING:
> [SetPropertiesRule]{Server/Service/Engine/Host/Context}
> Setting property 'source' to
> 'org.eclipse.jst.jee.server: (project name)'
> did not find a matching property.
Seems this message does not have any severe... | The solution to this problem is very simple. Double click on your tomcat server. It will open the server configuration. Under server options check ‘Publish module contents to separate XML files’ checkbox. Restart your server. This time your page will come without any issues. | From [Eclipse Newsgroup](http://dev.eclipse.org/newslists/news.eclipse.webtools/msg16008.html "Eclipse newsgroup"):
> The warning about the source property
> is new with Tomcat 6.0.16 and may be
> ignored. WTP adds a "source" attribute
> to identify which project in the
> workspace is associated with the
> context. Th... | "SetPropertiesRule" warning message when starting Tomcat from Eclipse | [
"",
"java",
"eclipse",
"tomcat",
"eclipse-3.4",
""
] |
Is there a (cross-platform) way to get a C FILE\* handle from a C++ std::fstream ?
The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE\*. | The short answer is no.
The reason, is because the `std::fstream` is not required to use a `FILE*` as part of its implementation. So even if you manage to extract file descriptor from the `std::fstream` object and manually build a FILE object, then you will have other problems because you will now have two buffered ob... | There isn't a standardized way. I assume this is because the C++ standardization group didn't want to assume that a file handle can be represented as a fd.
Most platforms do seem to provide some non-standard way to do this.
<http://www.ginac.de/~kreckel/fileno/> provides a good writeup of the situation and provides c... | Getting a FILE* from a std::fstream | [
"",
"c++",
"c",
"file",
"file-io",
"fstream",
""
] |
In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.
It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.
Does anyone know of a method for getting the context directory s... | This should give you the real path that you can use to extract / edit files.
[Javadoc Link](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String))
We're doing something similar in a context listener.
```
public class MyServlet extends HttpServlet {
public ... | > *In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying*
You can also access the files in the WebContent by [`ServletContext#getResource()`](http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContext.html#getResource%28java.lang.String%29). So if your JS file ... | Accessing Tomcat Context Path from Servlet | [
"",
"java",
"tomcat",
"servlets",
""
] |
I am re-factoring some code and am wondering about the use of a `lock` in the instance constructor.
```
public class MyClass {
private static Int32 counter = 0;
private Int32 myCount;
public MyClass() {
lock(this) {
counter++;
myCount = counter;
}
}
}
```
Ple... | @ajmastrean
I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process.
i.e.
* Make the constructor private.
* Create a static instance method that returns the type.
* In the static instance method, use the lock keyword before instantiating.
* Instant... | If you are only incrementing a number, there is a special class (Interlocked) for just that...
<http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment.aspx>
> Interlocked.Increment Method
>
> Increments a specified variable and stores the result, as an atomic operation.
```
System.Threading.I... | Instance constructor sets a static member, is it thread safe? | [
"",
"c#",
".net",
"multithreading",
"thread-safety",
""
] |
What is the Java analogue of .NET's XML serialization? | **2008 Answer**
The "Official" Java API for this is now JAXB - Java API for XML Binding. See [Tutorial by Oracle](http://docs.oracle.com/javase/tutorial/jaxb/TOC.html). The reference implementation lives at <http://jaxb.java.net/>
**2018 Update**
Note that [the Java EE and CORBA Modules are deprecated in SE in JDK9 an... | [XStream](http://x-stream.github.io/) is pretty good at serializing object to XML without much configuration and money! (it's under BSD license).
We used it in one of our project to replace the plain old java-serialization and it worked almost out of the box. | XML serialization in Java? | [
"",
"java",
"xml",
"serialization",
""
] |
I've created a forum, and we're implementing an apc and memcache caching solution to save the database some work.
I started implementing the cache layer with keys like "Categories::getAll", and if I had user-specific data, I'd append the keys with stuff like the user ID, so you'd get `"User::getFavoriteThreads|1471"`.... | You might also want to have a look at the cost of storing the cache data, in terms of your effort and CPU cost, against how what the cache will buy you.
If you find that 80% of your forum views are looking at the first page of threads, then you could decide to cache that page only. That would mean both cache reads and... | Just an update:
I decided that Josh's point on data usage was a very good one.
People are unlikely to keep viewing page 50 of a forum.
Based on this model, I decided to cache the 90 latest threads in each forum. In the fetching function I check the limit and offset to see if the specified slice of threads is within ca... | Caching paginated results, purging on update - how to solve? | [
"",
"php",
"caching",
"pagination",
"memcached",
""
] |
How do i represent CRLF using Hex in C#? | Since no one has actually given the answer requested, here it is:
```
"\x0d\x0a"
``` | End-of-Line characters.
For DOS/Windows it's
```
x0d x0a (\r\n)
```
and for \*NIX it's
```
x0a (\n)
```
* dos2unix - Convert `x0d x0a` to `x0a` to make it \*NIX compatible.
* unix2dos - Convert `x0a` to `x0d x0a` to make it DOS/Win compatible. | representing CRLF using Hex in C# | [
"",
"c#",
""
] |
How can I add a column with a default value to an existing table in [SQL Server 2000](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis) / [SQL Server 2005](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005)? | ## Syntax:
```
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES
```
## Example:
```
ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogener... | ```
ALTER TABLE Protocols
ADD ProtocolTypeID int NOT NULL DEFAULT(1)
GO
```
The inclusion of the **DEFAULT** fills the column in **existing** rows with the default value, so the NOT NULL constraint is not violated. | How to add a column with a default value to an existing table in SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"sql-server-2000",
""
] |
Imagine this directory structure:
```
app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
```
I'm coding `mod1`, and I need to import something from `mod2`. How should I do it?
I tried `from ..sub2 import mod2`, but I'm getting an "Attempted relative import in non-pa... | The problem is that you're running the module as '\_\_main\_\_' by passing the mod1.py as an argument to the interpreter.
From [PEP 328](http://www.python.org/dev/peps/pep-0328/):
> Relative imports use a module's \_\_name\_\_ attribute to determine that module's position in the package hierarchy. If the module's nam... | Here is the solution which works for me:
I do the relative imports as `from ..sub2 import mod2`
and then, if I want to run `mod1.py` then I go to the parent directory of `app` and run the module using the python -m switch as `python -m app.sub1.mod1`.
The real reason why this problem occurs with relative imports, is ... | How can I do relative imports in Python? | [
"",
"python",
"python-import",
"python-module",
""
] |
I need to use XmlRpc in C++ on a Windows platform. Despite the fact that my friends assure me that XmlRpc is a "widely available standard technology", there are not many libraries available for it. In fact I only found one library to do this on Windows, (plus another one that claims "you'll have to do a lot of work to ... | I've written my own C++ library. It's available at sourceforge:
[xmlrpcc4win](http://sourceforge.net/projects/xmlrpcc4win/)
The reason I wrote it rather than using Chris Morley's was that:
* The Windows "wininet.lib" library gives you all the functionality for handling Http requests, so I'd rather use that. As a resu... | Until I wrote my own library, (see above) here was my answer:
Currently, the [XmlRpc++ library](http://xmlrpcpp.sourceforge.net/) by Chris Morley is the only public domain/LPGL XmlRpc implementation for C++ on Windows.
There are a couple of C++ implementations for Linux, either of which could be presumably easily por... | Using XmlRpc in C++ and Windows | [
"",
"c++",
"windows",
"ssl",
"xml-rpc",
""
] |
Is there some way to hide the browser toolbar / statusbar etc in current window via javascript? I know I can do it in a popup with `window.open()` but I need to do it this way. Is it possible at all? | As per the previous answer, this isn't possible to my knowledge and is best avoided anyway. Even if a solution can be found, bear in mind that most browsers these days allow the user to prevent Javascript from interfering with their browser settings and window chrome, even when using window.open. So you've got absolute... | I believe this is not possible. And anyway, just don't do it. Your page can do what it wants with the rendering area, but the rest of the browser belongs to the user and websites have no business messing with it. | Hiding toolbar / status bar with javascript in CURRENT browser window? | [
"",
"javascript",
"user-interface",
""
] |
I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependen... | I would suggest doing it in Application\_PreRequestHandlerExecute instead of after an error occurs. Generally, it'd be best not to enter normal processing if you know your database isn't available. I typically use something like below
```
void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
string ... | Drop an html file called "app\_offline.htm" into the root of your virtual directory. Simple as that.
[Scott Guthrie](http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx) on the subject and friendly errors. | Disable (Politely) a website when the sql server is offline | [
"",
"sql",
"asp.net",
"maintenance-mode",
""
] |
I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for.
An example...
```
public class Person
{
string firstName;
string lastName;
public string FirstName
{
get { return firstName... | What you see here is some syntatic sugar provided by the compiler. Under the hood what it really does is something like:
**Person p = new Person( FirstName = "Joe", LastName = "Smith" );**
```
Person _p$1 = new Person();
_p$1.FirstName = "Joe";
_p$1.LastName = "Smith";
Person p = _p$1;
```
So IMHO you are not really... | Object initializers does in no way replace constructors. The constructor defines the contract that you have to adhere to in order to create a instance of a class.
The main motivation for object initializers in the C# language is to support [Anonymous Types](http://msdn.microsoft.com/en-us/library/bb397696.aspx).
```
... | What do you think of using properties as object initializers in C#; | [
"",
"c#",
""
] |
I'd like to encourage our users of our RCP application to send the problem details to our support department. To this end, I've added a "Contact support" widget to our standard error dialogue.
I've managed to use URI headers to send a stacktrace using Java 6's JDIC call: [`Desktop.getDesktop().mail(java.net.URI)`](htt... | You could save a temporary .eml file, and Desktop.getDesktop().open(emlFile)
**Edit:** As you point out, this will unfortunately open outlook express instead of outlook.
However if you have Windows Live Mail installed, it will use that. | If you're using JDK 6 (you really should), the Desktop API is now part of the JRE. See <http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/> for more information. | How do I send an email attachment using the designated client, programmatically from Java | [
"",
"java",
"uri",
"email",
""
] |
Let's say I have this code:
```
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith(md5($_POST[$foo['bar']]);
}
```
I could shorten that down by doing:
```
$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
doSomethingWith($value);
}
```
But is there any pre-set variable that contains the first... | No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.
```
if (($value = md5(..)) == $somemd5) { ... }
```
In general, though, you'll want to avoid embedding assignments into conditional expressions:
* The code is denser and therefore hard... | Since the if is just using the result of an expression, you can't access parts of it.
Just store the results of the functions in a variable, like you wrote in your second snippet. | PHP: return a part of an if () { } | [
"",
"php",
""
] |
For example:
```
int a = 12;
cout << typeof(a) << endl;
```
Expected output:
```
int
``` | C++11 update to a very old question: Print variable type in C++.
The accepted (and good) answer is to use `typeid(a).name()`, where `a` is a variable name.
Now in C++11 we have `decltype(x)`, which can turn an expression into a type. And `decltype()` comes with its own set of very interesting rules. For example `decl... | Try:
```
#include <typeinfo>
// …
std::cout << typeid(a).name() << '\n';
```
You might have to activate RTTI in your compiler options for this to work. Additionally, the output of this depends on the compiler. It might be a raw type name or a name mangling symbol or anything in between. | Is it possible to print a variable's type in standard C++? | [
"",
"c++",
"variables",
"c++11",
"typeof",
""
] |
I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple `VARCHAR(10)` field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.
Is th... | ```
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
``` | ```
select replace(ltrim(replace(ColumnName,'0',' ')),' ','0')
``` | Removing leading zeroes from a field in a SQL statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Looking for C# class which wraps calls to do the following:
read and write a key value
read & write a key entry
enumerate the entries in a key. This is important. For example, need to list all entries in:
HKEY\_LOCAL\_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources
(I scanned through some codeproject.com registry c... | [Microsoft.Win32.Registry](http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx) | Use the standard C# / .NET registry classes and enumerate over the result of GetSubKeyNames().
See [here](http://www.java2s.com/Code/CSharp/Development-Class/EnumeratingRegistryKeys.htm) for an example. | Looking for C# registry class | [
"",
"c#",
"registry",
""
] |
I'm working on a `PHP` application that links into the `Protx VSP Direct payment gateway`. To handle "3D Secure" requests from the credit card processing company, I need to forward the user to a different website, mimicking a form that has been posted. I'm trying to use the `cURL` libraries, but seem to have hit a prob... | The 3D Secure API doesn't allow you to do the request in the background. You need to forward the user to the 3D secure site. Use javascript to automatically submit your form. Here's what our provider suggests:
```
<html>
<head>
<title>Processing your request...</title>
</head>
<body OnLoad="OnL... | I think you are a bit confused as to what curl does. It does exactly what you explained, it acts sort of like a browser and makes the call to the site and returns the content of that post. I don't know of any way you can actually redirect the browser server side and represent a post. I would actually create a Javascrip... | PHP :: Emulate <form method="post">, forwarding user to page | [
"",
"php",
"curl",
"protx",
""
] |
```
public static void main(String[] args) {
List<? extends Object> mylist = new ArrayList<Object>();
mylist.add("Java"); // compile error
}
```
The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessin... | Let's say you have an interface and two classes:
```
interface IResult {}
class AResult implements IResult {}
class BResult implements IResult {}
```
Then you have classes that return a list as a result:
```
interface ITest<T extends IResult> {
List<T> getResult();
}
class ATest implements ITest<AResult> {
// l... | In his book great 'Effective Java' (Second Edition) Joshua Bloch explains what he calls the producer/consumer principle for using generics. Josh's explaination should tell you why your example does not work (compile) ...
Chapter 5 (Generics) is freely available here: <http://java.sun.com/docs/books/effective/generics.... | Java Collections using wildcard | [
"",
"java",
""
] |
I have a string that contains the representation of a date. It looks like:
**Thu Nov 30 19:00:00 EST 2006**
I'm trying to create a Date object using SimpleDateFormat and have 2 problems.
1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor
2.) I can't find a way I could... | The format to pass to SimpleDateFormat could be looked up at <http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html>
```
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")
```
As for your second question, I don't know of any Java library to figure out a date format and parse it without knowing in ad... | The POJava date parser org.pojava.datetime.DateTime is an immutable, and robust parser that supports multiple languages, time zones, and formats.
Best of all, the parser is heuristic and does not require a pre-existing “format” to work. You just pass it a date/date-time text string and get out a java.util.Date! | How Would You Programmatically Create a Pattern from a Date that is Stored in a String? | [
"",
"java",
"date",
""
] |
I have the following code:
```
SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;
```
Is there any difference to the results or performance if I replace the COUNT(\*) with COUNT('x')?
(This question is related to a [previous one](https://stackoverflow.com/questions/59294/in-sql-whats-the-d... | To say that `SELECT COUNT(*) vs COUNT(1)` results in your DBMS returning "columns" is pure bunk. That *may* have been the case long, long ago but any self-respecting query optimizer will choose some fast method to count the rows in the table - there is **NO** performance difference between `SELECT COUNT(*), COUNT(1), C... | The major performance difference is that COUNT(\*) can be satisfied by examining the primary key on the table.
i.e. in the simple case below, the query will return immediately, without needing to examine any rows.
```
select count(*) from table
```
I'm not sure if the query optimizer in SQL Server will do so, but in... | In SQL, what’s the difference between count(*) and count('x')? | [
"",
"sql",
""
] |
When I place a control on a tabpage in Silverlight the control is placed ~10 pixels down and ~10 pixels right. For example, the following xaml:
```
<System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left="0" Canvas.Top="75" Width="800" Height="525" Background="Red" HorizontalContentAlignment="Left" Verti... | Look at the control template, it has a margin of that size. Use blend to modify the a copy of the tab control's template. | Check the control template of your TabItem , it might have some default Margin of 10. Just a guess | How do I position the content of a tabpage in Silverlight? | [
"",
"c#",
"silverlight",
""
] |
I've been developing Winforms applications in C# for a few years now and have been interested in moving future development toward WPF, mainly because of the positive things I've been hearing about it. But, I'm wondering what sort of hurdles others have had to overcome as they migrated to WPF. Was there a significant hi... | I'm not sure I can give you just one hurdle, because it is a complete departure from WinForms. My suggestion is get Adam Nathan's WPF Unleashed, forget everything you know about building UI's with any previous technology (Winforms, MFC, Java) and begin again at square one.
If you try and do it any other way it will ca... | In my admittedly limited experience with WPF, the bigger hurdles include a complete overhaul of my mental model for how UIs are built and the new terminology that needs to be learned as a result of that. It may be that others have an easier time adjusting to the model, though. I can see how someone coming from best pra... | What are the bigger hurdles to overcome migrating from Winforms to WPF? | [
"",
"c#",
"wpf",
"windows",
"winforms",
""
] |
I have been in both situations:
* Creating too many custom Exceptions
* Using too many general Exception class
In both cases the project started OK but soon became an overhead to maintain (and refactor).
So what is the best practice regarding the creation of your own Exception classes? | [The Java Specialists](http://www.javaspecialists.eu/) wrote a post about [Exceptions in Java](http://www.javaspecialists.eu/archive/Issue162.html), and in it they list a few "best practices" for creating Exceptions, summarized below:
* Don't Write Own Exceptions (there are lots of useful Exceptions that are already p... | Don't do what the developers at my company did. Somebody created an [sic] InvalidArguementException that parallels java.lang.IllegalArgumentException, and we now use it in (literally) hundreds of classes. Both indicate that a method has been passed an illegal or inappropriate argument. Talk about a waste...
Joshua Blo... | What is the general rule of thumbs for creating an Exception in Java? | [
"",
"java",
"exception",
""
] |
Given a `datetime.time` value in Python, is there a standard way to add an integer number of seconds to it, so that `11:34:59` + 3 = `11:35:02`, for example?
These obvious ideas don't work:
```
>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(... | You can use full `datetime` variables with `timedelta`, and by providing a dummy date then using `time` to just get the time value.
For example:
```
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
```
results ... | As others here have stated, you can just use full datetime objects throughout:
```
from datetime import datetime, date, time, timedelta
sometime = time(8,00) # 8am
later = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()
```
However, I think it's worth explaining why full datetime objects are ... | What is the standard way to add N seconds to datetime.time in Python? | [
"",
"python",
"datetime",
"time",
"math",
""
] |
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:
```
<div>
<!-- some html -->
<script type="text/javascript">
/** some javascript */
</script>
</div>
```
I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it?
Some ... | Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:
```
<html>
<head>
<script type='text/javascript'>
function addScript()
{
var str = "<script>alert('i am here');<\/script>";
var new... | You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName.
```
div.innerHTML = response;
var scripts = div.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
eval(scripts[ix].text);
}
``` | How do you execute a dynamically loaded JavaScript block? | [
"",
"javascript",
"ajax",
""
] |
Whilst refactoring some old code I realised that a particular header file was full of function declarations for functions long since removed from the .cpp file. Does anyone know of a tool that could find (and strip) these automatically? | You could if possible make a test.cpp file to call them all, the linker will flag the ones that have no code as unresolved, this way your test code only need compile and not worry about actually running. | PC-lint can be tunned for dedicated purpose:
I tested the following code against for your question:
```
void foo(int );
int main()
{
return 0;
}
```
```
lint.bat test_unused.cpp
```
and got the following result:
```
============================================================
--- Module: test_unused.cpp (C... | Tools for finding unused function declarations? | [
"",
"c++",
"function",
"header",
""
] |
For an open source project I am looking for a good, simple implementation of a Dictionary that is backed by a file. Meaning, if an application crashes or restarts the dictionary will keep its state. I would like it to update the underlying file every time the dictionary is touched. (Add a value or remove a value). A Fi... | * [**bplustreedotnet**](http://bplusdotnet.sourceforge.net/)
The bplusdotnet package is a library of cross compatible data structure implementations in C#, java, and Python which are useful for applications which need to store and retrieve persistent information. The bplusdotnet data structures make it easy to **sto... | Let me analyze this:
1. Retrieve information by key
2. Persistant storage
3. Do not want to write back the whole file when 1 value changes
4. Should survive crashes
I think you want a database.
Edit: I think you are searching for the wrong thing. Search for a database that fits your requirements. And change some of ... | Looking for a simple standalone persistent dictionary implementation in C# | [
"",
"c#",
".net",
""
] |
There are hundreds of shopping cart solutions available for every platform, and all hosting plans come with several already installed. As a developer I understand that most of these are fairly similar from a user perspective.
But which ones are built with the developer in mind? For example, which ones have a decent AP... | osCommerce is one of those products that was badly designed from the beginning, and becomes basically unmaintainable as time moves forward. Addons are patches, and custom code modifies core. (Unless things have drastically changed since I last looked at it - judging by the version numbers, they have not).
While probab... | Magento is pretty good, and really powerful, but getting to grips with how to go about extending/replacing things is pretty tricky. The codebase is massively flexible, and just about anything can be replaced or extended, but there's very little documentation on how to go about doing it.
There are plenty of 3rd-party a... | Which PHP open source shopping cart solutions have features that benefit me as the web developer? | [
"",
"php",
"e-commerce",
"shopping-cart",
""
] |
In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions? | Convert from `String` to `byte[]`:
```
String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
```
Convert from `byte[]` to `String`:
```
byte[] b = {(byte) 99, (byte)97, (byte)116};
String s = new String(b, StandardCharsets.US_ASCII);
```
You should, of course, use the correct encoding name. My... | Here's a solution that avoids performing the Charset lookup for every conversion:
```
import java.nio.charset.Charset;
private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
String decodeUTF8(byte[] bytes) {
return new String(bytes, UTF8_CHARSET);
}
byte[] encodeUTF8(String string) {
return string.g... | How to convert Strings to and from UTF8 byte arrays in Java | [
"",
"java",
"string",
"encoding",
"character-encoding",
""
] |
**Edit**: Let me completely rephrase this, because I'm not sure there's an XML way like I was originally describing.
**Yet another edit**: This needs to be a repeatable process, and it has to be able to be set up in a way that it can be called in C# code.
In database A, I have a set of tables, related by PKs and FKs.... | I think most likely what I'm going to use is typed datasets. It won't be a generalized solution; we'll have to regenerate them if any of the tables change. But based on what I've been told, that's not a problem; the tables aren't expected to change much.
Datasets will make it reasonably easy to loop through the data h... | I think the SQL Server utility [tablediff.exe](http://weblogs.sqlteam.com/mladenp/archive/2007/03/03/60125.aspx) might be what you are looking for.
See also [this thread](https://stackoverflow.com/questions/121243/hidden-features-of-sql-server). | Copying relational data from database to database | [
"",
"sql",
"sql-server",
"sql-server-2005",
".net-3.5",
""
] |
How can I insert ASCII special characters (e.g. with the ASCII value 0x01) into a string?
I ask because I am using the following:
```
str.Replace( "<TAG1>", Convert.ToChar(0x01).ToString() );
```
and I feel that there must be a better way than this. Any Ideas?
Update:
Also If I use this methodology, do I need to w... | I believe you can use `\uXXXX` to insert specified codes into your string.
ETA: I just tested it and it works. :-)
```
using System;
class Uxxxx {
public static void Main() {
Console.WriteLine("\u20AC");
}
}
``` | > Also If I use this methodology, do I need to worry about unicode & ASCII clashing?
Your first problem will be your tags clashing with ASCII. Once you get to TAG10, you will clash with 0x0A: line feed. If you ensure that you will never get more than nine tags, you should be safe. Unicode-encoding (or rather: UTF8) is... | C# String ASCII representation | [
"",
"c#",
"regex",
"string",
"ascii",
""
] |
My developers are waging a civil war. In one camp, they've embraced Hibernate and Spring. In the other camp, they've denounced frameworks - they're considering Hibernate though.
The question is: Are there any nasty surprises, weaknesses or pit-falls that newbie Hibernate-Spring converts are likely to stumble on?
---
... | I've used Hibernate a number of times in the past. Each time I've run into edge cases where determining the syntax devolved into a scavenger hunt through the documentation, Google, and old versions. It is a powerful tool but poorly documented (last I looked).
As for Spring, just about every job I've interviewed for or... | They've denounced *frameworks*?
That's nuts. If you don't use an off-the-shelf framework, then you create your own. It's still a framework. | Java Frameworks War: Spring and Hibernate | [
"",
"java",
"hibernate",
"spring",
""
] |
Does the Java virtual machine ever move objects in memory, and if so, how does it handle updating references to the moved object?
I ask because I'm exploring an idea of storing objects in a distributed fashion (ie. across multiple servers), but I need the ability to move objects between servers for efficiency reasons.... | In reference to the comment above about walking the heap.
Different GC's do it different ways.
Typically copying collectors when they walk the heap, they don't walk all of the objects in the heap. Rather they walk the LIVE objects in the heap. The implication is that if it's reachable from the "root" object, the obje... | The keyword you're after is "compacting garbage collector". JVMs are permitted to use one, meaning that objects can be relocated. Consult your JVM's manual to find out whether yours does, and to see whether there are any command-line options which affect it.
The conceptually simplest way to explain compaction is to as... | Does the Java VM move objects in memory, and if so - how? | [
"",
"java",
"memory-management",
"garbage-collection",
"jvm",
""
] |
I have a dl containing some input boxes that I "clone" with a bit of JavaScript like:
```
var newBox = document.createElement('dl');
var sourceBox = document.getElementById(oldkey);
newBox.innerHTML = sourceBox.innerHTML;
newBox.id = newkey;
document.getElementById('boxes').appendChild(columnBox);
```
In... | [Firefox vs. IE: innerHTML handling](https://stackoverflow.com/questions/36778/firefox-vs-ie-innerhtml-handling#36793) ? | You could try the `cloneNode` method. It might do a better job of copying the contents. It should also be faster in most cases
```
var newBox;
var sourceBox = document.getElementById(oldkey);
if (sourceBox.cloneNode)
newBox = sourceBox.cloneNode(true);
else {
newBox = document.createElement(sourceBox.tagName)... | How do I get the most recently updated form item to "stick" in Firefox when I copy its container? | [
"",
"javascript",
"firefox",
"dom",
""
] |
I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels.
What assembly and/or class should I use? | [Bitmap](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx) class from System.Drawing.dll assembly:
```
Bitmap bitmap = new Bitmap(@"C:\image.png");
Color clr = bitmap.GetPixel(0, 0);
``` | Of course I googled already and found the PngBitmapDecoder class, but it doesn't seem to be available in .Net 2.0?
<http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.pngbitmapdecoder.aspx>
The above link mentions it's in the PresentationCore assembly which I don't seem to have included with .Net 2.... | Reading a PNG image file in .Net 2.0 | [
"",
"c#",
".net",
""
] |
In C#, if you have multiple constructors, you can do something like this:
```
public MyClass(Guid inputId, string inputName){
// do something
}
public MyClass(Guid inputId): this(inputId, "foo") {}
```
The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic neede... | The most common pattern used to solve this problem is to have an Initialize() method that your constructors call, but in the example you just gave, adding a static method that you called like the code below, would do the trick.
```
public MyClass(MyOtherClass inputObject): this(inputObject.ID, GetHelperText(inputObjec... | I don't see any reason to believe that creating an object in the constructor will automatically dispose the object. Yes, your object will immediately go out of scope and be available for garbage collection, but that is certainly not the same as being disposed.
There really isn't a great way to do exactly what you want... | Multiple Constructors with complex logic | [
"",
"c#",
".net",
""
] |
I'm developing a WinForms application (.Net 3.5, no WPF) where I want to be able to display foreign key lookups in a databound DataGridView.
An example of the sort of relationship is that I have a table of OrderLines. Orderlines have a foreign key relationship to Products and Products in turn have a foreign key relati... | I think the problem you're having is that when you are binding to a grid, it is not enough to support INotifyPropertyChanged, but you have to fire the ListChanged events in your [IBindingList](http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglist.aspx) implementation and make sure that you override... | welcome to StackOverflow :)
Normally what you would do is base the information in the drop down on two values [ValueMember and DisplayMember](http://windowsclient.net/blogs/faqs/archive/2006/07/12/what-are-the-displaymember-and-valuemember.aspx).
The ValueMember is the source of the actual controls value (this will b... | WinForms databinding and foreign key relationships | [
"",
"c#",
".net",
"winforms",
""
] |
I need to get a list of attribute values from child elements in Python.
It's easiest to explain with an example.
Given some XML like this:
```
<elements>
<parent name="CategoryA">
<child value="a1"/>
<child value="a2"/>
<child value="a3"/>
</parent>
<parent name="CategoryB">
... | I'm not really an old hand at Python, but here's an XPath solution using libxml2.
```
import libxml2
DOC = """<elements>
<parent name="CategoryA">
<child value="a1"/>
<child value="a2"/>
<child value="a3"/>
</parent>
<parent name="CategoryB">
<child value="b1"/>
<ch... | [ElementTree 1.3](http://effbot.org/zone/elementtree-13-intro.htm) (unfortunately not 1.2 which is the one included with Python) [supports XPath](http://effbot.org/zone/element-xpath.htm) like this:
```
import elementtree.ElementTree as xml
def getValues(tree, category):
parent = tree.find(".//parent[@name='%s']"... | Get list of XML attribute values in Python | [
"",
"python",
"xml",
"xpath",
"parent-child",
"xml-attribute",
""
] |
That is, I'd like to have a tuple of values.
The use case on my mind:
```
Dictionary<Pair<string, int>, object>
```
or
```
Dictionary<Triple<string, int, int>, object>
```
Are there built-in types like Pair or Triple? Or what's the best way of implementing it?
**Update** There are some general-purpose tuples impl... | I have implemented a tuple library in C#. Visit <http://www.adventuresinsoftware.com/generics/> and click on the "tuples" link. | ## **Builtin Classes**
In certain specific cases, the .net framework already provides tuple-like classes that you may be able to leverage.
***Pairs and Triples***
The generic
**[System.Collections.Generic.KeyValuePair](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx)**
class could be used as an adhoc pair impl... | What's the best way of using a pair (triple, etc) of values as one value in C#? | [
"",
"c#",
"generics",
"data-structures",
"tuples",
""
] |
Basically I am trying to restart a service from a php web page.
Here is the code:
```
<?php
exec ('/usr/bin/sudo /etc/init.d/portmap restart');
?>
```
But, in `/var/log/httpd/error_log`, I get
> unable to change to sudoers gid: Operation not permitted
and in /var/log/messages, I get
> Sep 22 15:01:56 ri kernel: a... | The problem is not with sudo at the moment, but with [SELinux](http://en.wikipedia.org/wiki/Selinux), which is (reasonably) set to deny the HTTPD from gaining root privileges.
You will need to either explicitly allow this (you can use [audit2allow](http://fedoraproject.org/wiki/SELinux/audit2allow) for this), or set ... | The error you are getting seems to be related to your SELinux configuration. You might try temporarily disabling that.
As an aside, I would strongly suggest that you adjust your sudo configuration to be more restrictive.
```
User_Alias WWW=apache
Cmnd_Alias WEBCMDS=/etc/init.d/portmap
WWW ALL=NOPASSWD: WEBCMDS
``` | PHP webpage doesn't launch unix command even after updated sudoers | [
"",
"php",
"exec",
"sudo",
""
] |
I've used several modules to make EXEs for Python, but I'm not sure if I'm doing it right.
How should I go about this, and why? Please base your answers on personal experience, and provide references where necessary. | [Auto PY to EXE](https://pypi.org/project/auto-py-to-exe/) - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.
---
[py2exe](http://www.py2exe.org/) is probably what you want, but it only works on Windows.
[PyInstaller](http://www.pyinstaller.org/) works on Windows... | I found this presentation to be very helpfull.
[How I Distribute Python applications on Windows - py2exe & InnoSetup](http://pyvideo.org/video/147/pycon-2009--how-i-distribute-python-applications-)
From the site:
> There are many deployment options for
> Python code. I'll share what has
> worked well for me on Windo... | How can I make an EXE file from a Python program? | [
"",
"python",
"exe",
"executable",
""
] |
I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.
I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in
```
MessageBox("Hello, World!");
``... | MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like
```
if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
//some interesting ... | Code summary:
```
using System.Windows.Forms;
...
MessageBox.Show( "hello world" );
```
Also ([as per this other stack post](https://stackoverflow.com/a/6639482/1582588)): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select `System.Windows.Forms` on Framework tab. ... | How do I create a MessageBox in C#? | [
"",
"c#",
".net",
""
] |
Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?
For instance, I currently do something like this depending on the circumstances:
```
int i = 0;
foreach (Object o in colle... | The `foreach` is for iterating over collections that implement [`IEnumerable`](http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx). It does this by calling [`GetEnumerator`](http://msdn.microsoft.com/en-us/library/s793z9y2(v=vs.110).aspx) on the collection, which will return an [`Enumerator`](http://ms... | Ian Mercer posted a similar solution as this on [Phil Haack's blog](http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx):
```
foreach (var item in Model.Select((value, i) => new { i, value }))
{
var value = item.value;
var index = item.i;
}
```
This gets you the item (`item.value`) and its ... | How do you get the index of the current iteration of a foreach loop? | [
"",
"c#",
"foreach",
""
] |
I have a page which spawns a popup browser window. I have a JavaScript variable in the parent browser window and I would like to pass it to the popped-up browser window.
Is there a way to do this? I know this can be done across frames in the same browser window but I'm not sure if it can be done across browser windows... | Provided the windows are from the same security domain, and you have a reference to the other window, yes.
Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to ... | Putting code to the matter, you can do this from the parent window:
```
var thisIsAnObject = {foo:'bar'};
var w = window.open("http://example.com");
w.myVariable = thisIsAnObject;
```
or this from the new window:
```
var myVariable = window.opener.thisIsAnObject;
```
I prefer the latter, because you will probably n... | Can I pass a JavaScript variable to another browser window? | [
"",
"javascript",
"browser",
""
] |
I need a Java way to find a running Win process from which I know to name of the executable. I want to look whether it is running right now and I need a way to kill the process if I found it. | You can use command line windows tools `tasklist` and `taskkill` and call them from Java using `Runtime.exec()`. | ```
private static final String TASKLIST = "tasklist";
private static final String KILL = "taskkill /F /IM ";
public static boolean isProcessRunning(String serviceName) throws Exception {
Process p = Runtime.getRuntime().exec(TASKLIST);
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInput... | How to find and kill running Win-Processes from within Java? | [
"",
"java",
"windows",
"process",
""
] |
I have a table in my database the records start and stop times for a specific task. Here is a sample of the data:
```
Start Stop
9/15/2008 5:59:46 PM 9/15/2008 6:26:28 PM
9/15/2008 6:30:45 PM 9/15/2008 6:40:49 PM
9/16/2008 8:30:45 PM 9/15/2008 9:20:29 PM
9/16/2008 12:30:45 PM... | ```
SELECT SUM( CASE WHEN Stop = '31 dec 9999'
THEN DateDiff(mi, Start, Stop)
ELSE DateDiff(mi, Start, GetDate())
END ) AS TotalMinutes
FROM task
```
However, a better solution would be to make the `Stop field nullable, and make it null when the task is still r... | I think this is cleaner:
```
SELECT SUM(
DATEDIFF(mi, Start, ISNULL(NULLIF(Stop,'99991231'), GetDate()))
) AS ElapsedTime
FROM Table
``` | Transact-SQL to sum up elapsed time | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm asking for a template trick to detect if a class has a specific member function of a given signature.
The problem is similar to the one cited here
<http://www.gotw.ca/gotw/071.htm>
but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a partic... | I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size\_t used\_memory() const).
```
template<typename T>
struct HasUsedMemoryMethod
{
template<typename U, size_t (U::*)() const> struct SFINAE... | Here's a possible implementation relying on C++11 features. It correctly detects the function even if it's inherited (unlike the solution in the accepted answer, as Mike Kinghan observes in [his answer](https://stackoverflow.com/a/10707822/947836)).
The function this snippet tests for is called `serialize`:
```
#incl... | Check if a class has a member function of a given signature | [
"",
"c++",
"c++11",
"templates",
"sfinae",
""
] |
I visited few web sites in the past where they had a set of photo thumbnails and clicking on one of them created a cool effect of an expanding popup showing the full size image.
Is there any available free JavaScript library that will do this?
I'm interested mostly in the popup effect and less in the rest of the album... | Lightbox is another popular one:
[Lightbox Project Page](http://www.lokeshdhakar.com/projects/lightbox2/) | The [thickbox plugin](http://jquery.com/demo/thickbox/) for [jQuery](http://www.jquery.com) will do what you want. | javascript library to show photo album | [
"",
"javascript",
""
] |
I'm currently looking to perform some headless HTML rendering to essentially create resources off screen and persist the result as an image. The purpose is to take a subset of the HTML language and apply it to small screen devices (like PocketPCs) because our users know HTML and the transition from Photoshop to HTML ma... | <http://www.phantomjs.org/>
**Full web stack**
PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. | [You can use Gecko to do this.](http://weblogs.mozillazine.org/roc/archives/2005/05/rendering_web_p.html) | Headless HTML rendering, preferably open source | [
"",
"c#",
".net",
"html",
"browser",
""
] |
After compiling a simple C++ project using Visual Studio 2008 on vista, everything runs fine on the original vista machine and other vista computers. However, moving it over to an XP box results in an error message: "The application failed to start because the application configuration is incorrect".
What do I have to... | You need to install the Visual Studios 2008 runtime on the target computer:
> <http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en>
Alternatively, you could also link the run time statically, in the project properties window go to:
> c++ -> Code Generation -> ... | You probably need to distribute the VC runtime with your application. There are a variety of ways to do this. [This article](http://blogs.msdn.com/vcblog/archive/2007/10/12/how-to-redistribute-the-visual-c-libraries-with-your-application.aspx) from the Microsoft Visual C++ Team best explains the different ways to distr... | Different versions of C++ libraries | [
"",
"c++",
"windows",
"windows-vista",
"windows-xp",
""
] |
In C#, if I need to open an HTTP connection, download XML and get one value from the result, how would I do that?
For consistency, imagine the webservice is at www.webservice.com and that if you pass it the POST argument fXML=1 it gives you back
```
<xml><somekey>somevalue</somekey></xml>
```
I'd like it to spit out... | I use this code and it works great:
```
System.Xml.XmlDocument xd = new System.Xml.XmlDocument;
xd.Load("http://www.webservice.com/webservice?fXML=1");
string xPath = "/xml/somekey";
// this node's inner text contains "somevalue"
return xd.SelectSingleNode(xPath).InnerText;
```
---
EDIT: I just realized you're talki... | I think it will be useful to read this first:
[Creating and Consuming a Web Service](https://web.archive.org/web/20211020134836/https://aspnet.4guysfromrolla.com/articles/062602-1.aspx) (in .NET)
This is a series of tutorials of how web services are used in .NET, including how XML input is used (deserialization). | How do I get a value from an XML web service in C#? | [
"",
"c#",
"xml",
"web-services",
""
] |
I need to specifically catch SQL server timeout exceptions so that they can be handled differently. I know I could catch the SqlException and then check if the message string Contains "Timeout" but was wondering if there is a better way to do it?
```
try
{
//some code
}
catch (SqlException ex)
{
if (ex.Messag... | To check for a timeout, I believe you check the value of ex.Number. If it is -2, then you have a timeout situation.
-2 is the error code for timeout, returned from DBNETLIB, the MDAC driver for SQL Server. This can be seen by downloading [Reflector](http://www.red-gate.com/products/reflector/), and looking under Syste... | Updated for c# 6:
```
try
{
// some code
}
catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout
{
// handle timeout
}
```
Very simple and nice to look at!! | How to catch SQLServer timeout exceptions | [
"",
"c#",
".net",
"sql-server",
"error-handling",
""
] |
How does the comma operator work in C++?
For instance, if I do:
```
a = b, c;
```
Does a end up equaling b or c?
(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)
**Update:** This question has exposed a nuance when using the comma operator. Just to document this:... | It would be equal to `b`.
The comma operator has a lower precedence than assignment. | The comma operator has the **lowest** precedence of all C/C++ operators. Therefore it's always the last one to bind to an expression, meaning this:
```
a = b, c;
```
is equivalent to:
```
(a = b), c;
```
Another interesting fact is that the comma operator introduces a [sequence point](http://en.wikipedia.org/wiki/S... | How does the comma operator work, and what precedence does it have? | [
"",
"c++",
"operator-precedence",
"comma-operator",
""
] |
I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication.
Is there a way I can use GreaseMonkey to log me int... | It is possible to log in using HTTP authentication by setting the "Authorization" HTTP header, with the value of this header set to the string "basic username:password", but with the "username:password" portion of the string Base 64 encoded.
<http://frontier.userland.com/stories/storyReader$2159>
A bit of researching... | HTTP authentication information is sent on every request, not just to log in. The browser will cache the login information for the session after you log in the first time. So, you don't really save anything by trying to check if you are already logged in.
You could also forget about greasemonkey altogether and just gi... | GreaseMonkey script to auto login using HTTP authentication | [
"",
"javascript",
"http",
"authentication",
"greasemonkey",
"http-authentication",
""
] |
Has anyone successfully implemented a Java based solution that uses Microsoft SQL Server 2005 Reporting Services? Reporting Services comes with a set of Web Services that allow you to control the creation of a report, execution of a report, etc and I am just starting development on a POC of this integration. A couple o... | My experience with RS would lead me to suggest you go with just about anything else. I think the web services portion would work fine but I'd be concerned about how RS manages memory and how many reports you need to be running at once before making any decisions. I'm fighting with memory management problems today with ... | I just wanted to come back and answer my own question. I started with Axis2, Apache's implementation of SOAP. After generating the client using WSDL2Java, I was able to successfully invoke Microsoft Reporting Services WebService and generate reports, output in Excel, PDF, CSV and other formats. In my case, I also used ... | Microsoft Reporting Services WebServices and Java | [
"",
"java",
"web-services",
"reporting-services",
"axis",
""
] |
I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependenci... | I am using #3: the boost string format library - but I have to admit that I've never had any problem with the differences in format specifications.
Works like a charm for me - and the external dependencies could be worse (a very stable library)
Edited: adding an example how to use boost::format instead of printf:
``... | Here's the idiom I like for making functionality identical to 'sprintf', but returning a std::string, and immune to buffer overflow problems. This code is part of an open source project that I'm writing (BSD license), so everybody feel free to use this as you wish.
```
#include <string>
#include <cstdarg>
#include <ve... | C++: how to get fprintf results as a std::string w/o sprintf | [
"",
"c++",
"unix",
"format",
"printf",
"stdstring",
""
] |
I've always been told that adding an element to an array happens like this:
> An empty copy of the array+1element is
> created and then the data from the
> original array is copied into it then
> the new data for the new element is
> then loaded
If this is true, then using an array within a scenario that requires a l... | Look at the generic `List<T>` as a replacement for arrays. They support most of the same things arrays do, including allocating an initial storage size if you want. | This really depends on what you mean by "add."
If you mean:
```
T[] array;
int i;
T value;
...
if (i >= 0 && i <= array.Length)
array[i] = value;
```
Then, no, this does not create a new array, and is in-fact the fastest way to alter any kind of IList in .NET.
If, however, you're using something like ArrayList,... | How and when to abandon the use of arrays in C#? | [
"",
"c#",
".net",
"arrays",
"theory",
""
] |
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config? | ```
using System.Configuration;
Configuration config =
ConfigurationManager.OpenExeConfiguration("C:\Test.exe");
```
You can then access the app settings, connection strings, etc from the config instance. This assumes of course that the config file is properly formatted and your app has read access to the directo... | It appears that you can use the [`AppDomain.SetData`](http://msdn.microsoft.com/en-us/library/37z40s1c.aspx) method to achieve this. The documentation states:
> You cannot insert or modify system entries with this method.
Regardless, doing so does appear to work. The documentation for the [`AppDomain.GetData`](http:/... | Accessing App.config in a location different from the binary | [
"",
"c#",
""
] |
When encoding a query string to be sent to a web server - when do you use `escape()` and when do you use `encodeURI()` or `encodeURIComponent()`:
Use escape:
```
escape("% +&=");
```
OR
use `encodeURI()` / `encodeURIComponent()`
```
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("v... | # escape()
Don't use it!
`escape()` is defined in section [B.2.1.1 escape](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-escape-string) and the [introduction text of Annex B](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers) says:
> ... Al... | The difference between `encodeURI()` and `encodeURIComponent()` are exactly 11 characters encoded by encodeURIComponent but not by encodeURI:

I generated this table easily with **console.table** in Google C... | When are you supposed to use escape instead of encodeURI / encodeURIComponent? | [
"",
"javascript",
"encoding",
"query-string",
""
] |
How do I sort a list of dictionaries by a specific key's value? Given:
```
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
```
When sorted by `name`, it should become:
```
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
``` | The [`sorted()`](https://docs.python.org/library/functions.html#sorted) function takes a `key=` parameter
```
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
```
Alternatively, you can use [`operator.itemgetter`](https://docs.python.org/library/operator.html#operator.itemgetter) instead of defining the f... | ```
import operator
```
To sort the list of dictionaries by key='name':
```
list_of_dicts.sort(key=operator.itemgetter('name'))
```
To sort the list of dictionaries by key='age':
```
list_of_dicts.sort(key=operator.itemgetter('age'))
``` | How to sort a list of dictionaries by a value of the dictionary in Python? | [
"",
"python",
"list",
"sorting",
"dictionary",
"data-structures",
""
] |
Is it possible to use the [`OpenFileDialog`](https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=10&ct=1221809452&rver=5.5.4177.0&wp=MCLBI&wlcxt=msdn%24msdn%24msdn&wreply=http:%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fsystem.windows.forms.openfiledialog.aspx&id=254354&lc=1033) class select a file OR folder? It appe... | This is the solution I have been looking for, this article provides code and describes how to create a dialog that meets my needs.
[CodeProject: Full Implementation of IShellBrowser](http://www.codeproject.com/KB/dialog/FileDialogs.aspx) | Yes, you can use OpenFileDialog to select a folder. Here is an article in CodeProject that demonstrated a way to do it (<http://www.codeproject.com/KB/dialog/OpenFileOrFolderDialog.aspx>). | Is there an OpenFileOrFolderDialog object in .NET? | [
"",
"c#",
".net",
"filedialog",
""
] |
I've gotten to grips with the basics of Python and I've got a small holiday which I want to use some of to learn a little more Python. The problem is that I have no idea what to learn or where to start. I'm primarily web development but in this case I don't know how much difference it will make. | Well, there are great ressources for advanced Python programming :
* Dive Into Python ([read it for free](http://www.diveintopython.net/))
* Online python cookbooks (e.g. [here](http://code.activestate.com/recipes/langs/python/) and [there](http://the.taoofmac.com/space/Python/Grimoire))
* O'Reilly's Python Cookbook (... | Depending on exactly what you mean by "gotten to grips with the basics", I'd suggest reading through [Dive Into Python](http://www.diveintopython.net/) and typing/executing all the chapter code, then get something like [Programming Collective Intelligence](http://www.amazon.co.uk/Programming-Collective-Intelligence-Bui... | Python, beyond the basics | [
"",
"python",
""
] |
I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would b... | I found this article, which has a complete wrapper class included for manipulating the windows firewall. [Adding an Application to the Exception list on the Windows Firewall](http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8)
```
///
/// Allows basic a... | Not sure if this is the best way, but running [netsh](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490617(v=technet.10)) should work:
> netsh firewall add allowedprogram C:\MyApp\MyApp.exe MyApp ENABLE
I think this requires Administrator Permissions though,for obvious reasons :)
Ed... | Programmatically add an application to Windows Firewall | [
"",
"c#",
"windows",
"firewall",
""
] |
How do I turn a python program into an .egg file? | [Setuptools](http://peak.telecommunity.com/DevCenter/setuptools) is the software that creates [.egg files](http://peak.telecommunity.com/DevCenter/PythonEggs). It's an extension of the [`distutils`](http://docs.python.org/lib/module-distutils.html) package in the standard library.
The process involves creating a `setu... | Also, if you need to get an .egg package off a single .py file app, check this link: [EasyInstall - Packaging others projects as eggs](http://peak.telecommunity.com/DevCenter/EasyInstall#packaging-others-projects-as-eggs). | How do I turn a python program into an .egg file? | [
"",
"python",
"deployment",
"egg",
""
] |
I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key:
```
try
{
remoteKey = RegistryKey.OpenRemoteBaseKey(
Reg... | John's pointer to MSDN answered what UnauthorizedAccessException is for - it only appears when you try to access a key remotely, using OpenRemoteBaseKey.
We're a little wary about changing the security context on the computer - I've found a reference [here](http://vbcity.com/forums/topic.asp?tid=43510) about using WMI... | You probably have to use impersonation to change the credentials of the thread that calls the remote registry methods. See here ([linky](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx)) for some information on MSDN. Basically, your thread has a security context that i... | Connecting to registry remotely, and getting exceptions | [
"",
"c#",
"windows",
"exception",
""
] |
Essentially I have a PHP page that calls out some other HTML to be rendered through an object's method. It looks like this:
MY PHP PAGE:
```
// some content...
<?php
$GLOBALS["topOfThePage"] = true;
$this->renderSomeHTML();
?>
// some content...
<?php
$GLOBALS["topOfThePage"] = false;
$this->render... | Obviously, you cannot. The whole point of caching is that the 'thing' you cache is not going to change. So you either:
* provide a parameter
* aviod caching
* invalidate the cache when you set a different parameter
Or, you rewrite the cache mechanism yourself - to support some dynamic binding. | Chaching is handled differently by different frameworks, so you'd have to help us out with some more information. But I also wonder if you could pass that as a parameter instead of using `$GLOBALS.`
```
$this->renderSomeHTML(true);
``` | How might I pass variables through to cached content in PHP? | [
"",
"php",
"caching",
"variables",
""
] |
When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.
I'm currently doing the following, but am sure there must be a library function ... | This is what I use:
```
def shellquote(s):
return "'" + s.replace("'", "'\\''") + "'"
```
The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell... | [`shlex.quote()`](https://docs.python.org/3/library/shlex.html#shlex.quote) does what you want since python 3.
(Use [`pipes.quote`](https://docs.python.org/2/library/pipes.html#pipes.quote) to support both python 2 and python 3,
though note that `pipes` has been deprecated since 3.10
and slated for removal in 3.13) | How to escape os.system() calls? | [
"",
"python",
"shell",
"escaping",
""
] |
If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called? | ```
e => e.MoveNext() ? e.Current : null
```
This will advance the enumerator and return the current value, and return null when the enumeration is complete. | A Lambda expression can contain complex statements, so you can do the following:
```
Func<IEnumerator, object> f = ie => { ie.MoveNext(); return ie.Current; };
``` | Is it possible to advance an enumerator and get its value in a lambda? | [
"",
"c#",
"lambda",
""
] |
I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.
I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. [Internet Duct Tape's Greasemonkey tools, like ... | In Firefox, you could do something like this:
```
javascript:alert(
document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g)
.join("\n"))
```
How this works:
* Gets the selection text from the browser ("document.getSelection()" in FF, in IE it would be "document.selection.createRange().text")
* A... | Use a regular expression to detect the IP address. A couple examples:
```
/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/
/^([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+$/
``` | How can you find all the IP addresses in a selected block of text with a javascript bookmarklet? | [
"",
"javascript",
"ip-address",
"bookmarklet",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.