Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have the following code in WCF service to throw a custom fault based on certain situations. I am getting a "The creator of this fault did not specify a Reason" exception. What am I doing wrong?
```
//source code
if(!DidItPass)
{
InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started");
throw new FaultException<InvalidRoutingCodeFault>(fault);
}
//operation contract
[OperationContract]
[FaultContract(typeof(InvalidRoutingCodeFault))]
bool MyMethod();
//data contract
[DataContract(Namespace="http://myuri.org/Simple")]
public class InvalidRoutingCodeFault
{
private string m_ErrorMessage = string.Empty;
public InvalidRoutingCodeFault(string message)
{
this.m_ErrorMessage = message;
}
[DataMember]
public string ErrorMessage
{
get { return this.m_ErrorMessage; }
set { this.m_ErrorMessage = value; }
}
}
``` | After some addtional research, the following modified code worked:
```
if(!DidItPass)
{
InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started");
throw new FaultException<InvalidRoutingCodeFault>(fault, new FaultReason("Invalid Routing Code - No Approval Started"));
}
``` | The short answer is you are doing nothing wrong, just reading the results incorrectly.
On the client side when you catch the error, what is caught is of the type `System.ServiceModel.FaultException<InvalidRoutingCodeFault>`.
Your `InvalidRoutingCodeFault` object is actually in the `.detail` property of the FaultException. SO....
// client code
```
private static void InvokeMyMethod()
{
ServiceClient service = new MyService.ServiceClient();
try
{
service.MyMethod();
}
catch (System.ServiceModel.FaultException<InvalidRoutingCodeFault> ex)
{
// This will output the "Message" property of the System.ServiceModel.FaultException
// 'The creator of this fault did not specify a Reason' if not specified when thrown
Console.WriteLine("faultException Message: " + ex.Message);
// This will output the ErrorMessage property of your InvalidRoutingCodeFault type
Console.WriteLine("InvalidRoutingCodeFault Message: " + ex.Detail.ErrorMessage);
}
}
```
The Message property of the FaultException is what is displayed on the error page so if it's not populated like in John Egerton's post, you will see the 'The creator of this fault did not specify a Reason' message. To easily populate it, use the two parameter constructor when throwing the fault in the service as follows, passing your error message from your fault type:
```
InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started");
throw new FaultException<InvalidRoutingCodeFault>(fault, new FaultReason(fault.ErrorMessage));
``` | "The creator of this fault did not specify a Reason" Exception | [
"",
"c#",
".net",
"wcf",
"faults",
""
] |
I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.
What's included, and where can I get other good quality libraries from? | Firstly, the [python libary reference](https://docs.python.org/2/library/index.html) gives a blow by blow of what's actually included. And the [global module index](http://docs.python.org/modindex.html) contains a neat, alphabetized summary of those same modules. If you have dependencies on a library, you can trivially test for the presence with a construct like:
```
try:
import foobar
except:
print 'No foobar module'
```
If you do this on startup for modules not necessarily present in the distribution you can bail with a sensible diagnostic.
The [Python Package Index](http://pypi.python.org/pypi) plays a role similar to that of CPAN in the perl world and has a list of many third party modules of one sort or another. Browsing and searching this should give you a feel for what's about. There are also utilities such as [Yolk](http://pypi.python.org/pypi/yolk) which allow you to query the Python Package Index and the installed packages on Python.
Other good online Python resources are:
* [www.python.org](http://www.python.org)
* The [comp.lang.python](http://groups.google.com/group/comp.lang.python) newsgroup - this is still very active.
* Various of the [items linked off](http://www.python.org/links/) the Python home page.
* Various home pages and blogs by python luminaries such as [The Daily Python URL](http://www.pythonware.com/daily/), [effbot.org](http://www.effbot.org/), [The Python Cookbook](http://code.activestate.com/recipes/langs/python/), [Ian Bicking's blog](http://blog.ianbicking.org/) (the guy responsible for SQLObject), and the [Many blogs and sites off planet.python.org.](http://planet.python.org/) | run
```
pydoc -p 8080
```
and point your browser to <http://localhost:8080/>
You'll see everything that's installed and can spend lots of time discovering new things. :) | How to find all built in libraries in Python | [
"",
"python",
""
] |
I've seen (and used) code to have a link spawn a javascript action many times in my life, but I've never come to a firm conclusion on if the href attribute should be blank or #. Do you have any preference one way or the other, and if so, why?
```
<a href="" onclick="javascript: DoSomething();">linky</a>
```
or
```
<a href="#" onclick="javascript: DoSomething();">linky</a>
``` | You **must** have *something* for the `href` attribute, otherwise the browser will not treat it as a link (for example, making it focusable or giving it an underline) - that's why the use of "#" has become prevalent.
Also, the contents of the event attributes (`onclick`, `onmouseover`, `on...`) are already treated as javascript: you don't need to preface it with `javascript:`
So given your example, the best way to do that inline (which itself is not the best way, *probably*), is like this:
```
<a href="#" onclick="DoSomething(); return false">linky</a>
``` | Checkout the discussion over at [Href for Javascript links: “#” or “javascript:void(0)”?](https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0).
Also, leaving `href` blank causes the browser to not use the pointer cursor when the user mouses over, though you can fix that with CSS. | Using an anchor as a javascript action, what should the link be? | [
"",
"javascript",
"html",
""
] |
In C#, I'm trying to build an extension method for StringBuilder called AppendCollection() that would let me do this:
```
var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
var people = new List<Person>() { ...init people here... };
var orders = new List<Orders>() { ...init orders here... };
sb1.AppendCollection(people, p => p.ToString());
sb2.AppendCollection(orders, o => o.ToString());
string stringPeople = sb1.ToString();
string stringOrders = sb2.ToString();
```
stringPeople would end up with a line for each person in the list. Each line would be the result of p.ToString(). Likewise for stringOrders. I'm not quite sure how to write the code to make the lambdas work with generics. | Use the `Func<T,string>` delegate.
```
public static void AppendCollection<T>(this StringBuilder sb,
IEnumerable<T> collection, Func<T, string> method) {
foreach(T x in collection)
sb.AppendLine(method(x));
}
``` | ```
public static void AppendCollection<T>(this StringBuilder builder, IEnumerable<T> list, Func<T,string> func)
{
foreach (var item in list)
{
builder.AppendLine(func(item));
}
}
```
I wouldn't return a string, I would just append it to the original Stringbuilder that was passed in. | StringBuilder extension method for appending a collection in C# | [
"",
"c#",
"generics",
"lambda",
"stringbuilder",
""
] |
A link that stands out is <http://www.devdaily.com/blog/post/jfc-swing/handling-main-mac-menu-in-swing-application/> however the menu bar under Mac OS X displays as the package name as opposed to the application name. I'm using the code in the above link without any luck, so I'm unsure if anything's changed in recent Mac OS versions.
Here's an extract:
> ```
> public RootGUI() {
> super("Hello");
> JMenuBar menuBar = new JMenuBar();
> JMenu file = new JMenu("File");
> JMenuItem item = new JMenuItem("Woah");
> file.add(item);
> menuBar.add(file);
> setJMenuBar(menuBar);
> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
> setSize(100, 100);
> pack();
> setVisible(true);
> }
> ```
```
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new RootGUI();
}
catch(ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e.getMessage());
}
catch(InstantiationException e) {
System.out.println("InstantiationException: " + e.getMessage());
}
catch(IllegalAccessException e) {
System.out.println("IllegalAccessException: " + e.getMessage());
}
catch(UnsupportedLookAndFeelException e) {
System.out.println("UnsupportedLookAndFeelException: " + e.getMessage());
}
}
});
}
```
The first menu item on the menu bar should display as "test", unfortunately this isn't the case. The file menu works fine, on the other hand. Any ideas? | @Kezzer
I think I see what's going on. If you put the main() method in a *different class*, then everything works. So you need something like:
```
public class RootGUILauncher {
public static void main(String[] args) {
try {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e.getMessage());
}
catch(InstantiationException e) {
System.out.println("InstantiationException: " + e.getMessage());
}
catch(IllegalAccessException e) {
System.out.println("IllegalAccessException: " + e.getMessage());
}
catch(UnsupportedLookAndFeelException e) {
System.out.println("UnsupportedLookAndFeelException: " + e.getMessage());
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RootGUI();
}
});
}
```
And then put your RootGUI class in a different file. | You need to set the "com.apple.mrj.application.apple.menu.about.name" system property in the main thread, not in the Swing thread (in other words, just make it the first line in the program). | Native Swing Menu Bar Support For MacOS X In Java | [
"",
"java",
"swing",
"macos",
""
] |
I use XML serialization for the reading of my Config-POCOs.
To get intellisense support in Visual Studio for XML files I need a schema file. I can create the schema with xsd.exe mylibrary.dll and this works fine.
But I want that the schema is always created if I serialize an object to the file system. Is there any way without using xsd.exe? | Look at the [`System.Xml.Serialization.XmlSchemaExporter`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlschemaexporter(v=vs.110).aspx) class. I can't recall the exact details, but there is enough functionality in that namespace to do what you require. | thank you, this was the right way for me.
solution:
```
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlSchemas schemas = new XmlSchemas();
XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
Type type = toSerialize.GetType();
XmlTypeMapping map = importer.ImportTypeMapping(type);
exporter.ExportTypeMapping(map);
TextWriter tw = new StreamWriter(fileName + ".xsd");
schemas[0].Write(tw);
tw.Close();
``` | XML Serialization and Schema without xsd.exe | [
"",
"c#",
"xml-serialization",
""
] |
I would like to deploy a very simple DLL with my C# application, but any DLL that I build in Visual Studio 2008 seems to have a dependency on "Microsoft.VC90.CRT". Is it possible to build a DLL using VS2008 without this dependency? How can I tell what is causing the dependency? | I'm not sure about the latest VC++ versions, but previously you could tell the linker to link with a static version of the MSVCRT runtime library instead of the dynamic (DLL) version. It's possible this option still exists. | According to [this MSDN page](http://msdn.microsoft.com/en-us/library/abx4dbyh.aspx), static libraries are still available.
Go to project properties, configuration properties, C/C++, Code generation, Runtime Library.
Select Multithreaded Debug for the debug configuration, and Multithreaded for the release config. (Not sure if the names are all the same in VS2008, but should be "somewhere around there". Can update tomorrow with VS2008-specific differences)
Also, as wbic16 suggested, use dependency walker to identify other static dependencies. | Is it possible to build a DLL in C++ that has no dependencies? | [
"",
"c++",
"dll",
""
] |
I came across a c library for opening files given a Unicode filename. Before opening the file, it first converts the filename to a path by prepending "\\?\". Is there any reason to do this other than to increase the maximum number of characters allowed in the path, per [this msdn article](http://msdn.microsoft.com/en-us/library/aa365247.aspx)?
It looks like these "\\?\" paths require the Unicode versions of the Windows API and standard library. | Yes, it's just for that purpose. However, you will likely see compatibility problems if you decide to creating paths over MAX\_PATH length. For example, the explorer shell and the command prompt (at least on XP, I don't know about Vista) can't handle paths over that length and will return errors. | The best use for this method is probably not to create new files, but to manage existing files, which someone else may have created.
I managed a file server which routinely would get files with `path_length > MAX_PATH`. You see, the users saw the files as `H:\myfile.txt`, but on the server it was actually `H:\users\username\myfile.txt`. So if a user created a file with exactly `MAX_PATH` characters, on the server it was `MAX_PATH+len("users\username")`.
(Creating a file with MAX\_PATH characters is not so uncommon, since when you save a web page on Internet Explorer it uses the page title as the filename, which can be quite long for some pages).
Also, sharing a drive (via network or usb) with a Mac or a Linux machine, you can find yourself with files with names like con, prn or lpt1. And again, the prefix lets you and your scripts handle those files. | On Windows, when should you use the "\\\\?\\" filename prefix? | [
"",
"c++",
"winapi",
"unicode",
"filenames",
"max-path",
""
] |
I was chatting to someone the other day who suggested that Rails and PHP are the most suitable platforms for web applications, and to avoid Java. My background is mainly Java, and I know that it is considered by some to be too verbose and "heavyweight", but is used occasionally (e.g. by LinkedIn).
So I'm wondering whether anyone has had success using Java for a recent web application that has gone live, either using the language itself (e.g. with Stripes/Spring + Hibernate), or the runtime with a dymamic language (such as JRuby, Groovy, Jython)? If so, please share what worked and what you would do differently.
**Some background** *(added later)*:
Tim O'Reilly coined the phrased "Web 2.0" and here is his definition: <http://www.oreillynet.com/lpt/a/6228>
I think it's the "End of the release cycle" and "Lightweight programming model", involving rapid iterations and simplified deployment, where Java may be less suitable. Thoughts? | there are two totally different concepts called 'Web 2.0':
1. user generated content (usually with some 'social networking')
2. dynamic AJAX-based web apps
the second one somewhat dictates the technologies that you have to use (at least some JS, and machine-readable content in (some) responses). of course, there's nothing against using Java (or CGI, Perl, whatever) on the server.
the first one doesn't have anything to do with technology, and everything to do with the service itself you're providing. again, you can use anything you want.
why are these two mixed in the same therm? and more to your point: why are dynamic languages assumed 'more appropriate' for it? i'd guess it's just a temporal coincidence, all three things (user-generated content, AJAX, serious dynamic languages) jumped to the limelight roughly at the same time, and most of the proponents of each concept are using the other two.
in short, better avoid undefined marketroid terms like "web 2.0", and use proper descriptions. at least while working. when selling to the VCs and PHBs use any and all buzzwords that come near! | I would argue that there is no specific technology for Web 2.0. The main concept behind a Web 2.0 application is that much of the content is provided by it's users and not one specific person. If you can achieve this with Java, then that is fine. Many people are creating startup companies with technology that is free because they don't have the capital. | Is Java suitable for "Web 2.0" applications? | [
"",
"java",
"web-applications",
""
] |
In SQL, How we make a check to filter all row which contain a column data is null or empty ?
For examile
```
Select Name,Age from MEMBERS
```
We need a check Name should not equal to null or empty. | This will work in all sane databases (*wink, wink*) and will return the rows for which name is not null nor empty
```
select name,age from members where name is not null and name <> ''
``` | For DBMSs that treat '' as a value (not null), Vinko's query works:
```
select name,age from members where name is not null and name <> ''
```
For Oracle, which treats '' as a null, tha above doesn't work but this does:
```
select name,age from members where name is not null
```
I tried to think of a "DBMS-agnostic" solution, but failed - mainly due to the different concatenation operators/functions used by different DBMSs! | How can I filter out the rows which contain a particular column with null or empty data in SQL? | [
"",
"sql",
""
] |
I'm building a small Winform in which I can view types of food in my kitchen.
My entire stock can be displayed by a datagrid view.
Now, I have a filtermenu which contains a dropdownlist of items that can be checked and unchecked.
Based on which items in that list are checked, the display in the datagridview is changed. Only items which are selected are displayed.
At least, that's how I want it to be.
The menu currently has 5 items: Meat, Fish, Fruit, Vegetable and Other.
I'm using a abstract class Food and all the other classes are derived from it.
Eventually I make a string representation of each piece of food which looks a bit like this
FoodType\*FoodName\*AmountInStock\*...
So a star \* as seperator.
Then I do this
```
foreach(Food f in this.kitchen.FoodList)
{
string[] s = f.ToString().Split('*');
Object o = filterMenu.DropDownItems[s[0]];
}
```
With FoodList being an ArrayList.
Then I debug that with VisualStudio 2008
The Object o always contains null.
Yet s[0] always contains the name of the food type.
What I want is to be able to find out wheter an item on that menulist is checked. If checked, the datagridview must display it. If not, don't display it.
I fill it up in the constructor with this:
```
public static void Fill(ToolStripMenuItem item, Type food)
{
foreach (string element in Enum.GetNames(food))
{
if (element != "nothing")
{
ToolStripMenuItem it = (ToolStripMenuItem)item.DropDownItems.Add(element);
it.Checked = true;
it.CheckOnClick = true;
}
}
}
```
I've tried the object browser but I can't find anything that helps, so I turn here. | You could use the IndexOfKey property to find the ToolStripMenuItem back. That requires setting the Name property when you add them:
```
ToolStripMenuItem it = (ToolStripMenuItem)item.DropDownItems.Add(element);
it.Name = element;
// etc..
``` | You are reference checking when you do
filterMenu.DropDownItems[s[0]].
You don't match the value of s[0] with the items in DropDownItems but you match their references, and those don't match.
You either need to loop through all items and do a manual check if their **value** is the same, or you find a way to insert your own comparator into that process. | Dropdown items on a ToolstripmenuItem and seeing if their items are checked | [
"",
"c#",
"winforms",
"visual-studio-2008",
""
] |
What is the C# optimised version of the following, without using .Net's Timespan or DateTime. How would I NUnit test it?
```
TimeSpan ts = Date1 - Date2;
int numberOfDays = ts.Days;
``` | You could convert the dates to ticks, substract, then convert the ticks back to days. Though exactly why can't you use TimeSpan? It's likely doing just that.
Something like this:
```
DateTime a = DateTime.Now;
DateTime b = a.AddDays(2);
// ticks are in hns
long ticks = b.Ticks - a.Ticks;
long seconds = ticks / 10000000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
```
I get back "2" for days. | Date1 and Date2 are what type? In your exameple it looks to be DateTime. You want your Date in what variable if it's not DateTime? You can always have your Date1 and Date2 in String and play with SubString() to get Year, Month and days but that would be a real pain to work with.
The optimized way to do your problem of:
```
TimeSpan ts = Date1 - Date2;
int numberOfDays = ts.Days;
```
is
```
DateTime Date1 = new DateTime(2008,12,01);
DateTime Date2 = new DateTime(2008,12,25);
int numberOfDayBetweenDateThatShouldBe = 25;
Assert.IsTrue((Date2-Date1).TotalDays == numberOfDayBetweenDateThatShouldBe);
``` | NUnit test DateTime without .Net Timespan or DateTime function | [
"",
"c#",
"timespan",
""
] |
I'm hopeless at Javascript. This is what I have:
```
<script type="text/javascript">
function beginrefresh(){
//set the id of the target object
var marquee = document.getElementById("marquee_text");
if(marquee.scrollLeft >= marquee.scrollWidth - parseInt(marquee.style.width)) {
marquee.scrollLeft = 0;
}
marquee.scrollLeft += 1;
// set the delay (ms), bigger delay, slower movement
setTimeout("beginrefresh()", 10);
}
</script>
```
It scrolls to the left but I need it to repeat relatively seamlessly. At the moment it just jumps back to the beginning. It might not be possible the way I've done it, if not, anyone have a better method? | Here is a jQuery plugin with a lot of features:
<http://jscroller2.markusbordihn.de/example/image-scroller-windiv/>
And this one is "silky smooth"
<http://remysharp.com/2008/09/10/the-silky-smooth-marquee/> | Simple javascript solution:
```
window.addEventListener('load', function () {
function go() {
i = i < width ? i + step : 1;
m.style.marginLeft = -i + 'px';
}
var i = 0,
step = 3,
space = ' ';
var m = document.getElementById('marquee');
var t = m.innerHTML; //text
m.innerHTML = t + space;
m.style.position = 'absolute'; // http://stackoverflow.com/questions/2057682/determine-pixel-length-of-string-in-javascript-jquery/2057789#2057789
var width = (m.clientWidth + 1);
m.style.position = '';
m.innerHTML = t + space + t + space + t + space + t + space + t + space + t + space + t + space;
m.addEventListener('mouseenter', function () {
step = 0;
}, true);
m.addEventListener('mouseleave', function () {
step = 3;
}, true);
var x = setInterval(go, 50);
}, true);
```
```
#marquee {
background:#eee;
overflow:hidden;
white-space: nowrap;
}
```
```
<div id="marquee">
1 Hello world! 2 Hello world! <a href="#">3 Hello world!</a>
</div>
```
[JSFiddle](http://jsfiddle.net/lalatino/1r3957g4/) | Javascript Marquee to replace <marquee> tags | [
"",
"javascript",
"html",
"marquee",
""
] |
The list `sort()` method is a modifier function that returns `None`.
So if I want to iterate through all of the keys in a dictionary I cannot do:
```
for k in somedictionary.keys().sort():
dosomething()
```
Instead, I must:
```
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
```
Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps? | ```
for k in sorted(somedictionary.keys()):
doSomething(k)
```
Note that you can also get all of the keys and values sorted by keys like this:
```
for k, v in sorted(somedictionary.iteritems()):
doSomething(k, v)
``` | Can I answer my own question?
I have just discovered the handy function "sorted" which does exactly what I was looking for.
```
for k in sorted(somedictionary.keys()):
dosomething()
```
It shows up in [Python 2.5 dictionary 2 key sort](https://stackoverflow.com/questions/157424/python-25-dictionary-2-key-sort) | Is there a "one-liner" way to get a list of keys from a dictionary in sorted order? | [
"",
"python",
"iterator",
"syntactic-sugar",
""
] |
I would like to use `[Authorize]` for every action in my admin controller except the `Login` action.
```
[Authorize (Roles = "Administrator")]
public class AdminController : Controller
{
// what can I place here to disable authorize?
public ActionResult Login()
{
return View();
}
}
``` | I don't think you can do this with the standard Authorize attribute, but you could derive your own attribute from AuthorizeAttribute that takes a list of actions to allow and allows access to just those actions. You can look at the source for the AuthorizeAttribute at [www.codeplex.com](http://www.codeplex.com/aspnet) for ideas on how to do this. If you did, it might look like:
```
[AdminAuthorize (Roles = "Administrator", Exempt = "Login, Logout") ]
public class AdminController : Controller
{
public ActionResult Login()
{
return View();
}
public ActionResult Login()
{
return View();
}
... other, restricted actions ...
}
```
**EDIT**: FYI, I eventually ran across a need to do something similar on my own and I went a different direction. I created a default authorization filter provider and apply a global authorize filter. The authorization filter provider uses reflection to check if an action or controller has a specific authorize attribute applied and, if so, defers to it. Otherwise, it applies a default authorization filter. This is coupled with a PublicAttribute derived from AuthorizeAttribute that allows public access. Now, I get default secured access, but can grant public access via `[Public]` applied to an action or controller. More specific authorization can also be applied as necessary. See my blog at <http://farm-fresh-code.blogspot.com/2011/04/default-authorization-filter-provider.html> | You can decorate your controller with [Authorize] and then you can just decorate the method that you want to exempt with [AllowAnonymous] | Can you enable [Authorize] for controller but disable it for a single action? | [
"",
"c#",
"asp.net-mvc",
"authorization",
""
] |
I have a form that tries to modify a JComponent's graphics context. I use, for example,
```
((Graphics2D) target.getGraphics()).setStroke(new BasicStroke(5));
```
Now, immediately after I set the value and close the form, the change is not visible. Am I not allowed to modify a JComponent's graphics context? How else would I modify the stroke, color and transformations?
Thanks,
Vlad | There are several problems with that approach. The first is that most components will set these things themselves when ever they are asked to repaint themselves. This means that your change will be lost every time the component gets to the point where it would actually use it. But, on an even more fundamental level than that, Graphics2D objects are not persistant. They are typically instantiated every time the component is redrawn, meaning that the Graphics2D object you got won't be the same the component will be using when redrawing.
What you need to do, to achieve this kind of thing is either to reimplement the specific component yourself, or implement a new look and feel that will affect the entire set of swing components. Have a look at the following link for further details about this:
[<http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html>](http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html) | Nobody to answer? I have let some time to see if there is any good answer before mine: I am not a specialist of such question...
First, I don't fully understand your question: you change a setting then close the form?
Anyway, I am not too sure, but somewhere in the process, the graphics context might be recomputed or taken from default. Perhaps if you do this operation in the paint() method, you can get some result, although I am not sure.
For a number of changes, you usually use a decorator. I explored a bit this topic when answering a question on SO: [How do I add a separator to a JComboBox in Java?](https://stackoverflow.com/questions/138793/how-do-i-add-a-separator-to-a-jcombobox-in-java#139366 "How do I add a separator to a JComboBox in Java?"). I had to paint my own border there (asymmetrical), but often you just take an existing one, so it is quite simple.
I hope I provided some information, if it didn't helped, perhaps you should give more details on what you want to do (and perhaps a simple, minimal program illustrating your problem). | Modifying graphics context in Java | [
"",
"java",
"swing",
""
] |
Is there a generic container implementing the 'set' behaviour in .NET?
I know I could just use a `Dictionary<T, Object>` (and possibly add `nulls` as values), because its keys act as a set, but I was curious if there's something ready-made. | `HashSet<T>` in .NET 3.5 | I use the Iesi.Collections. namespace that comes with NHibernate (docs [here](http://monogis.org/monogis_doc/html/Iesi.Collections.html)) - maybe worth considering if you are in .NET < 3.5 | .NET Generic Set? | [
"",
"c#",
".net",
"generics",
"collections",
"set",
""
] |
Now I have a stack of free time on my hands, I wanna get into iphone dev fo real.
But Objective C scares me (a bit). It feels I'm going a bit back in time. I say this because I've spent the last 8 months coding in C++.
[JSCocoa](http://inexdo.com/JSCocoa) looks awesome, but does this actually work on the iphone?
What would need to be done to get this working on the iphone? | (Hi, I'm the JSCocoa dev)
JSCocoa works on the iPhone simulator. Check out the latest version from Google svn and compile iPhoneTest2.
To work on the iPhone, it needs libffi. I've seen <http://code.google.com/p/iphone-dev/source/browse/trunk/llvm-gcc-4.0-iphone/> and some libffi posts regarding Python for iPhone, but have not tested any further.
Also I don't own an iPhone, so testing will mostly be up to someone who owns one :) | a bit of off topic, but: You shouldn't be scared of Objective-C. Of course the syntax looks ugly at first (it did to me), but after a while you get hooked to it. And since you've spent 8 months in C++ i presume you have a good grasp of C which already lightens your weight on learning objective-c! | JSCocoa and the iPhone | [
"",
"javascript",
"iphone",
""
] |
Anyone know what the C# "M" syntax means?
```
var1 = Math.Ceiling(hours / (40.00M * 4.3M));
``` | M is the suffix for Decimal. Stands for "money" I assume.
<http://msdn.microsoft.com/en-us/library/364x0z75(VS.71).aspx> | it means that the number is a `decimal` type. | What is this " var1 = Math.Ceiling(hours / (40.00M * 4.3M));" | [
"",
"c#",
""
] |
If you're running Apache Geronimo in production why did you choose it over other application servers and what are your experiences with running Geronimo in production?
Can you also please share what servlet engine you decided to use (Tomcat/Jetty) and why you made this decision?
***UPDATE***: So far this question got two up-votes and one star but no answer. I'm starting to wonder, is anyone using Apache Geronimo at all? My logic would be, if you use Geronimo for development you'd also use it for deployment. Right? So, does that mean that no one is using Geronimo at all? | We definitely use Geronimo in production!
We have used the Tomcat version since 1.0, about four years ago as I recall. We are currently running mostly 2.1.1.4.
One of our apps gets about 1 million page views per day. The others are nowhere near that, but they are important apps that need to work well.
Our choice was based primarily on:
1. Price: At the time our company started using Java, we weren't sure what we needed out of an app server. So we decided to start at free and work our way up, if needed.
2. Basic features: I had experience with WebSphere (base/ND) and plain old Tomcat. Geronimo had the J2EE features we wanted, all within a lightweight package.
3. Open Source: Our primary client that we use Java for required Open Source.
4. Familiarity: Being an Apache-based server, we were already comfortable with Tomcat, OpenJPA, Axis web services, and others. Furthermore, we were comfortable with the Apache community as far as bug tracking and other minor things.
5. Support: We expected to be mostly on our own, but knowing that the Apache community was active was important. As was the availability of commercial support from IBM, as we are an IBM Business Partner.
Our experience has been great overall. The servers are very reliable. I search our logs once in awhile and sometimes see weird errors with a database connection, an EJB call, but those are pretty rare (and quite possibly our code's fault).
Performance is impressive. I joke that we could run Geronimo from my laptop and the clients wouldn't see a difference. Give it any decent server and it will purr along for months.
I'm not sure how many people actual run Geronimo. I'm rather confused about that. I've seen slides (years ago) that listed some big names like eBay using it. The mailing list is active but sometimes seems like only the Geronimo team communicating with each other.
The only serious bug I've run into is [this one](https://issues.apache.org/jira/browse/GERONIMO-5800). It is a big deal to us, but of course Geronimo is free and I don't expect them to fix bugs that are important just to me.
I've been meaning to check out Apache TomEE server, wondering if it is more actively or openly used. Just to see how the community and usage compares to Geronimo. | WebSphere community edition is Geronimo. So IBM chose it as a platform of choice.
When choosing an application server, you're really choosing the APIs you want to use in your application and maybe the administration interface (but you only use that once in a while). | Running Apache Geronimo in production | [
"",
"java",
"jakarta-ee",
"geronimo",
""
] |
Data table structure is:
id1,id2,id3,id4,... (some other fields).
I want to create summary query to find out how many times some ID value is used in every column.
Data
1,2,3,4,2008
2,3,5,1,2008
1,3,2,5,2007
1,2,3,6,2007
3,1,2,5,2007
For value 1, the result should be
1,0,0,1,2008
2,1,0,0,2007
How to accomplish this with one query (in MySQL). | This seems like the best solution (from [Wiki](http://en.wikibooks.org/wiki/Programming:MySQL/Pivot_table)):
```
select years,
sum(1*(1-abs(sign(id1-56)))) as id1,
sum(1*(1-abs(sign(id2-56)))) as id2,
sum(1*(1-abs(sign(id3-56)))) as id3,
sum(1*(1-abs(sign(id4-56)))) as id4,
from mytable
group by years
``` | Use a characteristic or delta function:
```
DECLARE @look_for AS int
SET @look_for = 1
SELECT SUM(CASE WHEN id1 = @look_for THEN 1 ELSE 0 END) AS id1_count
,SUM(CASE WHEN id2 = @look_for THEN 1 ELSE 0 END) AS id2_count
,SUM(CASE WHEN id3 = @look_for THEN 1 ELSE 0 END) AS id3_count
,SUM(CASE WHEN id4 = @look_for THEN 1 ELSE 0 END) AS id4_count
FROM tbl
```
There are ways to code generate this (also a technique using PIVOT and UNPIVOT in SQL Server which is not ANSI) based on your table and the distinct ID values also. | Summary query from several fields in SQL | [
"",
"sql",
"mysql",
"count",
""
] |
Does anyone know of a library or set of classes for splines - specifically b-splines and NURBS (optional).
A fast, efficient b-spline library would be so useful for me at the moment. | 1.) For B Splines - You should check Numerical Recipes in C (there is book for that and it is also available online for reference)
2.) Also check: [sourceforge.net/projects/einspline/](http://sourceforge.net/projects/einspline/)
& [this](https://www.gnu.org/software/gsl/doc/html/bspline.html)
-AD | I know I'm answering months after this question was asked, but for others who might be searching for a similar answer, I'll point out [openNURBS](http://www.opennurbs.org/).
OpenNURBS also happens to be the library used in the modeling package [Rhinoceros](http://www.rhino3d.com/). It's a very complete library and it's worth consideration. | Spline, B-Spline and NURBS C++ library | [
"",
"c++",
"graphics",
""
] |
I asked [how to render a UserControl's HTML](https://stackoverflow.com/questions/288409/how-do-i-get-the-html-output-of-a-usercontrol-in-net-c) and got the code working for a dynamically generated UserControl.
Now I'm trying to use LoadControl to load a previously generated Control and spit out its HTML, but it's giving me this:
*Control of type 'TextBox' must be placed inside a form tag with runat=server.*
I'm not actually adding the control to the page, I'm simply trying to grab its HTML. Any ideas?
Here's some code I'm playing with:
```
TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
UserControl myControl = (UserControl)LoadControl("newUserControl.ascx");
myControl.RenderControl(myWriter);
return myTextWriter.ToString();
``` | Alternatively you could disable the ServerForm/Event-validation on the page that is rendering the control to a string.
The following example illustrates how to do this.
```
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string rawHtml = RenderUserControlToString();
}
private string RenderUserControlToString()
{
UserControl myControl = (UserControl)LoadControl("WebUserControl1.ascx");
using (TextWriter myTextWriter = new StringWriter())
using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
{
myControl.RenderControl(myWriter);
return myTextWriter.ToString();
}
}
public override void VerifyRenderingInServerForm(Control control)
{ /* Do nothing */ }
public override bool EnableEventValidation
{
get { return false; }
set { /* Do nothing */}
}
}
``` | This is a dirty solution I used for the moment (get it working then get it right, right?).
I had already created a new class that inherits the UserControl class and from which all other "UserControls" I created were derived. I called it formPartial (nod to Rails), and this is going inside the public string renderMyHTML() method:
```
TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
UserControl myDuplicate = new UserControl();
TextBox blankTextBox;
foreach (Control tmpControl in this.Controls)
{
switch (tmpControl.GetType().ToString())
{
case "System.Web.UI.LiteralControl":
blankLiteral = new LiteralControl();
blankLiteral.Text = ((LiteralControl)tmpControl).Text;
myDuplicate.Controls.Add(blankLiteral);
break;
case "System.Web.UI.WebControls.TextBox":
blankTextBox = new TextBox();
blankTextBox.ID = ((TextBox)tmpControl).ID;
blankTextBox.Text = ((TextBox)tmpControl).Text;
myDuplicate.Controls.Add(blankTextBox);
break;
// ...other types of controls (ddls, checkboxes, etc.)
}
}
myDuplicate.RenderControl(myWriter);
return myTextWriter.ToString();
```
Drawbacks off the top of my head:
1. You need a case statement with every
possible control (or controls you
expect).
2. You need to transfer all
the important attributes from the
existing control (textbox, etc) to
the new blank control.
3. Doesn't take full advantage of
Controls' RenderControl method.
It'd be easy to mess up 1 or 2. Hopefully, though, this helps someone else come up with a more elegant solution. | UserControl's RenderControl is asking for a form tag in (C# .NET) | [
"",
"c#",
"html",
".net",
"user-controls",
""
] |
In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, `topDict[word1][word2][word3]` returns the number of times these words appear in the text, `topDict[word1][word2]` returns a dictionary with all the words that appeared following words 1 and 2, etc.
This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.
My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.
From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.
So, does anyone have any suggestions for me?
Edited to add:
Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (i.e. I want something like the result of `topDict[word1, word2].keys()`).
The current dataset I am playing around with is the most recent version of [Wikipedia For Schools](http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm). The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive. | Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record:
```
295760 S. Lott's answer
237984 S. Lott's with keys interned before passing in
203172 [*] d[(a,b,c)] = int(freq)
203156 d[a][b][c] = int(freq)
189132 keys.append((a,b,c)); freqs.append(int(freq))
146132 d[intern(a),intern(b)][intern(c)] = int(freq)
145408 d[intern(a)][intern(b)][intern(c)] = int(freq)
83888 [*] d[a+' '+b+' '+c] = int(freq)
82776 [*] d[(intern(a),intern(b),intern(c))] = int(freq)
68756 keys.append((intern(a),intern(b),intern(c))); freqs.append(int(freq))
60320 keys.append(a+' '+b+' '+c); freqs.append(int(freq))
50556 pair array
48320 squeezed pair array
33024 squeezed single array
```
The entries marked [\*] have no efficient way to look up a pair (a,b); they're listed only because others have suggested them (or variants of them). (I was sort of irked into making this because the top-voted answers were not helpful, as the table shows.)
'Pair array' is the scheme below in my original answer ("I'd start with the array with keys
being the first two words..."), where the value table for each pair is
represented as a single string. 'Squeezed pair array' is the same,
leaving out the frequency values that are equal to 1 (the most common
case). 'Squeezed single array' is like squeezed pair array, but gloms key and value together as one string (with a separator character). The squeezed single array code:
```
import collections
def build(file):
pairs = collections.defaultdict(list)
for line in file: # N.B. file assumed to be already sorted
a, b, c, freq = line.split()
key = ' '.join((a, b))
pairs[key].append(c + ':' + freq if freq != '1' else c)
out = open('squeezedsinglearrayfile', 'w')
for key in sorted(pairs.keys()):
out.write('%s|%s\n' % (key, ' '.join(pairs[key])))
def load():
return open('squeezedsinglearrayfile').readlines()
if __name__ == '__main__':
build(open('freqs'))
```
I haven't written the code to look up values from this structure (use bisect, as mentioned below), or implemented the fancier compressed structures also described below.
**Original answer:** A simple sorted array of strings, each string being a space-separated concatenation of words, searched using the bisect module, should be worth trying for a start. This saves space on pointers, etc. It still wastes space due to the repetition of words; there's a standard trick to strip out common prefixes, with another level of index to get them back, but that's rather more complex and slower. (The idea is to store successive chunks of the array in a compressed form that must be scanned sequentially, along with a random-access index to each chunk. Chunks are big enough to compress, but small enough for reasonable access time. The particular compression scheme applicable here: if successive entries are 'hello george' and 'hello world', make the second entry be '6world' instead. (6 being the length of the prefix in common.) Or maybe you could get away with using [zlib](http://www.python.org/doc/2.5.2/lib/module-zlib.html)? Anyway, you can find out more in this vein by looking up dictionary structures used in full-text search.) So specifically, I'd start with the array with keys being the first two words, with a parallel array whose entries list the possible third words and their frequencies. It might still suck, though -- I think you may be out of luck as far as batteries-included memory-efficient options.
Also, binary tree structures are *not* recommended for memory efficiency here. E.g., [this paper](https://dl.acm.org/doi/abs/10.1145/506309.506312) tests a variety of data structures on a similar problem (unigrams instead of trigrams though) and finds a hashtable to beat all of the tree structures by that measure.
I should have mentioned, as someone else did, that the sorted array could be used just for the wordlist, not bigrams or trigrams; then for your 'real' data structure, whatever it is, you use integer keys instead of strings -- indices into the wordlist. (But this keeps you from exploiting common prefixes except in the wordlist itself. Maybe I shouldn't suggest this after all.) | Use tuples.
Tuples can be keys to dictionaries, so you don't need to nest dictionaries.
```
d = {}
d[ word1, word2, word3 ] = 1
```
Also as a plus, you could use defaultdict
* so that elements that don't have entries always return 0
* and so that u can say `d[w1,w2,w3] += 1` without checking if the key already exists or not
example:
```
from collections import defaultdict
d = defaultdict(int)
d["first","word","tuple"] += 1
```
If you need to find all words "word3" that are tupled with (word1,word2) then search for it in dictionary.keys() using list comprehension
if you have a tuple, t, you can get the first two items using slices:
```
>>> a = (1,2,3)
>>> a[:2]
(1, 2)
```
a small example for searching tuples with list comprehensions:
```
>>> b = [(1,2,3),(1,2,5),(3,4,6)]
>>> search = (1,2)
>>> [a[2] for a in b if a[:2] == search]
[3, 5]
```
You see here, we got a list of all items that appear as the third item in the tuples that start with (1,2) | Memory Efficient Alternatives to Python Dictionaries | [
"",
"python",
"memory",
"data-structures",
""
] |
In javascript, I've got a block of HTML like this:
```
<h2>{title}</h2>
<p><a href="{url}">{content}</a></p>
```
And I'm trying use regex "match" to spit out an array of all the {item}'s. So my output should look like:
```
['title', 'url', 'content']
```
I've gotten as far as:
```
var pattern = new RegExp("\{[a-zA-Z]+\}+");
var match = pattern.exec("{Sample} bob {text}");
```
But it's only returning the first tag.
This is just beyond my regex skills. Can anyone help?
Cheers! | You need to create a pattern with the global flag:
```
var pattern = new RegExp("\{[a-zA-Z]+\}", "g");
```
or:
```
var pattern = /\{[a-zA-Z]+\}/g;
```
Then you can call the match() method on your string to get a list of matches:
```
var matches = "{Sample} bob {text}".match(pattern);
``` | I think you want:
```
var pattern = new RegExp("\{[a-zA-Z]+\}+", "g");
```
The second option is a flag telling it to search the entire string and return all matches.
See: <http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/> for more details. | RegExp to match words wrapped in braces | [
"",
"javascript",
"regex",
"arrays",
"templates",
"match",
""
] |
I am trying to add a "title" element but am getting a NO\_MODIFICATION\_ALLOWED\_ERR error...
```
private static void saveDoc(String f) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
// create DOMSource for source XML document
DOMSource xmlSource = new DOMSource(doc);
Node nextNode = xmlSource.getNode().getFirstChild();
while (nextNode != null) {
System.out.print("\n node name: " + nextNode.getNodeName() + "\n");
if (nextNode.getNodeName().equals("map")) {
nextNode.appendChild(doc.createElement("title"));
```
**the line above is throwing error:**
> Exception in thread "main" org.w3c.dom.DOMException: `NO_MODIFICATION_ALLOWED_ERR`: An attempt is made to modify an object where modifications are not allowed.
> at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(Unknown Source)
> at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(Unknown Source)
> at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(Unknown Source)
> at myProject.Main.saveDoc(Main.java:171)
> at myProject.Main.main(Main.java:48)
```
break;
}
nextNode = nextNode.getNextSibling();
}
}
```
My xml file looks like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<?dctm xml_app="LOPackage"?>
<!DOCTYPE map PUBLIC "-//OASIS//DTD DITA Map//EN" "file:C:/Documents%20and%20Settings/joe/Desktop//LOPackage/map.dtd">
<map xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" class="- map/map " ditaarch:DITAArchVersion="1.1" domains="(map mapgroup-d) (topic indexing-d)">
<topicref class="- map/topicref " href="dctm://ai/0501869e80002504?DMS_OBJECT_SPEC=RELATION_ID" type="Le"/>
<topicref class="- map/topicref " href="dctm://ai/0501869e80002505?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/>
<topicref class="- map/topicref " href="dctm://ai/0501869e80002506?DMS_OBJECT_SPEC=RELATION_ID" type="Pr"/>
</map>
``` | Not sure if that's the reason, but check if your DOM implementation validates all the changes to the DOM. Because in you code,
```
nextNode.appendChild(doc.createTextNode("title"));
```
will attempt to create a text node as the child of `map` element and DITA Map doesn't allow that. Instead, try
```
Element title = doc.createElement("title");
title.appendChild(doc.createTextNode("title content"))
nextNode.appendChild(title);
``` | Where is the original document coming from?
That's the cause of the issue - the code that's reading in the document is constructing a read-only document. Without knowing how you're reading it in, it's pretty hard to work out how to change that.
I just did a quick test on Windows with JDK 1.4.2-11, and I can confirm that using the DocumentBuilderFactory (with the XML content coming from a Reader) does not create a read only Document. | How to add an xml element in Java 1.4 | [
"",
"java",
"jdk1.4",
""
] |
I know it's probably not the right way to structure a database but does the database perform faster if the data is put in one huge table instead of breaking it up logically in other tables?
I want to design and create the database properly using keys to create relational integrity across tables but when quering, is JOIN'ing slower than reading the required data from one table? I want to make the database queries as fast as possible. | So many other facets affect the answer to your question. What is the size of the table? width? how many rows? What is usage pattern? Are there different usage patterns for different subsets of the columns in the table? (i.e., are two columns hit 1000 times per second, and the other 50 columns only hit once or twice a day? ) this scenario would be a prime candidate to split (partition) the table vertically (two columns in one table, the rest on another)
In general, normalize the schema to the maximum degree possible, then run performance testing with typical or predicted loads and usage patterns, and denormalize and partition to the point where the performance becomes acceptable, and no more... | It depends on the dbms flavor and your actual data, of course. But *generally* more smaller (narrower) tables are faster than fewer larger (wider) tables. | Is it better for faster access to split tables and JOIN in a SQL database or leave a few monolithic tables? | [
"",
"sql",
"database-design",
"optimization",
""
] |
thanks in advance for your help. I am wondering if there is a (design) pattern that can be applied to this problem.
**I am looking to parse, process, and extract out values from text files with similar, but differing formats.**
More specifically, I am building a processing engine that accepts Online Poker Hand History files from a multitude of different websites and parses out specific data fields (Hand #, DateTime, Players). I will need the logic to parse the files to be slightly different for each format, but the processing of the extracted values will be the same.
My first thought would be to create just 1 class that accepts a "schema" for each file type and parses/processes accordingly. I am sure there is a better solution to this.
Thanks!
**Bonus Point:**
Any specific implementation hints in C#. | This sounds like a candidate for the Strategy pattern. An example in C# can be found [here](http://www.dofactory.com/Patterns/PatternStrategy.aspx) and another one [here](http://www.c-sharpcorner.com/UploadFile/rmcochran/strategyPattern08072006095804AM/strategyPattern.aspx). A brief description is available on [Wikipedia](http://en.wikipedia.org/wiki/Strategy_pattern).
More complete descriptions is available in book by [Fowler](http://www.amazon.co.uk/Refactoring-Improving-Design-Existing-Technology/dp/0201485672/ref=sr_1_1?ie=UTF8&s=books&qid=1228233270&sr=8-1) and [Kerievsky](http://www.amazon.co.uk/Refactoring-Patterns-Addison-Wesley-Signature-Kerievsky/dp/0321213351/ref=pd_sim_b_5).
It is also available from the GoF book. | The "Provider" pattern is the one you're looking for... it is what is used in ADO.Net. Each database vendor has a separate data "Provider" that "knows" how to read the data from it's specific DB vendors product, but delivers it in a standard format (interface) to downstream systems... You will write a small "Provider" component (a single class will suffice) that "knows" the format for each of your different website poker history data providers, and exposes that data in exactly the same way to the upstream system that reads it... | Design Pattern: Parsing similar, but differing schemas in text files | [
"",
"c#",
".net",
"design-patterns",
"architecture",
"poker",
""
] |
You'll have to forgive my ignorance, but I'm not used to using wide character sets in c++, but is there a way that I can use wide string literals in c++ without putting an L in front of each literal?
If so, how? | No, there isn't. You have to use the L prefix (or a macro such as \_T() with VC++ that expands to L anyway when compiled for Unicode). | The new C++0x Standard defines another way of doing this:
<http://en.wikipedia.org/wiki/C%2B%2B0x#New_string_literals> | How to use wide string literals in c++ without putting L in front of each one | [
"",
"c++",
"string",
"literals",
""
] |
I found several controlsets for that nice looking ribbons (DotNetBar, DivElements, ...), but all require a license for at least 100 USD. Is there a free controlset that looks quite as nice as the commericial ones? | You can download the Microsoft WPF Ribbon Control through the Office Developer UI Licence.
It was meant to be released last week.
<http://windowsclient.net/wpf/wpf35/wpf-35sp1-ribbon-walkthrough.aspx>
I'll see if i can dig out a download link.
Edit:
Think this is what your looking for
[Office Fluent User Interface Developer Portal](http://msdn.microsoft.com/en-us/office/aa905530.aspx) | Might want to take a look at <http://arstechnica.com/journals/linux.ars/2007/08/30/mono-developer-brings-the-ribbon-interface-to-linux>
It's for mono, but might be worth a look. | Is there a way to create an desktop application with that office2007 toolbar for free? | [
"",
"c#",
".net",
"ribbon",
""
] |
I've long toyed with the idea of some kind of auto-cleanup page that performs routine maintenence tasks and is called out of scope of the current page execution by means of calling a 1x1 pixel gif with the asp.net page as the src parameter. One thing I've never really decided on, however, is how to handle the timing of such a page's execution so that it doesn't execute with every request, maybe like.. every 5th request. or every 30 minutes or some other interval.
How would you consider building such a mechanism? | I have come across this situation many times and I generally just end up using task scheduler to just call the page, that way it is consistent and reliable. The problem with relying on a page to be called is that you have to be sure that there will always be requests to your page. If you can guarantee that, then just store a variable at the application level with the timestamp of the last time the task was run and have every page check that timestamp and update it once a request comes in that has passed a certain threshold. | It sounds like you might want to use the global.asax file instead - assuming you want something to happen every Nth time. For example, if you wanted to do something for every 5th visitor to your site, you could do something along the lines of,
```
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["Sessions"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Application.Lock();
Application["Sessions"] = (int)Application["Sessions"] + 1;
if ((int)Application["Sessions"] % 5 == 0)
{
DoSomething();
Application["Sessions"] = 0;
}
Application.UnLock();
}
```
I would heavily recommend something along these lines rather than attaching a script to the source of a GIF file. You have much more control and security. | ASP.NET auto-executing page | [
"",
"c#",
"asp.net",
""
] |
Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?
I.e. I want to set a timeout on blocking socket in boost asio?
socket.read\_some(boost::asio::buffer(pData, maxSize), error\_);
Example: I want to read some from the socket, but I want to throw an error if 10 seconds have passed. | Under Linux/BSD the timeout on I/O operations on sockets is directly supported by the operating system. The option can be enabled via `setsocktopt()`. I don't know if `boost::asio` provides a method for setting it or exposes the socket scriptor to allow you to directly set it -- the latter case is not really portable.
For a sake of completeness here's the description from the man page:
> **SO\_RCVTIMEO** and **SO\_SNDTIMEO**
>
> ```
> Specify the receiving or sending timeouts until reporting an
> error. The argument is a struct timeval. If an input or output
> function blocks for this period of time, and data has been sent
> or received, the return value of that function will be the
> amount of data transferred; if no data has been transferred and
> the timeout has been reached then -1 is returned with errno set
> to EAGAIN or EWOULDBLOCK just as if the socket was specified to
> be non-blocking. If the timeout is set to zero (the default)
> then the operation will never timeout. Timeouts only have
> effect for system calls that perform socket I/O (e.g., read(2),
> recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for
> select(2), poll(2), epoll_wait(2), etc.
> ``` | TL;DR
```
socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{ 200 });
```
FULL ANSWER
This question keep being asked over and over again for many years. Answers I saw so far are quite poor. I'll add this info right here in one of the first occurrences of this question.
Everybody trying to use ASIO to simplify their networking code would be perfectly happy if the author would just add an optional parameter timeout to all sync and async io functions. Unfortunately, this is unlikely to happen (in my humble opinion, just for ideological reasons, after all, AS in ASIO is for a reason).
So these are the ways to skin this poor cat available so far, none of them especially appetizing. Let's say we need 200ms timeout.
1) Good (bad) old socket API:
```
const int timeout = 200;
::setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof timeout);//SO_SNDTIMEO for send ops
```
Please note those peculiarities:
- const int for timeout - on Windows the required type is actually DWORD, but the current set of compilers luckily has it the same, so const int will work both in Win and Posix world.
- (const char\*) for value. On Windows const char\* is required, Posix requires const void\*, in C++ const char\* will convert to const void\* silently while the opposite is not true.
Advantages: works and probably will always work as the socket API is old and stable. Simple enough. Fast.
Disadvantages: technically might require appropriate header files (different on Win and even different UNIX flavors) for setsockopt and the macros, but current implementation of ASIO pollutes global namespace with them anyway. Requires a variable for timeout. Not type-safe. On Windows, requires that the socket is in overlapped mode to work (which current ASIO implementation luckily uses, but it is still an implementation detail). UGLY!
2) Custom ASIO socket option:
```
typedef boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO> rcv_timeout_option; //somewhere in your headers to be used everywhere you need it
//...
socket.set_option(rcv_timeout_option{ 200 });
```
Advantages: Simple enough. Fast. Beautiful (with typedef).
Disadvantages: Depends on ASIO implementation detail, which might change (but OTOH everything will change eventually, and such detail is less likely to change then public APIs subject to standardization). But in case this happens, you'll have to either write a class according to <https://www.boost.org/doc/libs/1_68_0/doc/html/boost_asio/reference/SettableSocketOption.html> (which is of course a major PITA thanks to obvious overengineering of this part of ASIO) or better yet revert to 1.
3) Use C++ async/future facilities.
```
#include <future>
#include <chrono>
//...
auto status = std::async(std::launch::async, [&] (){ /*your stream ops*/ })
.wait_for(std::chrono::milliseconds{ 200 });
switch (status)
{
case std::future_status::deferred:
//... should never happen with std::launch::async
break;
case std::future_status::ready:
//...
break;
case std::future_status::timeout:
//...
break;
}
```
Advantages: standard.
Disadvantages: always starts a new thread (in practice), which is relatively slow (might be good enough for clients, but will lead to DoS vulnerability for servers as threads and sockets are "expensive" resources). Don't try to use std::launch::deferred instead of std::launch::async to avoid new thread launch as wait\_for will always return future\_status::deferred without trying to run the code.
4) The method prescribed by ASIO - use async operations only (which is not really the answer to the question).
Advantages: good enough for servers too if huge scalability for short transactions is not required.
Disadvantages: quite wordy (so I will not even include examples - see ASIO examples). Requires very careful lifetime management of all your objects used both by async operations and their completion handlers, which in practice requires all classes containing and using such data in async operations be derived from enable\_shared\_from\_this, which requires all such classes allocated on heap, which means (at least for short operations) that scalability will start taper down after about 16 threads as every heap alloc/dealloc will use a memory barrier. | How to set a timeout on blocking sockets in boost asio? | [
"",
"c++",
"sockets",
"boost",
"boost-asio",
""
] |
I am calling an executable in C#. When the executable runs, it writes out to the console so the C# code is getting the console output and writing it to a text file. When the crash happens a couple of things occur.
1) The output of the text file is not completely written out.
2) The executable process seems to run completely through because it generates a report just like a successful run.
I suspect that the reason for this crash is because of how I'm writing the file out.
Update:
- As far as the crash, a dialog comes up saying that the "Manager has encountered a problem and needs to close. We are sorry for the inconvenience." Then it has an OK button. When you click OK, there is a dialog that I have setup that asks if I want to start the manager again.
* The manager application that is calling the executable is single threaded. The executable may run multi-threaded.
Here is a small snippet of the call:
```
// Set up process to redirect standard output and standard error to
// a file.
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
FileInfo ofi = new FileInfo(outputPath);
FileStream ofs = ofi.OpenWrite();
StreamWriter sw = new StreamWriter(ofs);
WriteToTextWriterEventHandler wtsweh = new WriteToTextWriterEventHandler(sw);
DataReceivedEventHandler handler = wtsweh.HandleDataReceived;
process.OutputDataReceived += handler;
process.ErrorDataReceived += handler;
//
statusAcceptor.ReportStatus("Running process.");
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
statusAcceptor.ReportStatus("Waiting for process to complete.");
process.WaitForExit();
int processExitCode = process.ExitCode;
process.Close();
sw.Close();
//
private class WriteToTextWriterEventHandler
{
private TextWriter tw;
public WriteToTextWriterEventHandler(TextWriter tw)
{
this.tw = tw;
}
public void HandleDataReceived(object sendingProcess,
DataReceivedEventArgs outLine)
{
// Collect the sort command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
tw.Write(Environment.NewLine + outLine.Data);
}
}
}
``` | Try adding a flush after the tw.Write. That should cause the complete output up to the point of failure to be produced, which may include error messages from the executable (if that's what is crashing?) | What is the crash that you are getting? A .Net exception?
That the file is not written completely could be because you do not flush the stream into the file and then close it.
I think it might be a problem that you use the same stream for both standard out and error out messages. This might lead to concurrency problems. | Calling executable using Process crashes intermittently | [
"",
"c#",
"executable",
""
] |
```
SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value
FROM prodtree_element pe
LEFT JOIN prodtree_link pl
ON pe.prodtree_element_id = pl.to_prodtree_node_id
LEFT JOIN line li
ON pe.line_code = li.line_code
INNER JOIN attribute_values av
ON av.attribute_definition_id = #statusCode#
LEFT JOIN attribute_values av2
ON pe.prodtree_element_id = av.prodtree_element_id
WHERE pe.prodtree_element_func_type <> 'WIZARD'
AND pe.prodtree_element_topo_type = 'NODE'
```
"#statusCode#" is a static id that matches an id in the attribute definition table (let's say 22 for the sake of argument). The problem is, the query has some massive trouble finishing in any sane amount of time. The bigger problem is, I kinda need it to finish earlier, but the number of records is enormous that it has to draw back (around 30-50,000). I need data from multiple tables, which is where it starts to slow down. This is just a piece of what I need, I also need an entire other tables worth of data matching the current "prodtree\_elment\_id".
I'm using ColdFusion but even running the query directly in SQL Server 2005 creates the 15-30+ minute wait for this query (if it even finishes). Is there any conceivable way to speed up this query to take at most 5 minutes or less? | ```
INNER JOIN attribute_values av
ON av.attribute_definition_id = #statusCode#
LEFT JOIN attribute_values av2
ON pe.prodtree_element_id = av.prodtree_element_id
```
This is the problem.
There is a cross join between pe and av, followed by an outer join onto the cross join.
You're lucky it only takes 30 mins :-)
I think you want this:
```
SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value
FROM prodtree_element pe
LEFT JOIN prodtree_link pl
ON pe.prodtree_element_id = pl.to_prodtree_node_id
LEFT JOIN line li
ON pe.line_code = li.line_code
--replacement
LEFT JOIN
attribute_values av
ON pe.prodtree_element_id = av.prodtree_element_id AND
av.attribute_definition_id = #statusCode#
--end replacement
WHERE pe.prodtree_element_func_type <> 'WIZARD'
AND pe.prodtree_element_topo_type = 'NODE'
``` | Without knowing the DDL its very hard to test. 30-50K rows should still take only a few seconds.
Try switching the where clause ordering.
You should probably have this implemented
```
INNER JOIN attribute_values av
ON av.attribute_definition_id = #statusCode#
```
in the where clause. | Need to speed up this query in SQL Server | [
"",
"sql",
"sql-server",
"performance",
"t-sql",
"outer-join",
""
] |
I am doing some calculations that require a large array to be initialized. The maximum size of the array determines the maximum size of the problem I can solve.
Is there a way to programmatically determine how much memory is available for say, the biggest array of bytes possible?
Thanks | Well, relying on a single huge array has a range of associated issues - memory fragmentation, contiguous blocks, the limit on the maximum object size, etc. If you need a lot of data, I would recommend creating a class that simulates a large array using lots of smaller (but still large) arrays, each of fixed size - i.e. the indexer divides to to find the appropriate array, then uses % to get the offset inside that array.
You might also want to ensure you are on a 64-bit OS, with lots of memory. This will give you the maximum available head-room.
Depending on the scenario, more sophisticated algorithms such as sparse arrays, eta-vectors, etc might be of use to maximise what you can do. You might be amazed what people could do years ago with limited memory, and just a tape spinning backwards and forwards... | In order to ensure you have enough free memory you could use a [MemoryFailPoint](http://msdn.microsoft.com/en-us/library/system.runtime.memoryfailpoint.aspx). If the memory cannot be allocated, then an [InsufficientMemoryException](http://msdn.microsoft.com/en-us/library/system.insufficientmemoryexception.aspx) will be generated, which you can catch and deal with in an appropriate way. | Finding how much memory I can allocate for an array in C# | [
"",
"c#",
"memory",
""
] |
In my quest to learn javascript (which seems to be my latest source of questions for SO these days) i've found this API for drawing <http://www.c-point.com/javascript_vector_draw.htm>
Meanwhile I've been making some experiments with graphics, which tend to be heavy on the amount of stuff to draw. This guy is drawing with divs, every square part of the image is a div. You can easily check it by inspecting his example at the page.
He goes to making divs 1px/1px to draw a pixel
Now what i have to ask is the following:
Is this the best method? It seems quite heavy when a drawing is more elaborate. Which other methods would you sugest?
This [Javascript drawing library?](https://stackoverflow.com/questions/96486/javascript-drawing-library) already has a couple of links to libs so no need to put any here.
I've seen here in SO other questions regarding drawing. I'm just wondering to which point drawing with divs isn't awful! | for vector drawing, libraries like [Raphael](http://raphaeljs.com/) provide a consistent API over SVG and VML.
for raster drawing, you can use <canvas> for browsers that support canvas.
for IE, you would default to DIVS or have your drawing API use silverlight if it's available. Note that for efficiency, divs should not be 1px by 1px but rather be as long as necessary for the shape you are drawing. 20 1-pixel divs of the same color should be 1 div that is 20 pixels wide. Generally you won't get very interactive with the div approach, because the browser you're targetting (IE) has slow DOM access
**EDIT:** The linked library does do the div-optimizations.
for HTML-only solutions (no SVG/VML/canvas) you [use css and custom border-widths:](http://infimum.dk/HTML/slantinfo.html) | Not, it is the worst method, elaborated before there was SVG or canvas elements... It would be very heavy on memory and very slow. An amusing, interesting hack, but not really usable in the real world.
Beside the libraries mentioned in the other thread, relying on canvas/SVG/VML, I saw games made with sprites, ie. some images positioned absolutely. There was also an awesome hack coding a [first-person 3D shooting game in 5k of JavaScript](http://www.wolf5k.com/ "Wolfenstein 5K - A fun first-person 3D shooting game in 5k of JavaScript"), using generation of XBM images on the fly. But support for this image format have been removed from recent versions of Windows... :-(
Come to think of it, you can also make images using "data:image/png;base64" protocol, but the encoding would be quite slow, and IE browsers would be out. | Drawing in javascript with divs | [
"",
"javascript",
"drawing",
"html",
""
] |
I have got this error when using Enterprise Library 3.1 May 2007 version. We are developing a product and have a common lib directory beneath the Subversion Trunk directory
<>\Trunk\Lib\ into which we put all the third party DLLs. Inside this we have Microsoft\EnterpriseLibrary\v3.1 in which we have copied all the dlls from \Program Files\Microsoft Enterprise Library May2007\bin. Everything was working properly until one of the developers installed the source code on this machine. There were some dlls copied at the end of the source code installation and once that was done, he is not able to run the project anymore. He always gets this error
**'Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)'**
What is the problem here? I thought that when the source code was installed it was just supposed to build everything and copy in the bin directory within the source code parent directory. Also we have copied the Dlls from Microsoft Enterprise Library May 2007\bin directory into our product development directory and references into our project with a copylocal flag set to true.
Can anyone help me out here
RK | I used to get that when I developed against the signed version of the dll and deployed where only the unsigned version was available.
Also, [fuslogvw.exe](http://msdn.microsoft.com/en-us/library/e74a18c4(VS.71).aspx). EVERY. TIME. | I assume the error lies in the developer having compiled the code against the unsigned source code compilation he has.
Make sure he adds the reference to the signed DLLs before compiling his code.
Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, **PublicKeyToken=null**
should be something like:
Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, **PublicKeyToken=fa03fef243232** | System.IO.FileLoadException | [
"",
"c#",
".net",
"enterprise-library",
"fileloadexception",
""
] |
Edit: How to return/serve a file from a python controller (back end) over a web server, with the file\_name? as suggested by @JV | Fully supported in CherryPy using
```
from cherrypy.lib.static import serve_file
```
As documented in the [CherryPy docs - FileDownload](http://www.cherrypy.org/wiki/FileDownload):
```
import glob
import os.path
import cherrypy
from cherrypy.lib.static import serve_file
class Root:
def index(self, directory="."):
html = """<html><body><h2>Here are the files in the selected directory:</h2>
<a href="index?directory=%s">Up</a><br />
""" % os.path.dirname(os.path.abspath(directory))
for filename in glob.glob(directory + '/*'):
absPath = os.path.abspath(filename)
if os.path.isdir(absPath):
html += '<a href="/index?directory=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
else:
html += '<a href="/download/?filepath=' + absPath + '">' + os.path.basename(filename) + "</a> <br />"
html += """</body></html>"""
return html
index.exposed = True
class Download:
def index(self, filepath):
return serve_file(filepath, "application/x-download", "attachment")
index.exposed = True
if __name__ == '__main__':
root = Root()
root.download = Download()
cherrypy.quickstart(root)
``` | You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it.
Or, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle.
It is not recommended to pass the actual data as files can be arbiterally large and the program could run out of memory.
In your case, you probably want to return a tuple containing the open file handle, the file name and any other meta data you are interested in. | Return file from python module | [
"",
"python",
"file",
"mime-types",
"download",
""
] |
I often find myself using Integers to represent values in different "spaces". For example...
```
int arrayIndex;
int usersAge;
int daysToChristmas;
```
Ideally, I'd like to have separate classes for each of these types "Index","Years" and "Days", which should prevent me accidentally mixing them up. Typedefs are a help from a documnentation perspective, but aren't type-safe enough.
I've tried wrapper classes, but end up with too much boilerplate for my liking. Is there a straightforward template-based solution, or maybe something ready-to-go in Boost?
EDIT: Several people have talked about bounds-checking in their answers. That maybe a handy side-effect, but is NOT a key requirement. In particular, I don't just want to prevent out-of-bound assignments, but assignments between "inappropriate" types. | You could try BOOST\_STRONG\_TYPEDEF. From `boost/strong_typedef.hpp`:
```
// macro used to implement a strong typedef. strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation. typedef does not create
// a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.
``` | Boost does in fact have a library specifically for this type of thing! Check out the [Boost.Units library](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_units.html). | Multiple Integer-type classes in C++ | [
"",
"c++",
"class",
"boost",
"templates",
""
] |
Seeing as C# can't `switch` on a Type (which I gather wasn't added as a special case because `is` relationships mean that more than one distinct `case` might apply), is there a better way to simulate switching on type other than this?
```
void Foo(object o)
{
if (o is A)
{
((A)o).Hop();
}
else if (o is B)
{
((B)o).Skip();
}
else
{
throw new ArgumentException("Unexpected type: " + o.GetType());
}
}
``` | Switching on types is definitely lacking in C# (**UPDATE: in C#7 / VS 2017 switching on types is supported - [see Zachary Yates's answer](https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type/299001#299001)**). In order to do this without a large if/else if/else statement, you'll need to work with a different structure. I wrote a blog post awhile back detailing how to build a TypeSwitch structure.
<https://learn.microsoft.com/archive/blogs/jaredpar/switching-on-types>
Short version: TypeSwitch is designed to prevent redundant casting and give a syntax that is similar to a normal switch/case statement. For example, here is TypeSwitch in action on a standard Windows form event
```
TypeSwitch.Do(
sender,
TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
```
The code for TypeSwitch is actually pretty small and can easily be put into your project.
```
static class TypeSwitch {
public class CaseInfo {
public bool IsDefault { get; set; }
public Type Target { get; set; }
public Action<object> Action { get; set; }
}
public static void Do(object source, params CaseInfo[] cases) {
var type = source.GetType();
foreach (var entry in cases) {
if (entry.IsDefault || entry.Target.IsAssignableFrom(type)) {
entry.Action(source);
break;
}
}
}
public static CaseInfo Case<T>(Action action) {
return new CaseInfo() {
Action = x => action(),
Target = typeof(T)
};
}
public static CaseInfo Case<T>(Action<T> action) {
return new CaseInfo() {
Action = (x) => action((T)x),
Target = typeof(T)
};
}
public static CaseInfo Default(Action action) {
return new CaseInfo() {
Action = x => action(),
IsDefault = true
};
}
}
``` | [With C# 7](https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/), which shipped with Visual Studio 2017 (Release 15.\*), you are able to use Types in `case` statements (pattern matching):
```
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
```
With C# 6, you can use a switch statement with the [nameof() operator](https://msdn.microsoft.com/en-us/library/dn986596.aspx) (thanks @Joey Adams):
```
switch(o.GetType().Name) {
case nameof(AType):
break;
case nameof(BType):
break;
}
```
With C# 5 and earlier, you could use a switch statement, but you'll have to use a magic string containing the type name... which is not particularly refactor friendly (thanks @nukefusion)
```
switch(o.GetType().Name) {
case "AType":
break;
}
``` | Is there a better alternative than this to 'switch on type'? | [
"",
"c#",
"switch-statement",
"system.type",
""
] |
I am having a lot of trouble finding good information on how to call a standard SOAP/WSDL web service with Android. All I've been able to find are either very convoluted documents and references to "kSoap2" and then some bit about parsing it all manually with [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML). OK, that's fine, but it's 2008, so I figured there should be some good library for calling standard web services.
The web service is just basically one created in [NetBeans](http://en.wikipedia.org/wiki/NetBeans). I would like to have IDE support for generating the plumbing classes. I just need the easiest/most-elegant way to contact a [WSDL](http://en.wikipedia.org/wiki/Web_Services_Description_Language) based web service from an Android-based phone. | Android does not provide any sort of SOAP library. You can either write your own, or use something like [kSOAP 2](http://ksoap2.sourceforge.net/). As you note, others have been able to compile and use kSOAP2 in their own projects, but I haven't had to.
Google has shown, to date, little interest in adding a SOAP library to Android. My suspicion for this is that they'd rather support the current trends in Web Services toward REST-based services, and using JSON as a data encapsulation format. Or, using XMPP for messaging. But that is just conjecture.
XML-based web services are a slightly non-trivial task on Android at this time. Not knowing NetBeans, I can't speak to the tools available there, but I agree that a better library should be available. It is possible that the XmlPullParser will save you from using SAX, but I don't know much about that. | `org.apache.http.impl.client.DefaultHttpClient` comes in the Android SDK by default. That'll get you connected to the WSDL.
```
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.example.com/" + URL);
HttpResponse response = httpClient.execute(httpGet, localContext);
``` | How to call a SOAP web service on Android | [
"",
"java",
"android",
"web-services",
"soap",
"wsdl",
""
] |
I am trying to merge several XML files in a single XDocument object.
Merge does not exist in XDocument object. I miss this.
Has anyone already implemented a Merge extension method for XDocument, or something similar ? | I tried a bit myself :
```
var MyDoc = XDocument.Load("File1.xml");
MyDoc.Root.Add(XDocument.Load("File2.xml").Root.Elements());
```
I dont know whether it is good or bad, but it works fine to me :-) | Being pragmatic, `XDocument` vs `XmLDocument` isn't all-or-nothing (unless you are on Silverlight) - so if `XmlDoucument` does something you need, and `XDocument` doesn't, then perhaps use `XmlDocument` (with `ImportNode` etc).
That said, even with `XDocument`, you could presumably use `XNode.ReadFrom` to import each, then simply `.Add` it to the main collection.
Of course, if the files are big, `XmlReader/XmlWriter` might be more efficient... but more complex. Fortunately, `XmlWriter` has a `WriteNode` method that accepts an `XmlReader`, so you can navigate to the first child in the `XmlReader` and then just blitz it to the output file. Something like:
```
static void AppendChildren(this XmlWriter writer, string path)
{
using (XmlReader reader = XmlReader.Create(path))
{
reader.MoveToContent();
int targetDepth = reader.Depth + 1;
if(reader.Read()) {
while (reader.Depth == targetDepth)
{
writer.WriteNode(reader, true);
}
}
}
}
``` | Merge XML files in a XDocument | [
"",
"c#",
"xml",
"linq-to-xml",
""
] |
What would be the benefit of using decimal.compare vs. just using a > or < to compare to variables? | In the CLI, decimal is not a native type like Int32, String, and others are. I am guessing that C# uses Compare behind the scenes to implement the comparison operators.
Also, you can pass Compare as a parameter to a sort routine without creating a delegate, reducing the method-nesting levels inside the sort.
That’s a couple of things off the top of my head. | For one thing it makes it really easier to build a [`Comparison<decimal>`](http://msdn.microsoft.com/en-us/library/tfakywbh.aspx) delegate instance:
```
Comparison<decimal> foo = decimal.Compare;
```
This is handy to pass into things which take arbitrary comparison delegates.
It may also be useful if you're using a language which doesn't support overloaded operators. That's the reason it's recommended that you don't expose functionality which is *only* supported by operators. | C# decimal.compare vs. > or < | [
"",
"c#",
"comparison",
""
] |
The documentation of the Python [`readline`](http://www.python.org/doc/2.5.2/lib/module-readline.html) module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:
```
$ uname -a
Darwin greg.local 8.11.1 Darwin Kernel Version 8.11.1: Wed Oct 10 18:23:28 PDT 2007; root:xnu-792.25.20~1/RELEASE_I386 i386 i386
$ which python
/usr/bin/python
$ python
Python 2.3.5 (#1, Nov 26 2007, 09:16:55)
[GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named readline
>>>
```
I have also installed Python 2.5 through MacPorts but `readline` is not available there either.
What can I do to provide `readline` functionality for Python's `raw_input()` function on OS X? | Have you tried to install the `py-readline` (or `py25-readline` for Python 2.5) port?
Also, in the snippet above, you are NOT using the MacPort python, but rather the Apple Python.
The MacPort version should be located in the `/opt/local` directory structure. You should check your path. | Try `rlwrap`. It should work with any version of python and in general any shell.
Install via `brew install rlwrap` on Mac OS X
usage as `rlwrap python`. It stores history as well. | Why is the Python readline module not available on OS X? | [
"",
"python",
"macos",
"readline",
""
] |
Having recently introduced an overload of a method the application started to fail.
Finally tracking it down, the new method is being called where I did not expect it to be.
We had
```
setValue( const std::wstring& name, const std::wstring& value );
std::wstring avalue( func() );
setValue( L"string", avalue );
std::wstring bvalue( func2() ? L"true", L"false" );
setValue( L"bool", bvalue );
setValue( L"empty", L"" );
```
It was changed so that when a bool value is stored we use the same strings (internal data storage of strings)
```
setValue( const std::wstring& name, const std::wstring& value );
setValue( const std::wstring& name, const bool& value );
std::wstring avalue( func() );
setValue( L"string", avalue );
setValue( L"bool", func2() );
setValue( L"empty", L"" ); << --- this FAILS!?!
```
The problem with L"" is that it is implicitly casting and previously it was happy to be a std::wstring, but not it prefers to be a bool.
The MSVC compiler does not complain, or raise warning, so I'm worried that even if I "fix" the setValue( L"empty", L"" ); to be
```
setValue( L"empty", std::wstring() );
```
somebody else may come later and simply use setValue( L"empty", L"" ); and have to track down this issue again.
We thought to use explicit on the method but it is not a valid keyword for this usage.
Is there some way to get the compiler to complain about this, or otherwise prevent the issue? Otherwise I'm thinking to change the name of the method which takes a bool to ensure it can't make an incorrect guess. | First, the cause of this issue: C++ Standard [`[over.ics.rank]/2.1`](http://eel.is/c++draft/over.ics.rank#2.1)1 defines an order for conversion sequences. It says that a user defined conversion sequence is worse than a standard conversion sequence. What happens in your case is that the string literal undergoes a boolean-conversion (defined at `4.12`. This is a standard conversion). It does not use the user defined conversion to `std::wstring` which would be needed if it took the other overload.
I would recommend to simply change the name of one of the overloads or adding an overload that accepts the string literal directly (using parameter type `wchar_t const*`).
---
1)
> When comparing the basic forms of implicit conversion sequences (as defined in `[over.best.ics]`)
>
> (2.1) a standard conversion sequence is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and
> (2.2) a user-defined conversion sequence is a better conversion sequence than an ellipsis conversion sequence. | L"" is a pointer to a wide character string. The compiler believes that the conversion to a bool takes precedence over a conversion to a std::wstring.
To fix the problem, introduce a new setValue:
```
void setValue(std::wstring const& name, const wchar_t * value);
``` | Why does the compiler choose bool over string for implicit typecast of L""? | [
"",
"c++",
"visual-c++",
"implicit",
"explicit",
""
] |
I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.
Currently, I have this:
```
import sys
sys.path.append('..//shared1//reusable_foo')
import Foo
sys.path.append('..//shared2//reusable_bar')
import Bar
```
My preference would be the following:
```
import Foo
import Bar
```
My background is primarily in the .NET platform so I am accustomed to having meta files such as \*.csproj, \*.vbproj, \*.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.
Does Python have equivalent support for this and, if not, what are some techniques and approaches? | The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path.
You can also extend the search path by adding .pth files somewhere in your path.
See <https://docs.python.org/2/install/#modifying-python-s-search-path> for more details
Oh, and python 2.6/3.0 adds support for PEP370, [Per-user site-packages Directory](http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory) | If your reusable files are packaged (that is, they include an `__init__.py` file) and the path to that package is part of your PYTHONPATH or sys.path then you should be able to do just
```
import Foo
```
[This question](https://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder#279287) provides a few more details.
(Note: As Jim said, you could also drop your reusable code into your `site-packages` directory.) | In Python, how can I efficiently manage references between script files? | [
"",
"python",
"scripting",
"metadata",
""
] |
I have **CustomForm** inherited from **Form** which implements a boolean property named **Prop**. The forms I'll be using will inherit from **CustomForm**. This property will do some painting and changes (if it's enabled) to the form. However, this is not working as it should, the VS IDE designed is not being refresh to show the changes. But if I press Ctrl+Shift+B (Menu: Build » Build Solution) the VS IDE will refresh, the form designer will even disappear for a split second and will redraw itself with the new changes applied.
So, is there a way, by code, to force the VS IDE designer to refresh itself just like it happens when I build the solution? If so, I could add that code to the **Prop** set accessor and my problem was gone.
Note that I've tried to call Invalidate(), Refresh() and Update. But none of them seemed to fix the problem...
---
Here's a little insight on my real problem. My code goes something like this:
```
internal class MyForm : Form {
private FormBorderStyle formBorderStyle;
private bool enableSkin;
[DefaultValue(false)]
public bool EnableSkin {
get {
return enableSkin;
} set {
enableSkin = value;
if(enableSkin) {
BackColor = Color.Lime;
MaximizedBounds = Screen.GetWorkingArea(this);
TransparencyKey = Color.Lime;
base.FormBorderStyle = FormBorderStyle.None;
} else {
BackColor = SystemColors.Control;
MaximizedBounds = Rectangle.Empty;
TransparencyKey = Color.Empty;
base.FormBorderStyle = FormBorderStyle;
}
}
}
[DefaultValue(FormBorderStyle.Sizable)]
public new FormBorderStyle FormBorderStyle {
get {
return formBorderStyle;
} set {
formBorderStyle = value;
if(EnableSkin) {
base.FormBorderStyle = FormBorderStyle.None;
} else {
base.FormBorderStyle = formBorderStyle;
}
}
}
internal MyForm() {
EnableSkin = false;
FormBorderStyle = FormBorderStyle.Sizable;
}
}
```
And the problem I'm having is something like this: <http://blogs.msdn.com/calvin_hsia/archive/2007/05/01/windows-vista-aero-borderstyle-paint-problem-as-non-administrator.aspx>
In my case, that happens when you set the EnableSkin to True, change it back to False and then, changing the FormBorderStyle will cause the issue you can see on the link above. As stated in the article, the problem doesn't happen when running VS as administrator.
That's why I'm looking for a way to refresh the VS IDE designer. In other words, now that I've found that article, I need to recreate the window just like it happens when the solution is rebuilt.
---
How do I declare a property in the base form?
I currently have:
```
public class MyForm : Form { }
```
And I can only declare properties inside that class, not inside the Form one... I also have used Invalidate() as I said in the first post, but it doesn't fix my problem. | Someone else helped me out and to fix the problem. I just call **ReCreateHandle()** when the user sets **EnableSkin** to false. Problem solved :)
Thanks everyone though :) | All you need to do is add this Attribute to your property:
```
[Description("Description of your property."), NotifyParentProperty(true),
RefreshProperties(RefreshProperties.Repaint)]
```
That will cause the IDE to repaint when the value is changed. | Question How to invalidate/refresh the VS IDE designer for C#? | [
"",
"c#",
"visual-studio-2008",
"ide",
"refresh",
"designer",
""
] |
I'm looking at doing some work (for fun) in a compiled language to run some simple tests and benchmarks against php.
Basically I'd like to see what other people use for C++ CGI programming. (Including backend database, like mysql++ or something else) | I'm not sure exactly what you're looking for, but there is a C++ web framework called wt (pronounced "witty"). It's been kept pretty much up to date and if you want robust C++ server-side code, this is probably what you're looking for.
You can check it out and read more at the [wt homepage](http://www.webtoolkit.eu/wt/).
P.S. You may have some trouble installing wt if you don't have experience with \*nix or C++ libraries. There are walkthroughs but since frameworks like these are the road less traveled, expect to hit a few bumps. | Another option is the Cgicc library which appears to be mature (currently at version 3.x):
<http://www.gnu.org/software/cgicc/> | Which C++ Library for CGI Programming? | [
"",
"c++",
"cgi",
""
] |
Is there an API to access Subversion from C#? | [**Svn.NET**](http://www.pumacode.org/projects/svndotnet/) is a continuation (fork) of [SubversionSharp](http://www.softec.st/en/OpenSource/ClrProjects/SubversionSharp/SubversionSharp.html) mentioned in [CMS](https://stackoverflow.com/users/5445/cms)'s [answer](https://stackoverflow.com/questions/287862/subversion-access-from-net#287869). SubversionSharp is limited to the .NET 1.1 platform.
Svn.NET supports the following platforms:
* .NET 2.0 on Windows Platforms
* Mono on Win32 (2.0 framework)
* Mono on Linux (2.0 framework) | [SharpSvn](http://sharpsvn.net/) is a new Subversion wrapper library for .Net/C# that hides all interopand memory management for you and includes a staticly compiled Subversion library for easy integration. It is probably the only Subversion binding designed to perform well in a multithreaded environment.
SharpSvn is not platform independent, but it makes it really easy to use Subversion from your .Net applications. Several projects switched from other libraries to using SharpSvn in the last year. (AnkhSVN, Collabnet desktop for Visual Studio, SharpForge, to name a few) | Is there a Subversion API that can be used to program against in .NET | [
"",
"c#",
".net",
"svn",
""
] |
How do I check if a string represents a numeric value in Python?
```
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
```
The above works, but it seems clunky.
---
If what you are testing comes from user input, it is *still* a string *even if it represents* an `int` or a `float`. See [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/) for converting the input, and [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/) for ensuring that the input represents an `int` or `float` (or other requirements) before proceeding. | > Which, not only is ugly and slow
I'd dispute both.
A regex or other string parsing method would be uglier and slower.
I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.
The issue is that any numeric conversion function has two kinds of results
* A number, if the number is valid
* A status code (e.g., via errno) or exception to show that no valid number could be parsed.
C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.
I think your code for doing this is perfect. | For non-negative (unsigned) integers only, use [`isdigit()`](https://docs.python.org/3/library/stdtypes.html#str.isdigit "str.isdigit"):
```
>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
```
---
Documentation for `isdigit()`: [Python2](https://docs.python.org/2/library/stdtypes.html#str.isdigit), [Python3](https://docs.python.org/3/library/stdtypes.html#str.isdigit)
For Python 2 Unicode strings:
[`isnumeric()`](https://docs.python.org/2/library/stdtypes.html#unicode.isnumeric "unicode.isnumeric"). | How do I check if a string represents a number (float or int)? | [
"",
"python",
"casting",
"floating-point",
"type-conversion",
""
] |
I have a huge dictionary of blank values in a variable called current like so:
```
struct movieuser {blah blah blah}
Dictionary<movieuser, float> questions = new Dictionary<movieuser, float>();
```
So I am looping through this dictionary and need to fill in the "answers", like so:
```
for(var k = questions.Keys.GetEnumerator();k.MoveNext(); )
{
questions[k.Current] = retrieveGuess(k.Current.userID, k.Current.movieID);
}
```
Now, this doesn't work, because I get an InvalidOperationException from trying to modify the dictionary I am looping through. However, you can see that the code should work fine - since I am not adding or deleting any values, just modifying the value. I understand, however, why it is afraid of my attempting this.
What is the preferred way of doing this? I can't figure out a way to loop through a dictionary WITHOUT using iterators.
I don't really want to create a copy of the whole array, since it is a lot of data and will eat up my ram like its still Thanksgiving.
Thanks,
Dave | Matt's answer, getting the keys first, separately is the right way to go. Yes, there'll be some redundancy - but it will work. I'd take a working program which is easy to debug and maintain over an efficient program which either won't work or is hard to maintain any day.
Don't forget that if you make `MovieUser` a reference type, the array will only be the size of as many references as you've got users - that's pretty small. A million users will only take up 4MB or 8MB on x64. How many users have you really got?
Your code should therefore be something like:
```
IEnumerable<MovieUser> users = RetrieveUsers();
IDictionary<MovieUser, float> questions = new Dictionary<MovieUser, float>();
foreach (MovieUser user in users)
{
questions[user] = RetrieveGuess(user);
}
```
If you're using .NET 3.5 (and can therefore use LINQ), it's even easier:
```
IDictionary<MovieUser, float> questions =
RetrieveUsers.ToDictionary(user => user, user => RetrieveGuess(user));
```
Note that if `RetrieveUsers()` can stream the list of users from its source (e.g. a file) then it will be efficient anyway, as you never need to know about more than one of them at a time while you're populating the dictionary.
A few comments on the rest of your code:
* Code conventions matter. Capitalise the names of your types and methods to fit in with other .NET code.
* You're not calling `Dispose` on the `IEnumerator<T>` produced by the call to `GetEnumerator`. If you just use `foreach` your code will be simpler *and* safer.
* `MovieUser` should almost certainly be a class. Do you have a genuinely good reason for making it a struct? | Is there any reason you can't just populate the dictionary with both keys and values at the same time?
```
foreach(var key in someListOfKeys)
{
questions.Add(key, retrieveGuess(key.userID, key.movieID);
}
``` | Hopefully simple question about modifying dictionaries in C# | [
"",
"c#",
".net",
"dictionary",
""
] |
In Visual c# Express Edition, is it possible to make some (but not all) items in a ListBox bold? I can't find any sort of option for this in the API. | You need to change listbox's DrawMode to DrawMode.OwnerDrawFixed. Check out these articles on msdn:
[DrawMode Enumeration](http://msdn.microsoft.com/en-us/library/system.windows.forms.drawmode.aspx)
[ListBox.DrawItem Event](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.drawitem.aspx)
[Graphics.DrawString Method](http://msdn.microsoft.com/en-us/library/19sb1bw6.aspx)
Also look at this question on msdn forums:
[Question on ListBox items](http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/dacea8cd-963e-4a40-9af6-1495acf1d3c5/)
A simple example (both items - Black-Arial-10-Bold):
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ListBox1.Items.AddRange(new Object[] { "First Item", "Second Item"});
ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
}
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font("Arial", 10, FontStyle.Bold), Brushes.Black, e.Bounds);
e.DrawFocusRectangle();
}
}
``` | To add to Mindaugas Mozūras's solution, I had a problem where my `e.Bounds` wasn't large enough and text was getting cut off. To solve this problem (thanks to a post [here](http://arstechnica.com/civis/viewtopic.php?f=20&t=314206)), you override the `OnMeasureItem` event and changes your DrawMode to `DrawMode.OwnerDrawVariable`.
In designer:
```
listBox.DrawMode = DrawMode.OwnerDrawVariable;
```
In handler:
```
void listBox_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = 18;
}
```
Solved my issues of having the height cut off text. | How can I make some items in a ListBox bold? | [
"",
"c#",
".net",
"visual-studio",
"listbox",
""
] |
I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.
I've seen a model of testing for
```
$b.parents('nodename').length>0
```
Which is fantastic when you only need to check if an element is a child of any node by that name.
But what about a specific node? You can't test
```
$b.parents($a).length>0
```
Because jQuery parents takes a nodename expression as an argument to filter.
As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.
Thanks! | In [jQuery ancestors using jQuery objects](https://stackoverflow.com/questions/245241/jquery-ancestors-using-jquery-objects#245266) I suggested
```
if ($(obj1).parents().index($(obj2)) >= 0) {
// obj1 is a descendant of obj2
}
``` | ```
a.contains(b)
```
This is a pure JavaScript solution using [Node.contains](https://developer.mozilla.org/en-US/docs/DOM/Node.contains). The function is inclusive, `a.contains(a)` evaluates to true.
There's an edge case in IE9: if `b` is a text node, `contains` will always return false. | Testing objects for ancestor/descendent relationship in JavaScript or Jquery | [
"",
"javascript",
"jquery",
"dom",
""
] |
I've got an `RSA` private key in `PEM` format, is there a straight forward way to read that from .NET and instantiate an `RSACryptoServiceProvider` to decrypt data encrypted with the corresponding public key? | ### Update 03/03/2021
.NET 5 now supports this out of the box.
To try the code snippet below, generate a keypair and encrypt some text at <http://travistidwell.com/jsencrypt/demo/>
```
var privateKey = @"-----BEGIN RSA PRIVATE KEY-----
{ the full PEM private key }
-----END RSA PRIVATE KEY-----";
var rsa = RSA.Create();
rsa.ImportFromPem(privateKey.ToCharArray());
var decryptedBytes = rsa.Decrypt(
Convert.FromBase64String("{ base64-encoded encrypted string }"),
RSAEncryptionPadding.Pkcs1
);
// this will print the original unencrypted string
Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes));
```
### Original answer
I solved, thanks. In case anyone's interested, [bouncycastle](http://www.bouncycastle.org/) did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:
```
var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(@"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key
keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair.Private);
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
``` | With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is "No, not with a PEM of the private key alone."
However, as alluded to above by Simone, you can simply combine the PEM of the private key (\*.key) and the certificate file using that key (\*.crt) into a \*.pfx file which can then be easily imported.
To generate the PFX file from the command line:
```
openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx
```
Then use normally with the .NET certificate class such as:
```
using System.Security.Cryptography.X509Certificates;
X509Certificate2 combinedCertificate = new X509Certificate2(@"C:\path\to\file.pfx");
```
Now you can follow the example from [MSDN](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.aspx) for encrypting and decrypting via RSACryptoServiceProvider:
I left out that for decrypting you would need to import using the PFX password and the Exportable flag. (see: [BouncyCastle RSAPrivateKey to .NET RSAPrivateKey](https://stackoverflow.com/questions/949727/bouncycastle-rsaprivatekey-to-net-rsaprivatekey))
```
X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
X509Certificate2 cert = new X509Certificate2("my.pfx", "somepass", flags);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
RSAParameters rsaParam = rsa.ExportParameters(true);
``` | How to read a PEM RSA private key from .NET | [
"",
"c#",
".net",
"cryptography",
"rsa",
""
] |
I have an application that is using Windows Authentication and a SqlRoleProvider for user authentication and role management respectively. It is working fine with my test users that I have added to the database as defaults. The application requires users to login (using Windows credentials) and then be able to use this internal application as a basic "user". If the user needs to be added to a high level role, an admin would be responsible for this after the first log in.
With that said, how would I add a user to the default role when they first log in? Logically, I know that I would need to call Roles.IsUserInRole() and then add them if they are not; however, where would I do this? I'm having trouble locating which event in the Global.asax to use.
Thanks
**EDIT:**
To expand the scenario a bit, I'm not using a full membership provider system due to requirements on writing new providers to allow the connection string to be stored outside of the web.config. I am not using any form of registration or login page and letting the Windows Integrated Authentication in IIS handle the authentication aspects while my enhanced SqlRoleProvider manages the user roles. The system is working fine for users that I have setup roles via hard coded tests. I am just looking for a way to add new users (who would be authenticated by IIS) to be immediately added to a default "Users" role. I think I found it; however, am now examining ways to make it not fire upon every request for performance reasons. | I was able to locate the solution after digging and playing around a bit more. I added the following code to my Global.asax file and it is accomplishing what I am hoping for.
```
protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)
{
if (!Roles.IsUserInRole(e.Identity.Name, "Users"))
{
Roles.AddUsersToRole(new string[] { e.Identity.Name }, "Users");
}
}
```
I'm concerned since this code fires with every page request. Is there a better way to limit when this occurs? Should I just add this code to the landing page's page\_load event instead of the Global.asax? | I would add the default role to the user directly after the user was fetched.
Something like such:
```
user = Membership.GetUser()
if (user != null)
{
// default role
string[] defaultRoles = {"MyRole"};
AddUsersToRoles(user, defaultRoles);
}
``` | How do I set a default role for a new user using Windows Authentication with the SqlRoleProvider? | [
"",
"c#",
"asp.net",
"security",
"windows-authentication",
""
] |
What is the difference and what should go in each?
If I understand the theory correctly, the query optimizer should be able to use both interchangeably.
(Note: this question is *not* a duplicate of [Explicit vs Implicit SQL Joins](https://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins).
The answer may be related (or even the same) but the **question** is different.) | They are not the same thing.
Consider these queries:
```
SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID
WHERE Orders.ID = 12345
```
and
```
SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID
AND Orders.ID = 12345
```
The first will return an order and its lines, if any, for order number `12345`.
The second will return all orders, but only order `12345` will have any lines associated with it.
With an `INNER JOIN`, the clauses are *effectively* equivalent. However, just because they are functionally the same, in that they produce the same results, does not mean the two kinds of clauses have the same semantic meaning. | * Does **not** matter for **inner** joins
* **Does** matter for **outer** joins
a. **`WHERE` clause**: Records will be ***filtered after join*** has taken place.
b. **`ON` clause**: Records, from the right table, will be ***filtered before joining***. This may end up as null in the result (since OUTER join).
**Example**: Consider the below two tables:
1. documents:
| id | name |
| --- | --- |
| 1 | Document1 |
| 2 | Document2 |
| 3 | Document3 |
| 4 | Document4 |
| 5 | Document5 |
2. downloads:
| id | document\_id | username |
| --- | --- | --- |
| 1 | 1 | sandeep |
| 2 | 1 | simi |
| 3 | 2 | sandeep |
| 4 | 2 | reya |
| 5 | 3 | simi |
a) Inside `WHERE` clause:
```
SELECT documents.name, downloads.id
FROM documents
LEFT OUTER JOIN downloads
ON documents.id = downloads.document_id
WHERE username = 'sandeep'
```
For the above query, the intermediate join table will look like this.
| id(from documents) | name | id (from downloads) | document\_id | username |
| --- | --- | --- | --- | --- |
| 1 | Document1 | 1 | 1 | sandeep |
| 1 | Document1 | 2 | 1 | simi |
| 2 | Document2 | 3 | 2 | sandeep |
| 2 | Document2 | 4 | 2 | reya |
| 3 | Document3 | 5 | 3 | simi |
| 4 | Document4 | NULL | NULL | NULL |
| 5 | Document5 | NULL | NULL | NULL |
After applying the `WHERE` clause and selecting the listed attributes, the result will be:
| name | id |
| --- | --- |
| Document1 | 1 |
| Document2 | 3 |
b) Inside `JOIN` clause
```
SELECT documents.name, downloads.id
FROM documents
LEFT OUTER JOIN downloads
ON documents.id = downloads.document_id
AND username = 'sandeep'
```
For above query the intermediate join table will look like this.
| id(from documents) | name | id (from downloads) | document\_id | username |
| --- | --- | --- | --- | --- |
| 1 | Document1 | 1 | 1 | sandeep |
| 2 | Document2 | 3 | 2 | sandeep |
| 3 | Document3 | NULL | NULL | NULL |
| 4 | Document4 | NULL | NULL | NULL |
| 5 | Document5 | NULL | NULL | NULL |
Notice how the rows in `documents` that did not match both the conditions are populated with `NULL` values.
After Selecting the listed attributes, the result will be:
| name | id |
| --- | --- |
| Document1 | 1 |
| Document2 | 3 |
| Document3 | NULL |
| Document4 | NULL |
| Document5 | NULL | | SQL JOIN: what is the difference between WHERE clause and ON clause? | [
"",
"sql",
"join",
"where-clause",
"on-clause",
""
] |
I need to bitwise shift a value 64 times in JavaScript. But JavaScript starts rounding after `32`.
For example:
```
for(var j = 0; j < 64; j++)
{
mask = mask << 1;
console.log(mask);
}
```
This prints value from `0` to `1073741824` but then rounds of and starts printing `0`. | "In Java, the bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow. JavaScript is rarely used for doing bit manipulation." - Douglas Crockford, [Javascript: The Good Parts](http://safari.oreilly.com/9780596517748/bitwise_operators)
The point is that you don't really have any reason to use bitwise operators. Just multiply or divide by 2^numbits.
Your code should be:
```
for(var j = 0; j < 64; j++) {
mask = mask * 2;
console.log(mask);
}
```
Or generally:
```
function lshift(num, bits) {
return num * Math.pow(2,bits);
}
```
You get the idea. | JavaScript stores all its numbers as 64 bit initally, but as soon as you start using bitwise operators the interpreter converts the number to a 32 bit representation..
Bitwise operators are a bit hacky in JS and so annoyingly you will probably have to do something a bit more clever, like write your own 64 bit functions. | JavaScript: Bitwise shift of long long number | [
"",
"javascript",
""
] |
How can I use a database and PHP sessions to store a user's shopping cart? I am using CodeIgniter, if that helps.
Example code would also be nice. | I would write an add to basket function like this:
```
function AddToBasket(){
if(is_numeric($_GET["ID"])){
$ProductID=(int)$_GET["ID"];
$_SESSION["Basket"][]=$ProductID;
$sOut.=ShowBasketDetail();
return $sOut;
}
}
```
In this shopping basket function we save Product IDs in an session array.
Here is what I would have in the show basket function:
```
function ShowBasket(){
foreach($_SESSION[Basket] as $ProductID){
$sql="select * from products where ProductID=$ProductID";
$result=mysql_query($sql);
$row=mysql_fetch_row($result);
echo "Product: ".$row[0];
}
}
```
For each ProudctID in our session basket we make a SQL query to output product information.
Now last but not least, a clear basket function:
```
function ClearBasket(){
unset($_SESSION[Basket]);
}
```
Don't forget `session_start();` before you add any Product IDs to your session basket. Also don't forget the `mysql_connect();` function, you need this before you make any queries with the database. | I would recommend that you look at [the CodeIgnitor Session Class](http://codeigniter.com/user_guide/libraries/sessions.html).
Additionally, you could look at [Chris Shiflett's discussion](http://shiflett.org/articles/storing-sessions-in-a-database) on this topic. | How can I use a database and PHP sessions to store a user's shopping cart? | [
"",
"php",
"codeigniter",
""
] |
I'm trying to get information like OS version, hard disk space, disk space available, and installed RAM on a Linux system in C++. I know I can use `system()` to run different Linux commands and capture their output (which is what I'm currently doing) but I was wondering if there's a better way? Is there something in the C++ standard library that I can use to get information from the operating system? | If you are using \*nix commands via system.
Then do man scroll to the bottom of the man page and it will usually show you what relevant C system calls are related.
```
Example: man uname:
SEE ALSO
uname(2), getdomainname(2), gethostname(2)
Explanation of numbers:
(1): User UNIX Command
(2): Unix and C system calls
(3): C Library routines
(4): Special file names
(5): File formats
(6):
(7):
(8): System admin commands
```
So if you are using system("uname"). From the man page you can see that there is also a uname C system call (uname(2)). So you can now do a 'man 2 uname' to get information about how to use the C system call uname. | There is nothing in the C++ Standard library for these purposes. The library you could use is `libhal`, which abstracts the view of programs to the hardware, collecting various informations from `/proc`, `/sys` and others. [HAL](http://www.freedesktop.org/wiki/Software/hal), scroll down, there seems to be an unofficial C++ binding available too (haven't tested it though, while libhal works also fine for C++ programs). Use the command `lshal` to display all device informations available to HAL. | How do I read system information in C++? | [
"",
"c++",
"linux",
"operating-system",
"system",
""
] |
In answering this question (<https://stackoverflow.com/questions/352317/c-coding-question#352327>), it got me wondering...
Is there any danger in regarding a static class as being equivalent to a non-static class instatiation that implements the singleton pattern? | The only thing that seems immediately apparent to me is that a static class is basically just a collection of scoped functions (explicitly avoiding "methods" here) and a singleton is still something you can instantiate, even if you can only have 1. 1 > 0.
You can pass a singleton as an argument to something that expects an object of a certain interface, you cannot pass a static class anywhere (except through some reflection trickery) | In many ways, a static class and a singleton are similar. One big difference is that a singleton might implement some interfaces, which isn't possible with a static class. For example, `Comparer<T>.Default` / `EqualityComparer<T>.Default` provide (via the interface) the ability to use the item in sorting / dictionary usage.
It is also possible (though tricky) to use a singleton with the standard serialization frameworks. With a static class, you'd have to manage any state persistence manually. | Static classes in c# | [
"",
"c#",
"design-patterns",
"static",
"singleton",
""
] |
Good day,
We just converted our web application .NET 1.1 to .NET 2.0. We have a major problem sending emails.
We are using distribution group (eg: WebDeveloppersGroup) to send emails to all the developpers in the company. These groups don't end with '@ something.com'. These groups are created in Lotus Notes, and we cannot access all the individual emails contained in these groups
In .NET 2.0 you cannot use email.To and are required to use: email.To.Add("WebDeveloppersGroup");
This causes a System.Format with the following message:
The specified string is not in the form required for an e-mail address.
Does anyone know how to send to an email group in 2.0 ? | I believe you can interact with Lotus Notes from .net and query it to get you the xyz@xyz.xyz addresses in the group. I'm not very familiar with it but you could start here:
* <http://www.codeproject.com/KB/cs/lotusnoteintegrator.aspx>
* [IBM Lotus Notes and .NET](http://www.ibm.com/developerworks/lotus/library/domino-msnet/index.html?S_TACT=105AGX13&S_CMP=EDU)
Good luck! | You can give the groups a full internet e-mail address. Ask your admin if you don't know how. | .NET 2.0: Sending email to a distribution group | [
"",
"c#",
"email",
".net-2.0",
""
] |
I need to use a datetime.strptime on the text which looks like follows.
"Some Random text of undetermined length Jan 28, 1986"
how do i do this? | Using the ending 3 words, no need for regexps (using the `time` module):
```
>>> import time
>>> a="Some Random text of undetermined length Jan 28, 1986"
>>> datetuple = a.rsplit(" ",3)[-3:]
>>> datetuple
['Jan', '28,', '1986']
>>> time.strptime(' '.join(datetuple),"%b %d, %Y")
time.struct_time(tm_year=1986, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=28, tm_isdst=-1)
>>>
```
Using the `datetime` module:
```
>>> from datetime import datetime
>>> datetime.strptime(" ".join(datetuple), "%b %d, %Y")
datetime.datetime(1986, 1, 28, 0, 0)
>>>
``` | You may find [this](https://stackoverflow.com/questions/285408/python-module-to-extract-probable-dates-from-strings) question useful. I'll give the answer I gave there, which is to use the [dateutil](http://labix.org/python-dateutil) module. This accepts a fuzzy parameter which will ignore any text that doesn't look like a date. ie:
```
>>> from dateutil.parser import parse
>>> parse("Some Random text of undetermined length Jan 28, 1986", fuzzy=True)
datetime.datetime(1986, 1, 28, 0, 0)
``` | How do I strptime from a pattern like this? | [
"",
"python",
"regex",
"datetime",
""
] |
Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first.
This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as `Decimal("%.15f" % my_float)`, which will give you garbage at the 15th decimal place if you also have any significant digits before decimal (`Decimal("%.15f" % 100000.3) == Decimal('100000.300000000002910')`).
Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported? | ### Python <2.7
```
"%.15g" % f
```
Or in Python 3.0:
```
format(f, ".15g")
```
### Python 2.7+, 3.2+
Just pass the float to `Decimal` constructor directly, like this:
```
from decimal import Decimal
Decimal(f)
``` | I suggest this
```
>>> a = 2.111111
>>> a
2.1111110000000002
>>> str(a)
'2.111111'
>>> decimal.Decimal(str(a))
Decimal('2.111111')
``` | Python float to Decimal conversion | [
"",
"python",
"decimal",
""
] |
I'm using .NET 2.0, and a recent code change has invalidated my previous Assert.AreEqual call (which compared two strings of XML). Only one element of the XML is actually different in the new codebase, so my hope is that a comparison of all the other elements will give me the result I want. The comparison needs to be done programmatically, since it's part of a unit test.
At first, I was considering using a couple instances of XmlDocument. But then I found this:
<http://drowningintechnicaldebt.com/blogs/scottroycraft/archive/2007/05/06/comparing-xml-files.aspx>
It looks like it might work, but I was interested in Stack Overflow feedback in case there's a better way.
I'd like to avoid adding another dependency for this if at all possible.
## Similar questions
* [Is there an XML asserts for NUnit?](https://stackoverflow.com/questions/3552648/is-there-an-xml-asserts-for-nunit)
* [How would you compare two XML Documents?](https://stackoverflow.com/questions/167946/how-would-you-compare-two-xml-documents) | It really depends on what you want to check as "differences".
Right now, we're using Microsoft XmlDiff: <http://msdn.microsoft.com/en-us/library/aa302294.aspx> | You might find it's less fragile to parse the XML into an XmlDocument and base your Assert calls on XPath Query. Here are some helper assertion methods that I use frequently. Each one takes a XPathNavigator, which you can obtain by calling CreateNavigator() on the XmlDocument or on any node retrieved from the document. An example of usage would be:
```
XmlDocument doc = new XmlDocument( "Testdoc.xml" );
XPathNavigator nav = doc.CreateNavigator();
AssertNodeValue( nav, "/root/foo", "foo_val" );
AssertNodeCount( nav, "/root/bar", 6 )
private static void AssertNodeValue(XPathNavigator nav,
string xpath, string expected_val)
{
XPathNavigator node = nav.SelectSingleNode(xpath, nav);
Assert.IsNotNull(node, "Node '{0}' not found", xpath);
Assert.AreEqual( expected_val, node.Value );
}
private static void AssertNodeExists(XPathNavigator nav,
string xpath)
{
XPathNavigator node = nav.SelectSingleNode(xpath, nav);
Assert.IsNotNull(node, "Node '{0}' not found", xpath);
}
private static void AssertNodeDoesNotExist(XPathNavigator nav,
string xpath)
{
XPathNavigator node = nav.SelectSingleNode(xpath, nav);
Assert.IsNull(node, "Node '{0}' found when it should not exist", xpath);
}
private static void AssertNodeCount(XPathNavigator nav, string xpath, int count)
{
XPathNodeIterator nodes = nav.Select( xpath, nav );
Assert.That( nodes.Count, Is.EqualTo( count ) );
}
``` | What is the best way to compare XML files for equality? | [
"",
"c#",
".net",
"xml",
"unit-testing",
"comparison",
""
] |
I am using a JSP bean and when I do an assignment to a new object, it gets over-written on a submit to the previous object.
```
<jsp:useBean id="base" class="com.example.StandardBase" scope="session" />
...
//base object id = 396
base = new Base()
//base object id = 1000
```
and on a resubmit of the page I get
```
<jsp:useBean id="base" class="com.example.StandardBase" scope="session" />
//base object id = 396
```
Is there a way to tell JSP to do a new assignment? | I'm not completely sure, but I think `base = new Base()` does not update the reference stored in the session scope. Therefore, the bean you created with the initial `<jsp:useBean/>` is still around while the one you create manually, and then updated, isn't.
Get rid of `base = new Base()` and you should be fine.
If you insist upon updating it, you use [`HttpSession.setAttribute()`](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpSession.html#setAttribute(java.lang.String,%20java.lang.Object)). Like so:
```
session.setAttribute("bean", bean);
```
I believe the variable `session` is automatically created and initialized for you by the JSP engine. | You're not supposed to new the bean yourself. Let JSP do that for you | Using a jsp bean in a session | [
"",
"java",
"jsp",
"javabeans",
""
] |
When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.
For example, when writing this in vim
```
for i in range(10):
#
```
the # does not stay there where I entered it.
It is moved like so, by vim.
```
for i in range(10):
#
```
Does anyone know of a configuration item in vim that would change this?
If it helps, I am using Ubuntu 8.10. | I found an answer here <http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash>
It seems that the vim smartindent option is the cause of the problem.
The referenced page above describes work-a-rounds but after reading the help in smartindent in vim itself (:help smartindent), I decided to try cindent instead of smartindent.
I replaced
```
set smartindent
```
with
```
set cindent
```
in my .vimrc file
and so far it is working perfectly.
This changed also fixed the behavior of '<<' and '>>' for indenting visual blocks that include python comments.
There are more configuration options for and information on indentation in the vim help for smartindent and cindent (:help smartindent and :help cindent). | @PolyThinker Though I see that response a lot to this question, in my opinion it's not a good solution. The editor still thinks it should be indented all the way to left - check this by pushing == on a line that starts with a hash, or pushing = while a block of code with comments in it is highlighted to reindent.
I would strongly recommend `filetype indent on`, and remove the `set smartindent` and `set autoindent` (or `set cindent`) lines from your vimrc. Someone else (appparently David Bustos) was kind enough to write a full indentation parser for us; it's located at $VIMDIRECTORY/indent/python.vim.
(Paul's `cindent` solution probably works for python, but `filetype indent on` is much more generally useful.) | How to configure vim to not put comments at the beginning of lines while editing python files | [
"",
"python",
"vim",
""
] |
Being fairly new to JavaScript, I'm unable to discern when to use each of these.
Can anyone help clarify this for me? | If your situation requires the use of a regular expression, use the `search()` method, otherwise; the `indexOf()` method is more performant. | [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) is for plain substrings, [`search`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) is for regular expressions. | What is the difference between indexOf() and search()? | [
"",
"javascript",
"string",
""
] |
We have recently been faced with the problem of porting our C++ framework to an ARM platform running uClinux where the only vendor supported compiler is GCC 2.95.3. The problem we have run into is that exceptions are extremely unreliable causing everything from not being caught at all to being caught by an unrelated thread(!). This seems to be a documented bug, i.e. [here](http://gcc.gnu.org/ml/gcc/2003-08/msg01013.html) and [here](http://osdir.com/ml/lib.uclibc.general/2003-05/msg00121.html).
After some deliberation we decided to eliminate exceptions altoghether as we have reached a point where exceptions do a lot of damage to running applications. The main concern now is how to manage cases where a constructor failed.
We have tried [lazy evaluation](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=264), where each method has the ability to instantiate dynamic resources and return a status value but that means that every class method has to return a return value which makes for a **lot** of ifs in the code and is very annoying in methods which generally would never cause an error.
We looked into adding a static *create* method which returns a pointer to a created object or NULL if creation failed but that means we cannot store objects on the stack anymore, and there is still need to pass in a reference to a status value if you want to act on the actual error.
According to Google's C++ Style Guide they [do not use exceptions](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Exceptions) and only do trivial work in their constructors, using an init method for non-trivial work ([Doing Work in Constructors](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Doing_Work_in_Constructors)). I cannot however find anything about how they handle construction errors when using this approach.
Has anyone here tried eliminating exceptions and come up with a good solution to handling construction failure? | Generally you end up with code like this for objects on the stack:
```
MyClassWithNoThrowConstructor foo;
if (foo.init(bar, baz, etc) != 0) {
// error-handling code
} else {
// phew, we got away with it. Now for the next object...
}
```
And this for objects on the heap. I assume you override global operator new with something that returns NULL instead of throwing, to save yourself remembering to use nothrow new everywhere:
```
MyClassWithNoThrowConstructor *foo = new MyClassWithNoThrowConstructor();
if (foo == NULL) {
// out of memory handling code
} else if (foo->init(bar, baz, etc) != 0) {
delete foo;
// error-handling code
} else {
// success, we can use foo
}
```
Obviously if you possibly can, use smart pointers to save having to remember the deletes, but if your compiler doesn't support exceptions properly, then you might have trouble getting Boost or TR1. I don't know.
You also might want to structure the logic differently, or abstract the combined new and init, to avoid deeply-nested "arrow code" whenever you're handling multiple objects, and to common-up the error-handling between the two failure cases. The above is just the basic logic in its most painstaking form.
In both cases, the constructor sets everything to default values (it can take some arguments, provided that what it does with those arguments cannot possibly fail, for instance if it just stores them). The init method can then do the real work, which might fail, and in this case returns 0 success or any other value for failure.
You probably need to enforce that every init method across your whole codebase reports errors in the same way: you do *not* want some returning 0 success or a negative error code, some returning 0 success or a positive error code, some returning bool, some returning an object by value that has fields explaining the fault, some setting global errno, etc.
You could perhaps take a quick look at some Symbian class API docs online. Symbian uses C++ without exceptions: it does have a mechanism called "Leave" that partially makes up for that, but it's not valid to Leave from a constructor, so you have the same basic issue in terms of designing non-failing constructors and deferring failing operations to init routines. Of course with Symbian the init routine is permitted to Leave, so the caller doesn't need the error-handling code I indicate above, but in terms of splitting work between a C++ constructor and an additional init call, it's the same.
General principles include:
* If your constructor wants to get a value from somewhere in a way that might fail, defer that to the init and leave the value default-initialised in the ctor.
* If your object holds a pointer, set it to null in the ctor and set it "properly" in the init.
* If your object holds a reference, either change it to a (smart) pointer so that it can null to start with, or else make the caller pass the value into the constructor as a parameter instead of generating it in the ctor.
* If your constructor has members of object type, then you're fine. Their ctors won't throw either, so it's perfectly OK to construct your members (and base classes) in the initializer list in the usual way.
* Make sure you keep track of what's set and what isn't, so that the destructor works when the init fails.
* All functions other than constructors, the destructor, and init, can assume that init has succeeded, provided you document for your class that it is not valid to call any method other than init until init has been called and succeeded.
* You can offer multiple init functions, which unlike constructors can call each other, in the same way that for some classes you'd offer multiple constructors.
* You can't provide implicit conversions that might fail, so if your code currently relies on implicit conversions which throw exceptions then you have to redesign. Same goes for most operator overloads, since their return types are constrained. | You could use a flag to keep track of whether the constructor failed. You might already have a member variable that's only valid if the constructor succeeds, e.g.
```
class MyClass
{
public:
MyClass() : m_resource(NULL)
{
m_resource = GetResource();
}
bool IsValid() const
{
return m_resource != NULL;
}
private:
Resource * m_resource;
};
MyClass myobj;
if (!myobj.IsValid())
{
// error handling goes here
}
``` | Exception elimination in C++ constructors | [
"",
"c++",
"exception",
""
] |
Hiya - been pointed at you guys by a friend of mine.
I have an MDI application (C#, Winforms, .NET 2.0, VS2005, DevExpress 8.2) and one of my forms is behaving very strangely - not repainting itself properly where it overlaps with another instance of the same form class.
The forms contain a custom control (which contains various DevExpress controls), and are inherited from a base form (which is itself inherited).
Due to issues with form inheritance (that old chestnut) there is a bit of control rearranging going on in the constructor.
Problem 1 (minor): None of this control repositioning/resizing seems to take effect unless the form is resized, so I nudge the width up and down by one pixel after the rearranging. Ugly, hacky and I'd really like to not have to do this.
Problem 2 (major):
If forms are shown then attached to the MDI form using the API call SetParent, when I display the 2nd instance, various parts of the two forms are not correctly drawn where they overlap - bits of the top one are behind the existing one - and this problem gets worse when the forms are moved around, rendering them basically unuseable. Other child forms (if present) of a different type seem unaffected...
STOP PRESS: I've established that it doesn't have to be 2 instances of the child form. With only one there are still problems - mainly round the edges of the form, like the area that's being refreshed is smaller than the form itself.
The problem does not occur if the parent is set using the .MDIParent property of the child form - but we cannot do this as the form may be being displayed by a control hosted in a non-.Net application. Also I need to display the child forms non-maximised even if the existing children (of a different type) are maximised, and that only happens using SetParent.
I have tried Refresh() on all the forms of this type (I have a controller that keeps a list of them), but no joy. I have tried to reproduce this effect form a basic app with the same inheritance structure, but I can't. Clearly it is something about the form - since I recreated the form from scratch yesterday and it is still the same it must be the code - but what??
I am not the hottest on form painting events etc. so have I missed something? | Ah ha!
I was changing the FormBorderStyle in code before showing the form. I removed that line and the problem went away...
That'll do for me. :-) | Yes, that would do it. Changing the FormBorderStyle requires Windows Forms to recreate the window from scratch, now using different style flags in the CreateWindowEx() call. That would make it completely forget about the parent you set with the SetParent() P/Invoke. There are lots of other properties that causes this to happen. Avoid the kind of trouble you got into by making these calls in an override of the OnHandleCreated() method.
Better yet, avoid troublesome APIs like SetParent() completely by putting all your controls and logic in a UserControl. | MDI Child refresh/repaint problems (C#, Winforms, .NET 2.0, VS2005, DevExpress 8.2) | [
"",
"c#",
"winforms",
"visual-studio-2005",
".net-2.0",
""
] |
I need to match a string holiding html using a regex to pull out all the nested spans, I assume I assume there is a way to do this using a regex but have had no success all morning.
So for a sample input string of
```
<DIV id=c445c9c2-a02e-4cec-b254-c134adfa4192 style="BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid; BACKGROUND-COLOR: #eeeeee">
<SPAN id=b8db8cd1-f600-448f-be26-2aa56ea09a9c>
<SPAN id=304ccd38-8161-4def-a557-1a048c963df4>
<IMG src="http://avis.co.uk/Assets/build/menu.gif">
</SPAN>
</SPAN>
<SPAN id=bc88c866-5370-4c72-990b-06fbe22038d5>
<SPAN id=55b88bbe-15ca-49c9-ad96-cecc6ca7004e>UK<BR></SPAN>
</SPAN>
<SPAN id=52bb62ca-8f0a-42f1-a13b-9b263225ff1d>
<SPAN id=0e1c3eb6-046d-4f07-96c1-d1ac099d5f1c>
<IMG src="http://avis.co.uk/Assets/build/menu.gif">
</SPAN>
</SPAN>
<SPAN id=4c29eef2-cd77-4d33-9828-e442685a25cb>
<SPAN id=0d5a266a-14ae-4a89-9263-9e0ab57f7ad2>Italy</SPAN>
</SPAN>
<SPAN id=f0a72eea-fddd-471e-89e6-56e9b9efbece>
<SPAN id=b7d9ada7-ade0-49fe-aa5f-270237e87c2b>
<IMG src="http://avis.co.uk/Assets/build/menu.gif">
</SPAN>
</SPAN>
<SPAN id=7604df94-34ba-4c89-bf11-125df01731ff>
<SPAN id=330d6429-4f1b-46a2-a485-9001e2c6b8c1>Netherlands</SPAN>
</SPAN>
<SPAN id=a18fb516-451e-4c32-ab31-3e3be29235f6>
<SPAN id=6c70238d-78f9-468f-bb8d-370fff13c909>
<IMG src="http://avis.co.uk/Assets/build/menu.gif">
</SPAN>
</SPAN>
<SPAN id=5a2465eb-b337-4f94-a4f8-6f5001dfbd75>
<SPAN id=47877a9e-a7d5-4f13-a41e-6948f899e385>Malta & Gozo
```
i would want to get each outer span and its containing span so in the above text there should be Eight results
Any help gladly accepted | Try this:
```
@"(?is)<SPAN\b[^>]*>\s*(<SPAN\b[^>]*>.*?</SPAN>)\s*</SPAN>"
```
This is basically the same as PhiLho's regex, except it permits whitespace between the tags at either end. I also had to add the SingleLine/DOTALL modifier to accomodate line separators within the matched text. I don't know if either of those changes was really necessary; the sample data the OP posted was all on one line, but PhiLho broke it up (thereby breaking his own regex). | Once again [use an HTML parser](http://www.developer.com/net/csharp/article.php/2230091) to walk the DOM: regexs will never be robust enough to do this. | Using Lookahead to match a string using a regular expression | [
"",
"c#",
"html",
"regex",
""
] |
I'm using reflection to loop through a `Type`'s properties and set certain types to their default. Now, I could do a switch on the type and set the `default(Type)` explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default? | * In case of a value type use [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) and it should work fine.
* When using reference type just return null
```
public static object GetDefault(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
```
In the newer version of .net such as .net standard, `type.IsValueType` needs to be written as `type.GetTypeInfo().IsValueType` | Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:
```
public object GetDefault(Type t)
{
return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
}
public T GetDefaultGeneric<T>()
{
return default(T);
}
``` | Programmatic equivalent of default(Type) | [
"",
"c#",
"reflection",
"default",
""
] |
I want a single number that represents the current date and time, like a [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time). | ### Timestamp in milliseconds
To get the number of milliseconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time), call [`Date.now`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now):
```
Date.now()
```
Alternatively, use the unary operator `+` to call [`Date.prototype.valueOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf):
```
+ new Date()
```
Alternatively, call [`valueOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf) directly:
```
new Date().valueOf()
```
To support IE8 and earlier (see [compatibility table](http://kangax.github.io/compat-table/es5/#Date.now)), create a *shim* for `Date.now`:
```
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
```
Alternatively, call [`getTime`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) directly:
```
new Date().getTime()
```
---
### Timestamp in seconds
To get the number of seconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time), i.e. *Unix timestamp*:
```
Math.floor(Date.now() / 1000)
```
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations [1](https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number), [2](https://stackoverflow.com/a/11446757/1519836)):
```
Date.now() / 1000 | 0
```
---
### Timestamp in milliseconds (higher resolution)
Use [`performance.now`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now):
```
var isPerformanceSupported = (
window.performance &&
window.performance.now &&
window.performance.timing &&
window.performance.timing.navigationStart
);
var timeStampInMs = (
isPerformanceSupported ?
window.performance.now() +
window.performance.timing.navigationStart :
Date.now()
);
console.log(timeStampInMs, Date.now());
``` | I like this, because it is small:
```
+new Date
```
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
```
Date.now()
``` | How do I get a timestamp in JavaScript? | [
"",
"javascript",
"datetime",
"timestamp",
"date-arithmetic",
""
] |
I'm wondering if this is a good design. I have a number of tables that require address information (e.g. street, post code/zip, country, fax, email). Sometimes the same address will be repeated multiple times. For example, an address may be stored against a supplier, and then on each purchase order sent to them. The supplier may then change their address and any subsequent purchase orders should have the new address. It's more complicated than this, but that's an example requirement.
Option 1
Put all the address columns as attributes on the various tables. Copy the details down from the supplier to the PO as it is created. Potentially store multiple copies of the
Option 2
Create a separate address table. Have a foreign key from the supplier and purchase order tables to the address table. Only allow insert and delete on the address table as updates could change more than you intend. Then I would have some scheduled task that deletes any rows from the address table that are no longer referenced by anything so unused rows were not left about. Perhaps also have a unique constraint on all the non-pk columns in the address table to stop duplicates as well.
I'm leaning towards option 2. Is there a better way?
EDIT: I must keep the address on the purchase order as it was when sent. Also, it's a bit more complicated that I suggested as there may be a delivery address and a billing address (there's also a bunch of other tables that have address information).
After a while, I will delete old purchase orders en-masse based on their date. It is after this that I was intending on garbage collecting any address records that are not referenced anymore by anything (otherwise it feels like I'm creating a leak). | I actually use this as one of my interview questions. The following is a good place to start:
```
Addresses
---------
AddressId (PK)
Street1
... (etc)
```
and
```
AddressTypes
------------
AddressTypeId
AddressTypeName
```
and
```
UserAddresses (substitute "Company", "Account", whatever for Users)
-------------
UserId
AddressTypeId
AddressId
```
This way, your addresses are totally unaware of how they are being used, and your entities (Users, Accounts) don't directly know anything about addresses either. It's all up to the linking tables you create (UserAddresses in this case, but you can do whatever fits your model).
One piece of somewhat contradictory advice for a potentially large database: go ahead and put a "primary" address directly on your entities (in the Users table in this case) along with a "HasMoreAddresses" field. It seems icky compared to just using the clean design above, but can simplify coding for typical use cases, and the denormalization can make a big difference for performance. | Option 2, without a doubt.
Some important things to keep in mind: it's an important aspect of design to indicate to the users when addresses are linked to one another. I.e. corporate address being the same as shipping address; if they want to change the shipping address, do they want to change the corporate address too, or do they want to specify a new loading dock? This sort of stuff, and the ability to present users with this information and to change things with this sort of granularity is VERY important. This is important, too, about the updates; give the user the granularity to "split" entries. Not that this sort of UI is easy to design; in point of fact, it's a bitch. But it's really important to do; anything less will almost certainly cause your users to get very frustrated and annoyed.
Also; I'd strongly recommend keeping around the old address data; don't run a process to clean it up. Unless you have a VERY busy database, your database software will be able to handle the excess data. Really. One common mistake I see about databases is attempting to overoptimize; you DO want to optimize the hell out of your queries, but you DON'T want to optimize your unused data out. (Again, if your database activity is VERY HIGH, you may need to have something does this, but it's almost a certainty that your database will work well with still having excess data around in the tables.) In most situations, it's actually more advantageous to simply let your database grow than it is to attempt to optimize it. (Deletion of sporadic data from your tables won't cause a significant reduction in the size of your database, and when it does... well, the reindexing that that causes can be a gigantic drain on the database.) | Is this a good way to model address information in a relational database? | [
"",
"sql",
"database-design",
"rdbms",
""
] |
I've been scanning through all the popular js libraries, but I can't find one that has a width function for a DOM element that actually accounts for quirks mode in Internet Explorer. The issue is that padding and borders don't get counted in the the width when quirks mode is engaged. As far as I can tell this happens when the doctype is left out or the doctype is set to html 3.2.
Obviously I could just set the doctype to something standards compliant, but this script can be embedded anywhere so I don't have control over the doctype.
To break the problem down into smaller parts:
1) How do you detect quirks mode?
2) What's the best way to extract the border and padding from an element to compensate?
Example with prototype:
```
<html>
<head>
</head>
<body>
<div id="mydiv" style="width: 250px; pading-left: 1px; border: 2px black solid">hello</div>
<script>
alert($('mydiv').getWidth())
</script>
</body>
</html>
```
result:
253 (ff)
250 (ie)
Thanks in advance! | @1
```
document.compatMode
```
"CSS1Compat" means "*standards mode*" and "BackCompat" means "*quirks mode*".
@2
offsetWidth property of a HTML elements gives its width on screen, in pixels.
```
<div id="mydiv" style="width: 250px; padding-left: 1px; border: 2px black solid">hello</div>
document.getElementById('mydiv').offsetWidth
//255 (standards) 250 (quirks)
```
A function that compensates the width for IE quirksmode has to check for the rendering mode then add borders and padding to the width;
```
function compensateWidth( el, targetWidth ){
var removeUnit = function( str ){
if( str.indexOf('px') ){
return str.replace('px','') * 1;
}
else { //because won't work for other units... one may wish to implement
return 0;
}
}
if(document.compatMode && document.compatMode=="BackCompat"){
if(targetWidth && el.offsetWidth < targetWidth){
el.style.width = targetWidth;
}
else if (el.currentStyle){
var borders = removeUnit(el.currentStyle['borderLeftWidth']) + removeUnit(el.currentStyle['borderRightWidth']);
var paddings = removeUnit(el.currentStyle['paddingLeft']) + removeUnit(el.currentStyle['paddingRight']);
el.style.width = el.offsetWidth + borders + paddings +'px';
}
}
}
```
Now there are two ways to use it:
```
var div = document.getElementById('mydiv')
// will try to calculate target width, but won't be able to work with units other than px
compensateWidth( div );
//if you know what the width should be in standards mode
compensateWidth( div, 254 );
``` | ```
javascript:(function(){
var mode=document.compatmode,m;if(mode){
if(mode=='BackCompat')m='quirks';
else if(mode=='CSS1Compat')m='Standard';
else m='Almost Standard';
alert('The page is rendering in '+m+' mode.');
}
})();
```
that code will detect the mode for you.
IE will also throw into quirks mode if ANYTHING but doctype is on the first line. Even a blank first line with doctype on the second line will cause quirks mode. | Width of an element accounting for quirks mode in javascript? | [
"",
"javascript",
"html",
"css",
""
] |
If I'm using `Long uuid = UUID.randomUUID().getMostSignificantBits()` how likely is it to get a collision. It cuts off the least significant bits, so there is a possibility that you run into a collision, right? | According to [the documentation](http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html), the static method `UUID.randomUUID()` generates a type 4 UUID.
This means that six bits are used for some type information and the remaining 122 bits are assigned randomly.
The six non-random bits are distributed with four in the most significant half of the UUID and two in the least significant half. So the most significant half of your UUID contains 60 bits of randomness, which means you on average need to generate 2^30 UUIDs to get a collision (compared to 2^61 for the full UUID).
So I would say that you are rather safe. Note, however that this is absolutely not true for other types of UUIDs, as Carl Seleborg mentions.
Incidentally, you would be slightly better off by using the least significant half of the UUID (or just generating a random long using SecureRandom). | Raymond Chen has a really excellent blog post on this:
[GUIDs are globally unique, but substrings of GUIDs aren't](https://devblogs.microsoft.com/oldnewthing/20080627-00/?p=21823) | Likelihood of collision using most significant bits of a UUID in Java | [
"",
"java",
"collision",
"uuid",
""
] |
I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.
However, I'm looking through the *wxPython in Action* book and notice that "self" isn't used all the time. For example:
```
import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 100))
panel = wx.Panel(self, -1)
basicLabel = wx.StaticText(panel, -1, "Basic Control:")
basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
size=(175, -1))
basicText.SetInsertionPoint(0)
pwdLabel = wx.StaticText(panel, -1, "Password:")
pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
style=wx.TE_PASSWORD)
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
panel.SetSizer(sizer)
```
The one below does use "self".
```
import wx
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Button Example',
size=(300, 100))
panel = wx.Panel(self, -1)
self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
def OnClick(self, event):
self.button.SetLabel("Clicked")
```
If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb? | You use `self.attribute` to reference an attribute of your current instance.
You use `wx.Frame.__init__()` to reference a method of the parent class.
You don't use `self` if you only reference a local name (variable) of the method (function) you are in.
These are not "rules of thumb," because there are no exceptions.
---
What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns.
If you look at the documentation to `wx.Panel`, though, you will see that *its* constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns.
Magic :) | In those instances, if you do not use `self` then you will create only a local variable of that name. In the first example, `panel` is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing `self` to the wx.Panel constructor associated it with the current object in some fashion, so it doesn't just disappear when the function returns. | When is "self" required? | [
"",
"python",
"wxpython",
""
] |
Can anyone think of a good solution for getting IOC into a console application?
At the moment we are just using a static class with the following method:
```
public static T Resolve<T>()
{
return dependencyResolver.Resolve<T>();
}
```
I would like the experience to be seamless but cannot think of a way of achieving this from a console application. | You will have to make a service locater call (`Resolve<T>()`) somewhere. The trick is to get it as out-of-the-way as possible. For console applications this bootstrapping happens in the `Main()` method. Do it there and minimize those Resolve calls elsewhere and you'll be great. For most dependencies, use constructor injection. | Console applications do not have any limitation over a web or form application for IoC. You can use any of your choice (Spring, Ninject, Unity, etc.). Most of them are configurable with XML file outside your console application and some like Ninjector require a configuration inside your application. | IOC for a Console Application? | [
"",
"c#",
"dependency-injection",
"inversion-of-control",
"console-application",
""
] |
Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:
```
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
```
Or is there some other way I can do this? | Since 1.8.5 it's possible to [seal and freeze the object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze), so define the above as:
```
const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
```
or
```
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
```
and voila! JS enums.
However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:
```
let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors
```
One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like [TypeScript](https://www.typescriptlang.org/) or [Flow](https://flow.org/).
Quotes aren't needed but I kept them for consistency. | This isn't much of an answer, but I'd say that works just fine, personally
Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value. | How can I guarantee that my enums definition doesn't change in JavaScript? | [
"",
"javascript",
""
] |
I have a set of classes, each one is a different [strategy](http://en.wikipedia.org/wiki/Strategy_pattern) to do the same work.
```
namespace BigCorp.SuperApp
{
public class BaseClass { }
public class ClassA : BaseClass { }
public class ClassB : BaseClass { }
}
```
The choice of which strategy to use is configurable. I want to configure only the class name 'ClassB' instead of the full type name 'BigCorp.SuperApp.ClassB' in the app.config file.
```
<appConfig>
<SuperAppConfig>
<Handler name="ClassB" />
</SuperAppConfig>
</appConfig>
```
However, the reflection calls fail because they expect the full type name, particularly
```
Type t = Type.GetType("ClassB"); // results in t == null
BaseClass c = Activator.CreateInstance(t) as BaseClass; // fails
```
How can I get this to work while configuring only the class name? Concatenate the namespace to the class name for full type name? Is there another reflection call that works?
If you think this is useless and I should expect the configuration to contain the full type name, I am open to that solution! Just provide rationale to convince me.
(I will not be loading a type from outside this assembly/namespace) | Since you know all classes will be coming from the same namespace, configure it once and use that:
```
<appConfig>
<SuperAppConfig handlerNamespace="BigCorp.SuperApp">
<Handler class="ClassB" />
</SuperAppConfig>
</appConfig>
```
**Edit:** I changed *name* to *class* to better denote the meaning of that attribute. | Either use the assembly-qualified-name, or get hold of the Assembly and use `Assembly.GetType(name)`. In this case, since you want the types in the config file, assembly-qualified is a valid way to go - but since you know all your types are in the same assembly:
```
Assembly assembly = typeof(SomeKnownType).Assembly; // in the same assembly!
Type type = assembly.GetType(name); // full name - i.e. with namespace (perhaps concatenate)
object obj = Activator.CreateInstance(type);
```
The static `Type.GetType(string)` has probing rules that often cause confusion... it looks at the calling assembly, and a few system assemblies - but not all loaded assemblies. | Create an object knowing only the class name? | [
"",
"c#",
".net",
"reflection",
"configuration",
""
] |
How do I create the default for a generic in VB? in C# I can call:
```
T variable = default(T);
```
1. How do I do this in VB?
2. If this just returns null (C#) or nothing (vb) then what happens to value types?
3. Is there a way to specify for a custom type what the default value is? For instance what if I want the default value to be the equivalent to calling a parameterless constructor on my class. | ## Question 1:
```
Dim variable As T
' or '
Dim variable As T = Nothing
' or '
Dim variable As New T()
```
Notice that the latter only works if you specify the `Structure` constraint for the generic type (for reference types, `New T()` in VB does something else than `default(T)` in C#).
## Question 2:
For value types all members of the struct are “nulled” out, i.e. all reference type members are set to `null` (`Nothing`) and all value types are in turn nulled out.
And no, since `string` is a reference type, it does *not* result in `""` for strings as suggested in the other answer.
## Question 3:
No, there's no way to specify this. There are some threads about this on Stack Overflow already, e.g. [here](https://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net). Jon has posted an [excellent explanation](https://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net#333840) why this is. | Actually folks the correct way of doing this is to cast the `null` (`Nothing`) type as your generic type as follows:
```
Dim tmpObj As T = CType(Nothing, T)
```
If you want to return the default value for the generic you simply return `CType(Nothing, T)` | Default value for generics | [
"",
"c#",
".net",
"vb.net",
"generics",
""
] |
[PySmell](http://github.com/orestis/pysmell/tree/master) seems like a good starting point.
I think it should be possible, PySmell's `idehelper.py` does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one.
```
>>> import idehelper
>>> # The path is where my PYSMELLTAGS file is located:
>>> PYSMELLDICT = idehelper.findPYSMELLDICT("/Users/dbr/Desktop/pysmell/")
>>> options = idehelper.detectCompletionType("", "" 1, 2, "", PYSMELLDICT)
>>> completions = idehelper.findCompletions("proc", PYSMELLDICT, options)
>>> print completions
[{'dup': '1', 'menu': 'pysmell.pysmell', 'kind': 'f', 'word': 'process', 'abbr': 'process(argList, excluded, output, verbose=False)'}]
```
It'll never be perfect, but it would be extremely useful (even if just for completing the stdlib modules, which should never change, so you wont have to constantly regenerate the PYSMELLTAGS file whenever you add a function)
---
Progressing! I have the utter-basics of completion in place - barely works, but it's close..
I ran `python pysmells.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/*.py -O /Library/Python/2.5/site-packages/pysmell/PYSMELLTAGS`
Place the following in a TextMate bundle script, set "input: entire document", "output: insert as text", "activation: key equivalent: alt+esc", "scope selector: source.python"
```
#!/usr/bin/env python
import os
import sys
from pysmell import idehelper
CUR_WORD = os.environ.get("TM_CURRENT_WORD")
cur_file = os.environ.get("TM_FILEPATH")
orig_source = sys.stdin.read()
line_no = int(os.environ.get("TM_LINE_NUMBER"))
cur_col = int(os.environ.get("TM_LINE_INDEX"))
# PYSMELLS is currently in site-packages/pysmell/
PYSMELLDICT = idehelper.findPYSMELLDICT("/Library/Python/2.5/site-packages/pysmell/blah")
options = idehelper.detectCompletionType(cur_file, orig_source, line_no, cur_col, "", PYSMELLDICT)
completions = idehelper.findCompletions(CUR_WORD, PYSMELLDICT, options)
if len(completions) > 0:
new_word = completions[0]['word']
new_word = new_word.replace(CUR_WORD, "", 1) # remove what user has already typed
print new_word
```
Then I made a new python document, typed "import urll" and hit alt+escape, and it completed it to "import urllib"!
As I said, it's entirely a work-in-progress, so don't use it yet..
---
*Last update:*
orestis has integrated this into the PySmell project's code! Any further fiddling will happen [on github](http://github.com/orestis/pysmell/tree/master) | EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose.
You can grab it here: <http://github.com/orestis/pysmell/tree/master> (hit download and do python setup.py install). It's rough but it works. - please report any errors on <http://code.google.com/p/pysmell/>
--
Hi, I'm the developer of PySmell. I also use a Mac, so if you can send me an email (contact info is in the source code) with your progress so far, I can try to integrate it :)
Oh BTW it's called PySmell - no trailing 's' :) | This isn't exactly what you're looking for but it might be able to get you started:
[Using TextMate with Django](http://code.djangoproject.com/wiki/TextMate)
They appear to be somewhat Django specific but some snippets may assist with your needs. You also may be able to build on top of that with PySmells. | Is it possible to implement Python code-completion in TextMate? | [
"",
"python",
"autocomplete",
"text-editor",
"textmate",
""
] |
MathWorks currently doesn't allow you to use `cout` from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, [mexPrintf, that they request you use instead](http://www.mathworks.com/support/tech-notes/1600/1605.html). After googling around a bit, I think that it's possible to extend the `std::stringbuf` class to do what I need. Here's what I have so far. Is this robust enough, or are there other methods I need to overload or a better way to do this? (Looking for portability in a general UNIX environment and the ability to use `std::cout` as normal if this code is not linked against a mex executable)
```
class mstream : public stringbuf {
public:
virtual streamsize xsputn(const char *s, std::streamsize n)
{
mexPrintf("*s",s,n);
return basic_streambuf<char, std::char_traits<char>>::xsputn(s,n);
}
};
mstream mout;
outbuf = cout.rdbuf(mout.rdbuf());
``` | You don't really want to overload `std::stringbuf`, you want to overload `std::streambuf` or `std::basic_streambuf` (if you want to support multiple character types), also you need to override the overflow method as well.
But I also think you need to rethink your solution to your problem.
`cout` is just an `ostream`, so if all classes / functions takes an `ostream` then you can pass in anything you like. e.g. `cout`, `ofstream`, etc
If that's too hard then I would create my own version of `cout`, maybe called `mycout` that can be defined at either compiler time or runtime time (depending on what you want to do).
A simple solution may be:
```
#include <streambuf>
#include <ostream>
class mystream : public std::streambuf
{
public:
mystream() {}
protected:
virtual int_type overflow(int_type c)
{
if(c != EOF)
{
char z = c;
mexPrintf("%c",c);
return EOF;
}
return c;
}
virtual std::streamsize xsputn(const char* s, std::streamsize num)
{
mexPrintf("*s",s,n);
return num;
}
};
class myostream : public std::ostream
{
protected:
mystream buf;
public:
myostream() : std::ostream(&buf) {}
};
myostream mycout;
```
And the cout version could just be:
```
typedef std::cout mycout;
```
A runtime version is a bit more work but easily doable. | Shane, thanks very much for your help. Here's my final working implementation.
```
class mstream : public std::streambuf {
public:
protected:
virtual std::streamsize xsputn(const char *s, std::streamsize n);
virtual int overflow(int c = EOF);
};
```
...
```
std::streamsize
mstream::xsputn(const char *s, std::streamsize n)
{
mexPrintf("%.*s",n,s);
return n;
}
int
mstream::overflow(int c)
{
if (c != EOF) {
mexPrintf("%.1s",&c);
}
return 1;
}
```
...
```
// Replace the std stream with the 'matlab' stream
// Put this in the beginning of the mex function
mstream mout;
std::streambuf *outbuf = std::cout.rdbuf(&mout);
```
...
```
// Restore the std stream buffer
std::cout.rdbuf(outbuf);
``` | Correctly over-loading a stringbuf to replace cout in a MATLAB mex file | [
"",
"c++",
"matlab",
"cout",
"mex",
"stringbuffer",
""
] |
When using Google Reader and browsing RSS entries in the "Expanded" view, entries will automatically be marked as 'read' once a certain percentage of the div is visible on the screen (difficult to tell what percentage has to be visible in the case of Google Reader). So, as I scroll down line-by-line, the javascript code can determine that a) the entry is being rendered in the visible window and b) a certain amount is visible and when those conditions are met, the state is toggled to read.
Does anyone have any idea how that feature is implemented? Specifically, does anyone here know how to tell if a div has scrolled into view an how much of the div is visible?
As an aside, I'm using jQuery, so if anyone has any jQuery-specific examples, they would be much appreciated. | The real trick is to keep track of where the scrollbar is in the element containing your items. Here's some code I once whipped up to do it: <http://pastebin.com/f4a329cd9>
You can see that as you scroll it changes focus. You just need to add more handler code to the function that handles each focus change. It works scrolling in both direction, and also by clicking right on the scrollbar, which simple mouse tracking won't give you (though in this case since the example elements are all the same size, with the same text, it's hard to tell that it has indeed scrolled). The other issue is what to do when the container bottoms out. The solution I have right now only works in FF. If you want to have it look nice in IE, you'll have to use a dummy element that blends into the background, like the one I have commented out in the code. | I just came across this as I need the same thing, and it looks super useful:
<http://www.appelsiini.net/projects/viewport> | Detecting divs as rendered in the window to implement Google-Reader-like auto-mark-as-read? | [
"",
"javascript",
"jquery",
"scroll",
""
] |
I see there are [a few](http://codeigniter.com/wiki/Category:Libraries::Authentication/). Which ones are maintained and easy to use? What are their pros and cons? | ## Update (May 14, 2010):
**It turns out, the russian developer Ilya Konyukhov picked up the gauntlet after reading this and created a new auth library for CI based on DX Auth, following the recommendations and requirements below.**
**And the resulting [Tank Auth](http://konyukhov.com/soft/tank_auth/) is looking like the answer to the OP's question. I'm going to go out on a limb here and call Tank Auth the best authentication library for CodeIgniter available today. It's a rock-solid library that has all the features you need and none of the bloat you don't:**
## Tank Auth
> Pros
>
> * Full featured
> * Lean footprint (20 files) considering the feature set
> * Very good documentation
> * Simple and elegant database design (just 4 DB tables)
> * Most features are optional and easily configured
> * Language file support
> * reCAPTCHA supported
> * Hooks into CI's validation system
> * Activation emails
> * Login with email, username or both (configurable)
> * Unactivated accounts auto-expire
> * Simple yet effective error handling
> * Uses phpass for hashing (and also hashes autologin codes in the DB)
> * Does not use security questions
> * Separation of user and profile data is very nice
> * Very reasonable security model around failed login attempts (good protection against bots and DoS attacks)
>
> (Minor) Cons
>
> * Lost password codes are not hashed in DB
> * Includes a native (poor) CAPTCHA, which is nice for those who don't want to depend on the (Google-owned) reCAPTCHA service, but it really isn't secure enough
> * Very sparse online documentation (minor issue here, since the code is nicely documented and intuitive)
[Download Tank Auth here](http://konyukhov.com/soft/tank_auth/)
---
Original answer:
I've implemented my own as well (currently about 80% done after a few weeks of work). I tried all of the others first; FreakAuth Light, DX Auth, Redux, SimpleLogin, SimpleLoginSecure, pc\_user, Fresh Powered, and a few more. None of them were up to par, IMO, either they were lacking basic features, inherently INsecure, or too bloated for my taste.
Actually, I did a detailed roundup of all the authentication libraries for CodeIgniter when I was testing them out (just after New Year's). FWIW, I'll share it with you:
## DX Auth
> Pros
>
> * Very full featured
> * Medium footprint (25+ files), but manages to feel quite slim
> * Excellent documentation, although some is in slightly broken English
> * Language file support
> * reCAPTCHA supported
> * Hooks into CI's validation system
> * Activation emails
> * Unactivated accounts auto-expire
> * Suggests grc.com for salts (not bad for a PRNG)
> * Banning with stored 'reason' strings
> * Simple yet effective error handling
>
> Cons
>
> * Only lets users 'reset' a lost password (rather than letting them pick a new one upon reactivation)
> * Homebrew pseudo-event model - good intention, but misses the mark
> * Two password fields in the user table, bad style
> * Uses two separate user tables (one for 'temp' users - ambiguous and redundant)
> * Uses potentially unsafe md5 hashing
> * Failed login attempts only stored by IP, not by username - unsafe!
> * Autologin key not hashed in the database - practically as unsafe as storing passwords in cleartext!
> * Role system is a complete mess: is\_admin function with hard-coded role names, is\_role a complete mess, check\_uri\_permissions is a mess, the whole permissions table is a bad idea (a URI can change and render pages unprotected; permissions should always be stored exactly where the sensitive logic is). Dealbreaker!
> * Includes a native (poor) CAPTCHA
> * reCAPTCHA function interface is messy
## FreakAuth Light
> Pros
>
> * Very full featured
> * Mostly quite well documented code
> * Separation of user and profile data is a nice touch
> * Hooks into CI's validation system
> * Activation emails
> * Language file support
> * Actively developed
>
> Cons
>
> * Feels a bit bloated (50+ files)
> * And yet it lacks automatic cookie login (!)
> * Doesn't support logins with both username and email
> * Seems to have issues with UTF-8 characters
> * Requires a lot of autoloading (impeding performance)
> * Badly micromanaged config file
> * Terrible View-Controller separation, with lots of program logic in views and output hard-coded into controllers. Dealbreaker!
> * Poor HTML code in the included views
> * Includes substandard CAPTCHA
> * Commented debug echoes everywhere
> * Forces a specific folder structure
> * Forces a specific Ajax library (can be switched, but shouldn't be there in the first place)
> * No max limit on login attempts - VERY unsafe! Dealbreaker!
> * Hijacks form validation
> * Uses potentially unsafe md5 hashing
## pc\_user
> Pros
>
> * Good feature set for its tiny footprint
> * Lightweight, no bloat (3 files)
> * Elegant automatic cookie login
> * Comes with optional test implementation (nice touch)
>
> Cons
>
> * Uses the old CI database syntax (less safe)
> * Doesn't hook into CI's validation system
> * Kinda unintuitive status (role) system (indexes upside down - impractical)
> * Uses potentially unsafe sha1 hashing
## Fresh Powered
> Pros
>
> * Small footprint (6 files)
>
> Cons
>
> * Lacks a lot of essential features. Dealbreaker!
> * Everything is hard-coded. Dealbreaker!
## Redux / Ion Auth
According to [the CodeIgniter wiki](http://codeigniter.com/wiki/Redux_Auth), Redux has been discontinued, but the Ion Auth fork is going strong: <https://github.com/benedmunds/CodeIgniter-Ion-Auth>
Ion Auth is a well featured library without it being overly heavy or under advanced. In most cases its feature set will more than cater for a project's requirements.
> Pros
>
> * Lightweight and simple to integrate with CodeIgniter
> * Supports sending emails directly from the library
> * Well documented online and good active dev/user community
> * Simple to implement into a project
>
> Cons
>
> * More complex DB schema than some others
> * Documentation lacks detail in some areas
## SimpleLoginSecure
> Pros
>
> * Tiny footprint (4 files)
> * Minimalistic, absolutely no bloat
> * Uses phpass for hashing (excellent)
>
> Cons
>
> * Only login, logout, create and delete
> * Lacks a lot of essential features. Dealbreaker!
> * More of a starting point than a library
---
**Don't get me wrong:** I don't mean to disrespect any of the above libraries; I am very impressed with what their developers have accomplished and how far each of them have come, and I'm not above reusing some of their code to build my own. What I'm saying is, sometimes in these projects, the focus shifts from the essential 'need-to-haves' (such as hard security practices) over to softer 'nice-to-haves', and that's what I hope to remedy.
Therefore: back to basics.
## Authentication for CodeIgniter done *right*
Here's my MINIMAL required list of features from an authentication library. It also happens to be a subset of my own library's feature list ;)
> 1. Tiny footprint with optional test implementation
> 2. Full documentation
> 3. No autoloading required. Just-in-time loading of libraries for performance
> 4. Language file support; no hard-coded strings
> 5. reCAPTCHA supported but optional
> 6. Recommended TRUE random salt generation (e.g. using random.org or random.irb.hr)
> 7. Optional add-ons to support 3rd party login (OpenID, Facebook Connect, Google Account, etc.)
> 8. Login using either username or email
> 9. Separation of user and profile data
> 10. Emails for activation and lost passwords
> 11. Automatic cookie login feature
> 12. Configurable phpass for hashing (properly salted of course!)
> 13. Hashing of passwords
> 14. Hashing of autologin codes
> 15. Hashing of lost password codes
> 16. Hooks into CI's validation system
> 17. NO security questions!
> 18. Enforced strong password policy server-side, with optional client-side (Javascript) validator
> 19. Enforced maximum number of failed login attempts with **BEST PRACTICES countermeasures** against both dictionary and DoS attacks!
> 20. All database access done through prepared (bound) statements!
Note: those last few points are *not* super-high-security overkill that you don't need for your web application. **If an authentication library doesn't meet these security standards 100%, DO NOT USE IT!**
Recent high-profile examples of irresponsible coders who left them out of their software: #17 is how Sarah Palin's AOL email was hacked during the Presidential campaign; a nasty combination of #18 and #19 were the culprit recently when the Twitter accounts of Britney Spears, Barack Obama, Fox News and others were hacked; and #20 alone is how Chinese hackers managed to steal 9 million items of personal information from more than 70.000 Korean web sites in one automated hack in 2008.
These attacks are not brain surgery. If you leave your back doors wide open, you shouldn't delude yourself into a false sense of security by bolting the front. Moreover, if you're serious enough about coding to choose a best-practices framework like CodeIgniter, you owe it to yourself to at least get the most *basic* security measures done right.
---
<rant>
Basically, here's how it is: *I don't care* if an auth library offers a bunch of features, advanced role management, PHP4 compatibility, pretty CAPTCHA fonts, country tables, complete admin panels, bells and whistles -- if the library actually makes my site **less secure** by not following best practices. It's an *authentication* package; it needs to do ONE thing right: Authentication. If it fails to do *that*, it's actually doing more harm than good.
</rant>
/Jens Roland | Note that the "comprehensive listing" by Jens Roland doesn't include user roles. If you're interested in assigning different user roles (like admin/user or admin/editor/user), these libraries allow it:
* Ion\_Auth (rewrite of Redux)
* Redux
* Backend Pro
Tank\_Auth (#1 above in Jens's list) doesn't have user roles. I realize it's not exactly part of authentication, but since
* authentication and role management are both handled upon page load
* Both involve security
* The same table/model can be used for both.
* Both can be set up to load in the controller constructor (or even autoload)
It makes a LOT of sense to have one library to handle both, if you need it. I'm switching to Ion\_Auth from Tank\_Auth because of this. | How should I choose an authentication library for CodeIgniter? | [
"",
"php",
"codeigniter",
"authentication",
""
] |
I have the string
```
a.b.c.d
```
I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.
(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop). | My 'idiomatic one-liner' for this is:
```
int count = StringUtils.countMatches("a.b.c.d", ".");
```
Why write it yourself when it's already in [commons lang](http://commons.apache.org/lang/)?
Spring Framework's oneliner for this is:
```
int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");
``` | How about this. It doesn't use regexp underneath so should be faster than some of the other solutions and won't use a loop.
```
int count = line.length() - line.replace(".", "").length();
``` | How do I count the number of occurrences of a char in a String? | [
"",
"java",
"string",
""
] |
Say I have the following in my `models.py`:
```
class Company(models.Model):
name = ...
class Rate(models.Model):
company = models.ForeignKey(Company)
name = ...
class Client(models.Model):
name = ...
company = models.ForeignKey(Company)
base_rate = models.ForeignKey(Rate)
```
I.e. there are multiple `Companies`, each having a range of `Rates` and `Clients`. Each `Client` should have a base `Rate` that is chosen from its parent `Company's Rates`, not another `Company's Rates`.
When creating a form for adding a `Client`, I would like to remove the `Company` choices (as that has already been selected via an "Add Client" button on the `Company` page) and limit the `Rate` choices to that `Company` as well.
How do I go about this in Django 1.0?
My current `forms.py` file is just boilerplate at the moment:
```
from models import *
from django.forms import ModelForm
class ClientForm(ModelForm):
class Meta:
model = Client
```
And the `views.py` is also basic:
```
from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm()
return render_to_response('addclient.html', {'form': form, 'the_company':the_company})
```
In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:
```
manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]
```
[`ForeignKey.limit_choices_to`](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) seems promising but I don't know how to pass in `the_company.id` and I'm not clear if that will work outside the Admin interface anyway.
Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.) | ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for [ModelChoiceField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield).
So, provide a QuerySet to the field's `queryset` attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.
```
form.rate.queryset = Rate.objects.filter(company_id=the_company.id)
```
If you take the default ModelForm object, `form.fields["rate"].queryset = ...`
This is done explicitly in the view. No hacking around. | In addition to S.Lott's answer and as becomingGuru mentioned in comments, its possible to add the queryset filters by overriding the `ModelForm.__init__` function. (This could easily apply to regular forms) it can help with reuse and keeps the view function tidy.
```
class ClientForm(forms.ModelForm):
def __init__(self,company,*args,**kwargs):
super (ClientForm,self ).__init__(*args,**kwargs) # populates the post
self.fields['rate'].queryset = Rate.objects.filter(company=company)
self.fields['client'].queryset = Client.objects.filter(company=company)
class Meta:
model = Client
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(the_company,request.POST) #<-- Note the extra arg
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm(the_company)
return render_to_response('addclient.html',
{'form': form, 'the_company':the_company})
```
This can be useful for reuse say if you have common filters needed on many models (normally I declare an abstract Form class). E.g.
```
class UberClientForm(ClientForm):
class Meta:
model = UberClient
def view(request):
...
form = UberClientForm(company)
...
#or even extend the existing custom init
class PITAClient(ClientForm):
def __init__(company, *args, **args):
super (PITAClient,self ).__init__(company,*args,**kwargs)
self.fields['support_staff'].queryset = User.objects.exclude(user='michael')
```
Other than that I'm just restating Django blog material of which there are many good ones out there. | How do I filter ForeignKey choices in a Django ModelForm? | [
"",
"python",
"django",
"django-forms",
""
] |
I'd like to check a few queries generated by ActiveRecord, but I don't need to actually run them. Is there a way to get at the query before it returns its result? | Both of these articles should help you do what you want.
<http://weblog.jamisbuck.org/2007/1/8/watching-activerecord-do-it-s-thing>
<http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord> | i think it's buried in:
```
construct_finder_sql,
```
<http://groups.google.com/group/rubyonrails-talk/browse_frm/thread/38c492e3939dd9bf/?pli=1> | How can I see the SQL ActiveRecord generates? | [
"",
"sql",
"ruby-on-rails",
"ruby",
"activerecord",
""
] |
I have a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.
How can I do this? Do I have to `fork()` before `calling os.execlp()`? | > subprocess: The `subprocess` module
> allows you to spawn new processes,
> connect to their input/output/error
> pipes, and obtain their return codes.
<http://docs.python.org/library/subprocess.html>
Usage:
```
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
``` | You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html). There's a few ways to do it:
```
import subprocess
cmd = ['/run/myscript', '--arg', 'value']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print line
p.wait()
print p.returncode
```
Or, if you don't care what the external program actually does:
```
cmd = ['/run/myscript', '--arg', 'value']
subprocess.Popen(cmd).wait()
``` | Launch a shell command with in a python script, wait for the termination and return to the script | [
"",
"python",
"subprocess",
"popen",
"os.execl",
""
] |
I want a way to list files in a directory and putting a check box beside each one of them so I can select some of them and perform operations with each selected file, what's the best way to do this? | Drop a CheckedListBox control onto the form, then populate the contents using the DirectoryInfo and FileSystemInfo classes, like this:
```
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("c:\\");
System.IO.FileSystemInfo[] files = di.GetFileSystemInfos();
checkedListBox1.Items.AddRange(files);
``` | You can use checked list box control which is built-in winforms control (see links below):
<http://www.functionx.com/vcsharp/controls/checkedlistbox1.htm>
<http://msdn.microsoft.com/en-us/library/3ss05xx6.aspx> | Listing Files With CheckBoxes (C# / WinForms) | [
"",
"c#",
"winforms",
"file",
"list",
""
] |
I am currently writing a system that stores meta data for around 140,000 ish images stored within a legacy image library that are being moved to cloud storage. I am using the following to get the jpg data...
```
System.Drawing.Image image = System.Drawing.Image.FromFile("filePath");
```
Im quite new to image manipulation but this is fine for getting simple values like width, height, aspect ratio etc but what I cannot work out is how to retrieve the physical file size of the jpg expressed in bytes. Any help would be much appreciated.
Thanks
Final solution including an MD5 hash of the image for later comparison
```
System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
if (image != null)
{
int width = image.Width;
int height = image.Height;
decimal aspectRatio = width > height ? decimal.divide(width, height) : decimal.divide(height, width);
int fileSize = (int)new System.IO.FileInfo(filePath).Length;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(fileSize))
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
Byte[] imageBytes = stream.GetBuffer();
System.Security.Cryptography.MD5CryptoServiceProvider provider = new System.Security.Cryptography.MD5CryptoServiceProvider();
Byte[] hash = provider.ComputeHash(imageBytes);
System.Text.StringBuilder hashBuilder = new System.Text.StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
hashBuilder.Append(hash[i].ToString("X2"));
}
string md5 = hashBuilder.ToString();
}
image.Dispose();
}
``` | If you get your image directly from file, you can use the following code to get size of original file in bytes.
```
var fileLength = new FileInfo(filePath).Length;
```
If you get your image from other source, like getting one bitmap and composing it with other image, like adding watermark you will have to calculate size in run-time. You can't just use original file size, because compressing may lead to different size of output data after modification. In this case, you can use MemoryStream to save image to:
```
long jpegByteSize;
using (var ms = new MemoryStream(estimatedLength)) // estimatedLength can be original fileLength
{
image.Save(ms, ImageFormat.Jpeg); // save image to stream in Jpeg format
jpegByteSize = ms.Length;
}
``` | If you don't have the original file, the file size is not clear as it depends on the image format and quality. So what you'd have to do is write the image to a stream (e.g. MemoryStream) and then use the stream's size. | How to get the file size of a "System.Drawing.Image" | [
"",
"c#",
"image",
"image-processing",
"image-manipulation",
""
] |
What is the arrow operator (`->`) a synonym for? | The following two expressions are equivalent:
```
a->b
(*a).b
```
(subject to operator overloading, as Konrad mentions, but that's unusual). | `a->b` is generally a synonym for `(*a).b`. The parenthesises here are necessary because of the binding strength of the operators `*` and `.`: `*a.b` wouldn't work because `.` binds stronger and is executed first. This is thus equivalent to `*(a.b)`.
Beware of overloading, though: Since both `->` and `*` can be overloaded, their meaning can differ drastically. | What can I use instead of the arrow operator, `->`? | [
"",
"c++",
"pointers",
""
] |
DataGridView, for example, lets you do this:
```
DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];
```
but for the life of me I can't find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes?
ETA: Thanks for all the quick answers. Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like `public object this[int x, int y]{ get{...}; set{...} }`; the indexer for DataGridView does not throw, at least according to the documentation. It doesn't mention what happens if you supply invalid coordinates.
ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates. Fair warning. | you can find how to do it [here](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx).
In short it is:
```
public object this[int i]
{
get { return InnerList[i]; }
set { InnerList[i] = value; }
}
```
If you only need a getter the syntax in [answer below](https://stackoverflow.com/a/34098286/21733) can be used as well (starting from C# 6). | That would be the item property: <http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx>
Maybe something like this would work:
```
public T Item[int index, int y]
{
//Then do whatever you need to return/set here.
get; set;
}
``` | How do I overload the square-bracket operator in C#? | [
"",
"c#",
"collections",
"operators",
"operator-overloading",
""
] |
I was wondering what people thought about the decision to support Entity Framework over LINQ-to-SQL? I have an application I'm developing originally in LINQ-to-SQL. I found it the perfect solution for our application.
While attempting to port to Entity Framework I was surprised how rough it was. IMHO, not even close to being ready for prime time. No lazy loading, no POCOs, horrible dependency on inheritance. I found it largely unusable in my case and instead decided to stick with LINQ-to-SQL until somehow this Entity Framework can get more polished.
Anyone else have similar experience with it? | That is pretty much my view. See my previous reply [here](https://stackoverflow.com/questions/276433/do-you-think-its-advantageous-to-switch-to-entity-framework#276439). This other question wasn't specifically about the problems in EF, but yes: it has a fair few glitches. For example (in addition to your existing options):
* no support for `Expression.Invoke` (re-using expression trees to form a more complex expression)
* no support for table-UDFs, which can be used to create well-defined, callable methods in the database that are still composable with sort/skip/take etc
LINQ-to-SQL handles both just fine... | I think it depends on the application platform. When my team set out to create a new ASP.net app, we wanted to go with EF... but after playing around with it for a bit, we went with Linq-To-SQL. In a web environment, managing the L2S datacontext was a lot easier. Also, we liked that L2S entities expose the original Id field (e.g. EmployeeTypeId), unlike EF, which would only have the child entity exposed. In a web environment, a lot of times you really don't need that extra information, the Id is enough because it is a reference to a dropdown list that has already been loaded (and probably cached). | Thoughts on Entity Framework | [
"",
"sql",
".net",
"entity-framework",
"linq-to-sql",
""
] |
I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run.
So far I have:
```
SELECT startTime, endTime,
cast(datediff(hh,starttime,endtime) as varchar)
+':'
+cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME
FROM applog
WHERE runID = 33871
ORDER BY startTime DESC
```
When I execute this I get expected values and also some unexpected.
For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54.
How do I get a quere in MS SQL SMS to return the value 3:06 for this case?
Thanks.
Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well. | Try these
Assuming 2 declared dates.
```
declare @start datetime
set @start = '2008-11-02 15:59:59.790'
declare @end datetime
set @end = '2008-11-02 19:05:41.857'
```
This will return the hours / mins / seconds
```
select
(datediff(ss, @start, @end) / 3600),
(datediff(ss, @start, @end) / 60) % 60,
(datediff(ss, @start, @end) % 60) % 60
--returns
----------- ----------- -----------
3 5 42
```
This is the zero-padded concatenated string version
```
select
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 3600)), 2) + ':' +
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 60) % 60), 2) + ':' +
RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) % 60) % 60), 2)
--------
03:05:42
``` | [Here's](http://www.sqlservercurry.com/2008/04/find-hours-minutes-and-seconds-in.html) a way to do it:
```
-- Find Hours, Minutes and Seconds in between two datetime
DECLARE @First datetime
DECLARE @Second datetime
SET @First = '04/02/2008 05:23:22'
SET @Second = getdate()
SELECT DATEDIFF(day,@First,@Second)*24 as TotalHours,
DATEDIFF(day,@First,@Second)*24*60 as TotalMinutes,
DATEDIFF(day,@First,@Second)*24*60*60 as TotalSeconds
``` | SQL: get DATEDIFF to not return negative values | [
"",
"sql",
"sql-server-2005",
"t-sql",
"datediff",
""
] |
I'm finding that hitting the "Refresh" button on my browser will temporarily screw up the ViewState for controls inside an UpdatePanel.
Here's my situation : I made a custom WebControl that stores values in the ViewState. I put this control inside an UpdatePanel. When I hit the "refresh" button on my browser, it will temporarily wipe out the values in ViewState. However, on the next postback, the values that were in the ViewState before I hit "refresh" magically reappear.
This behavior screws up my webcontrol. After I hit "refresh," the control is returned to its initial state, since the ViewState is empty and IsPostBack is set to false. However, when I click on one of the postback controls within my WebControl, the WebControl will reload with the same values that were in ViewState before I hit "refresh."
Strangely, this only happens when I'm using AJAX. When my control is outside of an UpdatePanel, Firefox gives me it's standard message, "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier (Resend) (Cancel)." This is fine, because at least the behavior is consistent. However, I absolutely must use AJAX for this project.
So this is what I would like to do - I want to make the "refresh" behavior consistent. It would be best if hitting "refresh" didn't affect the ViewState at all. But if it has to wipe out the ViewState, that's fine, as long as the ViewState STAYS wiped out. None of this stuff with values disappearing and reappearing.
Oh yeah, and here's my example code :
```
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace TestControls
{
public class TestControl : WebControl
{
int _clickCount;
bool _mustUpdate;
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
_clickCount = ((int)ViewState["clickCount"]);
_mustUpdate = ((bool)ViewState["mustUpdate"]);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Controls.Clear();
ControlCreator();
}
private void ControlCreator()
{
Label tempLabel = new Label();
LiteralControl tempLiteral = new LiteralControl("<br/><br/>");
LinkButton tempLink = new LinkButton();
tempLink.ID = "testLink";
tempLink.Text = "Click me!";
tempLink.Click += new EventHandler(tempLink_Click);
tempLabel.ID = "testLabel";
tempLabel.Text = _clickCount.ToString();
Controls.Add(tempLabel);
Controls.Add(tempLiteral);
Controls.Add(tempLink);
}
void tempLink_Click(object sender, EventArgs e)
{
_clickCount++;
_mustUpdate = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (_mustUpdate)
{
Controls.Clear();
ControlCreator();
_mustUpdate = false;
}
}
protected override object SaveViewState()
{
ViewState["clickCount"] = _clickCount;
ViewState["mustUpdate"] = _mustUpdate;
return base.SaveViewState();
}
}
}
``` | I just re-read your question and realised I missed something...
**You are hitting the *browsers* refresh button!**
Is this a problem? **YES!**
What happens when you hit the refresh button on the browser?
It refreshes the current page. If there was a postback, it will resend the post data.
The AJAX callback may update the ViewState as far as the page is concerned but hitting the browser refresh button will re-post the old ViewState.
There is a wealth is discussion on the matter which you can Google.
One very simple idea is to perhaps store the information in Session state instead perhaps. That too also can have its own issue too of course. But it may achieve your immediate goal.
A tip for wiping the history of a postback (to prevent the re-post) is to redirect back to the same page again. | Try the following...
```
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
object[] myState = (object[])savedState;
if (myState[0] != null) base.LoadViewState(myState[0]);
if (myState[1] != null) _clickCount = ((int)myState[1]);
if (myState[2] != null) _mustUpdate = ((bool)myState[2]);
}
}
protected override object SaveViewState()
{
object[] allStates = new object[3];
allStates[0] = base.SaveViewState();
allStates[1] = _clickCount;
allStates[2] = _mustUpdate;
return allStates;
}
```
Basically derived the above code from [Control.LoadViewState Method](http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadviewstate.aspx) and [Control.SaveViewState Method](http://msdn.microsoft.com/en-us/library/system.web.ui.control.saveviewstate.aspx) from MSDN. | Inconsistent behavior with AJAX and ViewState in .NET | [
"",
"c#",
".net",
"ajax",
"updatepanel",
"viewstate",
""
] |
I apologize in advance if this question seems remedial.
Which would be considered more efficient in Python:
**Standard import**
```
import logging
try:
...some code...
exception Exception, e:
logging.error(e)
```
...or...
**Contextual import**
```
try:
...some code...
exception Exception, e:
import logging
logging.error(e)
``` | Contextual imports are technically more efficient, but I think they can create other problems.
Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code. | It depends on how often you execute the contextual import.
An `import` statement requires checking to see if the module exists, which has a non-zero cost.
Lots of contextual imports will be a performance penalty for no real gain in simplicity. There's very little benefit, unless you are really sure that the import will be used rarely or never.
Contextual imports inside `if` statements make sense, especially when it's done at the top level, which means precisely once.
```
if someConfig:
import this as bigDeal
else:
import that as bigDeal
``` | Which is more efficient in Python: standard imports or contextual imports? | [
"",
"python",
""
] |
I am implementing an asynchronous command pattern for the "client" class in a client/server application. I have done some socket coding in the past and I like the new Async pattern that they used in the Socket / SocketAsyncEventArgs classes.
My async method looks like this: `public bool ExecuteAsync(Command cmd);` It returns true if the execution is pending and false if it completed synchronously. **My question is: Should I always call the callback (cmd.OnCompleted), even in the event of an exception? Or should I throw exceptions right from ExecuteAsync?**
Here are some more details if you need them. This is similar to using SocketAsyncEventArgs, but instead of SocketAsyncEventArgs my class is called SomeCmd.
```
SomeCmd cmd = new SomeCmd(23, 14, 10, "hike!");
cmd.OnCompleted += this.SomeCmd_OnCompleted;
this.ConnectionToServer.ExecuteAsync(cmd);
```
As with the Socket class, if you need to coordinate with your callback method (SomeCmd\_OnCompleted in this case), you can use the return value of ExecuteAsync to know if the operation is pending (true) or if the operation completed synchronously.
```
SomeCmd cmd = new SomeCmd(23, 14, 10, "hike!");
cmd.OnCompleted += this.SomeCmd_OnCompleted;
if( this.ConnectionToServer.ExecuteAsync(cmd) )
{
Monitor.Wait( this.WillBePulsedBy_SomeCmd_OnCompleted );
}
```
Here is a greatly simplified version of my base classes, but you can see how it works:
```
class Connection
{
public bool ExecuteAsync(Command cmd)
{
/// CONSIDER: If you don't catch every exception here
/// then every caller of this method must have 2 sets of
/// exception handling:
/// One in the handler of Command.OnCompleted and one where ExecuteAsync
/// is called.
try
{
/// Some possible exceptions here:
/// 1) remote is disposed. happens when the other side disconnects (WCF).
/// 2) I do something wrong in TrackCommand (a bug that I want to fix!)
this.TrackCommand(cmd);
remote.ServerExecuteAsync( cmd.GetRequest() );
return true;
}
catch(Exception ex)
{
/// Command completing synchronously.
cmd.Completed(ex, true);
return false;
}
}
/// <summary>This is what gets called by some magic when the server returns a response.</summary>
internal CommandExecuteReturn(CommandResponse response)
{
Command cmd = this.GetTrackedCommand(response.RequestId);
/// Command completing asynchronously.
cmd.Completed(response, false);
}
private IServer remote;
}
abstract class Command: EventArgs
{
internal void Completed(Exception ex, bool synchronously)
{
this.Exception = ex;
this.CompletedSynchronously = synchronously;
if( this.OnCompleted != null )
{
this.OnCompleted(this);
}
}
internal void Completed(CommandResponse response, bool synchronously)
{
this.Response = response;
this.Completed(response.ExceptionFromServer, synchronously)
}
public bool CompletedSynchronously{ get; private set; }
public event EventHandler<Command> OnCompleted;
public Exception Exception{ get; private set; }
internal protected abstract CommandRequest GetRequest();
}
``` | throwing an exception from the dispatch point may or may not be useful
calling the callback passing an exception argument requires the completion callback to do 2 distinct things
a second callback for exception reporting might make sense instead | One general pattern for asynchronous operations in .NET (at least for the `BackgroundWorker` and the `BeginInvoke()/EndInvoke()` method pairs is to have a result object that separates the callback from the actual return value or any exceptions that occurred. It's the responsibility of the callback to handle the exception.
Some C#-like pseudocode:
```
private delegate int CommandDelegate(string number);
private void ExecuteCommandAsync()
{
CommandDelegate del = new CommandDelegate(BeginExecuteCommand);
del.BeginInvoke("four", new AsyncCallback(EndExecuteCommand), null);
}
private int BeginExecuteCommand(string number)
{
if (number == "five")
{
return 5;
}
else
{
throw new InvalidOperationException("I only understand the number five!");
}
}
private void EndExecuteCommand(IAsyncResult result)
{
CommandDelegate del;
int retVal;
del = (CommandDelegate)((AsyncResult)result).AsyncDelegate;
try
{
// Here's where we get the return value
retVal = del.EndInvoke(result);
}
catch (InvalidOperationException e)
{
// See, we had EndExecuteCommand called, but the exception
// from the Begin method got tossed here
}
}
```
So if you call `ExecuteCommandAsync()`, it returns immediately. The `BeginExecuteCommand()` is launched in a separate thread. If it tosses an exception, that exception won't get thrown until you call `EndInvoke()` on the `IAsyncResult` (which you can cast to `AsyncResult`, which is documented but you could pass it in the state if the cast makes you uncomfortable. This way, the exception handling code is "naturally placed" around where you would be interacting with the return value of the method.
For more information, checkout more information on [the IAsyncResult pattern on MSDN](http://msdn.microsoft.com/en-us/library/ms228969.aspx).
Hope this helps. | Async command pattern - exception handling | [
"",
"c#",
".net",
"exception",
"design-patterns",
""
] |
I'm using jQuery and wanting to target the nth <li> in a list after clicking the nth link.
```
<ul id="targetedArea">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div id="clickedItems">
<a></a>
<a></a>
<a></a>
<a></a>
</div>
```
I can target them individually, but I know there must be a faster way by passing which <a> element I clicked on.
```
$("#clickedItem a:eq(2)").click(function() {
$("#targetedArea:eq(2)").addClass('active');
return false;
});
```
Cheers,
Steve | how about something like this:
```
$('#clickedItems a').click(function() {
// figure out what position this element is in
var n = $('#clickedItems a').index($(this) );
// update the targetedArea
$('#targetedArea li:eq('+n+')').html('updated!');
return false;
});
```
assuming a 1:1 relationship between your `<a>` and `<li>` elements it will update the appropriate `<li>` | I know this is not directly answering your question, but maybe you're making it more difficult than it is.
Give each of the A and LI elements an ID, and make the IDs so you can infer them from each other. As soon as an A is clicked, you immediately know the LI's ID and can refer to it directly.
As a side effect, this is more efficient than any clever jQuery that might do the same thing. | After clicking the nth item, how do I manipulate another nth element? | [
"",
"javascript",
"jquery",
""
] |
Hey! I was looking at this code at <http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html>
I noticed that in some situations they used hex numbers, like in line 134:
```
for (j = 1; val && j <= 0x80; j <<= 1, q++)
```
Now why would they use the 0x80? I am not that good with hex but I found an online hex to decimal and it gave me 128 for 0x80.
Also before line 134, on line 114 they have this:
```
small_n = (n & 0xffff0000) == 0;
```
The hex to decimal gave me 4294901760 for that hex number.
So here in this line they are making a bit AND and comparing the result to 0??
Why not just use the number?
Can anyone please explain and please do give examples of other situations.
Also I have seen large lines of code where it's just hex numbers and never really understood why :( | In both cases you cite, the bit pattern of the number is important, not the actual number.
For example,
In the first case,
`j` is going to be 1, then 2, 4, 8, 16, 32, 64 and finally 128 as the loop progresses.
In binary, that is,
`0000:0001`, `0000:0010`, `0000:0100`, `0000:1000`, `0001:0000`, `0010:0000`, `0100:0000` and `1000:0000`.
There's no option for binary constants in C (until C23) or C++ (until C++14), but it's a bit clearer in Hex:
`0x01`, `0x02`, `0x04`, `0x08`, `0x10`, `0x20`, `0x40`, and `0x80`.
In the second example,
the goal was to remove the lower two bytes of the value.
So given a value of 1,234,567,890 we want to end up with 1,234,567,168.
In hex, it's clearer: start with `0x4996:02d2`, end with `0x4996:0000`. | There's a direct mapping between hex (or octal for that matter) digits and the underlying bit patterns, which is not the case with decimal. A decimal '9' represents something different with respect to bit patterns depending on what column it is in and what numbers surround it - it doesn't have a direct relationship to a bit pattern. In hex, a '9' always means '1001', no matter which column. 9 = '1001', 95 = '\*1001\*0101' and so forth.
As a vestige of my 8-bit days I find hex a convenient shorthand for anything binary. Bit twiddling is a dying skill. Once (about 10 years ago) I saw a third year networking paper at university where only 10% (5 out of 50 or so) of the people in the class could calculate a bit-mask. | Why use hex? | [
"",
"c++",
"c",
"hex",
""
] |
Sometimes, when we're doing small changes to our web apps, e.g. bug fixes, we don't build a whole new WAR-file each time, but merely replace just the affected class files in the exploded web app directory under `WEB-INF/classes` and restart the app.
Is that okay? | I'd say that probably isn't a best practice, because of versioning: how do you know which version of the application you've got deployed? If you deploy a .war file your build process can take care of updating a build number (from source control, or separately, whatever - as long as each build has a different number it's OK).
If you're using continuous integration (and it's definitely a good idea to be) then your build process should be kicking out an 'artifact' (war file) each time you make changes in source code. also perhaps tagging the code in version control with the build number.
So, when you deploy your web app, you know exactly which version is running and which source code makes up that version.
Making small incremental changes by updating individual .class files I'd say is probably not a good idea for anything other than local developer testing. | You can solve your deployment tasks using maven.
Every time you change anything, just type
```
svn update
mvn clean compile war:exploded tomcat:inplace -P deployment
```
you have 'deployment' profile in your pom.xml file, containing all the configuraiton needed for deployment environment.
this way you can event automate the deployment process and never fail when manually copying wrong/old/etc files. | Is it okay to update a Java web application by replacing just single class files? | [
"",
"java",
"web-applications",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.