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 app](https://play.google.com/store/apps/details?id=org.kivy.showcase)
|
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 necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.
|
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 a part of itself to run on Windows and Linux! To get it work is a bit tricky, but there is an [exhaustive article](http://web.archive.org/web/20090228071059/http://blog.platinumsolutions.com/node/234) with working example.
Besides that, you may look at the bin\service.bat in [Apache Tomcat](http://tomcat.apache.org/) to get an idea how to setup the service. In Tomcat they rename the Procrun binaries (prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe).
Something I struggled with using Procrun, your start and stop methods must accept the parameters (String[] argv). For example "start(String[] argv)" and "stop(String[] argv)" would work, but "start()" and "stop()" would cause errors. If you can't modify those calls, consider making a bootstrapper class that can massage those calls to fit your needs.
|
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" try googling "win32 /subject/" or "win32 api /subject/"
|
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 GetDefaultPrinter with NULL as a buffer pointer first will return the name length and then you can allocate a name buffer big enough to hold the name.
```
DWORD numprinters;
DWORD defprinter=0;
DWORD dwSizeNeeded=0;
DWORD dwItem;
LPPRINTER_INFO_2 printerinfo = NULL;
// Get buffer size
EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS , NULL, 2, NULL, 0, &dwSizeNeeded, &numprinters );
// allocate memory
//printerinfo = (LPPRINTER_INFO_2)HeapAlloc ( GetProcessHeap (), HEAP_ZERO_MEMORY, dwSizeNeeded );
printerinfo = (LPPRINTER_INFO_2)new char[dwSizeNeeded];
if ( EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, // what to enumerate
NULL, // printer name (NULL for all)
2, // level
(LPBYTE)printerinfo, // buffer
dwSizeNeeded, // size of buffer
&dwSizeNeeded, // returns size
&numprinters // return num. items
) == 0 )
{
numprinters=0;
}
{
DWORD size=0;
// Get the size of the default printer name.
GetDefaultPrinter(NULL, &size);
if(size)
{
// Allocate a buffer large enough to hold the printer name.
TCHAR* buffer = new TCHAR[size];
// Get the printer name.
GetDefaultPrinter(buffer, &size);
for ( dwItem = 0; dwItem < numprinters; dwItem++ )
{
if(!strcmp(buffer,printerinfo[dwItem].pPrinterName))
defprinter=dwItem;
}
delete buffer;
}
}
```
|
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 != None):
pb.save("screenshot.png","png")
print "Screenshot saved to screenshot.png."
else:
print "Unable to get the screenshot."
```
Borrowed from <http://ubuntuforums.org/showpost.php?p=2681009&postcount=5>
|
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.data, "raw", "BGRX")
image.show()
finally:
dsp.close()
```
One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.
---
**Edit:**
We can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:
```
#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>
//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c
void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data)
{
Display *display = XOpenDisplay(NULL);
Window root = DefaultRootWindow(display);
XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);
unsigned long red_mask = image->red_mask;
unsigned long green_mask = image->green_mask;
unsigned long blue_mask = image->blue_mask;
int x, y;
int ii = 0;
for (y = 0; y < H; y++) {
for (x = 0; x < W; x++) {
unsigned long pixel = XGetPixel(image,x,y);
unsigned char blue = (pixel & blue_mask);
unsigned char green = (pixel & green_mask) >> 8;
unsigned char red = (pixel & red_mask) >> 16;
data[ii + 2] = blue;
data[ii + 1] = green;
data[ii + 0] = red;
ii += 3;
}
}
XDestroyImage(image);
XDestroyWindow(display, root);
XCloseDisplay(display);
}
```
And then the python-file:
```
import ctypes
import os
from PIL import Image
LibName = 'prtscn.so'
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
grab = ctypes.CDLL(AbsLibPath)
def grab_screen(x1,y1,x2,y2):
w, h = x2-x1, y2-y1
size = w * h
objlength = size * 3
grab.getScreen.argtypes = []
result = (ctypes.c_ubyte*objlength)()
grab.getScreen(x1,y1, w, h, result)
return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)
if __name__ == '__main__':
im = grab_screen(0,0,1440,900)
im.show()
```
|
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(String s, out Guid value)
{
try
{
value = new Guid(s);
return true;
}
catch (FormatException)
{
value = Guid.Empty;
return false;
}
}
```
is not suitable.
I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard.
Additionally, I thought certain Guid values are invalid(?)
---
**Update 1**
[ChristianK](https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829) had a good idea to catch only `FormatException`, rather than all. Changed the question's code sample to include suggestion.
---
**Update 2**
Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often?
The answer is *yes*. That is why I am using TryStrToGuid - I **am** expecting bad data.
**Example 1** [Namespace extensions can be specified by appending a GUID to a folder name](http://msdn.microsoft.com/en-us/library/cc144096(VS.85).aspx). I might be parsing folder names, checking to see if the text after the final **.** is a GUID.
```
c:\Program Files
c:\Program Files.old
c:\Users
c:\Users.old
c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666}
c:\Windows
c:\Windows.old
```
**Example 2** I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be.
**Example 3** I might be parsing a search expression entered by a user.

If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.)
---
**Update 3 - Performance benchmarks**
Test converting 10,000 good Guids, and 10,000 bad Guids.
```
Catch FormatException:
10,000 good: 63,668 ticks
10,000 bad: 6,435,609 ticks
Regex Pre-Screen with try-catch:
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
```
*p.s. I shouldn't have to justify a question.*
|
**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) Answer:**
```
/// <summary>
/// Attempts to convert a string to a guid.
/// </summary>
/// <param name="s">The string to try to convert</param>
/// <param name="value">Upon return will contain the Guid</param>
/// <returns>Returns true if successful, otherwise false</returns>
public static Boolean TryStrToGuid(String s, out Guid value)
{
//ClsidFromString returns the empty guid for null strings
if ((s == null) || (s == ""))
{
value = Guid.Empty;
return false;
}
int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value);
if (hresult >= 0)
{
return true;
}
else
{
value = Guid.Empty;
return false;
}
}
namespace PInvoke
{
class ObjBase
{
/// <summary>
/// This function converts a string generated by the StringFromCLSID function back into the original class identifier.
/// </summary>
/// <param name="sz">String that represents the class identifier</param>
/// <param name="clsid">On return will contain the class identifier</param>
/// <returns>
/// Positive or zero if class identifier was obtained successfully
/// Negative if the call failed
/// </returns>
[DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
public static extern int CLSIDFromString(string sz, out Guid clsid);
}
}
```
---
Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop.
If you need to convert a guid in String representation to a Guid, use
```
new Guid(someString);
```
|
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 currently selected item to the nth item, what would the `postmessage` look like?
I am guessing that it would involve `ON_CBN_SELCHANGE`, but I can't get it to work right.
|
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 PostMessage. CBN\_SELCHANGE is the notification that the control sends *back to you* when the selection is changed.
Finally, you might want to add the c++ tag to this question.
|
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 just stting the Text property of a combo box.
|
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 the DataGridViewComboBoxColumn. Just make sure you supply the correct rowindex and columnindex along with setting the value to the correct type (the same type as the ValueMember property of the DataGridViewComboBoxColumn).
|
```
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 enabled ) and these are the places where the breakpoints should definitely be hit .
But for some reason , my breakpoints are not hit .
PS : All pdb's are present in correct location .
Is there any setting i am missing .
|
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/img204/3017/capture5ct4.png>
Most of the time, leaving "automatically determine the type of code to debug" setting on works for me. However, in some cases, the debugger is not able to understand that I want to attach to managed code (if I have launched my application from a batch file, for example) and when it does that, the above solution works for me.
|
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 when finished with the temporary hover behaviour.
I think these can be stored using the `jQuery.data()` function:
```
//save old hover behavior (somehow)
$('#foo').data('oldhoverin',???)
$('#foo').data('oldhoverout',???);
//set new hover behavior
$('#foo').hover(newhoverin,newhoverout);
```
Do stuff with new hover behaviour...
```
//restore old hover behaviour
$('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout'));
```
But how do I get the currently registered hover functions from jQuery?
Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?"
|
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 namespacing: <http://docs.jquery.com/Events_(Guide)#Namespacing_events>
|
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("_mouseenter"));
obj.unbind("mouseleave", obj.data("_mouseleave"));
obj.data("_mouseenter", undefined);
obj.data("_mouseleave", undefined);
}
$(document).ready(function() {
var test = $("#test");
setHover(test, function(e) {
alert("original " + e.type);
}, function(e) {
alert("original " + e.type);
});
var saved_mouseenter = test.data("_mouseenter");
var saved_mouseleave = test.data("_mouseleave");
removeHover(test);
setHover(test, function() {
alert("zip");
}, function() {
alert('zam');
});
removeHover(test);
setHover(test, saved_mouseenter, saved_mouseleave);
});
```
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Jquery - Get, change and restore hover handlers</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p><a id="test" href="">test</a></p>
</body>
</html>
```
If not, maybe it'll give you some ideas.
|
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 all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree.
Now, first you need
1. to bind the Key-Combo with a Command using an `InputBinding` like this
2. you can then hookup the command to your handler (e.g. code that gets called by `SaveAll`) via a `CommandBinding`.
For the `Windows` Key, you use the right [Key](http://msdn.microsoft.com/en-us/library/system.windows.input.key.aspx) enumerated member, **`Key.LWin`** or **`Key.RWin`**
```
public WindowMain()
{
InitializeComponent();
// Bind Key
var ib = new InputBinding(
MyAppCommands.SaveAll,
new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control));
this.InputBindings.Add(ib);
// Bind handler
var cb = new CommandBinding( MyAppCommands.SaveAll);
cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );
this.CommandBindings.Add (cb );
}
private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e)
{
// Do the Save All thing here.
}
```
|
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;
using System.Diagnostics;
using System.Linq;
using System.Net.Mime;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
namespace UnManaged
{
public class HotKey : IDisposable
{
private static Dictionary<int, HotKey> _dictHotKeyToCalBackProc;
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, UInt32 fsModifiers, UInt32 vlc);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public const int WmHotKey = 0x0312;
private bool _disposed = false;
public Key Key { get; private set; }
public KeyModifier KeyModifiers { get; private set; }
public Action<HotKey> Action { get; private set; }
public int Id { get; set; }
// ******************************************************************
public HotKey(Key k, KeyModifier keyModifiers, Action<HotKey> action, bool register = true)
{
Key = k;
KeyModifiers = keyModifiers;
Action = action;
if (register)
{
Register();
}
}
// ******************************************************************
public bool Register()
{
int virtualKeyCode = KeyInterop.VirtualKeyFromKey(Key);
Id = virtualKeyCode + ((int)KeyModifiers * 0x10000);
bool result = RegisterHotKey(IntPtr.Zero, Id, (UInt32)KeyModifiers, (UInt32)virtualKeyCode);
if (_dictHotKeyToCalBackProc == null)
{
_dictHotKeyToCalBackProc = new Dictionary<int, HotKey>();
ComponentDispatcher.ThreadFilterMessage += new ThreadMessageEventHandler(ComponentDispatcherThreadFilterMessage);
}
_dictHotKeyToCalBackProc.Add(Id, this);
Debug.Print(result.ToString() + ", " + Id + ", " + virtualKeyCode);
return result;
}
// ******************************************************************
public void Unregister()
{
HotKey hotKey;
if (_dictHotKeyToCalBackProc.TryGetValue(Id, out hotKey))
{
UnregisterHotKey(IntPtr.Zero, Id);
}
}
// ******************************************************************
private static void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled)
{
if (!handled)
{
if (msg.message == WmHotKey)
{
HotKey hotKey;
if (_dictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey))
{
if (hotKey.Action != null)
{
hotKey.Action.Invoke(hotKey);
}
handled = true;
}
}
}
}
// ******************************************************************
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// ******************************************************************
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be _disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be _disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
Unregister();
}
// Note disposing has been done.
_disposed = true;
}
}
}
// ******************************************************************
[Flags]
public enum KeyModifier
{
None = 0x0000,
Alt = 0x0001,
Ctrl = 0x0002,
NoRepeat = 0x4000,
Shift = 0x0004,
Win = 0x0008
}
// ******************************************************************
}
```
|
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',' ','S','p','l','i','t']
```
As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:
```
[doSomethingWith(ch) for ch in s]
```
|
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?](https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle).
---
To clarify the accepted answer (and maybe my question), replacing `count(column_name)` with `count(*)` would return an extra row in the result that contains a `null` and the count of `null` values in the column.
|
`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 values(null,null)
select count(*),count(id),count(id2)
from #bla
```
results
7 3 2
|
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']
}
] ;
```
How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities?
Thanks
**EDIT** Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads.
|
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
```
After running the above code, you could say
```
states["Texas"]
```
which would return
```
['Austin','Dallas','San Antonio']
```
|
(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 = [
{
"states" : "Texas",
"cities" : ['Austin','Dallas','San Antonio']
},
{
"states" :"Arkansas",
"cities" : ['Little Rock','Texarkana','Hot Springs']
}
] ;
```
These JQuery functions will populate the city select box based on the state select box selection
```
$(function() { // create an array to be referenced by state name
state = [] ;
for(var i=0; i<area.length; i++) {
state[area[i].states] = area[i].cities ;
}
});
$(function() {
// populate states select box
var options = '' ;
for (var i = 0; i < area.length; i++) {
options += '<option value="' + area[i].states + '">' + area[i].states + '</option>';
}
$("#states").html(options); // populate select box with array
// selecting state (change) will populate cities select box
$("#states").bind("change",
function() {
$("#cities").children().remove() ; // clear select box
var options = '' ;
for (var i = 0; i < state[this.value].length; i++) {
options += '<option value="' + state[this.value][i] + '">' + state[this.value][i] + '</option>';
}
$("#cities").html(options); // populate select box with array
} // bind function end
); // bind end
});
```
|
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 unavailable, use:
```
string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());
```
See the [MSDN Link](http://msdn2.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx) for a detailed description.
|
```
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 functional programming since PHP 4. The flavors are:
```
$cb1 = 'someGlobalFunction';
$cb2 = ['ClassName', 'someStaticMethod'];
$cb3 = [$object, 'somePublicMethod'];
// this syntax is callable since PHP 5.2.3 but a string containing it
// cannot be called directly
$cb2 = 'ClassName::someStaticMethod';
$cb2(); // fatal error
// legacy syntax for PHP 4
$cb3 = array(&$object, 'somePublicMethod');
```
This is a safe way to use callable values in general:
```
if (is_callable($cb2)) {
// Autoloading will be invoked to load the class "ClassName" if it's not
// yet defined, and PHP will check that the class has a method
// "someStaticMethod". Note that is_callable() will NOT verify that the
// method can safely be executed in static context.
$returnValue = call_user_func($cb2, $arg1, $arg2);
}
```
Modern PHP versions allow the first three formats above to be invoked directly as `$cb()`. `call_user_func` and `call_user_func_array` support all the above.
See: <http://php.net/manual/en/language.types.callable.php>
Notes/Caveats:
1. If the function/class is namespaced, the string must contain the fully-qualified name. E.g. `['Vendor\Package\Foo', 'method']`
2. `call_user_func` does not support passing non-objects by reference, so you can either use `call_user_func_array` or, in later PHP versions, save the callback to a var and use the direct syntax: `$cb()`;
3. Objects with an [`__invoke()`](https://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke) method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term.
4. The legacy `create_function()` creates a global function and returns its name. It's a wrapper for `eval()` and anonymous functions should be used instead.
|
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 define any custom interfaces you might need.
```
#include "windows.h"
#include "shobjidl.h"
#include "atlbase.h"
//
// compile with: cl /EHsc test.cpp
//
// A fun little program to demonstrate creating an OCX.
// (CLSID_TaskbarList in this case)
//
BOOL CALLBACK RemoveFromTaskbarProc( HWND hwnd, LPARAM lParam )
{
ITaskbarList* ptbl = (ITaskbarList*)lParam;
ptbl->DeleteTab(hwnd);
return TRUE;
}
void HideTaskWindows(ITaskbarList* ptbl)
{
EnumWindows( RemoveFromTaskbarProc, (LPARAM) ptbl);
}
// ============
BOOL CALLBACK AddToTaskbarProc( HWND hwnd, LPARAM lParam )
{
ITaskbarList* ptbl = (ITaskbarList*)lParam;
ptbl->AddTab(hwnd);
return TRUE;// continue enumerating
}
void ShowTaskWindows(ITaskbarList* ptbl)
{
if (!EnumWindows( AddToTaskbarProc, (LPARAM) ptbl))
throw "Unable to enum windows in ShowTaskWindows";
}
// ============
int main(int, char**)
{
CoInitialize(0);
try {
CComPtr<IUnknown> pUnk;
if (FAILED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**) &pUnk)))
throw "Unabled to create CLSID_TaskbarList";
// Do something with the object...
CComQIPtr<ITaskbarList> ptbl = pUnk;
if (ptbl)
ptbl->HrInit();
HideTaskWindows(ptbl);
MessageBox( GetDesktopWindow(), _T("Check out the task bar!"), _T("StackOverflow FTW"), MB_OK);
ShowTaskWindows(ptbl);
}
catch( TCHAR * msg ) {
MessageBox( GetDesktopWindow(), msg, _T("Error"), MB_OK);
}
CoUninitialize();
return 0;
}
```
|
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 Visual Basic Editor (if you have excel 2007 it's on the 'Developer' ribbon tab thing
Now that you're in happy visual basic land...
1. From the `Tools` menu, select `References`
2. Select your OCX/COM object from the list, or click `Browse...` to find the file if it's not registered with COM - You may be able to skip this step if your OCX is already registered.
3. From the `Insert` menu, select `UserForm`
4. In the floating `Toolbox` window, right click and select `Additional Controls`
5. Find your OCX in the list and tick it
6. You can then drag your OCX from the toolbox onto the userform
7. From the `Run` menu, run it.
8. Test your OCX and play around with it.
9. SAVE THE EXCEL FILE so you don't have to repeat these steps every time.
|
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"/>
...
</Bars>
</Foo>
```
For JSON, this serializes to:
```
{"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]}
```
What I'd really like to have is this serialize to better reflect the underlying relationship. E.g.,
```
<Foo>
<Bars>
<Key0 value="value0"/>
<Key1 value="value1"/>
...
</Bars>
</Foo>
```
I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this?
I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g.
```
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
foreach (Bar bar in Bars){
info.AddValue(bar.Key. bar);
}
}
```
Any suggestions? What's the best practice here?
|
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, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it "works" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON?
|
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 unit test framework (be it NUnit, MbUnit or whatever else) and your own binaries side by side.
This is fine for debugging, but once I build a **release version**, I really do not want my code to **reference the unit testing framework** any more.
One solution I found is to enclose all your unit tests within #if DEBUG -- #endif directives: when no code references an unit testing assembly, the compiler is clever enough to omit the reference in the compiled code.
Are there any other (possibly more comfortable) options to achieve a similar goal?
|
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 test classes and methods in another project.
One thing to remember if you want to test classes and methods with the 'internal' accessor is to add the following line to the AssemblyInfo.cs file for each project to be tested:
```
[assembly: InternalsVisibleTo("UnitTestProjectName")]
```
|
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 the approach is not good for you but I personally hate using `+`. But, anyway, is it possible to add new methods to the String class in Java?
Thanks and regards.
|
`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 your String as such:
```
MyString StringOne = new MyString("Stringy stuff");
```
and when you need to call a method in the String library, simple do so like this:
```
StringOne.str.equals("");
```
or something similar, and there you have it...extending of the String class.
|
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>
<attribute name="Main-Class" value="MyApplication"/>
</manifest>
</jar>
```
At least, I think that's easy... :-)
The point is that META-INF should be considered an internal Java *meta* directory. Don't mess with it! Any files you want to include with your JAR should be placed in some other sub-directory or at the root of the JAR itself.
|
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 the Java 2 Platform to configure applications, extensions, class loaders and services:
>
> * `MANIFEST.MF`
>
> The manifest file that is used to define extension and package related data.
>
> * `INDEX.LIST`
>
> This file is generated by the new "`-i`" option of the jar tool, which contains location information for packages defined in an application or extension. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.
>
> * `x.SF`
>
> The signature file for the JAR file. 'x' stands for the base file name.
>
> * `x.DSA`
>
> The signature block file associated with the signature file with the same base file name. This file stores the digital signature of the corresponding signature file.
>
> * `services/`
>
> This directory stores all the service provider configuration files.
New since Java 9 implementing [JEP 238](https://openjdk.java.net/jeps/238) are multi-release JARs. One will see a sub folder `versions`. This is a feature which allows to package classes which are meant for different Java version in one jar.
|
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 develop drivers?
* Do you have to do a lot of API hooks, or does C# have the facilities to interface with the kernel without a lot of hackery?
* Can anyone speak to the reliability and safety of running a C# program closer to Ring 0 than would normally be the case?
I want my devices to be usable in C#, and if driver dev in C# is mature that's obviously the way to go, but I don't want to spend a lot of effort there if it's not recommended.
* What are some good resources to get started, say, developing a simple virtual serial port driver?
-Adam
|
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 analyze and JIT the binary during loading prohibits the direct access the driver subsystem needs to load the binary.
There is work underway, however, to lift some device drivers into user mode, you can see an interview [here](http://channel9.msdn.com/posts/Charles/Peter-Wieland-User-Mode-Driver-Framework/) with Peter Wieland of the UDMF (User Mode Driver Framework) team.
User-mode drivers would be much more suited for managed work, but you'll have to google a bit to find out if C# and .NET will be directly supported. All I know is that kernel level drivers are not doable in only C#.
You can, however, probably make a C/C++ driver, and a C# service (or similar) and have the driver talk to the managed code, if you absolutely have to write a lot of code in C#.
|
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 javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.
Your advice, experience and recommendations are appreciated.
|
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 to a URL based on the value of the option:
```
$("#mySelect option").each(function() {
$("<div>" + $(this).text() + "</div>").appendTo($("#myDiv")).bind("click", $(this).val(), function(event) {
location.href = "goto.php?id=" + event.data;
});
});
$("#mySelect").remove();
```
Does this do what you want?
|
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.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#registerKeyboardAction%28java.awt.event.ActionListener,%20java.lang.String,%20javax.swing.KeyStroke,%20int%29).
|
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 like AIR. Yahoo uses it for their [Zimbra](http://www.zimbra.com/) email desktop client.
|
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.CreateInstanceFromAndUnwrap(pathToDll, t.FullName);
```
If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object.
Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.
|
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 interest for exception handling. They are `.eh_frame` and `.gcc_except_table`.
`.eh_frame` follows the DWARF format (the debugging format that primarily comes into play when you're using gdb). It has exactly the same format as the `.debug_frame` section emitted when compiling with `-g`. Essentially, it contains the information necessary to pop back to the state of the machine registers and the stack at any point higher up the call stack. See the Dwarf Standard at dwarfstd.org for more information on this.
`.gcc_except_table` contains information about the exception handling "landing pads" the locations of handlers. This is necessary so as to know when to stop unwinding. Unfortunately this section is not well documented. The only snippets of information I have been able to glean come from the gcc mailing list. See particularly [this post](http://gcc.gnu.org/ml/gcc-help/2010-09/msg00116.html)
The remaining piece of information is then what actual code interprets the information found in these data sections. The relevant code lives in libstdc++ and libgcc. I cannot remember at the moment which pieces live in which. The interpreter for the DWARF call frame information can be found in the gcc source code in the file gcc/unwind-dw.c
|
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/statically-linking-on-aix/) ([documentation about the tree building code](http://gcc.gnu.org/onlinedocs/gccint/GIMPLE-Exception-Handling.html) includes the statement "throwing an exception is not directly represented in GIMPLE, since it is implemented by calling a function").
Unfortunately I'm not familiar with these functions and can't tell you what to look at (other than the source for libgcc -- which includes the exception handling runtime).
There is an "[Exception Handling for Newbies](http://gcc.gnu.org/wiki/Dwarf2EHNewbiesHowto)" document available.
|
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 static org.hamcrest.Matchers.is;
import mockit.Expectations;
import org.testng.annotations.Test;
public class PrimitiveMatcherTest {
private MyClass obj;
@Test
public void testPrimitiveMatcher() {
new Expectations(true) {
MyClass c;
{
obj = c;
invokeReturning(c.getFoo(with(is(false))), "bas");
}
};
assert "bas".equals(obj.getFoo(false));
Expectations.assertSatisfied();
}
public static class MyClass {
public String getFoo(boolean arg) {
if (arg) {
return "foo";
} else {
return "bar";
}
}
}
}
/******************************************************/
```
The line containing the call to invokeReturning(...) throws a NullPointerException.
If I change this call to not use a matcher, as in:
```
invokeReturning(c.getFoo(false), "bas");
```
it works just fine. This is no good for me, because in my real code I'm actually mocking a multi-parameter method and I need to use a matcher on another argument. In this case, the Expectations class requires that **all** arguments use a matcher.
I'm pretty sure this is a bug, or perhaps it's not possible to use Matchers with primitive types (that would make me sad). Has anyone encountered this issue, and know how to get around it?
|
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 call to typeVariable.getClass() does not do what the author expects, and the call to Utilities.defaultValueFor type returns null. The de-autoboxing back the the primitive boolean value is where the NPE comes from.
I fixed it by changing the invokeReturning(...) call to:
```
invokeReturning(withEqual(false)), "bas");
```
I'm no longer using a matcher here, but it's good enough for what I need.
|
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 problem.
But JMockit's Expectation is not using it for matching value, it uses it for some kind of parsing to determine the method call signature type..which in this case the Matchers will resulted in Boolean type while your method is primitive type..so it fails to mock it properly.
I'm sorry that I can not tell you any workaround for this. Maybe somebody else can help.
|
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 impact, however, does anyone know how to get rid of it?
|
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. The fact that the Context
> object in Tomcat has no corresponding
> source property doesn't cause any
> problems.
I realize that this doesn't answer how to get rid of the warning, but I hope it helps.
|
"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 objects writing to the same file descriptor.
The real question is why do you want to convert the `std::fstream` object into a `FILE*`?
Though I don't recommend it, you could try looking up `funopen()`.
Unfortunately, this is **not** a POSIX API (it's a BSD extension) so its portability is in question. Which is also probably why I can't find anybody that has wrapped a `std::stream` with an object like this.
```
FILE *funopen(
const void *cookie,
int (*readfn )(void *, char *, int),
int (*writefn)(void *, const char *, int),
fpos_t (*seekfn) (void *, fpos_t, int),
int (*closefn)(void *)
);
```
This allows you to build a `FILE` object and specify some functions that will be used to do the actual work. If you write appropriate functions you can get them to read from the `std::fstream` object that actually has the file open.
|
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 code that hides all the platform specific grossness, at least for GCC. Given how gross this is just on GCC, I think I'd avoid doing this all together if possible.
|
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 so that I can load and write files to disk?
|
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 void init(final ServletConfig config) {
final String context = config.getServletContext().getRealPath("/");
...
}
...
}
```
|
> *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 is for example located at `WebContent/js/file.js` then you can use the following in your `Servlet` to get a `File` handle of it:
```
File file = new File(getServletContext().getResource("/js/file.js").getFile());
```
or to get an `InputStream`:
```
InputStream input = getServletContext().getResourceAsStream("/js/file.js");
```
That said, how often do you need to minify JS files? I have never seen the need for request-based minifying, it would only unnecessarily add much overhead. You probably want to do it only once during application's startup. If so, then using a `Servlet` for this is a bad idea. Better use [`ServletContextListener`](http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContextListener.html) and do your thing on `contextInitialized()`.
|
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;
}
}
}
```
Please confirm
1. Instance constructors are thread-safe.
2. The lock statement prevents access to that code block, not to the static 'counter' member.
If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a `MyClass` and changing the count before this one sets its count?
*FYI - This class is not a singleton. Instances must simply be aware of their number.*
|
@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.
* Instantiate a new instance of the type.
* Increment the count.
* Unlock and return the new instance.
### EDIT
One problem that has occurred to me, if how would you know when the count has gone down? ;)
### EDIT AGAIN
Thinking about it, you could add code to the destructor that calls another static method to decrement the counter :D
|
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.Interlocked.Increment(myField);
```
More information about threading best practices...
<http://msdn.microsoft.com/en-us/library/1c9txz50.aspx>
|
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 and to be removed from SE in JDK11](http://openjdk.java.net/jeps/320). Therefore, to use JAXB it will either need to be in your existing enterprise class environment bundled by your e.g. app server, or you will need to bring it in manually.
|
[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"`. When a user added a new favorite thread, I'd delete the cache key, and it would recreate the entry.
**However, and here comes the problem:**
I wanted to cache the threads in a forum. Simple enough, "Forum::getThreads|$iForumId". But... With pagination, I'd have to split this into several cache entries, for example
```
"Forum::getThreads|$iForumId|$iLimit|$iOffset".
```
Which is alright, until someone posts a new thread in the forum. I will now have to delete all the keys under `"Forum::getThreads|$iForumId"`, no matter what the limit and offset is.
What would be a good way of solving this problem? I'd really rather not loop through every possible limit and offset until I find something that doesn't match anymore.
Thanks.
|
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 writes are much simpler to implment.
Likewise with the list of a user's favourite threads. If this is something that each person visits rarely then cache might not improve performance too much.
|
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 cache or not. If it is within the cache limit, I use array\_slice() to retrieve the right part and return it.
This way, I can use a single cache key per forum, and it takes very little effort to clear/update the cache :-)
I'd also like to point out that in other more resource heavy queries, I went with flungabunga's model, storing the relations between keys. Unfortunately Stack Overflow won't let me accept two answers.
Thanks!
|
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 autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
```
## Notes:
**Optional Constraint Name:**
If you leave out `CONSTRAINT D_SomeTable_SomeCol` then SQL Server will autogenerate
a Default-Contraint with a funny Name like: `DF__SomeTa__SomeC__4FB7FEF6`
**Optional With-Values Statement:**
The `WITH VALUES` is only needed when your Column is Nullable
and you want the Default Value used for Existing Records.
If your Column is `NOT NULL`, then it will automatically use the Default Value
for all Existing Records, whether you specify `WITH VALUES` or not.
**How Inserts work with a Default-Constraint:**
If you insert a Record into `SomeTable` and do ***not*** Specify `SomeCol`'s value, then it will Default to `0`.
If you insert a Record ***and*** Specify `SomeCol`'s value as `NULL` (and your column allows nulls),
then the Default-Constraint will ***not*** be used and `NULL` will be inserted as the Value.
Notes were based on everyone's great feedback below.
Special Thanks to:
@Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.
|
```
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-package".
I googled around, but I found only "`sys.path` manipulation" hacks. Isn't there a clean way?
---
All my `__init__.py`'s are currently empty
I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.).
The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) ([thanks John B](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python#comment8465_72852)).
|
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 name does not contain any package information (e.g. it is set to '\_\_main\_\_') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
In Python 2.6, they're adding the ability to reference modules relative to the main module. [PEP 366](http://python.org/dev/peps/pep-0366/) describes the change.
|
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 that relative imports works by taking the `__name__` property of the module. If the module is being directly run, then `__name__` is set to `__main__` and it doesn't contain any information about package structure. And, thats why python complains about the `relative import in non-package` error.
So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.
I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)
Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.
|
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 get this to compile on Windows). The library I found was Chris Morley's "XmlRpc++". However, it doesn't have support for SSL.
My question therefore is: what library should I be using?
|
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 result, I only needed 1700 LOC.
* "wininet.lib", and therefore my implementation, supports HTTPS
* Chris Morley's use of STL containers was quite inefficient (Chris, mail me if you read this).
|
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 ported to Windows, but the fact seems to be that no-one has yet done so and made it publicly available. Also, as eczamy says, "The XML-RPC specification is somewhat simple and it would not be difficult to implement your own XML-RPC client."
I'm using Chris Morley's library successfully, despite having had to find and fix quite a number of bugs. The [Help Forum](http://sourceforge.net/forum/forum.php?forum_id=240495 "Help Forum") for this project seems to be somewhat active, but no-one has fixed these bugs and done a new release. I have been in correspondence with Chris Morley and he has vague hopes to do a new release, and he has contributed to this stackOverflow question (see below/above) and he claims to have fixed most of the bugs, but so far he has not made a release that fixes the many bugs. The last release was in 2003.
It is disappointing to me that a supposed widely supported (and simple!) protocol has such poor support on Windows + C++. Please can someone reading this page pick up the baton and e.g. take over XmlRpc++ or properly port one of the Linux implementations.
|
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 absolutely no way of guarenteeing the behaviour that you're looking for and consequently you're best off forgetting about it altogether. Let the user decide how they want their window configured.
|
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 (dependent on what has to be done).
Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down.
Hopefully, something can be implemented globally rather than per page.
|
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 sPage = Request.ServerVariables["SCRIPT_NAME"];
if (!sPage.EndsWith("Maintenance.aspx", StringComparison.OrdinalIgnoreCase))
{
//test the database connection
//if it fails then redirect the user to Maintenance.aspx
string connStr = ConfigurationManager.ConnectionString["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
}
catch(Exception ex)
{
Session["DBException"] = ex;
Response.Redirect("Maintenance.aspx");
}
finally
{
conn.Close();
}
}
}
```
|
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; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName= value; }
}
}
```
Then doing object intialization with.....
```
Person p = new Person{ FirstName = "Joe", LastName = "Smith" };
Person p = new Person{ FirstName = "Joe" };
```
|
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 breaking any constructor fundamentals but using a nice language artifact in order to ease readability and maintainability.
|
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).
```
var v = new { Foo = 1, Bar = "Hi" };
Console.WriteLine(v.Bar);
```
|
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)`](http://java.sun.com/javase/6/docs/api/java/net/URI.html). This will fire up the user's mail client, ready for them to add their comments, and hit send.
I like firing up the email client, because it's what the user is used to, it tells support a whole lot about the user (sigs, contact details etc) and I don't really want [to ship with Java Mail](http://www.catb.org/~esr/jargon/html/Z/Zawinskis-Law.html).
What I'd like to do is attach the log file and the stacktrace as a file, so there is no maximum length requirement, and the user sees a nice clean looking email, and the support department has a lot more information to work with.
Can I do this with the approach I'm taking? Or is there a better way?
**Edit**:
I'm in an OSGi context, so bundling JDIC would be necessary. If possible, I'd like to ship with as few dependencies as possible, and bundling up the JDIC for multiple platforms does not sound fun, especially for such a small feature.
JavaMail may be suitable, but for the fact that this will be on desktops of our corporate clients. The **setup/discovery of configuration** would have to be transparent, automatic and reliable. Regarding JavaMail, configuration seems to be manual only. Is this the case?
The answer I like most is using the `Desktop.open()` for an \*.eml file. Unfortunately **Outlook Express (rather than Outlook) opens eml files**. I have no idea if this is usual or default to have Windows configured for to open EML files like this. Is this usual? Or is there another text based format that a) is easy to generate, b) opens by default in the same email client as users would be using already?
|
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 or second condition of the current if? Like for instance:
```
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith($if1);
}
```
May be a unnecessary way of doing it, but I'm just wondering.
|
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 harder to read, with more nested parentheses.
* Mixing = and == in the same expression is just asking for them to get mixed up.
|
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 `decltype(a)` and `decltype((a))` will generally be different types (and for good and understandable reasons once those reasons are exposed).
Will our trusty `typeid(a).name()` help us explore this brave new world?
No.
But the tool that will is not that complicated. And it is that tool which I am using as an answer to this question. I will compare and contrast this new tool to `typeid(a).name()`. And this new tool is actually built on top of `typeid(a).name()`.
**The fundamental issue:**
```
typeid(a).name()
```
throws away cv-qualifiers, references, and lvalue/rvalue-ness. For example:
```
const int ci = 0;
std::cout << typeid(ci).name() << '\n';
```
For me outputs:
```
i
```
and I'm guessing on MSVC outputs:
```
int
```
I.e. the `const` is gone. This is not a QOI (Quality Of Implementation) issue. The standard mandates this behavior.
What I'm recommending below is:
```
template <typename T> std::string type_name();
```
which would be used like this:
```
const int ci = 0;
std::cout << type_name<decltype(ci)>() << '\n';
```
and for me outputs:
```
int const
```
`<disclaimer>` I have not tested this on MSVC. `</disclaimer>` But I welcome feedback from those who do.
**The C++11 Solution**
I am using `__cxa_demangle` for non-MSVC platforms as recommend by [ipapadop](https://stackoverflow.com/users/487362/ipapadop) in his answer to demangle types. But on MSVC I'm trusting `typeid` to demangle names (untested). And this core is wrapped around some simple testing that detects, restores and reports cv-qualifiers and references to the input type.
```
#include <type_traits>
#include <typeinfo>
#ifndef _MSC_VER
# include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>
template <class T>
std::string
type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> own
(
#ifndef _MSC_VER
abi::__cxa_demangle(typeid(TR).name(), nullptr,
nullptr, nullptr),
#else
nullptr,
#endif
std::free
);
std::string r = own != nullptr ? own.get() : typeid(TR).name();
if (std::is_const<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += "&";
else if (std::is_rvalue_reference<T>::value)
r += "&&";
return r;
}
```
**The Results**
With this solution I can do this:
```
int& foo_lref();
int&& foo_rref();
int foo_value();
int
main()
{
int i = 0;
const int ci = 0;
std::cout << "decltype(i) is " << type_name<decltype(i)>() << '\n';
std::cout << "decltype((i)) is " << type_name<decltype((i))>() << '\n';
std::cout << "decltype(ci) is " << type_name<decltype(ci)>() << '\n';
std::cout << "decltype((ci)) is " << type_name<decltype((ci))>() << '\n';
std::cout << "decltype(static_cast<int&>(i)) is " << type_name<decltype(static_cast<int&>(i))>() << '\n';
std::cout << "decltype(static_cast<int&&>(i)) is " << type_name<decltype(static_cast<int&&>(i))>() << '\n';
std::cout << "decltype(static_cast<int>(i)) is " << type_name<decltype(static_cast<int>(i))>() << '\n';
std::cout << "decltype(foo_lref()) is " << type_name<decltype(foo_lref())>() << '\n';
std::cout << "decltype(foo_rref()) is " << type_name<decltype(foo_rref())>() << '\n';
std::cout << "decltype(foo_value()) is " << type_name<decltype(foo_value())>() << '\n';
}
```
and the output is:
```
decltype(i) is int
decltype((i)) is int&
decltype(ci) is int const
decltype((ci)) is int const&
decltype(static_cast<int&>(i)) is int&
decltype(static_cast<int&&>(i)) is int&&
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int&
decltype(foo_rref()) is int&&
decltype(foo_value()) is int
```
Note (for example) the difference between `decltype(i)` and `decltype((i))`. The former is the type of the *declaration* of `i`. The latter is the "type" of the *expression* `i`. (expressions never have reference type, but as a convention `decltype` represents lvalue expressions with lvalue references).
Thus this tool is an excellent vehicle just to learn about `decltype`, in addition to exploring and debugging your own code.
In contrast, if I were to build this just on `typeid(a).name()`, without adding back lost cv-qualifiers or references, the output would be:
```
decltype(i) is int
decltype((i)) is int
decltype(ci) is int
decltype((ci)) is int
decltype(static_cast<int&>(i)) is int
decltype(static_cast<int&&>(i)) is int
decltype(static_cast<int>(i)) is int
decltype(foo_lref()) is int
decltype(foo_rref()) is int
decltype(foo_value()) is int
```
I.e. Every reference and cv-qualifier is stripped off.
**C++14 Update**
Just when you think you've got a solution to a problem nailed, someone always comes out of nowhere and shows you a much better way. :-)
[This answer](https://stackoverflow.com/a/35943472/576911) from [Jamboree](https://stackoverflow.com/users/2969631/jamboree) shows how to get the type name in C++14 at compile time. It is a brilliant solution for a couple reasons:
1. It's at compile time!
2. You get the compiler itself to do the job instead of a library (even a std::lib). This means more accurate results for the latest language features (like lambdas).
[Jamboree's](https://stackoverflow.com/users/2969631/jamboree) [answer](https://stackoverflow.com/a/35943472/576911) doesn't quite lay everything out for VS, and I'm tweaking his code a little bit. But since this answer gets a lot of views, take some time to go over there and upvote his answer, without which, this update would never have happened.
```
#include <cstddef>
#include <stdexcept>
#include <cstring>
#include <ostream>
#ifndef _MSC_VER
# if __cplusplus < 201103
# define CONSTEXPR11_TN
# define CONSTEXPR14_TN
# define NOEXCEPT_TN
# elif __cplusplus < 201402
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN
# define NOEXCEPT_TN noexcept
# else
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN constexpr
# define NOEXCEPT_TN noexcept
# endif
#else // _MSC_VER
# if _MSC_VER < 1900
# define CONSTEXPR11_TN
# define CONSTEXPR14_TN
# define NOEXCEPT_TN
# elif _MSC_VER < 2000
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN
# define NOEXCEPT_TN noexcept
# else
# define CONSTEXPR11_TN constexpr
# define CONSTEXPR14_TN constexpr
# define NOEXCEPT_TN noexcept
# endif
#endif // _MSC_VER
class static_string
{
const char* const p_;
const std::size_t sz_;
public:
typedef const char* const_iterator;
template <std::size_t N>
CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN
: p_(a)
, sz_(N-1)
{}
CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN
: p_(p)
, sz_(N)
{}
CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;}
CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;}
CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;}
CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;}
CONSTEXPR11_TN char operator[](std::size_t n) const
{
return n < sz_ ? p_[n] : throw std::out_of_range("static_string");
}
};
inline
std::ostream&
operator<<(std::ostream& os, static_string const& s)
{
return os.write(s.data(), s.size());
}
template <class T>
CONSTEXPR14_TN
static_string
type_name()
{
#ifdef __clang__
static_string p = __PRETTY_FUNCTION__;
return static_string(p.data() + 31, p.size() - 31 - 1);
#elif defined(__GNUC__)
static_string p = __PRETTY_FUNCTION__;
# if __cplusplus < 201402
return static_string(p.data() + 36, p.size() - 36 - 1);
# else
return static_string(p.data() + 46, p.size() - 46 - 1);
# endif
#elif defined(_MSC_VER)
static_string p = __FUNCSIG__;
return static_string(p.data() + 38, p.size() - 38 - 7);
#endif
}
```
This code will auto-backoff on the `constexpr` if you're still stuck in ancient C++11. And if you're painting on the cave wall with C++98/03, the `noexcept` is sacrificed as well.
**C++17 Update**
In the comments below [Lyberta](https://stackoverflow.com/users/3624760/lyberta) points out that the new `std::string_view` can replace `static_string`:
```
template <class T>
constexpr
std::string_view
type_name()
{
using namespace std;
#ifdef __clang__
string_view p = __PRETTY_FUNCTION__;
return string_view(p.data() + 34, p.size() - 34 - 1);
#elif defined(__GNUC__)
string_view p = __PRETTY_FUNCTION__;
# if __cplusplus < 201402
return string_view(p.data() + 36, p.size() - 36 - 1);
# else
return string_view(p.data() + 49, p.find(';', 49) - 49);
# endif
#elif defined(_MSC_VER)
string_view p = __FUNCSIG__;
return string_view(p.data() + 84, p.size() - 84 - 7);
#endif
}
```
I've updated the constants for VS thanks to the very nice detective work by Jive Dadson in the comments below.
## Update:
Be sure to check out [this](https://stackoverflow.com/a/56766138/576911) rewrite or [this](https://stackoverflow.com/a/64490578/576911) rewrite below which eliminate the unreadable magic numbers in my latest formulation.
|
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 there a way in SQL to easily remove the leading zeroes in this way? I know there is an `RTRIM` function, but this seems only to remove spaces.
|
```
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 classes and they didn't enumerate)
|
[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 problem. My code is the following:
```
<?php
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
// Perform a POST
curl_setopt($ch, CURLOPT_POST, 1);
// If not set, curl prints output to the browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
// Set the "form fields"
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$output = curl_exec($ch);
curl_close($ch);
?>
```
All this does is grab the content of the URL passed through, and doesn't forward the user anywhere. I've tried Googling and reading up as much as I can, but can't figure out what i'm missing. Any ideas? I don't want to have to create a HTML form that auto-submits itself if I can avoid it.
Thanks for any help :-)
|
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="OnLoadEvent();">
<form name="downloadForm" action="<%=RedirURL%>" method="POST">
<noscript>
<br>
<br>
<div align="center">
<h1>Processing your 3-D Secure Transaction</h1>
<h2>JavaScript is currently disabled or is not supported by your browser.</h2><BR>
<h3>Please click Submit to continue the processing of your 3-D Secure transaction.</h3><BR>
<input type="submit" value="Submit">
</div>
</noscript>
<input type="hidden" name="PaReq" value="<%=PAREQ%>">
<input type="hidden" name="MD" value="<%=TransactionID%>">
<input type="hidden" name="TermUrl" value="<%=TermUrl%>">
</form>
<SCRIPT LANGUAGE="Javascript">
<!--
function OnLoadEvent() {
document.downloadForm.submit();
}
//-->
</SCRIPT>
</body>
</html>
```
|
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 Javascript solution to do such a thing.
|
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 accessing.
In this case what purpose does the above fulfil ??
|
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> {
// look, overridden!
List<AResult> getResult();
}
class BTest implements ITest<BResult> {
// overridden again!
List<BResult> getResult();
}
```
It's a good solution, when you need "covariant returns", but you return collections instead of your own objects. The big plus is that you don't have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned - as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List<AResult> (returned as List<? extends T>), which doesn't make any sense.
So you have to remember this: List<? extends X> defines a list that could be easily overridden, but which is read-only.
|
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.pdf>
More information about the book (and the author) are available: <http://java.sun.com/docs/books/effective/>
|
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 parse the string using API to determine the pattern so I could reuse this for different patterns of date output
If anyone knows a solution using API or a custom solution I would greatly appreciate it.
|
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 advance what the format is.
|
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-difference-between-countcolumn-and-count))
|
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), COUNT('this is a silly conversation')`
Moreover, `SELECT(1) vs SELECT(*)` will NOT have any difference in INDEX usage -- most DBMS will actually optimize `SELECT( n ) into SELECT(*)` anyway. See the ASK TOM: Oracle has been optimizing `SELECT(n) into SELECT(*)` for the better part of a decade, if not longer:
<http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789>
> problem is in count(col) to count(*)
> conversion* \*\*03/23/00 05:46 pm \*\*\* one workaround is to set event 10122 to
> turn off count(col) ->count(*)
> optimization. Another work around is
> to change the count(col) to count(*),
> it means the same, when the col has a
> NOT NULL constraint. The bug number is
> 1215372.
One thing to note - if you are using COUNT(col) (don't!) and col is marked NULL, then it will actually have to count the number of occurrences in the table (either via index scan, histogram, etc. if they exist, or a full table scan otherwise).
Bottom line: if what you want is the count of rows in a table, use COUNT(\*)
|
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 the example above, if the column you are grouping on has an index the server should be able to satisfy the query without hitting the actual table at all.
To clarify: this answer refers specifically to SQL Server. I don't know how other DBMS products handle this.
|
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" VerticalContentAlignment="Top" Padding="0" Margin="0">
<System_Windows_Controls:TabItem Header="Test" VerticalContentAlignment="Top" BorderThickness="0" Margin="0" Padding="0" HorizontalContentAlignment="Left">
<ContentControl>
<Grid Width="400" Height="200" Background="White"/>
</ContentControl>
</System_Windows_Controls:TabItem>
</System_Windows_Controls:TabControl>
```
will produce:

How do I position the content at 0,0?
|
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 hit to your productivity or any particular issues which you found challenging?
|
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 cause utter frustration.
ETA: the reason I say to just start from scratch is because sometimes it's easier to learn new concepts if you go in with a clean slate. In the past, I've discovered that I can be my own worst enemy when it comes to learning something new if I try to carry knowledge from technology to technology (e.g. thinking that doing asmx web services for years precludes me from reading the first couple chapters of a WCF book).
|
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 practices in the web world would find the transition much more natural.
There was definitely a significant hit to my productivity (so significant that I'm not yet comfortable with the idea of going to my employer and saying "let me do this with WPF instead of Winforms"). I don't think that I'll never get there, but I need to develop some additional comfort with the technology through practice in my personal time.
I didn't run into any particular issues that I found to be more challenging than any others. I believe [Adam Nathan](http://blogs.msdn.com/Adam_Nathan/)'s [WPF Unleashed](https://rads.stackoverflow.com/amzn/click/com/0672328917) was mentioned elsewhere, and that's definitely a worthwhile read. I've also heard good things about [Charles Petzold's](http://www.charlespetzold.com/blog/blog.xml) [book](https://rads.stackoverflow.com/amzn/click/com/0735619573), though I can't personally vouch for it.
|
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 part of the Java API)
* Write Useful Exceptions (if you have to write your own Exceptions, make sure they provide useful information about the problem that occurred)
|
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 Bloch covers this in *Effective Java Programming Language Guide* [my bible of first resort on Best Practices] **Chapter 8. Exceptions** *Item 42: Favor the use of standard exceptions*. Here's a bit of what he says,
> Reusing preexisting exceptions has several benefits. Chief among these, it makes your API easier to learn and use because **it matches established conventions with which programmers are already familiar** [*my emphasis, not Bloch's*]. A close second is that programs using your API are easier to read because they aren't cluttered with unfamiliar exceptions. Finally, fewer exception classes mean a smaller memory footprint and less time spent loading classes.
>
> The most commonly reused exception is IllegalArgumentException. This is generally the exception to throw when the caller passes in an argument whose value is inappropriate. For example, this would be the exception to throw if the caller passed a negative number in a parameter representing the number of times some action were to be repeated.
That said, you should **never** throw Exception itself. Java has a well-chosen, diverse and well-targeted bunch of built-in exceptions that cover most situations **AND** describe the exception that occurred well enough so that you can remedy the cause.
Be friendly to the programmers who have to maintain your code in the future.
|
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(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
```
In the end I have written functions like this:
```
def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
```
I can't help thinking that I'm missing an easier way to do this though.
### Related
* [python time + timedelta equivalent](https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent)
|
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 in the two values, three seconds apart:
```
11:34:59
11:35:02
```
You could also opt for the more readable
```
b = a + datetime.timedelta(seconds=3)
```
if you're so inclined.
---
If you're after a function that can do this, you can look into using `addSecs` below:
```
import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)
```
This outputs:
```
09:11:55.775695
09:16:55
```
|
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 required. Consider what would happen if I added 2 hours to 11pm. What's the correct behavior? An exception, because you can't have a time larger than 11:59pm? Should it wrap back around?
Different programmers will expect different things, so whichever result they picked would surprise a lot of people. Worse yet, programmers would write code that worked just fine when they tested it initially, and then have it break later by doing something unexpected. This is very bad, which is why you're not allowed to add timedelta objects to time objects.
|
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 details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?
|
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 newdiv = document.createElement('div');
newdiv.innerHTML = str;
document.getElementById('target').appendChild(newdiv);
}
</script>
</head>
<body>
<input type="button" value="add script" onclick="addScript()"/>
<div>hello world</div>
<div id="target"></div>
</body>
</html>
```
|
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++)
--- Wrap-up for Module: test_unused.cpp
Info 752: local declarator 'foo(int)' (line 2, file test_unused.cpp) not referenced
test_unused.cpp(2) : Info 830: Location cited in prior message
============================================================
```
So you can pass the warning number 752 for your puropse:
```
lint.bat -"e*" +e752 test_unused.cpp
```
-e"\*" will remove all the warnings and +e752 will turn on this specific one
|
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 FileWatcher is not required but it could be useful.
```
class PersistentDictionary<T,V> : IDictionary<T,V>
{
public PersistentDictionary(string filename)
{
}
}
```
Requirements:
* Open Source, with no dependency on native code (no sqlite)
* Ideally a very short and simple implementation
* When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value.
**Similar Questions**
* [Persistent Binary Tree / Hash table in .Net](https://stackoverflow.com/questions/108435/persistent-binary-tree-hash-table-in-net)
* [Disk backed dictionary/cache for c#](https://stackoverflow.com/questions/408401/disk-backed-dictionary-cache-for-c)
* [`PersistentDictionary<Key,Value>`](http://izlooite.blogspot.com/2011/04/persistent-dictionary.html)
|
* [**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 **store string keys associated with values permanently**.
* [**ESENT Managed Interface**](http://www.codeplex.com/ManagedEsent)
*Not 100% managed code but it's worth mentioning it as unmanaged library itself is already part of every windows XP/2003/Vista/7 box*
ESENT is an embeddable database storage engine (ISAM) which is part of Windows. It provides reliable, transacted, concurrent, high-performance data storage with row-level locking, write-ahead logging and snapshot isolation. This is a managed wrapper for the ESENT Win32 API.
* [**Akavache**](https://github.com/github/Akavache)
\*Akavache is an asynchronous, persistent key-value cache created for writing native desktop and mobile applications in C#. Think of it like memcached for desktop apps.
- [**The C5 Generic Collection Library**](http://www.itu.dk/research/c5/)
C5 provides functionality and data structures not provided by the standard .Net `System.Collections.Generic` namespace, such as **persistent tree data structures**, heap based priority queues, hash indexed array lists and linked lists, and events on collection changes.
|
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 your requirements, because I think it will be difficult to meet them all.
|
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 API so that my custom code doesn't get mingled with the core code or which ones have a well thought through template system so that I can easily customize it for each new client?
|
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 probably at a bit higher level than you seem to be asking, Drupal is a very attractive platform. It is a CMS at its base, and using [ecommerce](http://drupal.org/project/ecommerce) or [Ubercart](http://www.ubercart.org/) you can turn it into a store. With modules like [CCK](http://drupal.org/project/cck) and [Views](http://drupal.org/project/views) you can build very sophisticated ecommerce sites (specialized product types, attributes) with very little coding, plus you get all the CMS tools (editing, access control, etc) for free. If you write your own modules, you can hook into almost anything in Drupal without touching the core code, and you get a ton of flexibility.
Though a lot of developers may not consider it simply because they're stuck in this view that they should write something from scratch, Drupal is a really great development platform for this sort of thing. There is definitely a learning curve to it, especially when you need to write modules for it, but the time it takes to learn and implement a site is still probably less than writing a very customized ecommerce site from scratch.
|
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 addons, for different payment-providers and other things, and the built-in download-manager handles the installation of these, as well as upgrades to the core code, really well.
Compared to something like OSCommerce though, it wins hands down.
|
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 examples used US-ASCII and UTF-8, two commonly-used encodings.
|
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.getBytes(UTF8_CHARSET);
}
```
|
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. A parent table, with child and grandchild tables, let's say.
I want to **copy a set of rows from database A to database B**, which has identically named tables and fields. For each table, I want to insert into the same table in database B. But I can't be constrained to use the same primary keys. **The copy routine must create new PKs** for each row in database B, and must propagate those to the child rows. I'm keeping the same relations between the data, in other words, but not the same exact PKs and FKs.
How would you solve this? I'm open to suggestions. SSIS isn't completely ruled out, but it doesn't look to me like it'll do this exact thing. I'm also open to a solution in LINQ, or using typed DataSets, or using some XML thing, or just about anything that'll work in SQL Server 2005 and/or C# (.NET 3.5). The best solution wouldn't require SSIS, and wouldn't require writing a lot of code. But I'll concede that this "best" solution may not exist.
(I didn't make this task up myself, nor the constraints; this is how it was given to me.)
|
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 hierarchically and refresh PKs from the database after insert.
|
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 worry about unicode & ASCII clashing?
|
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 identical to ASCII-encoding when the byte-values are between 0 and 127. They only differ when the top-bit is set.
|
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?
---
PS: We've a DAO library that's not very sophisticated. I doubt that it has Hibernate's richness, but it's reaching some sort of maturity (i.e. it's not been changed in the last few projects it's included).
|
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 looked at in the past few years involved Spring, it's really become the de-facto standard for Java/web. Using it will help your developers be more marketable in the future, and it'll help you as you'll have a large pool of people who'll understand your application.
Writing your own framework is tempting, educational, and fun. Not so great on results.
|
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. Objects need to be able to contain pointers to each-other, even to objects on remote servers. I'm trying to think of the best way to update references to moved objects.
My two ideas so far are:
1. Maintain a reference indirection somewhere that doesn't move for the lifetime of the object, which we update if the object moves. But - how are these indirections managed?
2. Keep a list of reverse-references with each object, so we know what has to be updated if the object is moved. Of course, this creates a performance overhead.
I'd be interested in feedback on these approaches, and any suggestions for alternative approaches.
|
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 object is live.
So, at this stage is has to touch all of the live objects anyway, as it copies them from the old heap to the new heap. Once the copy of the live objects is done, all that remains in the old heap are either objects already copied, or garbage. At that point the old heap can be discarded completely.
The two primary benefits of this kind of collector are that it compacts the heap during the copy phase, and that it only copies living objects. This is important to many systems because with this kind of collector, object allocation is dirt cheap, literally little more than incrementing a heap pointer. When GC happens, none of the "dead" objects are copied, so they don't slow the collector down. It also turns out in dynamic systems that there's a lot more little, temporary garbage, than there is long standing garbage.
Also, by walking the live object graph, you can see how the GC can "know" about every object, and keep track of them for any address adjustment purposes performed during the copy.
This is not the forum to talk deeply about GC mechanics, as it's a non-trivial problem, but that's the basics of how a copying collector works.
A generational copying GC will put "older" objects in different heaps, and those end up being collected less often than "newer" heaps. The theory is that the long lasting objects get promoted to older generations and get collected less and less, improving overall GC performance.
|
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 assume that the garbage collector freezes all threads, relocates the object, searches heap and stack for all references to that object, and updates them with the new address. Actually it's more complex than that, since for performance reasons you don't want to perform a full sweep with threads stalled, so an incremental garbage collector will do work in preparation for compaction whenever it can.
If you're interested in indirect references, you could start by researching weak and soft references in Java, and also the remote references used by various RPC systems.
|
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 IE, the form in sourceBox is duplicated in newBox, complete with user-supplied values. In Firefox, last value entered in the orginal sourceBox is not present in newBox. How do I make this "stick?"
|
[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);
newBox.innerHTML = sourceBox.innerHTML;
}
newBox.id = newkey;
document.getElementById('boxes').appendChild(newBox);
```
|
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.0
|
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 needed? Say I want this constructor:
```
public MyClass(MyOtherClass inputObject)
{
Guid inputId = inputObject.ID;
MyThirdClass mc = inputObject.CreateHelper();
string inputText = mc.Text;
mc.Dispose();
// Need to call the main Constructor now with inputId and inputText
}
```
The caveat here is that I need to create an object that **has** to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection)
However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one?
Or is it possible to use
```
public MyClass(MyOtherClass inputObject): this(inputObject.ID,
inputObject.CreateHelper().Text)
{}
```
Would this automatically Dispose the generated Object from CreateHelper()?
**Edit:** Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0...). I do control my own class though, and since I've just started writing it, I have no problem refactoring the constructors if there is a good approach.
|
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(inputObject) {}
private static string GetHelperText(MyOtherClass o)
{
using (var helper = o.CreateHelper())
return helper.Text;
}
```
|
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 to do, but the whole thing feels like it could benefit from some refactoring. That is usually the case in my own code when I find myself trying to bend over backwards to create a constructor overload.
If you have control over MyOtherClass, why not simplify the access to that text property by adding a getter method that handles the dispose:
```
public class MyOtherClass
{
//...
public string GetText()
{
using (var h = CreateHelper())
return h.Text;
}
}
```
if you don't control MyOtherClass you could use an extension method
```
public static class MyOtherClassExtensions
{
public static string GetText(this MyOtherClass parent)
{
using(var helper = parent.CreateHelper())
{
return helper.Text;
}
}
}
```
Then, of course, in your constructor you can safely call
```
public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.GetText()) {}
```
|
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 relationship to ProductTypes.
I'd like to have a databound DataGridView where each row represents an orderline, displaying the line's product and producttype.
Users can add or edit orderlines direct to the grid and choose the product for the order line from a comboBoxColumn - this should then update the producttype column, showing the producttype for the selected product, in the same row.
The closest to a good fit that I've found so far is to introduce a domain object representing an orderline then bind the DataGridView to a collection of these orderlines. I then add properties to the orderline object that expose the product and the producttype, and raise relevant notifypropertychanged events to keep everything up to date. In my orderline repository I can then wire up the mappings between this orderline object and the three tables in my database.
This works for the databinding side of things, but having to hand code all that OR-mapping in the repository seems bad. I thought nHibernate would be able to help with this wiring up but am struggling with the mappings through all the foreign keys - they seem to work ok (the foreignkey lookup for an orderline's product creates the correct product object based on the foreign key) until I try to do the databinding, I can't get the databound id columns to update my product or producttype objects.
Is my general approach even in the right ballpark? If it is, what is a good solution to the mapping problem?
Or, is there a better solution to databinding rows including foreign key lookups that I haven't even considered?
|
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 and return true for the [SupportsChangeNotification](http://msdn.microsoft.com/en-us/library/system.componentmodel.ibindinglist.supportschangenotification.aspx) property. If you don't return true for this, the grid won't look for it to know if the data has changed.
In .NET 2.0+, you can create a generic collection using the [BindingList](http://msdn.microsoft.com/en-us/library/ms132679.aspx) class, this will take care of most of the nastiness (just don't forget to override and return true for the SupportsChangeNotification property).
If the class you use for data binding has a property that is a collection (such as IBindingList or BindingList), then you can bind the foreign key grid to that property directly. When you configure the bindings in the Forms designer, just select the collection property as the data source for the grid. It should "just work". The only sneaky part is making sure that you handle empty or null collections the right way.
|
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 be the key value in the order line), the display member is the value that is displayed to the user instead of the value (this will be the FK value).
Is there no particular reason you cannot just return all the data required and set these properties?
|
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">
<child value="b1"/>
<child value="b2"/>
<child value="b3"/>
</parent>
</elements>
```
I want to be able to do something like:
```
>>> getValues("CategoryA")
['a1', 'a2', 'a3']
>>> getValues("CategoryB")
['b1', 'b2', 'b3']
```
It looks like a job for XPath but I'm open to all recommendations. I'd also like to hear about your favourite Python XML libraries.
|
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"/>
<child value="b2"/>
<child value="b3"/>
</parent>
</elements>"""
doc = libxml2.parseDoc(DOC)
def getValues(cat):
return [attr.content for attr in doc.xpathEval("/elements/parent[@name='%s']/child/@value" % (cat))]
print getValues("CategoryA")
```
With result...
```
['a1', 'a2', 'a3']
```
|
[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']" % category)
return [child.get('value') for child in parent]
```
Then you can do
```
>>> tree = xml.parse('data.xml')
>>> getValues(tree, 'CategoryA')
['a1', 'a2', 'a3']
>>> getValues(tree, 'CategoryB')
['b1', 'b2', 'b3']
```
`lxml.etree` (which also provides the ElementTree interface) will also work in the same way.
|
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 implementations described in the answers, but for tuples used as keys in dictionaries you should additionaly verify correct calculation of the hash code. Some more info on that in another [question](https://stackoverflow.com/questions/102690/how-does-c-figure-out-the-hash-code-for-an-object).
**Update 2** I guess it is also worth reminding, that when you use some value as a key in dictionary, it should be immutable.
|
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 implementation. This is the class that the
generic Dictionary uses internally.
Alternatively, you may be able to make do with the
**[System.Collections.DictionaryEntry](http://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry.aspx)**
structure that acts as a rudimentary pair and has the advantage of
being available in mscorlib. On the down side, however, is that this structure is not
strongly typed.
Pairs and Triples are also available in the form of the
**[System.Web.UI.Pair](http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx)** and
**[System.Web.UI.Triplet](http://msdn.microsoft.com/en-us/library/system.web.ui.triplet.aspx)** classes. Even though theses classes live in the the *System.Web* assembly
they might be perfectly suitable for winforms development. However, these classes are
not strongly typed either and might not be suitable in some scenarios, such as a general purposed framework or library.
***Higher order tuples***
For higher order tuples, short of rolling your own class, there may
not be a simple solution.
If you have installed the
[F# language](http://research.microsoft.com/fsharp/fsharp.aspx), you could reference the *FSharp.Core.dll* that contains a set of generic immutable
**[Microsoft.Fsharp.Core.Tuple](http://research.microsoft.com/fsharp/manual/export-interop.aspx?0sr=a#Tuples)** classes
up to generic sextuples. However, even though an unmodified *FSharp.Code.dll*
can be redistributed, F# is a research language and a work in progress so
this solution is likely to be of interest only in academic circles.
If you do not want to create your own class and are uncomfortable
referencing the F# library, one nifty trick could consist in extending the generic KeyValuePair class so that the Value member is itself a nested KeyValuePair.
For instance, the following code illustrates how you could leverage the
KeyValuePair in order to create a Triples:
```
int id = 33;
string description = "This is a custom solution";
DateTime created = DateTime.Now;
KeyValuePair<int, KeyValuePair<string, DateTime>> triple =
new KeyValuePair<int, KeyValuePair<string, DateTime>>();
triple.Key = id;
triple.Value.Key = description;
triple.Value.Value = created;
```
This allows to extend the class to any arbitrary level as is required.
```
KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string> quadruple =
new KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>();
KeyValuePair<KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>, string> quintuple =
new KeyValuePair<KeyValuePair<KeyValuePair<KeyValuePair<string, string>, string>, string>, string>();
```
## **Roll Your Own**
In other cases, you might need to resort to rolling your own
tuple class, and this is not hard.
You can create simple structures like so:
```
struct Pair<T, R>
{
private T first_;
private R second_;
public T First
{
get { return first_; }
set { first_ = value; }
}
public R Second
{
get { return second_; }
set { second_ = value; }
}
}
```
## **Frameworks and Libraries**
This problem has been tackled before and general purpose frameworks
do exist. Below is a link to one such framework:
* [Tuple Library](http://www.adventuresinsoftware.com/generics/) by
[Michael L Perry](https://stackoverflow.com/users/7668/michael-l-perry).
|
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: audit(1222063316.536:777): avc: denied { getattr } for pid=4851 comm="sh" name="var" dev=dm-0 ino=114241 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:var\_t tclass=dir
> Sep 22 15:01:56 ri kernel: audit(1222063316.549:778): avc: denied { setrlimit } for pid=4851 comm="sudo" scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=process
> Sep 22 15:01:56 ri kernel: audit(1222063316.565:779): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:shadow\_t tclass=file
> Sep 22 15:01:56 ri kernel: audit(1222063316.568:780): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:shadow\_t tclass=file
> Sep 22 15:01:56 ri kernel: audit(1222063316.571:781): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability
> Sep 22 15:01:56 ri kernel: audit(1222063316.574:782): avc: denied { setuid } for pid=4851 comm="sudo" capability=7 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability
> Sep 22 15:01:56 ri kernel: audit(1222063316.577:783): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability
In my visudo, I added those lines
> User\_Alias WWW=apache
>
> WWW ALL=(ALL) NOPASSWD:ALL
Can you please help me ? Am I doing something wrong ?
Thanks for your help,
tiBoun
|
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 SELinux to be permissive instead. I'd suggest the former.
|
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 and Linux.
[Py2app](http://pypi.python.org/pypi/py2app/) works on the Mac.
|
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 Windows,
> packaging command line tools and
> services using py2exe and InnoSetup.
> I'll demonstrate a simple build script
> which creates windows binaries and an
> InnoSetup installer in one step. In
> addition, I'll go over common errors
> which come up when using py2exe and
> hints on troubleshooting them. This is
> a short talk, so there will be a
> follow-up Open Space session to share
> experience and help each other solve
> distribution problems.
|
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!");
```
I received the following error:
MessageBox is a 'type' but used as a 'variable'
Fair enough, it seems in C# MessageBox is an Object. I tried the following
```
MessageBox a = new MessageBox("Hello, World!");
```
I received the following error:
MessageBox does not contain a constructor that takes '1' arguments
Now I am stumped. Please help.
|
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 behaviour here
}
```
which I guess is a bit unwieldy but it gets the job done.
See <https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult> for additional enum options you can use here.
|
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. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.
|
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 collection)
{
// ...
i++;
}
```
|
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://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx).
This Enumerator has a method and a property:
* `MoveNext()`
* `Current`
`Current` returns the object that Enumerator is currently on, `MoveNext` updates `Current` to the next object.
The concept of an index is foreign to the concept of enumeration, and cannot be done.
Because of that, most collections are able to be traversed using an indexer and the for loop construct.
I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.
|
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 index (`item.i`) by using [this overload of LINQ's `Select`](https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx):
> the second parameter of the function [inside Select] represents the index of the source element.
The `new { i, value }` is creating a new [anonymous object](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types).
Heap allocations can be avoided by using `ValueTuple` if you're using C# 7.0 or later:
```
foreach (var item in Model.Select((value, i) => ( value, i )))
{
var value = item.value;
var index = item.i;
}
```
You can also eliminate the `item.` by using automatic destructuring:
```
foreach (var (value, i) in Model.Select((value, i) => ( value, i )))
{
// Access `value` and `i` directly here.
}
```
|
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 the window which created it.
Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.
|
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 need to wait for the new page to load anyway, so that you can access its elements, or whatever you want.
|
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.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if (line.contains(serviceName)) {
return true;
}
}
return false;
}
public static void killProcess(String serviceName) throws Exception {
Runtime.getRuntime().exec(KILL + serviceName);
}
```
EXAMPLE:
```
public static void main(String args[]) throws Exception {
String processName = "WINWORD.EXE";
//System.out.print(isProcessRunning(processName));
if (isProcessRunning(processName)) {
killProcess(processName);
}
}
```
|
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 12/31/9999 12:00:00 AM
```
I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress.
How would I do this using Transact-SQL?
|
```
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 running. That way, you could do this:`
```
SELECT SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes
FROM task
```
|
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 particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else".
A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization.
I don't like that solution for two reasons:
1. To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization!
2. The stack to resolve that
mess was 10 to 12 function invocations.
I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one)
Can you give me a hint to solve this puzzle?
|
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 {};
template<typename U> static char Test(SFINAE<U, &U::used_memory>*);
template<typename U> static int Test(...);
static const bool Has = sizeof(Test<T>(0)) == sizeof(char);
};
template<typename TMap>
void ReportMemUsage(const TMap& m, std::true_type)
{
// We may call used_memory() on m here.
}
template<typename TMap>
void ReportMemUsage(const TMap&, std::false_type)
{
}
template<typename TMap>
void ReportMemUsage(const TMap& m)
{
ReportMemUsage(m,
std::integral_constant<bool, HasUsedMemoryMethod<TMap>::Has>());
}
```
|
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`:
```
#include <type_traits>
// Primary template with a static assertion
// for a meaningful error message
// if it ever gets instantiated.
// We could leave it undefined if we didn't care.
template<typename, typename T>
struct has_serialize {
static_assert(
std::integral_constant<T, false>::value,
"Second template parameter needs to be of function type.");
};
// specialization that does the checking
template<typename C, typename Ret, typename... Args>
struct has_serialize<C, Ret(Args...)> {
private:
template<typename T>
static constexpr auto check(T*)
-> typename
std::is_same<
decltype( std::declval<T>().serialize( std::declval<Args>()... ) ),
Ret // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>::type; // attempt to call it and see if the return type is correct
template<typename>
static constexpr std::false_type check(...);
typedef decltype(check<C>(0)) type;
public:
static constexpr bool value = type::value;
};
```
Usage:
```
struct X {
int serialize(const std::string&) { return 42; }
};
struct Y : X {};
std::cout << has_serialize<Y, int(const std::string&)>::value; // will print 1
```
|
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 management.
|
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 markup would be acceptable.
I am also considering using WPF Imaging so if anyone can weigh in comments about its use (particularly tools you would point your users to for creating WPF layouts you can convert into images and how well it performs) it would be appreciated.
My order of preference is:
1. open source
2. high performance
3. native C# or C# wrapper
4. lowest complexity for implementation on Windows
I'm not very worried about how feature rich the headless rendering is since we won't make big use of JavaScript, Flash, nor other embedded objects aside from images. I'd be fine with anything that uses IE, Firefox, webkit, or even a custom rendering implementation so long as its implementation is close to standards compliant.
|
<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 do so my compiled EXE works on XP and Vista? I had this same problem a few months ago, and just fiddling with some settings on the project fixed it, but I don't remember which ones I changed.
|
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 -> Runtime
> Library and select "multi-threaded
> /MT"
|
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 distribute these dependencies if you are using Visual Studio 2005 or 2008.
As stated in the article, though you can download the Redistributable installer package and simply launch that on the client machine, that is almost always not the optimal option. There are usually better ways to include the required DLLs such as including the merge module if you are distributing via Windows Setup or App-Local copy if you just want to distribute a zipped folder.
Another option is to statically link against the runtime libraries, instead of distributing them with your application. This option is only suitable for standalone EXEs that do not load other DLLs. You also cannot do this with DLLs that are loaded by other applications.
|
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 "somevalue".
|
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 talking about a webservice and not just plain XML. In your Visual Studio Solution, try right clicking on References in Solution Explorer and choose "Add a Web Reference". A dialog will appear asking for a URL, you can just paste it in: "<http://www.webservice.com/webservice.asmx>". VS will autogenerate all the helpers you need. Then you can just call:
```
com.webservice.www.WebService ws = new com.webservice.www.WebService();
// this assumes your web method takes in the fXML as an integer attribute
return ws.SomeWebMethod(1);
```
|
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.Message.Contains("Timeout"))
{
//handle timeout
}
else
{
throw;
}
}
```
|
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 System.Data.SqlClient.TdsEnums for TIMEOUT\_EXPIRED.
Your code would read:
```
if (ex.Number == -2)
{
//handle timeout
}
```
Code to demonstrate failure:
```
try
{
SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
sql.Open();
SqlCommand cmd = sql.CreateCommand();
cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
cmd.ExecuteNonQuery(); // This line will timeout.
cmd.Dispose();
sql.Close();
}
catch (SqlException ex)
{
if (ex.Number == -2) {
Console.WriteLine ("Timeout occurred");
}
}
```
|
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:
```
a = b, c; // a is set to the value of b!
a = (b, c); // a is set to the value of c!
```
This question was actually inspired by a typo in code. What was intended to be
```
a = b;
c = d;
```
Turned into
```
a = b, // <- Note comma typo!
c = d;
```
|
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/Sequence_point). This means that the expression:
```
a+b, c(), d
```
is guaranteed to have its three subexpressions (**a+b**, **c()** and **d**) evaluated in order. This is significant if they have side-effects. Normally compilers are allowed to evaluate subexpressions in whatever order they find fit; for example, in a function call:
```
someFunc(arg1, arg2, arg3)
```
arguments can be evaluated in an arbitrary order. Note that the commas in the function call are *not* operators; they are separators.
|
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 into this site automatically?
Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit
|
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 found that GreaseMonkey has a a function built into it where you can send GET / POST requests to the server called GM\_xmlhttpRequest
<http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html>
So putting it all together (and also getting this JavaScript code to convert strings into base64 I get the following
<http://www.webtoolkit.info/javascript-base64.html>
```
var loggedInText = document.getElementById('metanav').firstChild.firstChild.innerHTML;
if (loggedInText != "logged in as jklp") {
var username = 'jklp';
var password = 'jklpPass';
var base64string = Base64.encode(username + ":" + password);
GM_xmlhttpRequest({
method: 'GET',
url: 'http://foo.com/trac/login',
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
'Accept': 'application/atom+xml,application/xml,text/xml',
'Authorization':'Basic ' + base64string,
}
});
}
```
So when I now visit the site, it traverses the DOM and if I'm not logged in, it automagically logs me in.
|
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 give your login into on the url like so:
```
http://username:password@host/
```
Of course, saving this in a bookmark may be a security risk, but not more-so than saving your password in the browser.
|
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 of choices I have yet to make is whether I want to use Axis2 for the wsdl-to-java functionality or use WebLogic's clientgen (wsdl 2 java) solution. I guess I can also use JAX-WS and wsimport. Before I dive into this, I wanted to see if anyone was doing this successfully with one of the many options available.
In the past, I've had a few issues on how null/blank/empty's are handled between .NET and Java web-services and I just wanted to see if this had come up as an issue with SSRS and Java integration. Thanks
|
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 RS and even on top of the line hardware it's hard to run large reports (large number of rows returned and a wide result set).
That being said if you think RS can handle your usage then it might be good. The development environment is sort of nice and it's easy to understand and lay out reports. The table layout paradigm it has is pretty good.
|
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 Axis2 or HttpClient's NTML authentication mechanism to have my application automatically 'log-in' using credentials from Active Directory and generate and distribute reports to many users.
|
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 dependencies are preferred.
Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to\_str() member function for A.
In pseudocode:
```
class A {
public:
...
void print(FILE* f);
B b;
...
};
...
void A::print(FILE *f)
{
std::string s = "stuff";
fprintf(f, "some %s", s);
b.print(f);
}
class C {
...
std::string foo;
bool set_foo(std::str);
...
}
...
A a = new A();
C c = new C();
...
// wish i knew how to write A's to_str()
c.set_foo(a.to_str());
```
I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE\* F) interface also needs to be preserved. I have considered several approaches to implementing A::to\_str(), each with advantages and disadvantages:
1. Change the calls to fprintf() to sprintf()
* I wouldn't have to rewrite any format strings
* print() could be reimplemented as: fprint(f, this.to\_str());
* But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string
2. Try to catch the results of a.print() in a string stream
* I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{
* print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though [this guy says it may be possible](http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html)).
3. Use Boost's string [format library](http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html)
* More external dependencies. Yuck.
* Format's syntax is different enough from printf() to be annoying:
printf(format\_str, args) -> cout << boost::format(format\_str) % arg1 % arg2 % etc
4. Use Qt's [QString::asprintf()](https://doc.qt.io/qt-5/qstring.html#asprintf%3E)
* A different external dependency.
So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?
Thanks.
|
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:
```
sprintf(buffer, "This is a string with some %s and %d numbers", "strings", 42);
```
would be something like this with the boost::format library:
```
string = boost::str(boost::format("This is a string with some %s and %d numbers") %"strings" %42);
```
Hope this helps clarify the usage of boost::format
I've used boost::format as a sprintf / printf replacement in 4 or 5 applications (writing formatted strings to files, or custom output to logfiles) and never had problems with format differences. There may be some (more or less obscure) format specifiers which are differently - but I never had a problem.
In contrast I had some format specifications I couldn't really do with streams (as much as I remember)
|
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 <vector>
#include <string>
std::string
format (const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
std::string buf = vformat (fmt, ap);
va_end (ap);
return buf;
}
std::string
vformat (const char *fmt, va_list ap)
{
// Allocate a buffer on the stack that's big enough for us almost
// all the time.
size_t size = 1024;
char buf[size];
// Try to vsnprintf into our buffer.
va_list apcopy;
va_copy (apcopy, ap);
int needed = vsnprintf (&buf[0], size, fmt, ap);
// NB. On Windows, vsnprintf returns -1 if the string didn't fit the
// buffer. On Linux & OSX, it returns the length it would have needed.
if (needed <= size && needed >= 0) {
// It fit fine the first time, we're done.
return std::string (&buf[0]);
} else {
// vsnprintf reported that it wanted to write more characters
// than we allotted. So do a malloc of the right size and try again.
// This doesn't happen very often if we chose our initial size
// well.
std::vector <char> buf;
size = needed;
buf.resize (size);
needed = vsnprintf (&buf[0], size, fmt, apcopy);
return std::string (&buf[0]);
}
}
```
EDIT: when I wrote this code, I had no idea that this required C99 conformance and that Windows (as well as older glibc) had different vsnprintf behavior, in which it returns -1 for failure, rather than a definitive measure of how much space is needed. Here is my revised code, could everybody look it over and if you think it's ok, I will edit again to make that the only cost listed:
```
std::string
Strutil::vformat (const char *fmt, va_list ap)
{
// Allocate a buffer on the stack that's big enough for us almost
// all the time. Be prepared to allocate dynamically if it doesn't fit.
size_t size = 1024;
char stackbuf[1024];
std::vector<char> dynamicbuf;
char *buf = &stackbuf[0];
va_list ap_copy;
while (1) {
// Try to vsnprintf into our buffer.
va_copy(ap_copy, ap);
int needed = vsnprintf (buf, size, fmt, ap);
va_end(ap_copy);
// NB. C99 (which modern Linux and OS X follow) says vsnprintf
// failure returns the length it would have needed. But older
// glibc and current Windows return -1 for failure, i.e., not
// telling us how much was needed.
if (needed <= (int)size && needed >= 0) {
// It fit fine so we're done.
return std::string (buf, (size_t) needed);
}
// vsnprintf reported that it wanted to write more characters
// than we allotted. So try again using a dynamic buffer. This
// doesn't happen very often if we chose our initial size well.
size = (needed > 0) ? (needed+1) : (size*2);
dynamicbuf.resize (size);
buf = &dynamicbuf[0];
}
}
```
|
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 lot of element activity is contra-indicated due to memory and CPU utilization, correct?
If that is the case, shouldn't you try to avoid using an array as much as possible when you will be adding a lot of elements? Should you use iStringMap instead? If so, what happens if you need more than two dimensions AND need to add a lot of element additions. Do you just take the performance hit or is there something else that should be used?
|
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, List, Collection, etc. then calling the "Add" method *may* create a new array -- but they are smart about it, they don't just resize by 1 element, they grow geometrically, so if you're adding lots of values only every once in a while will it have to allocate a new array. Even then, you can use the "Capacity" property to force it to grow before hand, if you know how many elements you're adding (`list.Capacity += numberOfAddedElements`)
|
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 directory. Notice the path is ***not*** "C:\Test.exe.config" The method looks for a config file associated with the file you specify. If you specify "C:\Test.exe.config" it will look for "C:\Test.exe.config.config" Kinda lame, but understandable, I guess.
Reference here: <http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.openexeconfiguration.aspx>
|
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://msdn.microsoft.com/en-us/library/system.appdomain.getdata.aspx) method lists the system entries available, of interest is the `"APP_CONFIG_FILE"` entry.
If we set the `"APP_CONFIG_FILE"` before any application settings are used, we can modify where the `app.config` is loaded from. For example:
```
public class Program
{
public static void Main()
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Temp\test.config");
//...
}
}
```
I found this solution documented in [this blog](http://weblogs.asp.net/israelio/archive/2005/01/10/349825.aspx) and a more complete answer (to a related question) can be found [here](https://stackoverflow.com/a/6151688/142794).
|
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("var1=value1&var2=value2");
```
|
# 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:
> ... All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. ...
> ... Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code....
Behaviour:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape>
Special characters are encoded with the exception of: @\*\_+-./
The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: `%xx`.
For characters with a greater code unit, the four-digit format `%uxxxx` is used. This is not allowed within a query string (as defined in [RFC3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.4)):
```
query = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
```
A percent sign is only allowed if it is directly followed by two hexdigits, percent followed by `u` is not allowed.
# encodeURI()
Use encodeURI when you want a working URL. Make this call:
```
encodeURI("http://www.example.org/a file with spaces.html")
```
to get:
```
http://www.example.org/a%20file%20with%20spaces.html
```
Don't call encodeURIComponent since it would destroy the URL and return
```
http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html
```
Note that encodeURI, like encodeURIComponent, does not escape the ' character.
# encodeURIComponent()
Use encodeURIComponent when you want to encode the value of a URL parameter.
```
var p1 = encodeURIComponent("http://example.org/?a=12&b=55")
```
Then you may create the URL you need:
```
var url = "http://example.net/?param1=" + p1 + "¶m2=99";
```
And you will get this complete URL:
`http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55¶m2=99`
Note that encodeURIComponent does not escape the `'` character. A common bug is to use it to create html attributes such as `href='MyUrl'`, which could suffer an injection bug. If you are constructing html from strings, either use `"` instead of `'` for attribute quotes, or add an extra layer of encoding (`'` can be encoded as %27).
For more information on this type of encoding you can check: <http://en.wikipedia.org/wiki/Percent-encoding>
|
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 Chrome with this code:
```
var arr = [];
for(var i=0;i<256;i++) {
var char=String.fromCharCode(i);
if(encodeURI(char)!==encodeURIComponent(char)) {
arr.push({
character:char,
encodeURI:encodeURI(char),
encodeURIComponent:encodeURIComponent(char)
});
}
}
console.table(arr);
```
|
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 function yourself
```
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
```
For completeness, add `reverse=True` to sort in descending order
```
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
```
|
```
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 appears only to allow the selection of a file, if you select a folder and then choose open it will navigate to that folder.
If the `OpenFileDialog` can not be used for this is there another object I should be using?
**EDIT**: The scenario is that I have a tool that can upload one...many files or folders. I need to be able to provide a dialog like the `OpenFileDialog` that allows a user to select a file, folder, or a combination of. I know about the `FolderBrowseDialog` and that is not the answer in this case.
|
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 (see amazon)
* A funny riddle game : [Python Challenge](http://www.pythonchallenge.com/)
Here is a list of subjects you must master if you want to write "Python" on your resume :
* [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions)
* [iterators and generators](https://stackoverflow.com/questions/231767/the-python-yield-keyword-explained/231855#231855)
* [decorators](https://stackoverflow.com/questions/739654/understanding-python-decorators/1594484#1594484)
They are what make Python such a cool language (with the standard library of course, that I keep discovering everyday).
|
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-Building-Applications/dp/0596529325/) and working through it - you'll learn python quite well, not to mention some quite excellent algorithms that'll come in handy to a web developer.
|
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 be the best way to have the changes made to the firewall so that it's *invisible* to the end user?
(The application is written in C#)
|
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 access to the windows firewall API.
/// This can be used to add an exception to the windows firewall
/// exceptions list, so that our programs can continue to run merrily
/// even when nasty windows firewall is running.
///
/// Please note: It is not enforced here, but it might be a good idea
/// to actually prompt the user before messing with their firewall settings,
/// just as a matter of politeness.
///
///
/// To allow the installers to authorize idiom products to work through
/// the Windows Firewall.
///
public class FirewallHelper
{
#region Variables
///
/// Hooray! Singleton access.
///
private static FirewallHelper instance = null;
///
/// Interface to the firewall manager COM object
///
private INetFwMgr fwMgr = null;
#endregion
#region Properties
///
/// Singleton access to the firewallhelper object.
/// Threadsafe.
///
public static FirewallHelper Instance
{
get
{
lock (typeof(FirewallHelper))
{
if (instance == null)
instance = new FirewallHelper();
return instance;
}
}
}
#endregion
#region Constructivat0r
///
/// Private Constructor. If this fails, HasFirewall will return
/// false;
///
private FirewallHelper()
{
// Get the type of HNetCfg.FwMgr, or null if an error occurred
Type fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
// Assume failed.
fwMgr = null;
if (fwMgrType != null)
{
try
{
fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType);
}
// In all other circumnstances, fwMgr is null.
catch (ArgumentException) { }
catch (NotSupportedException) { }
catch (System.Reflection.TargetInvocationException) { }
catch (MissingMethodException) { }
catch (MethodAccessException) { }
catch (MemberAccessException) { }
catch (InvalidComObjectException) { }
catch (COMException) { }
catch (TypeLoadException) { }
}
}
#endregion
#region Helper Methods
///
/// Gets whether or not the firewall is installed on this computer.
///
///
public bool IsFirewallInstalled
{
get
{
if (fwMgr != null &&
fwMgr.LocalPolicy != null &&
fwMgr.LocalPolicy.CurrentProfile != null)
return true;
else
return false;
}
}
///
/// Returns whether or not the firewall is enabled.
/// If the firewall is not installed, this returns false.
///
public bool IsFirewallEnabled
{
get
{
if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled)
return true;
else
return false;
}
}
///
/// Returns whether or not the firewall allows Application "Exceptions".
/// If the firewall is not installed, this returns false.
///
///
/// Added to allow access to this metho
///
public bool AppAuthorizationsAllowed
{
get
{
if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed)
return true;
else
return false;
}
}
///
/// Adds an application to the list of authorized applications.
/// If the application is already authorized, does nothing.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// This is the name of the application, purely for display
/// puposes in the Microsoft Security Center.
///
///
/// When applicationFullPath is null OR
/// When appName is null.
///
///
/// When applicationFullPath is blank OR
/// When appName is blank OR
/// applicationFullPath contains invalid path characters OR
/// applicationFullPath is not an absolute path
///
///
/// If the firewall is not installed OR
/// If the firewall does not allow specific application 'exceptions' OR
/// Due to an exception in COM this method could not create the
/// necessary COM types
///
///
/// If no file exists at the given applicationFullPath
///
public void GrantAuthorization(string applicationFullPath, string appName)
{
#region Parameter checking
if (applicationFullPath == null)
throw new ArgumentNullException("applicationFullPath");
if (appName == null)
throw new ArgumentNullException("appName");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("applicationFullPath must not be blank");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("appName must not be blank");
if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
throw new ArgumentException("applicationFullPath must not contain invalid path characters");
if (!Path.IsPathRooted(applicationFullPath))
throw new ArgumentException("applicationFullPath is not an absolute path");
if (!File.Exists(applicationFullPath))
throw new FileNotFoundException("File does not exist", applicationFullPath);
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed.");
if (!AppAuthorizationsAllowed)
throw new FirewallHelperException("Application exemptions are not allowed.");
#endregion
if (!HasAuthorization(applicationFullPath))
{
// Get the type of HNetCfg.FwMgr, or null if an error occurred
Type authAppType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);
// Assume failed.
INetFwAuthorizedApplication appInfo = null;
if (authAppType != null)
{
try
{
appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType);
}
// In all other circumnstances, appInfo is null.
catch (ArgumentException) { }
catch (NotSupportedException) { }
catch (System.Reflection.TargetInvocationException) { }
catch (MissingMethodException) { }
catch (MethodAccessException) { }
catch (MemberAccessException) { }
catch (InvalidComObjectException) { }
catch (COMException) { }
catch (TypeLoadException) { }
}
if (appInfo == null)
throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance.");
appInfo.Name = appName;
appInfo.ProcessImageFileName = applicationFullPath;
// ...
// Use defaults for other properties of the AuthorizedApplication COM object
// Authorize this application
fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo);
}
// otherwise it already has authorization so do nothing
}
///
/// Removes an application to the list of authorized applications.
/// Note that the specified application must exist or a FileNotFound
/// exception will be thrown.
/// If the specified application exists but does not current have
/// authorization, this method will do nothing.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// When applicationFullPath is null
///
///
/// When applicationFullPath is blank OR
/// applicationFullPath contains invalid path characters OR
/// applicationFullPath is not an absolute path
///
///
/// If the firewall is not installed.
///
///
/// If the specified application does not exist.
///
public void RemoveAuthorization(string applicationFullPath)
{
#region Parameter checking
if (applicationFullPath == null)
throw new ArgumentNullException("applicationFullPath");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("applicationFullPath must not be blank");
if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
throw new ArgumentException("applicationFullPath must not contain invalid path characters");
if (!Path.IsPathRooted(applicationFullPath))
throw new ArgumentException("applicationFullPath is not an absolute path");
if (!File.Exists(applicationFullPath))
throw new FileNotFoundException("File does not exist", applicationFullPath);
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
#endregion
if (HasAuthorization(applicationFullPath))
{
// Remove Authorization for this application
fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath);
}
// otherwise it does not have authorization so do nothing
}
///
/// Returns whether an application is in the list of authorized applications.
/// Note if the file does not exist, this throws a FileNotFound exception.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// The full path to the application executable. This cannot
/// be blank, and cannot be a relative path.
///
///
/// When applicationFullPath is null
///
///
/// When applicationFullPath is blank OR
/// applicationFullPath contains invalid path characters OR
/// applicationFullPath is not an absolute path
///
///
/// If the firewall is not installed.
///
///
/// If the specified application does not exist.
///
public bool HasAuthorization(string applicationFullPath)
{
#region Parameter checking
if (applicationFullPath == null)
throw new ArgumentNullException("applicationFullPath");
if (applicationFullPath.Trim().Length == 0)
throw new ArgumentException("applicationFullPath must not be blank");
if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0)
throw new ArgumentException("applicationFullPath must not contain invalid path characters");
if (!Path.IsPathRooted(applicationFullPath))
throw new ArgumentException("applicationFullPath is not an absolute path");
if (!File.Exists(applicationFullPath))
throw new FileNotFoundException("File does not exist.", applicationFullPath);
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
#endregion
// Locate Authorization for this application
foreach (string appName in GetAuthorizedAppPaths())
{
// Paths on windows file systems are not case sensitive.
if (appName.ToLower() == applicationFullPath.ToLower())
return true;
}
// Failed to locate the given app.
return false;
}
///
/// Retrieves a collection of paths to applications that are authorized.
///
///
///
/// If the Firewall is not installed.
///
public ICollection GetAuthorizedAppPaths()
{
// State checking
if (!IsFirewallInstalled)
throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed.");
ArrayList list = new ArrayList();
// Collect the paths of all authorized applications
foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
list.Add(app.ProcessImageFileName);
return list;
}
#endregion
}
///
/// Describes a FirewallHelperException.
///
///
///
///
public class FirewallHelperException : System.Exception
{
///
/// Construct a new FirewallHelperException
///
///
public FirewallHelperException(string message)
: base(message)
{ }
}
```
The ClickOnce sandbox did not present any problems.
|
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 :)
Edit: I just don't know enough about ClickOnce to know whether or not you can run external programs through it.
|
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 `setup.py` file, then `python setup.py bdist_egg` creates an .egg package.
|
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(
RegistryHive.LocalMachine, addr.Value).OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
return 1;
}
catch (IOException e)
{
IOException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 2;
}
catch (UnauthorizedAccessException e)
{
UnauthorizedAccessException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 3;
}
catch (System.Security.SecurityException e)
{
System.Security.SecurityException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 4;
}
```
Now, I have two problems:
* I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas?
* This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI.
Any help with either would be great.
|
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 (which we're already using for the vast majority of the heavy lifting) to access the registry, so I might try that instead.
|
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 is used to make managed and unmanaged calls.
|
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->renderSomeHTML();
?>
```
The first method call is cached, but I need renderSomeHTML() to display slightly different based upon its location in the page. I tried passing through to $GLOBALS, but the value doesn't change, so I'm assuming it is getting cached.
Is this not possible without passing an argument through the method or by not caching it? Any help is appreciated. This is not my application -- it is Magento.
**Edit:**
This is Magento, and it looks to be using memcached. I tried to pass an argument through renderSomeHTML(), but when I use func\_get\_args() on the PHP include to be rendered, what comes out is not what I put into it.
**Edit:**
Further down the line I was able to "invalidate" the cache by calling a different method that pulled the same content and passing in an argument that turned off caching. Thanks everyone for your help.
|
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 for this, or at least a more elegant/robust/efficient option:
```
def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
```
*Edit:* I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.
Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).
|
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 metacharacter.
**Update**: If you are using Python 3.3 or later, use [shlex.quote](http://docs.python.org/dev/library/shlex.html#shlex.quote) instead of rolling your own.
|
[`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 Comment Ninja](https://stackoverflow.com/users/4465/levik), are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.
I just want to be able to select a bunch of text on the comments page and click a bookmarklet ([http://bookmarklets.com](https://stackoverflow.com/users/8119/jacob)) in Firefox that pops up a window listing all the IP addresses found in the selection.
**Update:**
I kind of combined a the answers from [levik](https://stackoverflow.com/users/4465/levik) and [Jacob](https://stackoverflow.com/users/8119/jacob) to come up with this:
```
javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("<br>");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses)
```
The difference is that instead of an *alert* message, as in levik's answer, I open a new window similar to Jacob's answer. The *alert* doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a for the join instead of levik's *\n*.
Thanks for all the help, guys.
|
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")
* Applies a regular expression to march the IP addresses (as suggested by Muerr) - this results in an array of strings.
* Joins this array into one string separated by return characters
* Alerts that string
The way you get the selection is a little different on IE, but the principle is the same. To get it to be cross-browser, you'd need to check which method is available. You could also do more complicated output (like create a floating DIV and insert all the IPs into it).
|
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.