Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
After some find and replace refactoring I ended up with this gem:
```
const class A
{
};
```
What does "const class" mean? It seems to compile ok.
|
> What does "const class" mean? It seems to compile ok.
Not for me it doesn't. I think your compiler's just being polite and ignoring it.
**Edit:** Yep, VC++ silently ignores the const, GCC complains.
|
The `const` is meaningless in that example, and your compiler should give you an error, but if you use it to declare variables of that class between the closing `}` and the `;`, then that defines those instances as `const`, e.g.:
```
const class A
{
public:
int x, y;
} anInstance = {3, 4};
// The above is equivalent to:
const A anInstance = {3, 4};
```
|
What does "const class" mean?
|
[
"",
"c++",
"class",
"constants",
""
] |
Is there any meaningful distinction between:
```
class A(object):
foo = 5 # some default value
```
vs.
```
class B(object):
def __init__(self, foo=5):
self.foo = foo
```
If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?
|
There is a significant *semantic* difference (beyond performance considerations):
* **when the attribute is defined on the instance** (which is what we usually do), there can be multiple objects referred to. **Each gets a totally separate version of that attribute**.
* **when the attribute is defined on the class**, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then:
+ if the attribute is a **builtin type** (like int, float, boolean, string), operations on one object will overwrite (clobber) the value
+ if the attribute is a **mutable type** (like a list or a dict), we will get unwanted leakage.
For example:
```
>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]
>>> class A:
... def __init__(self): self.foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[]
```
|
The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance.
If coming from C++, attributes on the class are more like static member variables.
|
What is the difference between class and instance attributes?
|
[
"",
"python",
"attributes",
"member-variables",
""
] |
I'm working on a project where we're doing a lot of remote object transfer between a Java service and clients written in other various languages. Given our current constraints I've decided to see what it would take to generate code based on an existing Java class. Basically I need to take a `.class` file (or a collection of them) parse the bytecode to determine all of the data members and perhaps getters/setters and then write something that can output code in a different language to create a class with the same structure.
I'm not looking for standard decompilers such as JAD. I need to be able to take a `.class` file and create an object model of its data members and methods. Is this possible at all?
|
I've used BCEL and find it really quite awkward. [ASM](http://asm.objectweb.org/) is much better. It very extensively uses visitors (which can be a little confusing) and does not create an object model. Not creating an object model turns out to be a bonus, as any model you do want to create is unlikely to look like a literal interpretation of all the data.
|
From your description, it sounds like [simple reflection](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html) would suffice. You can discover all of the static structure of the class, as well as accessing the fields of a particular instance.
I would only move on to BCEL if you are trying to translate method instructions. (And if that's what you're trying to automate, good luck!)
|
Programmatically inspect .class files
|
[
"",
"java",
"bytecode",
"decompiling",
""
] |
Is there a way to compile multiple java source directories in a single maven project?
|
You can add a new source directory with build-helper:
```
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
|
I naively do it this way :
```
<build>
<finalName>osmwse</finalName>
<sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory>
</build>
```
|
Maven compile with multiple src directories
|
[
"",
"java",
"maven-2",
""
] |
I'm all for language diversity, but Objective C is insane. So I'm curious: is it possible to code iPhone apps with C++ while using the Cocoa API, etc?
|
Short answer, yes, sort of. You can use Objective-C++, which you can read about at [Apple Developer Connection.](http://web.archive.org/web/20101203170217/http://developer.apple.com/library/mac/#/web/20101204020949/http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCPlusPlus.html)
If you know C++ already, learning Objective-C would be pretty simple, if you decided to give that a try. More info on that topic is at the ADC as well.
|
Although Objective-C does indeed appear to be "insane" initially, I encourage you to stick with it. Once you have an "a-ha" moment, suddenly it all starts to make sense. For me it took about 2 weeks of focused Objective-C concentration to really understand the Cocoa frameworks, the language, and how it all fits together. But once I really "got" it, it was very very exciting.
It sounds cliché, but it's true. Stick it out.
Of course, if you're bringing in C++ libraries or existing C++ code, you can use those modules with Objective-C/Objective-C++.
|
Is it possible to program iPhone in C++
|
[
"",
"c++",
"iphone",
"objective-c",
""
] |
We are moving our database server to a bigger box. I have several databases with full text indexes. What is the best way to move the full text indexes?
|
I find backup and restore is the only reliable way to move databases. The FTS should move with it when you do that. Detaching and reattaching databases never really sits well with me.
|
My first attempt was to copy over the database files and reattach them. I ran into the following error when attempting to access the catalog:
**Full-text catalog '*database name*' is in an unstable state. Drop and re-create this full-text catalog. (Microsoft SQL Server, Error: 7624**
My second and **Successful** attempt was to restore the database from backup as Craig suggested. My catalog did come over but I received the following error:
**Property IsAccentSensitive is not available for FullTextCatalog '[CatalogName]'" This property may not exist for this object, or may not be retrievable due to insufficient access rights. (Microsoft.SqlServer.Smo)**
After a quick google search I found the answer
[MS KB 910067](http://support.microsoft.com/kb/910067)
Simply detach and reattach the database and I was fine.
|
Move/copy SQL Server 2005 full text index
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have a very painful library which, at the moment, is accepting a C# string as a way to get arrays of data; apparently, this makes marshalling for pinvokes easier.
So how do I make a ushort array into a string by bytes? I've tried:
```
int i;
String theOutData = "";
ushort[] theImageData = inImageData.DataArray;
//this is as slow like molasses in January
for (i = 0; i < theImageData.Length; i++) {
byte[] theBytes = System.BitConverter.GetBytes(theImageData[i]);
theOutData += String.Format("{0:d}{1:d}", theBytes[0], theBytes[1]);
}
```
I can do it this way, but it doesn't finish in anything remotely close to a sane amount of time.
What should I do here? Go unsafe? Go through some kind of IntPtr intermediate?
If it were a char\* in C++, this would be significantly easier...
edit: the function call is
```
DataElement.SetByteValue(string inArray, VL Length);
```
where VL is a 'Value Length', a DICOM type, and the function itself is generated as a wrapper to a C++ library by SWIG. It seems that the representation chosen is string, because that can cross managed/unmanaged boundaries relatively easily, but throughout the C++ code in the project (this is GDCM), the char\* is simply used as a byte buffer. So, when you want to set your image buffer pointer, in C++ it's fairly simple, but in C#, I'm stuck with this weird problem.
This is hackeration, and I know that probably the best thing is to make the SWIG library work right. I really don't know how to do that, and would rather a quick workaround on the C# side, if such exists.
|
P/Invoke can actually handle what you're after most of the time using StringBuilder to create writable buffers, for example see [pinvoke.net on GetWindowText and related functions](http://www.pinvoke.net/search.aspx?search=GetWindowText).
However, that aside, with data as ushort, I assume that it is encoded in UTF-16LE. If that is the case you can use Encoding.Unicode.GetString(), but that will exepect a byte array rather than a ushort array. To turn your ushorts into bytes, you can allocate a separate byte array and use Buffer.BlockCopy, something like this:
```
ushort[] data = new ushort[10];
for (int i = 0; i < data.Length; ++i)
data[i] = (char) ('A' + i);
string asString;
byte[] asBytes = new byte[data.Length * sizeof(ushort)];
Buffer.BlockCopy(data, 0, asBytes, 0, asBytes.Length);
asString = Encoding.Unicode.GetString(asBytes);
```
However, if unsafe code is OK, you have another option. Get the start of the array as a ushort\*, and hard-cast it to char\*, and then pass it to the string constructor, like so:
```
string asString;
unsafe
{
fixed (ushort *dataPtr = &data[0])
asString = new string((char *) dataPtr, 0, data.Length);
}
```
|
One thing you can do is switch from using a string to a stringBuilder it will help performance tremendously.
If you are willing to use unsafe code you can use pointers and implement the your c# code just like your c++. Or you could write a small c++\cli dll that implements this functionality.
|
C# ushort[] to string conversion; is this possible?
|
[
"",
"c#",
"string",
"ushort",
""
] |
I am using VC++. Is `assert(false)` ignored in release mode?
|
If compiling in release mode includes defining NDEBUG, then yes.
See [assert (CRT)](https://msdn.microsoft.com/library/9sb57dw4.aspx)
|
IIRC, assert(x) is a macro that evaluates to nothing when NDEBUG is defined, which is the standard for Release builds in Visual Studio.
|
Is assert(false) ignored in release mode?
|
[
"",
"c++",
"visual-c++",
"posix",
"assert",
""
] |
What is the string concatenation operator in Oracle SQL?
Are there any "interesting" features I should be careful of?
(This seems obvious, but I couldn't find a previous question asking it).
|
It is `||`, for example:
```
select 'Mr ' || ename from emp;
```
The only "interesting" feature I can think of is that `'x' || null` returns `'x'`, not `null` as you might perhaps expect.
|
There's also concat, but it doesn't get used much
```
select concat('a','b') from dual;
```
|
What is the string concatenation operator in Oracle?
|
[
"",
"sql",
"oracle",
"plsql",
"string-concatenation",
""
] |
I have a form with a textbox and a button. IE is the only browser that will not submit the form when Enter is pressed (works in FF, Opera, Safari, Chrome, etc.). I found this javascript function to try to coax IE into behaving; but no avail:
```
function checkEnter(e){
var characterCode
if (e && e.which) {
e = e
characterCode = e.which
} else {
e = event
characterCode = e.keyCode
}
if (characterCode == 13) {
document.forms[0].submit()
return false
} else {
return true
}
}
```
Implementation:
```
searchbox.Attributes("OnKeyUp") = "checkEnter(event)"
```
Any advice?
**EDIT:** [This page](http://www.codeproject.com/KB/aspnet/EnterKeyToButtonClick.aspx) on [CodeProject](http://www.codeproject.com/) outlines what Dillie was saying, and it works perfectly.
|
The other thing I have done in the past is wrap the form area in a Panel and set the DefaultButton attribute to the submit button you have. This effectively maps the enter key to the submission as long as you have a form element in focus in the panel area.
|
Just create a text input in a hidden div on the page. This will circumvent the IE bug.
Example div:
```
<!-- Fix for IE bug (One text input and submit, disables submit on pressing "Enter") -->
<div style="display:none">
<input type="text" name="hiddenText"/>
</div>
```
|
Enter button does not submit form (IE ONLY) ASP.NET
|
[
"",
"asp.net",
"javascript",
"internet-explorer",
"textbox",
""
] |
I'm working with an existing XML document which has a structure (in part) like so:
```
<Group>
<Entry>
<Name> Bob </Name>
<ID> 1 </ID>
</Entry>
<Entry>
<Name> Larry </Name>
</Entry>
</Group>
```
I'm using LINQ to XML to query the XDocument to retrieve all these entries as follows:
```
var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string)g.element("Name").Value,
id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
};
```
The "ID" elements aren't always there and so my solution to this was the Count() jazz above. But I'm wondering if someone has a better way to do this. I'm still getting comfortable with this new stuff and I suspect that there may be a better way to do this than how I'm currently doing it.
Is there a better/more preferred way to do what I want?
|
[XElement](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx) actually has [interesting explicit conversion operators](http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.op_explicit.aspx) that do the right thing in this case.
So, you rarely actually need to access the `.Value` property.
This is all you need for your projection:
```
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (string) g.Element("ID") ?? "none",
};
```
And if you'd prefer to use the value of `ID` as an integer in your anonymous type:
```
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (int?) g.Element("ID"),
};
```
|
In a similar situation I used an extension method:
```
public static string OptionalElement(this XElement actionElement, string elementName)
{
var element = actionElement.Element(elementName);
return (element != null) ? element.Value : null;
}
```
usage:
```
id = g.OptionalElement("ID") ?? "none"
```
|
LINQ to XML optional element query
|
[
"",
"c#",
"linq",
"linq-to-xml",
"anonymous-types",
""
] |
How should I show users which fields are compulsory in a windows forms application.
I have considered changing the label color or maybe the background color of the text box.
I use an error provider to show a red exclamation mark next to the field, however this is only visible after they have clicked the save button.
|
* Asterisk or icon to the side of control
* Red border when required validation fails (when user tries to save)
* Bold Labels
* Different background color for required controls (perhaps only when user tries to save)
|
Use the errorprovider extension control.
This places a red cross next to the control with a tooltip message.
|
How to show compulsory fields on a windows form
|
[
"",
"c#",
".net",
"windows",
"winforms",
""
] |
I want to use google chrome as a control.
I think Enso does this because they have a dir in their folder called chrome...
Maybe there is a google chrome toolkit, SDK
|
Lots of apps have folders named Chrome. The terms refers to the decorations and arrangments used for all the different GUI widgets.
|
google chrome is an application, not a window or a directX which you can create as a control.
You can however as someone already mention host a WebKit control. You can do that quite easily using QT which has a WebKit widget.
a folder called "chrome" can mean any number of things. "chrome" is a general term for the UI of a browser. Firefox also has the word "chrome" all over its code base.
|
How can I open a google chome window (only the page) using c#
|
[
"",
"c#",
""
] |
I realize that this would be COMPLETELY bad practice in normal situations, but this is just for a test app that needs to be taking input from a bar code scanner (emulating a keyboard). The problem is that I need to start up some scripts while scanning, so I need the window to regain focus directly after I click the script to run it. I've tried using Activate(), BringToFront(), Focus() as well as some Win32 calls like SetForegroundWindow(), Setcapture() and SetActiveWindow()... however the best I can get any of them to do is to make the taskbar item start blinking to tell me that it *wants* to have focus, but something is stopping it. BTW, I'm running this on XP SP2 and using .NET 2.0.
Is this possible?
Edit: To clarify, I am running the scripts by double-clicking on them in explorer. So I need it to steal focus back from explorer and to the test app.
|
## Visibility
Make the window a "Top-Most" window. This is the way the Task-Manager can remain on top of other windows. This is a property of a `Form` and you make the form top-most (floating above other windows) by setting the value to **`true`**.
You shouldn't need to override any of the "Active window" behaviour with the top-most setting.
## Focus
I asked a similar question [previously here on StackOverflow](https://stackoverflow.com/questions/91234/multiple-keyboards-and-low-level-hooks) and the answer would solve your problem. You can make the application use a low-level input hook and get notification of the key-codes coming from the scanner. This way, your application always gets these keys even though the application does not have focus.
You may need to enhance the solution to squash the key-codes so that they are not transmitted to the "in-focus" application (e.g. notepad).
Since Windows 2000, there is no official mechanism for an application to grab focus without direct intervention of the user. Peeking at the input streams through the RawInputDevices hook is the only sensible way to go.
A number of articles may help (C# implementations)
* [RawInput article on CodeProject](http://www.codeproject.com/KB/system/rawinput.aspx)
* [MSDN documentation of RawInput](http://msdn.microsoft.com/en-us/library/ms645536(VS.85).aspx)
|
I struggled with a similar problem for quite a while. After much experimentation and guessing, this is how I solved it:
```
// Get the window to the front.
this.TopMost = true;
this.TopMost = false;
// 'Steal' the focus.
this.Activate();
```
|
Keep window on top and steal focus in WinForms
|
[
"",
"c#",
".net",
"winforms",
""
] |
I'm having trouble with something that I thought would be easy...
I can't get my NotifyIcon to show a balloon tip. The basic code is:
```
public void ShowSystrayBubble(string msg, int ms)
{
sysTrayIcon.Visible = true;
sysTrayIcon.ShowBalloonTip(20, "Title", "Text", ToolTipIcon.None);
}
```
Nothing happens when I execute this code. I read that the timeout arg may be in seconds or ms, can't tell, so I tried both and neither works.
I'm using WinXP, .NET 3.5.
|
I had foiled myself... This turned out to be an issue at the OS level. I had previously disabled all balloons via the registry a few weeks ago.
You can read the information here on how to disable balloon tips in WinXP:
<http://support.microsoft.com/kb/307729>
To enable them, just set the registry value to 1 instead and logon again/restart.
|
You should then log the messages for users who have disabled the balloons be able to go review them in case of need. If you can get permissions to read the registry, you could check the value and act accordingly (not to modify the value, but to log or to show the balloon).
|
Balloon not showing up with NotifyIcon.ShowBalloonTip
|
[
"",
"c#",
".net",
"notifyicon",
"systray",
""
] |
I'm trying to write an iterator for results from a PDO statement but I can't find any way of rewinding to the first row. I would like to avoid the overhead of calling fetchAll and storing all the result data.
```
// first loop works fine
foreach($statement as $result) {
// do something with result
}
// but subsequent loops don't
foreach($statement as $result) {
// never called
}
```
Is there some way of reseting the statement or seeking the first row?
|
I'm pretty sure this is database dependent. Because of that, it is something you should try to avoid. However, I think you can achieve what you want by enabling [buffered queries](http://www.php.net/pdo-mysql#pdo-mysql.constants). If that doesn't work, you can always pull the result into an array with [`fetchAll`](http://www.php.net/manual/en/pdostatement.fetchall.php). Both solutions have implications for your applications performance, so think twice about it, if the resultsets are large.
|
This little class I wrote wraps a PDOStatement. It only stores the data that is fetched. If this doesn't work, you could move the cache to read and write to a file.
```
// Wrap a PDOStatement to iterate through all result rows. Uses a
// local cache to allow rewinding.
class PDOStatementIterator implements Iterator
{
public
$stmt,
$cache,
$next;
public function __construct($stmt)
{
$this->cache = array();
$this->stmt = $stmt;
}
public function rewind()
{
reset($this->cache);
$this->next();
}
public function valid()
{
return (FALSE !== $this->next);
}
public function current()
{
return $this->next[1];
}
public function key()
{
return $this->next[0];
}
public function next()
{
// Try to get the next element in our data cache.
$this->next = each($this->cache);
// Past the end of the data cache
if (FALSE === $this->next)
{
// Fetch the next row of data
$row = $this->stmt->fetch(PDO::FETCH_ASSOC);
// Fetch successful
if ($row)
{
// Add row to data cache
$this->cache[] = $row;
}
$this->next = each($this->cache);
}
}
}
```
|
Is it possible to rewind a PDO result?
|
[
"",
"php",
"iterator",
"pdo",
""
] |
How to implement CEditListCtrl?. List control with edit capabality (Report/Grid view).
I have a list view in Report View. It has some values. I need to extend this to edit the values present in the list view.
I declared a class which inherits from CListCtrl. And I have handled the two Window messages to start and end the edit. Upon getting the messages I am displaying a Text box. But I am not getting the control inside these message handlers. Is there a way to know the reason?
Or Is there a other way to implement this.
|
Thanks for all answers
I have done it easily.
1. I have handled the WM\_LBUTTONDOWN. This handler pops up the edit box to get the new
value for the field
2. Handled LVN\_ENDLABELEDIT to know the end of update.
3. After receiving the above message, updated the values.
“One thing I forgotten was to set the flag in the resource view for CListCtrl (Edit Labels to TRUE)”
We have to implement OnPaint() (in CListCtrl's derived class) also otherwise the UI won't update properly
|
There are some neat grid controls on Code Project which might help:
<http://www.codeproject.com/KB/miscctrl/gridctrl.aspx>
<http://www.codeproject.com/KB/library/gridprojects.aspx>
<http://www.codeproject.com/KB/MFC/UltimateGrid.aspx>
|
How to implement CEditListCtrl
|
[
"",
"c++",
"visual-c++",
"mfc",
""
] |
I am extending a class defined in a library which I cannot change:
```
public class Parent
{
public void init(Map properties) { ... }
}
```
If I am defining a class 'Child' that extends Parent and I am using Java 6 with generics, what is the best way to override the init method without getting unchecked warnings?
```
public class Child extends Parent
{
// warning: Map is a raw type. References to generic type Map<K,V> should be parameterized
public void init(Map properties) { }
}
```
If I add generic parameters, I get:
```
// error: The method init(Map<Object,Object>) of type Child has the same erasure as init(Map) of type Parent but does not override it
public void init(Map<Object,Object>) { ... }
// same error
public void init(Map<? extends Object,? extends Object>) { ... }
// same error
public void init(Map<?,?>) { ... }
```
This error occurs regardless of whether I use a specific type, a bounded wildcard, or an unbounded wildcard. Is there a correct or idiomatic way to override a non-generic method without warnings, and without using @SuppressWarnings("unchecked")?
|
Yes, you have to declare the overriding method with the same signature as in the parent class, without adding any generics info.
I think your best bet is to add the `@SuppressWarnings("unchecked")` annotation to the raw-type parameter, not the method, so you won't squelch other generics warnings you might have in your own code.
|
Short answer: no way to do that.
Unsatisfying answer: disable the (specific) warnings in your IDE/build.xml.
If you cannot change the library, alas, you have to stick with non-generic methods.
The problem is that, despite after type erasure both init() have the same signature, they may in fact be different methods -- or the same(\*). Compiler cannot tell should it do override or overload, so it's prohibited.
(\*)
Suppose the library developer meant init(Map<String,Integer>). Now you are implementing init(Map<String,String>). This is overloading, and two methods should exist in the vtable of Child class.
But what if the library developer meant init(Map<String,String>)? Then it's overriding, and your method should **replace** original init in Child class, and there would be only one method in the vtable of Child.
P.S. I hate how Generics implemented in Java :-(
|
Can unchecked warnings be avoided when overriding a method with raw type parameters?
|
[
"",
"java",
"generics",
"suppress-warnings",
"raw-types",
""
] |
I took the plunge this afternoon and began studying LINQ, so far just mucking around with LINQ on collections. One of the first things I tried was to implement QSort.
Now -- ignoring the fact that I *could* just use an ORDERBY and that this is a very silly qsort implementation -- what I came up with was this:
```
public class lqsort
{
public static List<int> QSLinq(List<int> _items)
{
if (_items.Count <= 1)
return _items;
int _pivot = _items[0];
List<int> _less = (from _item in _items where _item < _pivot select _item).ToList();
List<int> _same = (from _item in _items where _item == _pivot select _item).ToList();
List<int> _greater = (from _item in _items where _item > _pivot select _item).ToList();
return (QSLinq(_less).Concat(_same.Concat(QSLinq(_greater)))).ToList();
}
}
```
The only thing that really bugs me is all of the casting involved. Are there any LINQ tricks I might use? Or am I just using LINQ for things it wasn't intended for?
|
Just change the type of the parameter to `IEnumerable` and use the `var` construct instead of your `List<int>` for your local variables.
This will make your `QSLinq` method better because it will accept more types of parameters, for example `int[]`, as well as `List<int>`.
See the new method:
```
public static IEnumerable<int> QSLinq(IEnumerable<int> _items)
{
if (_items.Count() <= 1)
return _items;
var _pivot = _items.First();
var _less = from _item in _items where _item < _pivot select _item;
var _same = from _item in _items where _item == _pivot select _item;
var _greater = from _item in _items where _item > _pivot select _item;
return QSLinq(_less).Concat(QSLinq(_same)).Concat(QSLinq(_greater));
}
```
Hope this helps.
|
Fun Question! This doesn't outperform OrderBy, but it does limit the repeated enumerations some.
```
public static IEnumerable<int> QSort2(IEnumerable<int> source)
{
if (!source.Any())
return source;
int first = source.First();
return source
.GroupBy(i => i.CompareTo(first))
.OrderBy(g => g.Key)
.SelectMany(g => g.Key == 0 ? g : QSort2(g));
}
```
I inadvertently generated a stackoverflow during development, as I QSorted when the Key == 0.
---
Just for fun I tested these solutions. I commited the cardinal performance testing sin (testing in debug mode), but I don't think that affects the big O effect we'll see. Here is the input (reversed input is *worst case* for quicksort)
```
IEnumerable<int> source = Enumerable.Range(0, 1000).Reverse().ToList();
```
* The triple concat-where solution took 71000 milliseconds.
* My solution took 330 milliseconds
* OrderBy.ToArray took 15 milliseconds (the timer's resolution, so actual time is probably less)
|
Learning LINQ: QuickSort
|
[
"",
"c#",
".net",
"linq",
""
] |
Using C or C++, After I decrypt a file to disk- how can I guarantee it is deleted if the application crashes or the system powers off and can't clean it up properly? Using C or C++, on Windows and Linux?
|
Don't write the file decrypted to disk at all.
If the system is powerd off the file is still on disk, the disk and therefore the file can be accessed.
Exception would be the use of an encrypted file system, but this is out of control of your program.
|
Unfortunately, there's no 100% foolproof way to insure that the file will be deleted in case of a full system crash. Think about what happens if the user just pulls the plug while the file is on disk. No amount of exception handling will protect you from that (the worst) case.
The best thing you can do is not write the decrypted file to disk in the first place. If the file exists in both its encrypted and decrypted forms, that's a point of weakness in your security.
The next best thing you can do is use Brian's suggestion of structured exception handling to make sure the temporary file gets cleaned up. This won't protect you from all possibilities, but it will go a long way.
Finally, I suggest that you check for temporary decrypted files on start-up of your application. This will allow you to clean up after your application in case of a complete system crash. It's not ideal to have those files around for *any* amount of time, but at least this will let you get rid of them as quickly as possible.
|
How to guarantee files that are decrypted during run time are cleaned up?
|
[
"",
"c++",
"c",
"encryption",
"filesystems",
""
] |
F# declared namespace is not available in the c# project or visible through the object browser.
I have built a normal F# library project, but even after i build the project and reference it to my C# project, I am unable to access the desired namespace.
I am also unable to see it in the object browser, i get an error telling me that it has not been built. I am running on the september release can someone point out my error ?
F# Version 1.9.6.0
(6) Edit : Referencing the dll directly has fixed my problem, referencing the project allows me to compile but the intellisence does not work. When the dll is directly referenced the intellisence works perfectly.
---
This is the code found in the .fs file
```
#light
namespace Soilsiu.Core
module public Process =
open System.Xml.Linq
let private xname (tag:string) = XName.Get(tag)
let private tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href")
attribute.Value
let Bookmarks(xmlFile:string) =
let xml = XDocument.Load(xmlFile)
xml.Elements <| xname "A" |> Seq.map(tagUrl)
let PrintBookmarks (xmlFile:string) =
let list = Bookmarks(xmlFile)
list |> Seq.iter(fun u -> printfn "%s" u)
```
---
(5) Edit : Could ReSharper 4.0 be the problem?
(4) Edit : When i say the Object browser is unable to read the resulting assembly, i mean that when I try to open the assembly in the object browser i get an error telling me the project has not yet been built. yet again i can read the assembly using reflector.
(3) Edit : Reflector can Disassemble the dll but the Object Browser is unable to read it.
(2) Edit : I have Upgraded my F# version to 1.9.6.2 and still the same consequence
(1) Edit : I was able to Disassemble the dll to C# I get : (Everything seems to be fine here)
```
namespace Soilsiu.Core
{
[CompilationMapping(7)]
public static class Crawler
[CompilationMapping(7)]
public static class Process
}
```
---
```
[CompilationMapping(7)]
public static class Process
{
// Methods
static Process();
public static IEnumerable<string> Bookmarks(string xmlFile);
public static void PrintBookmarks(string xmlFile);
internal static string tagUrl(XElement tag);
internal static XName xname(string tag);
// Nested Types
[Serializable]
internal class clo@13 : FastFunc<XElement, string>
{
// Methods
public clo@13();
public override string Invoke(XElement tag@9);
}
[Serializable]
internal class clo@17 : FastFunc<string, Unit>
{
// Methods
public clo@17();
public override Unit Invoke(string u);
}
}
```
|
What if you reference the produced DLL directly (i.e., not via a project reference, but via a file reference)?
|
Maybe IntelliSense is just messed up? What compiler error do you get when you try to use it in C#? When you say "the object browser is unable to read it" what does that mean?
For what it's worth, I added this to a F# library project, referenced it (project) from a C# console app, and was able to use it. IntelliSense did not work at first though. (Had to rebuild.)
If you can make a solid repro, I'd suggest emailing it to F# bugs alias (fsbugs).
|
F# declared namespace is not available in the c# project or visible through the object browser
|
[
"",
"c#",
"f#",
"resharper",
"interop",
""
] |
How can I print a message to the error console, preferably including a variable?
For example, something like:
```
print('x=%d', x);
```
|
Install [Firebug](http://en.wikipedia.org/wiki/Firebug_(software)) and then you can use `console.log(...)` and `console.debug(...)`, etc. (see [the documentation](http://getfirebug.com/wiki/index.php/Console_Panel#Message_types) for more).
|
```
console.error(message); // Outputs an error message to the Web Console
console.log(message); // Outputs a message to the Web Console
console.warn(message); // Outputs a warning message to the Web Console
console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small "i" in front of the message.
```
You also can add CSS:
```
console.log('%c My message here', "background: blue; color: white; padding-left:10px;");
```
More info can be found here: <https://developer.mozilla.org/en-US/docs/Web/API/console>
|
JavaScript: How do I print a message to the error console?
|
[
"",
"javascript",
"debugging",
""
] |
There are times when I want to use *mootools* for certain things and Prototype & *`script.aculo.us`* for others but within the same site. I've even considered adding others, but was concerned about conflicts. Anyone have experience, or am I just trying to make things too complicated for myself?
|
If you really, really want to do this, then you will be able to without too many problems - the main libraries are designed to behave well inside their own namespaces, with a couple of notable exceptions - from [Using JQuery with Other Frameworks](http://docs.jquery.com/Using_jQuery_with_Other_Libraries):
> The jQuery library, and virtually all of its plugins are constrained within the jQuery namespace. As a general rule, "global" objects are stored inside the jQuery namespace as well, so you shouldn't get a clash between jQuery and any other library (like Prototype, MooTools, or YUI).
>
> That said, there is one caveat: By default, jQuery uses "$" as a shortcut for "jQuery", which you can over-ride.
So, yes, you can do it, but you'd likely be creating maintenance headaches further down the line for yourself - subtle differences between framework functions may be obvious to you today, but come back in 6 months and it can be a whole other story! So I would recommend keeping it as simple as you can, and having as few different frameworks (preferrably 1!) as you can in your codebase.
|
AFAIK, all the popular frameworks are designed to be combined with other frameworks. I don't think combining them is that much of a problem. I would however discourage combining them purely from a case of bandwidth needs. A slow site experience is less forgivable than a more complicated development experience.
|
What JavaScript frameworks conflict with each other?
|
[
"",
"javascript",
"frameworks",
"conflict",
""
] |
I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions.
Example: "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc.
The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions?
Note: boost:: is most welcome! :-)
**Update** Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)
|
```
#include <iostream>
#include <conio.h>
#include <string>
#include <map>
using namespace std;
struct Token
{
enum E
{
Replace,
Literal,
Eos
};
};
class ParseExp
{
private:
enum State
{
State_Begin,
State_Literal,
State_StartRep,
State_RepWord,
State_EndRep
};
string m_str;
int m_char;
unsigned int m_length;
string m_lexme;
Token::E m_token;
State m_state;
public:
void Parse(const string& str)
{
m_char = 0;
m_str = str;
m_length = str.size();
}
Token::E NextToken()
{
if (m_char >= m_length)
m_token = Token::Eos;
m_lexme = "";
m_state = State_Begin;
bool stop = false;
while (m_char <= m_length && !stop)
{
char ch = m_str[m_char++];
switch (m_state)
{
case State_Begin:
if (ch == '$')
{
m_state = State_StartRep;
m_token = Token::Replace;
continue;
}
else
{
m_state = State_Literal;
m_token = Token::Literal;
}
break;
case State_StartRep:
if (ch == '{')
{
m_state = State_RepWord;
continue;
}
else
continue;
break;
case State_RepWord:
if (ch == '}')
{
stop = true;
continue;
}
break;
case State_Literal:
if (ch == '$')
{
stop = true;
m_char--;
continue;
}
}
m_lexme += ch;
}
return m_token;
}
const string& Lexme() const
{
return m_lexme;
}
Token::E Token() const
{
return m_token;
}
};
string DoReplace(const string& str, const map<string, string>& dict)
{
ParseExp exp;
exp.Parse(str);
string ret = "";
while (exp.NextToken() != Token::Eos)
{
if (exp.Token() == Token::Literal)
ret += exp.Lexme();
else
{
map<string, string>::const_iterator iter = dict.find(exp.Lexme());
if (iter != dict.end())
ret += (*iter).second;
else
ret += "undefined(" + exp.Lexme() + ")";
}
}
return ret;
}
int main()
{
map<string, string> words;
words["hello"] = "hey";
words["test"] = "bla";
cout << DoReplace("${hello} world ${test} ${undef}", words);
_getch();
}
```
I will be happy to explain anything about this code :)
|
How many evaluation expressions do intend to have? If it's small enough, you might just want to use brute force.
For instance, if you have a `std::map<string, string>` that goes from your `key` to its `value`, for instance `user` to `Matt Cruikshank`, you might just want to iterate over your entire map and do a simple replace on your string of every `"${" + key + "}"` to its `value`.
|
Evaluating expressions inside C++ strings: "Hi ${user} from ${host}"
|
[
"",
"c++",
"parsing",
"boost",
"string",
"expression",
""
] |
There is small system, where a database table as queue on MSSQL 2005. Several applications are writing to this table, and one application is reading and processing in a FIFO manner.
I have to make it a little bit more advanced to be able to create a distributed system, where several processing application can run. The result should be that 2-10 processing application should be able to run and they should not interfere each other during work.
My idea is to extend the queue table with a row showing that a process is already working on it. The processing application will first update the table with it's idetifyer, and then asks for the updated records.
So something like this:
```
start transaction
update top(10) queue set processing = 'myid' where processing is null
select * from processing where processing = 'myid'
end transaction
```
After processing, it sets the processing column of the table to something else, like 'done', or whatever.
I have three questions about this approach.
First: can this work in this form?
Second: if it is working, is it effective? Do you have any other ideas to create such a distribution?
Third: In MSSQL the locking is row based, but after an amount of rows are locked, the lock is extended to the whole table. So the second application cannot access it, until the first application does not release the transaction. How big can be the selection (top x) in order to not lock the whole table, only create row locks?
|
This will work, but you'll probably find you'll run into blocking or deadlocks where multiple processes try and read/update the same data. I wrote a procedure to do exactly this for one of our systems which uses some interesting locking semantics to ensure this type of thing runs with no blocking or deadlocks, [described here](http://gregbeech.com/blog/retrieving-a-row-exactly-once-with-multiple-polling-processes-in-sql-server).
|
This approach looks reasonable to me, and is similar to one I have used in the past - successfully.
Also, the row/ table will only be locked while the update and select operations take place, so I doubt the row vs table question is really a major consideration.
Unless the processing overhead of your app is so low as to be negligible, I'd keep the "top" value low - perhaps just 1. Of course that entirely depends on the details of your app.
Having said all that, I'm not a DBA, and so will also be interested in any more expert answers
|
Parallel processing of database queue
|
[
"",
"c#",
"sql-server-2005",
"distributed-system",
""
] |
For example:
Base class header file has:
```
enum FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_USERSTART
};
```
Then the derived class has:
```
enum FOO
{
FOO_USERA=FOO_USERSTART
FOO_USERB,
FOO_USERC
};
```
Just to be clear on my usage it is for having an event handler where the base class has events and then derived classes can add events. The derived classes event handler would check for it's events and if the event was not for it, then it would pass the event down to the base class.
```
class Base
{
public:
virtual void HandleFoo(FOO event);
};
class Derived: public Base
{
public:
void HandleFoo(FOO event);
};
void Base::HandleFoo(FOO event)
{
switch(event)
{
case FOO_A:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
}
}
void Derived::HandleFoo(FOO event)
{
switch(event)
{
case FOO_USERA:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
default:
/* not my event, must be for someone else */
Base::HandleFoo(event);
break;
}
}
```
|
No. The compiler needs to be able to decide whether the enum fits in a char, short, int or long once it sees the }.
So if the base class header has
```
enum Foo {
A,
B,
MAX = 1<<15
};
```
a compiler may decide the enum fits in 16 bits. It can then use that, e.g. when laying out the base class. If you were later able to add 1<<31 to the enum, the base class enum member would not be able to hold one of the enum values.
|
Yes, as long as the enum's are both members of a class. If they weren't then they would be of the same type and the compiler would be very unhappy.
|
In C++: Is it possible to have a named enum be continued in a different file?
|
[
"",
"c++",
"enums",
"continue",
""
] |
I don't care what the differences are. I just want to know whether the contents are different.
|
The low level way:
```
from __future__ import with_statement
with open(filename1) as f1:
with open(filename2) as f2:
if f1.read() == f2.read():
...
```
The high level way:
```
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
...
```
|
If you're going for even basic efficiency, you probably want to check the file size first:
```
if os.path.getsize(filename1) == os.path.getsize(filename2):
if open('filename1','r').read() == open('filename2','r').read():
# Files are the same.
```
This saves you reading every line of two files that aren't even the same size, and thus can't be the same.
(Even further than that, you could call out to a fast MD5sum of each file and compare those, but that's not "in Python", so I'll stop here.)
|
In Python, is there a concise way of comparing whether the contents of two text files are the same?
|
[
"",
"python",
"file",
"compare",
""
] |
I wanted to make Map of Collections in Java, so I can make something like
```
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
Collection c = new Collection();
c.add(value);
put(key, value);
}
}
```
I've tried to make it with something like
```
public class CollectionMap<K, C extends Collection<V>> extends HashMap<K, C>
```
but compiler complains about the `<V>` part, and there would still be an issue of making proper new collection.
At the moment, I've made two classes: SetMap that look like this
```
1: public class SetMap<K, V> extends HashMap<K, Set<V>> {
2:
3: public void add(K key, V value) {
4: if (containsKey(key)) {
5: get(key).add(value);
6: } else {
7: Set<V> list = new HashSet<V>();
8: list.add(value);
9: put(key, list);
10: }
11: }
12:
13: }
```
and ListMap looks pretty much the same except the line 7 where I make new ArrayList. This sort of duplication is small enough to be tolerable, but question remains is this sort of "nested generics" possible in Java?
EDIT:
As [erickson said](https://stackoverflow.com/questions/254351/map-of-collections#254372), solution is in `<A, B extends Something<A>>` rather than just `<B extends Something<A>>`
so code can look something like
```
public abstract class CollelctionMap<K, V, C extends Collection<V>> extends HashMap<K, C> {
protected abstract C newCollection();
public void add(K key, V value) {
if (containsKey(key)) {
get(key).add(value);
} else {
C c = newCollection();
c.add(value);
put(key, c);
}
}
}
```
and ListMap and SetMap only provide proper collection
|
If `map` is a `Map<K, Collection<V>>`, use the idiom [`computeIfAbsent(...).add(...)`,](http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-) like this:
```
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
```
Or, for a `Set`:
```
map.computeIfAbsent(key, k -> new HashSet<>()).add(value);
```
|
If it's an option, you may want to just use the Google Collections API - <http://code.google.com/p/google-collections/>.
Even if you can't use it, maybe having a look at how they implemented their MultiMaps would help you with your implementation.
|
Map of collections
|
[
"",
"java",
"generics",
"collections",
""
] |
Say I create an object thus:
```
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
```
What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:
```
keys == ["ircEvent", "method", "regex"]
```
|
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method:
```
var keys = Object.keys(myObject);
```
The above has a full polyfill but a simplified version is:
```
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
```
Alternatively replace `var getKeys` with `Object.prototype.keys` to allow you to call `.keys()` on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
|
As [slashnick](https://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object#208020) pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate **only** over the object's own attributes, you can make use of the [Object#hasOwnProperty()](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty) method. Thus having the following.
```
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
/* useful code here */
}
}
```
|
How to list the properties of a JavaScript object?
|
[
"",
"javascript",
""
] |
I am refactoring some MFC code that is littered with `ASSERT` statements, and in preparation for a future Linux port I want to replace them with the standard `assert`. Are there any significant differences between the two implementations that people know of that could bite me on the backside?
Similarly, I have also come across some code that uses `ATLASSERT` which I would also like to replace.
|
No. The MFC version just includes an easy to debug break point.
|
Replace them with [your own assertion macro](https://stackoverflow.com/questions/17732/when-should-assertions-stay-in-production-code). That's how you get the most benefit out of it (logging, stack trace, etc.)
|
ASSERT vs. ATLASSERT vs. assert
|
[
"",
"c++",
"mfc",
"assert",
""
] |
Am I able to embed the .net runtime so that .net is not required on the host operating system? I was looking at doing this with Mono by looking here: <http://mono-project.com/Embedding_Mono> but seems to allude to using external modules to accomplish this. My goal is to have one single executable with no installed .net runtime. I do not know how this would be configured in my application to compile the native code, link the mono runtime- as well as compile the C# code and link that as well?
|
You can now [statically compile Mono assemblies](http://tirania.org/blog/archive/2008/Nov-05.html) as was just demonstrated at PDC. The purpose of doing this was to allow .Net applications to run on the iPhone, but this should work anywhere.
There are some limitations to this; obviously, it can't depend on runtime-generated code, so Reflection.Emit is out.
|
Third-party solution i've used with much success: [Xenocode](http://www.xenocode.com/)
|
Embedding .Net Runtime
|
[
"",
"c#",
"windows",
"mono",
"clr",
""
] |
I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError).
What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping references to objects which should be able to be garbage collected.
|
VisualVM is included in the most recent releases of Java. You can use this to create a heap dump, and look at the objects in it.
Alternatively, you can also create a heapdump commandine using jmap (in your jdk/bin dir):
```
jmap -dump:format=b,file=heap.bin <pid>
```
You can even use this to get a quick histogram of all objects
```
jmap -histo <pid>
```
I can recommend Eclipse Memory Analyzer (<http://eclipse.org/mat>) for advanced analysis of heap dumps. It lets you find out exactly why a certain object or set of objects is alive. Here's a blog entry showing you what Memory Analyzer can do: <http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/>
|
If you need something free, try [VisualVM](https://visualvm.github.io/)
From the project's description:
> VisualVM is a visual tool integrating commandline JDK tools and lightweight profiling capabilities. Designed for both development and production time use.
|
How can I see what is in my heap in Java?
|
[
"",
"java",
"out-of-memory",
""
] |
I know this question has been asked before, but I ran into a problem.
Oddly enough, when I execute this function, it includes the html of the page that the link you select to execute the function.
```
function exportCSV($table) {
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
}
```
Does anyone know why it would include the HTML in the csv file?
[alt text http://i35.tinypic.com/16i9oxi.jpg](http://i35.tinypic.com/16i9oxi.jpg)
|
My guess is that you've got some sort of template that generates the same HTML header and footer regardless of the page that is requested. Sometime before the exportCSV function is called, the header is generated.
You don't show the bottom of the output, but I'll bet the footer is there too, since I suspect the flow control will continue on to that code after the function exits.
|
php isn't really my thing, but it seems like you need to clear the response stream before writing out your content. Perhaps something else is writing html out to the stream, before reaching this function? Like a template or master page or something of that nature?
The HTML content looks like a typical header/nav bar. if there something else that's automatically including that content that you need to disable for this route?
|
Why am I getting HTML in my MySQL export to CSV?
|
[
"",
"php",
"mysql",
"csv",
""
] |
I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run:
```
groovy RunScript.groovy
```
instead of:
```
groovy -cp ojdbc5.jar RunScript.groovy
```
|
Summarized from *Groovy Recipes*, by Scott Davis, **Automatically Including JARs in the ./groovy/lib Directory**:
1. Create `.groovy/lib` in your login directory
2. Uncomment the following line in ${GROOVY\_HOME}/conf/groovy-starter.conf
`load !{user.home}/.groovy/lib/*.jar`
3. Copy the jars you want included to `.groovy/lib`
It appears that for Groovy 1.5 or later you get this by default (no need to edit the conf), just drop the jars in the /lib dir.
|
There are a few ways to do it. You can add the jar to your system's CLASSPATH variable. You can create a directory called .groovy/lib in your home directory and put the jar in there. It will be automatically added to your classpath at runtime. Or, you can do it in code:
```
this.class.classLoader.rootLoader.addURL(new URL("file:///path to file"))
```
|
How do I auto load a database jar in Groovy without using the -cp switch?
|
[
"",
"java",
"scripting",
"groovy",
"classpath",
""
] |
Is it possible to enable a second monitor programatically and extend the Windows Desktop onto it in C#? It needs to do the equivalent of turning on the checkbox in the image below.

|
[MSDN Device Context Functions](http://msdn.microsoft.com/en-us/library/ms533259.aspx)
What you basically need to do:
> Use the EnumDisplayDevices() API call
> to enumerate the display devices on
> the system and look for those that
> don't have the
> `DISPLAY_DEVICE_ATTACHED_TO_DESKTOP`
> flag set (this will include any
> mirroring devices so not all will be
> physical displays.) Once you've found
> the display device you'll need to get
> a valid display mode to change it to,
> you can find this by calling the
> EnumDisplaySettingsEx() API call -
> Generally you'd display all the
> available modes and allow the user to
> choose however in your case it sounds
> like this may be possible to hard-code
> and save you an additional step. For
> the sake of future-proofing your
> application though I'd suggest having
> this easily changeable without having
> to dig through the source every time,
> a registry key would be the obvious
> choice. Once you've got that sorted
> out populate a DevMode display
> structure with the information about
> the display positioning (set the
> PelsWidth/Height, Position,
> DisplayFrequency and BitsPerPel
> properties) then set these flags in
> the fields member. Finally call
> ChangeDisplaySettingsEx() with this
> settings structure and be sure to send
> the reset and update registry flags.
> That should be all you need, hope this
> helps,
[DISPLAY\_DEVICE](http://www.pinvoke.net/default.aspx/Structures/DISPLAY_DEVICE.html) structure import using PInvoke
[EnumDisplayDevices](http://www.pinvoke.net/default.aspx/user32/EnumDisplayDevices.html) function import
[EnumDisplaySettingsEx](http://www.pinvoke.net/default.aspx/user32/EnumDisplaySettingsEx.html) function import
etc. the rest of them functions can be found with a simple search by name.
|
If you have windows 7, then just start a process:
```
private static Process DisplayChanger = new Process
{
StartInfo =
{
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "DisplaySwitch.exe",
Arguments = "/extend"
}
};
```
then DisplayChanger.Start();
|
How do I enable a second monitor in C#?
|
[
"",
"c#",
"winforms",
"desktop",
"multiple-monitors",
""
] |
I'm trying to write a small app that monitors how much power is left in a notebook battery and I'd like to know which Win32 function I could use to accomplish that.
|
For Vista and up you can use [RegisterPowerSettingNotification](http://msdn.microsoft.com/en-us/library/aa373196(VS.85).aspx)
For earlier functions see the [Power Management Functions](http://msdn.microsoft.com/en-us/library/aa373163(VS.85).aspx) in this section of the MSDN page "Power Management Functions: Windows Server 2003 and Earlier"
You can see example code of the Vista method on [codeproject](http://www.codeproject.com/KB/vista/VGPowerMonitor.aspx).
|
I recommend the use of the Win32 [GetSystemPowerStatus](https://msdn.microsoft.com/en-us/library/windows/desktop/aa372693%28v=vs.85%29.aspx) function. A code snippet :
```
int getBatteryLevel()
{
SYSTEM_POWER_STATUS status;
GetSystemPowerStatus(&status);
return status.BatteryLifePercent;
}
```
|
Monitor battery charge with Win32 API
|
[
"",
"c++",
"c",
"winapi",
"monitor",
"power-management",
""
] |
Is there an elegant way to specialize a template based on one of its template parameters?
Ie.
```
template<int N> struct Junk {
static int foo() {
// stuff
return Junk<N - 1>::foo();
}
};
// compile error: template argument '(size * 5)' involves template parameter(s)
template<int N> struct Junk<N*5> {
static int foo() {
// stuff
return N;
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
```
Ie. I am trying to specialize a template based on the parameter being divisible by 5. The only way I can seem to do it is like below:
```
template<int N> struct JunkDivisibleBy5 {
static int foo() {
// stuff
return N;
}
};
template<int N> struct Junk {
static int foo() {
// stuff
if ((N - 1) % 5 == 0 && N != 1)
return JunkDivisibleBy5<N - 1>::foo();
else
return Junk<N - 1>::foo();
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
```
But this is significantly less elegant, and also necessitates instantiation of all templates even if the template argument shouldn't require it.
|
How's this:
```
#include <iostream>
using namespace std;
template < typename T, T N, T D >
struct fraction {
typedef T value_type;
static const value_type num = N;
static const value_type denom = D;
static const bool is_div = (num % denom == 0);
};
template< typename T, T N, T D, bool P >
struct do_if {
static void op() { cout << N << " NOT divisible by " << D << endl; }
};
template< typename T, T N, T D >
struct do_if< T, N, D, true > {
static void op() { cout << N << " divisible by " << D << endl; }
};
template < int N >
void foo() {
typedef fraction< int, N, 5 > f;
do_if< typename f::value_type, f::num, f::denom, f::is_div >::op();
}
int main() {
foo< -5 >();
foo< -1 >();
foo< 0 >();
foo< 1 >();
foo< 5 >();
foo< 10000005 >();
return 0;
}
```
|
Using D programming language templates, one could write it as:
```
struct Junk(int N)
{
static int foo()
{
static if (N == 0)
return 0;
else static if ((N % 5) == 0)
return N;
else
return Junk!(N - 1).foo();
}
}
```
static if's are executed at compile time.
|
Elegant template specialization
|
[
"",
"c++",
"templates",
""
] |
I have a file with data listed as follows:
```
0, 2, 10
10, 8, 10
10, 10, 10
10, 16, 10
15, 10, 16
17, 10, 16
```
I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers.
For some reason I can't find an easy way to do this in c++. The only success I've had is by inputting each line into an array, and then regexing out all the spaces and then splitting it up. This entire process took me a good 20-30 lines of code and its a pain to modify for say another separator(eg. space), etc.
This is the python equivalent of what I would like to have in C++:
```
f = open('input_hard.dat')
lines = f.readlines()
f.close()
#declarations
inint, inbase, outbase = [], [], []
#input parsing
for line in lines:
bits = string.split(line, ',')
inint.append(int(bits[0].strip()))
inbase.append(int(bits[1].strip()))
outbase.append(int(bits[2].strip()))
```
The ease of use of doing this in python is one of the reasons why I moved to it in the first place. However, I require to do this in C++ now and I would hate to have to use my ugly 20-30 line code.
Any help would be appreciated, thanks!
|
There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it's as short and readable as the python code:
```
FILE *fp = fopen("file.dat", "r");
int x, y, z;
std::vector<int> vx, vy, vz;
while (fscanf(fp, "%d, %d, %d", &x, &y, &z) == 3) {
vx.push_back(x);
vy.push_back(y);
vz.push_back(z);
}
fclose(fp);
```
|
There's no real need to use boost in this example as streams will do the trick nicely:
```
int main(int argc, char* argv[])
{
ifstream file(argv[1]);
const unsigned maxIgnore = 10;
const int delim = ',';
int x,y,z;
vector<int> vecx, vecy, vecz;
while (file)
{
file >> x;
file.ignore(maxIgnore, delim);
file >> y;
file.ignore(maxIgnore, delim);
file >> z;
vecx.push_back(x);
vecy.push_back(y);
vecz.push_back(z);
}
}
```
Though if I were going to use boost I'd prefer the simplicity of [tokenizer](http://www.boost.org/doc/libs/1_37_0/libs/tokenizer/tokenizer.htm) to regex... :)
|
c++ file io & splitting by separator
|
[
"",
"c++",
"file-io",
"split",
""
] |
For example, if I have a *unicode* string, I can encode it as an *ASCII* string like so:
```
>>> u'\u003cfoo/\u003e'.encode('ascii')
'<foo/>'
```
However, I have e.g. this *ASCII* string:
```
'\u003foo\u003e'
```
... that I want to turn into the same *ASCII* string as in my first example above:
```
'<foo/>'
```
|
It took me a while to figure this one out, but [this page](http://www.egenix.com/www2002/python/unicode-proposal.txt) had the best answer:
```
>>> s = '\u003cfoo/\u003e'
>>> s.decode( 'unicode-escape' )
u'<foo/>'
>>> s.decode( 'unicode-escape' ).encode( 'ascii' )
'<foo/>'
```
There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the "Unicode Constructors" section of the linked page for more details (since I'm not that Unicode-saavy).
EDIT: See also [Python Standard Encodings](http://www.python.org/doc/2.5.2/lib/standard-encodings.html).
|
On Python 2.5 the correct encoding is "unicode\_escape", not "unicode-escape" (note the underscore).
I'm not sure if the newer version of Python changed the unicode name, but here only worked with the underscore.
Anyway, this is it.
|
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
|
[
"",
"python",
"unicode",
"ascii",
""
] |
I have checked with the [wikipedia article](http://en.wikipedia.org/wiki/Facade_pattern), and it seems like it is missing the c++ version of a code example. I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?
|
**Facade pattern: provides a unified - simplified interface to a complex subsystem or set of interfaces. It provides a higher level interface simultaneously decoupling the client from the complex subsystem.**
An example to help you understand .. a cab driver. You tell the cab driver 'Take me to PointX' (unified simplified high-level interface) who then begins on a sequence of actions (turns the key, changes gears, presses the accelerator, etc...) to perform the task. He abstracts away the complexity of underlying subsystems (gearbox, engine, etc.) so that you don't have to worry about them.
The driver also decouples you from the actual vehicle used... you do not directly interface with the car. You could potentially give him a Merc but your interface to the Driver would still be TakeMeTo( X ).. you're not tied down to any specific model/make of the car.
In a real world example, you'll find facades where you interface with third party components or libraries. You don't want your code to depend on a specific vendor, so you introduce a facade interface to decouple. Also you'll simplify this interface, e.g. your facade interface would have a method called SendData( string ) but internally the implementation may call n methods on m sub-packages in a specific order to get the task done. This is what the diagram on the wikipedia page shows.
e.g. Translating [an example](http://www.theperlreview.com/Articles/v0i4/facade.pdf) to C++ and keeping it tiny
```
sResource = LWCPPSimple::get("http://www.perl.org")
```
Here the fictitious Library For WWW in C++ is a facade that unifies protocol, network and parsing aspects of the problem so that I can concentrate on my primary focus of fetching the resource. The get method hides/encapsulates/keeps-in-one-place the complexity (and in some cases ugliness) of HTTP, FTP and other varied protocols, request-response, connection management, etc. Also if tomorrow the creators of LWCPPSimple find a way to make get() to be twice as fast, I get the performance benefits for free. My client code doesn't have to change.
|
```
class Engine
{
public:
void Start() { }
};
class Headlights
{
public:
void TurnOn() { }
};
// That's your facade.
class Car
{
private:
Engine engine;
Headlights headlights;
public:
void TurnIgnitionKeyOn()
{
headlights.TurnOn();
engine.Start();
}
};
int Main(int argc, char *argv[])
{
// Consuming facade.
Car car;
car.TurnIgnitionKeyOn();
return 0;
}
```
|
Explain Facade pattern with c++ example?
|
[
"",
"c++",
"design-patterns",
"facade",
""
] |
I've developed an application (C#) that currently sits on a a number of workstations. Each workstation accesses the same database (MS-SQL). I've been asked to port this to Citrix. Can anyone offer insight into documentation or suggestion of where someone would start with this? Is the application installed on the Citrix server and then simply made available to users or do I need to do further development to make it ready for this type of deployment?
Can anyone offer insight into Citrix application development?
|
For fairly straight forward app things just run.
Does you app need use localization configuration? i.e. time / date or currency formatting? There are Citrix settings that can do many things in this area. The users computer settings can be "projected" into Citrix or they could be overridden in Citrix.
Also do you use the machine name for anything? That will be the server name and not the users local machine name.
You can get a bit of a simulation in a Windows Server environment by getting a couple of remote desktop sessions running your app.
|
I wrote a C# application for a client once, and they ran it off a Citrix server without ever informing me of this, so if you're lucky you won't need to worry about Citrix at all. The only problem I ever ran into was due to my use of ActiveReports, which released a hotfix that broke on 64-bit processors (like the one my clients used to run Citrix). If you do run into any problems, you'll have an easier time debugging them if you actually have access to the Citrix server.
|
What are the basics one needs to know when porting an application to Citrix?
|
[
"",
"c#",
"citrix",
""
] |
How does one go about converting an image to black and white in PHP?
Not just turning it into greyscale but every pixel made black or white?
|
Simply round the grayscale color to either black or white.
```
float gray = (r + g + b) / 3
if(gray > 0x7F) return 0xFF;
return 0x00;
```
|
Using the php [gd](https://www.php.net/manual/en/function.imagefilter.php) library:
```
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, -100);
```
Check the user comments in the link above for more examples.
|
How do you convert an image to black and white in PHP
|
[
"",
"php",
"image",
"imagefilter",
""
] |
I'm writing some Javascript to resize the large image to fit into the user's browser window. (I don't control the size of the source images unfortunately.)
So something like this would be in the HTML:
```
<img id="photo"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
```
**Is there a way for me to determine if the `src` image in an `img` tag has been downloaded?**
I need this because I'm running into a problem if `$(document).ready()` is executed before the browser has loaded the image. `$("#photo").width()` and `$("#photo").height()` will return the size of the placeholder (the alt text). In my case this is something like 134 x 20.
Right now I'm just checking if the photo's height is less than 150, and assuming that if so it is just alt text. But this is quite a hack, and it would break if a photo is less than 150 pixels tall (not likely in my particular case), or if the alt text is more than 150 pixels tall (could possibly happen on a small browser window).
---
**Edit:** For anyone wanting to see the code:
```
$(function()
{
var REAL_WIDTH = $("#photo").width();
var REAL_HEIGHT = $("#photo").height();
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(REAL_HEIGHT < 150)
{
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
if(REAL_HEIGHT < 150)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
```
---
**Update**: Thanks for the suggestions. There is a risk of the event not being fired if I set a callback for the `$("#photo").load` event, so I have defined an onLoad event directly on the image tag. For the record, here is the code I ended up going with:
```
<img id="photo"
onload="photoLoaded();"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
```
Then in Javascript:
```
//This must be outside $() because it may get called first
var isPhotoLoaded = false;
function photoLoaded()
{
isPhotoLoaded = true;
}
$(function()
{
//Hides scrollbars, so we can resize properly. Set with JS instead of
// CSS so that page doesn't break with JS disabled.
$("body").css("overflow", "hidden");
var REAL_WIDTH = -1;
var REAL_HEIGHT = -1;
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(!isPhotoLoaded)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
else if(REAL_WIDTH < 0)
{
//first time in this function since photo loaded
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
```
|
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.
```
<img id="photo"
onload='loaded(this.id)'
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
```
|
Using the [jquery data store](http://api.jquery.com/data/) you can define a 'loaded' state.
```
<img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" />
```
Then elsewhere you can do:
```
if ($('#myimage').data('loaded')) {
// loaded, so do stuff
}
```
|
How can I determine if an image has loaded, using Javascript/jQuery?
|
[
"",
"javascript",
"jquery",
"image",
""
] |
I'm reading *The C++ Programming Language* and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127. If not, why are their only 255 possible values in the second implementation possibility, not 256.
|
You're stuck in [two's complement](http://en.wikipedia.org/wiki/Two%27s_complement) thinking - The C++ standard does not define the representation used for negative numbers!
If your computer (god forbid) uses [ones's complement](http://en.wikipedia.org/wiki/Ones_complement#Ones.27_complement) to represent negative numbers, you have a range of -127 to + 127 in an 8-bit byte. On the upside, you have two different possible representations for zero...
However, in the real world, [you're unlikely to meet a one's complement computer](https://stackoverflow.com/questions/161797/is-ones-complement-a-real-world-issue-or-just-a-historical-one).
|
It's wrong to think that an unsigned char ranges from 0 to 255. that's only its minimal range. a char must have at least 8 bits, and signed char, unsigned char and char itself can have indeed more that just 8 bits. so then that means that unsigned char could go beyond 255. though admittedly, i haven't got an implementation where it had more than 8 bits, it theoretically is possible. that's specified in the c89 standard (on which c++03 bases), documenting file limits.h (CHAR\_BIT, UCHAR\_MAX, CHAR\_MAX).
|
Does the range for integer values of a char depend on implementation?
|
[
"",
"c++",
"language-implementation",
""
] |
The Winform application is release with ClickOnce in our Intranet. We store personal preference for the GUI in the Isolated Storage. All works pretty fine :)
The problem is when we have a new version of the application, we publish... all preferences are lost! User need to setup their preference over and over each version.
Is there a way to freeze the isolation for the whole application instead of the version?
|
You need to use *application* scoped, rather than *domain* scoped, isolated storage. This can be done by using one of **IsolatedStorageFileStream's** overloaded constructors.
Example:
```
using System.IO;
using System.IO.IsolatedStorage;
...
IsolatedStorageFile appScope = IsolatedStorageFile.GetUserStoreForApplication();
using(IsolatedStorageFileStream fs = new IsolatedStorageFileStream("data.dat", FileMode.OpenOrCreate, appScope))
{
...
```
However, now you will run into the issue of this code only working when the application has been launched via ClickOnce because that's the only time application scoped isolated storage is available. If you don't launch via ClickOnce (such as through Visual Studio), **GetUserStoreForApplication()** will throw an exception.
The way around *this* problem is to make sure **AppDomain.CurrentDomain.ActivationContext** is not null before trying to use application scoped isolated storage.
|
I was working on a ClickOnce app a while ago and used Environment.GetFolderPath(ApplicationData) - e.g. roaming app data folder, to store all settings. Worked fine and survived numerous updates. Just create a subdireectory with the name of your app or CompanyName/AppName or whatever and store everything in there.
|
ClickOnce and IsolatedStorage
|
[
"",
"c#",
"winforms",
".net-2.0",
"clickonce",
"isolatedstorage",
""
] |
The Zend Framework coding standard mentions the following:
> For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing whitespace into the response.
* [Zend Framework coding standard: file formatting](http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html)
However I do remember hearing about an issue (with tooling or including maybe?) where files needed to have closing tag.
Does anyone know of any issues (other than the developer issue of wanting symmetry) where you would need to have closing tags or are they generally a bad idea?
|
Removing the closing tags when you can is probably a best practice really. The reason for that is because if you have any character (even whitespace) outside of the ?> in a php file it can stop thing such as headers to stop working if the character gets sent to the browser before the header gets set.
|
If you use closing PHP tags then you can easily find files that have been accidentally truncated (e.g. haven't been uploaded completely).
However such problem should be fixed by making filesystem and transfers reliable rather than adding PHP "canary" tags :)
Another possible reason is that PEAR coding standards require it. They require it, because they require it and you're not allowed to question PEAR coding standards.
|
What are the arguments IN FAVOR of PHP closing tags for PHP only files?
|
[
"",
"php",
""
] |
I have a client server application that sends XML over TCP/IP from client to server and then broadcast out to other clients. How do i know at what the minimun size of the XML that would warrant a performance improvement by compression the XML rather than sending over the regular stream.
Are there any good metrics on this or examples?
|
Xml usually compresses very well, as it tends to have a lot of repetition.
Another option would be to swap to a binary format; BinaryFormatter or NetDataContractSerializer are simple options, but both are notoriously incompatible (for example with java) compared with xml.
Another option would be a portable binary format such as google's "protocol buffers". I maintain a .NET/C# version of this called [protobuf-net](http://code.google.com/p/protobuf-net/). This is designed to be side-by-side compatible with regular .NET approaches (such as XmlSerializer / DataContractSerializer), but is much smaller than xml, and requires significantly less processing (CPU etc) for both serialization and deserialization.
[This page](http://code.google.com/p/protobuf-net/wiki/Performance) shows some numbers for XmlSerializer, DataContractSerializer and protobuf-net; I *thought* it included stats with/without compression, but they seem to have vanished...
[update] I should have said - there is a TCP/IP example in the QuickStart project.
|
A loose metric would be to compress anything larger than a single packet, but that's just nitpicking.
There is no reason to refrain from using a binary format internally in your application - no matter how much time compression will take, the network overhead will be several orders of magnitude slower than compressing (unless we're talking about very slow devices).
If these two suggestions don't put you at ease, you can always benchmark to find the spot to compress at.
|
Compression XML metrics .
|
[
"",
"c#",
"xml",
"winforms",
"vb6",
"compression",
""
] |
I'm painfully new to PHP, and was trying to set up phpBB on my local site. I have a stock debian install of apache2 and php5. The phpBB installer ran fine, connected to the database and created all its tables with no problem. But when I tried to open the login page, I got a 0-byte response.
A little digging showed that it was never making it past the call to mysql\_pconnect(). The php binary just quits without error or message. Nothing at all. I tried running the following code:
```
<?php
$id = @mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
```
and the "id=" string never prints. It just does nothing. I don't know where to look to see what error happened, or what is going on at all. All i've installed is "mysql" using pear... perhaps I'm missing something else?
This has got to be a path problem somewhere. The mysql extension is built nicely at
```
/usr/lib/php5/20060613+lfs/mysql.so
```
**Answer:**
jishi: informed me that the "@" operator suppresses output, including error messages (@echo off, anyone?)
tomhaigh: extensions must be explicitly enabled in php.ini file. After adding the line "extension=mysql.so" to php.ini, the following code runs fine:
```
% cat d.php
<?php
ini_set('display_errors', true);
error_reporting(E_ALL | E_NOTICE);
$id = mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
% php -c /etc/php5/apache2/php.ini d.php
id=Resource id #4
```
JOY!
|
try doing this:
```
<?php
ini_set('display_errors', true);
error_reporting(E_ALL | E_NOTICE);
$id = mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
```
and see what the response is
**edit**
From your comment it looks like the mysql module is not installed or enabled. You could have a look in your php.ini file and see if there is a line like
```
extension=mysql.so
```
If it is commented with a semi-colon, try removing it and restarting apache
|
Just noted that you're using a @ in front of mysql\_pconnect(). That suppresses all errors, which in this case is a pretty bad idea. Remove that and you would probably see the output.
Otherwise:
Check your php.ini, should be in /etc/php5/apache2/php.ini for debian.
Check for a line called display\_errors, set that to true if you want error-output in your browser (not recommended for a production-system, but is useful during debugging and development).
Specify log\_errors on for apache to log your errors to apaches error logfile, which by default in debian would be (unless other error-file is specified for the phpBB-site):
/var/log/apache2/error.log
|
PHP5: calling external functions, and logging errors
|
[
"",
"php",
"mysql",
"pear",
""
] |
I recently installed VS 6.0 after installing VS 2008 and overwrite JIT settings .. when i started VS 2008 option dialog .. it said another debugger has taken over VS 2008 debugger and I asked me to reset .. so I did ..
Now everything works fine except javascript debugging. I am unable to debug javascript .. I can set breakpoint .. but in debug mode when I hover the breakpoint it says "The breakpoint will not currently be hit. The document is not loaded" ..
How can I solve this issue? Can I reset JIT Settings?
|
I guess I have to reinstall Visual Studio 2008 and see if that solves this problem
|
It sounds like your script debugging is disabled. To enable it goto, tools internet options, advanced and make sure disable script debugging is unticked.
What I also found helps is if you put a
> "debugger;"
line in your javascript. Remeber that if you put a debugger statement on the first line in a function it will not attach the debugger, as far as I am aware that is a known bug with the implemention of the javascript debugger engine.
```
var myFunction = new function()
{
debugger;
alert('This will not properly attach the debugger');
}
```
A workaround to that is:
```
var myFunctionThatDoesAttachTheDebugger = new function()
{
var x = 0;
debugger;
alert('this should work and attach the debugger');
}
```
A very usefull way I have also found, is by opening the website you want to debug, and then simply type the following in the url bar:
```
javascript:debugger;
```
That will also launch the debugger and give you a opportunity to attach the debugger.
Hope it helps
Rihan Meij
|
Script Debugging Not Working (VS 2008)
|
[
"",
"javascript",
"visual-studio-2008",
"debugging",
"jit",
""
] |
I use the Boost Test framework to unit test my C++ code and wondered if it is possible to test if a function will assert? Yes, sounds a bit strange but bear with me! Many of my functions check the input parameters upon entry, asserting if they are invalid, and it would be useful to test for this. For example:
```
void MyFunction(int param)
{
assert(param > 0); // param cannot be less than 1
...
}
```
I would like to be able to do something like this:
```
BOOST_CHECK_ASSERT(MyFunction(0), true);
BOOST_CHECK_ASSERT(MyFunction(-1), true);
BOOST_CHECK_ASSERT(MyFunction(1), false);
...
```
You can check for exceptions being thrown using Boost Test so I wondered if there was some assert magic too...
|
I don't think so. You could always write your own assert which throws an exception and then use BOOST\_CHECK\_NOTHROW() for that exception.
|
Having the same problem, I digged through the documentation (and code) and
found a "solution".
The Boost UTF uses `boost::execution_monitor` (in
`<boost/test/execution_monitor.hpp>`). This is designed with the aim to catch
everything that could happen during test execution. When an assert is found
execution\_monitor intercepts it and throws `boost::execution_exception`. Thus,
by using `BOOST_REQUIRE_THROW` you may assert the failure of an assert.
so:
```
#include <boost/test/unit_test.hpp>
#include <boost/test/execution_monitor.hpp> // for execution_exception
BOOST_AUTO_TEST_CASE(case_1)
{
BOOST_REQUIRE_THROW(function_w_failing_assert(),
boost::execution_exception);
}
```
Should do the trick. (It works for me.)
However (or disclaimers):
* It works for me. That is, on Windows XP, MSVC 7.1, boost 1.41.0. It might
be unsuitable or broken on your setup.
* It might not be the intention of the author of Boost Test.
(although it seem to be the purpose of execution\_monitor).
* It will treat every form of fatal error the same way. I e it could be
that something other than your assert is failing. In this case you
could miss e g a memory corruption bug, and/or miss a failed failed assert.
* It might break on future boost versions.
* I expect it would fail if run in Release config, since the assert will be
disabled and the code that the assert was set to prevent will
run. Resulting in very undefined behavior.
* If, in Release config for msvc, some assert-like or other fatal error
would occur anyway it would not be caught. (see execution\_monitor docs).
* If you use assert or not is up to you. I like them.
See:
* <http://www.boost.org/doc/libs/1_41_0/libs/test/doc/html/execution-monitor/reference.html#boost.execution_exception>
* the execution-monitor user-guide.
Also, thanks to Gennadiy Rozental (Author of Boost Test), if you happen to
read this, Great Work!!
|
Testing for assert in the Boost Test framework
|
[
"",
"c++",
"unit-testing",
"boost",
"assert",
"boost-test",
""
] |
What are some good jQuery Resources along with some gotchas when using it with ASP.Net?
|
One thing to note is that if you use WebMethods for Ajax, the response values will be returned wrapped in an object named 'd' for security reasons. You will have to unwrap that value, which is usually not a problem, unless you are using a component (such as the jqGrid plugin) that relies upon jquery ajax. To get around that, I just changed the code in the grid that called ajax and inserted a bit of code to unwrap. I do plan on sending in some code to the jquery crew to see if it can be accepted for future versions.
The next thing, as was mentioned previously, is the ids. If you have the time and inclination, I actually subclassed all of the HTML controls to make participating in the NamingContainer optional, like this:
```
protected override void RenderAttributes(HtmlTextWriter writer) {
HtmlControlImpl.RenderAttributes(this, writer);
}
```
And then the helper object (to prevent writing the same code in each object) looks like this:
```
public static void RenderAttributes(IFormControl cntrl, HtmlTextWriter writer) {
if (cntrl.ID != null) {
cntrl.Attributes.Remove("id");
cntrl.Attributes.Remove("name");
writer.WriteAttribute("id", cntrl.RenderedId);
writer.WriteAttribute("name", cntrl.RenderedName);
}
cntrl.Attributes.Render(writer);
HtmlContainerControl containerCntrl = cntrl as HtmlContainerControl;
if (containerCntrl == null)
writer.Write(" /");
}
public static string GetRenderedId(IFormControl cntrl) {
return cntrl.UseNamingContainer ? cntrl.ClientID : cntrl.ID;
}
public static string GetRenderedName(IFormControl cntrl) {
return cntrl.UseNamingContainer ? cntrl.UniqueID : cntrl.ID;
}
```
|
ASP.Net's autogenerated id's make using jQuery's selector syntax somewhat difficult.
Two easy ways around this problem:
* Search for objects using css class instead of id
* You can weed out the uniqueid garbage with: `$('[id$=myid]')`
|
jQuery & ASP.Net Resources & Gotchas
|
[
"",
"javascript",
"jquery",
"asp.net",
".net",
"resources",
""
] |
I am trying to come up with the best data structure for use in a high throughput C++ server. The data structure will be used to store anything from a few to several million objects, and no sorting is required (though a unique sort key can be provided very cheaply).
The requirements are that it can support efficient insert, ideally O(1), moderately efficient removal, and efficient traversal. It doesn't need to support a find operation (other than might be needed for removal).
The twist is that it must be thread safe with respect to modifications while other threads are enumerating the data structure. This means that a simple red-black tree doesn't work, since one thread can't insert an element (and perform the necessary tree rotations) without messing up any cursors held by other threads.
It is **not** acceptable to use a read/write lock and defer the write operations until all readers have finished, since read operations may be long lived. It doesn't matter if inserts that happen while there is a reader are visible to that reader or not.
Memory footprint is also very important, and small is obviously better!
What suggestions are there?
**Response to comments:**
Thanks for the answers.
No, inserts cannot invalidate existing iterators. Iterators may or may not see the new insert, but they must see everything that they would have seen if the insert hadn't occurred.
Deletion is required, however due to higher level rules I can guarantee that a iterator will never be stopped on an item that is available for deletion.
Locking per node for a cursor would have too great an impact on performance. There may be a number of threads reading at once, and any kind of memory hot spot that multiple threads are using in a lock kills memory bandwidth (as we discovered the hard way!). Even a simple count of readers with multiple threads calling InterlockedIncrement fails to scale cleanly.
I agree a linked list is likely the best approach. Deletes are rare, so paying the memory penalty for the back pointers to support O(1) delete is costly and we may compute those separately on demand and since deletes tend to be batch operations.
Fortunately insertion into a linked list doesn't require any locking for readers, as long as the pointers are updated in the inserted node before the head pointer is changed.
The lock-copy-unlock idea is interesting. The amount of data involved is too large for this to work as the default for readers, but it could be used for writers when they collide with readers. A read/write lock would protect the whole structure, and the write would clone the data structure if it collides with a reader. Writes are much rarer than reads.
|
Personally, I'm quite fond of persistent immutable data structures in highly-concurrent situations. I don't know of any specifically for C++, but Rich Hickey has created some excellent (and blisteringly fast) immutable data structures in Java for [Clojure](http://clojure.org). Specifically: vector, hashtable and hashset. They aren't too hard to port, so you may want to consider one of those.
To elaborate a bit more, persistent immutable data structures really solve a lot of problems associated with concurrency. Because the data structure itself is immutable, there isn't a problem with multiple threads reading/iterating concurrently (so long as it is a const iterator). "Writing" can also be asynchronous because it's not really writing to the existing structure but rather creating a new version of that structure which includes the new element. This operation is made efficient (*O(1)* in all of Hickey's structures) by the fact that you aren't actually copying everything. Each new version shares most of its structure with the old version. This makes things more memory efficient, as well as dramatically improving performance over the simple copy-on-write technique.
With immutable data structures, the only time where you actually need to synchronize is in actually writing to a reference cell. Since memory access is atomic, even this can usually be lock-free. The only caveat here is you might lose data between threads (race conditions). The data structure will never be corrupted due to concurrency, but that doesn't mean that inconsistent results are impossible in situations where two threads create a new version of the structure based on a single old and attempt to write their results (one of them will "win" and the other's changes will be lost). To solve this problem, you either need to have a lock for "writing operations", or use some sort of [STM](http://en.wikipedia.org/wiki/Software_transactional_memory). I like the second approach for ease-of-use and throughput in low-collision systems (writes are ideally non-blocking and reads *never* block), but either one will work.
You've asked a tough question, one for which there isn't really a good answer. Concurrency-safe data structures are hard to write, particularly when they need to be mutable. Completely lock-free architectures are provably impossible in the presence of shared state, so you may want to give up on that requirement. The best you can do is minimize the locking required, hence the immutable data structures.
|
Linked lists are definitely the answer here. Insertion and deletion in O(1), iteration from one node to the next in O(1) and stability across operations. `std::list` guarantees all of these, including that all iterators are valid unless the element is removed from the list (this include pointers and references to elements). For locking, you could just wrap the list in a locking class, or you could write your own list class (you wouldn't be able to use `std::list` in this case that supports node-based locking - e.g. you can lock down certain areas of the list for use while other threads perform operations on different areas. Which you use is largely dependent on the type of concurrent access you expect - if multiple operations on different parts of the list will be really common, write your own, but remember you will be putting a mutex object in each node, which isn't space-efficient.
|
Concurrent data structure design
|
[
"",
"c++",
"data-structures",
"concurrency",
""
] |
I want to scale an image in C# with quality level as good as Photoshop does. Is there any C# image processing library available to do this thing?
|
Here's a nicely commented Image Manipulation helper class that you can look at and use. I wrote it as an example of how to perform certain image manipulation tasks in C#. You'll be interested in the **ResizeImage** function that takes a System.Drawing.Image, the width and the height as the arguments.
```
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
namespace DoctaJonez.Drawing.Imaging
{
/// <summary>
/// Provides various image untilities, such as high quality resizing and the ability to save a JPEG.
/// </summary>
public static class ImageUtilities
{
/// <summary>
/// A quick lookup for getting image encoders
/// </summary>
private static Dictionary<string, ImageCodecInfo> encoders = null;
/// <summary>
/// A lock to prevent concurrency issues loading the encoders.
/// </summary>
private static object encodersLock = new object();
/// <summary>
/// A quick lookup for getting image encoders
/// </summary>
public static Dictionary<string, ImageCodecInfo> Encoders
{
//get accessor that creates the dictionary on demand
get
{
//if the quick lookup isn't initialised, initialise it
if (encoders == null)
{
//protect against concurrency issues
lock (encodersLock)
{
//check again, we might not have been the first person to acquire the lock (see the double checked lock pattern)
if (encoders == null)
{
encoders = new Dictionary<string, ImageCodecInfo>();
//get all the codecs
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
{
//add each codec to the quick lookup
encoders.Add(codec.MimeType.ToLower(), codec);
}
}
}
}
//return the lookup
return encoders;
}
}
/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
{
//a holder for the result
Bitmap result = new Bitmap(width, height);
//set the resolutions the same to avoid cropping due to resolution differences
result.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//use a graphics object to draw the resized image into the bitmap
using (Graphics graphics = Graphics.FromImage(result))
{
//set the resize quality modes to high quality
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//draw the image into the target bitmap
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
//return the resulting bitmap
return result;
}
/// <summary>
/// Saves an image as a jpeg image, with the given quality
/// </summary>
/// <param name="path">Path to which the image would be saved.</param>
/// <param name="quality">An integer from 0 to 100, with 100 being the
/// highest quality</param>
/// <exception cref="ArgumentOutOfRangeException">
/// An invalid value was entered for image quality.
/// </exception>
public static void SaveJpeg(string path, Image image, int quality)
{
//ensure the quality is within the correct range
if ((quality < 0) || (quality > 100))
{
//create the error message
string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality);
//throw a helpful exception
throw new ArgumentOutOfRangeException(error);
}
//create an encoder parameter for the image quality
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
//get the jpeg codec
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
//create a collection of all parameters that we will pass to the encoder
EncoderParameters encoderParams = new EncoderParameters(1);
//set the quality parameter for the codec
encoderParams.Param[0] = qualityParam;
//save the image using the codec and the parameters
image.Save(path, jpegCodec, encoderParams);
}
/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
public static ImageCodecInfo GetEncoderInfo(string mimeType)
{
//do a case insensitive search for the mime type
string lookupKey = mimeType.ToLower();
//the codec to return, default to null
ImageCodecInfo foundCodec = null;
//if we have the encoder, get it to return
if (Encoders.ContainsKey(lookupKey))
{
//pull the codec from the lookup
foundCodec = Encoders[lookupKey];
}
return foundCodec;
}
}
}
```
---
# Update
A few people have been asking in the comments for samples of how to consume the ImageUtilities class, so here you go.
```
//resize the image to the specified height and width
using (var resized = ImageUtilities.ResizeImage(image, 50, 100))
{
//save the resized image as a jpeg with a quality of 90
ImageUtilities.SaveJpeg(@"C:\myimage.jpeg", resized, 90);
}
```
## Note
Remember that images are disposable, so you need to assign the result of your resize to a using declaration (or you could use a try finally and make sure you call dispose in your finally).
|
When you draw the image using GDI+ it scales quite well in my opinion. You can use this to create a scaled image.
If you want to scale your image with GDI+ you can do something like this:
```
Bitmap original = ...
Bitmap scaled = new Bitmap(new Size(original.Width * 4, original.Height * 4));
using (Graphics graphics = Graphics.FromImage(scaled)) {
graphics.DrawImage(original, new Rectangle(0, 0, scaled.Width, scaled.Height));
}
```
|
High Quality Image Scaling Library
|
[
"",
"c#",
"image",
"image-processing",
"image-manipulation",
"image-scaling",
""
] |
I have a `contacts` table which contains fields such as `postcode`, `first name`, `last name`, `town`, `country`, `phone number` etc, all of which are defined as `VARCHAR(255)` even though none of these fields will ever come close to having 255 characters. (If you're wondering, it's this way because Ruby on Rails migrations map String fields to `VARCHAR(255)` by default and I never bothered to override it).
Since VARCHAR will only store the number of actual characters of the field (along with the field length), is there any distinct advantage (performance or otherwise) to using, say, `VARCHAR(16)` over `VARCHAR(255)`?
Additionally, most of these fields have indexes on them. Does a larger VARCHAR size on the field affect the size or performance of the index at all?
FYI I'm using MySQL 5.
|
In storage, `VARCHAR(255)` is smart enough to store only the length you need on a given row, unlike `CHAR(255)` which would always store 255 characters.
But since you tagged this question with MySQL, I'll mention a MySQL-specific tip: as rows are copied from the storage engine layer to the SQL layer, `VARCHAR` fields are converted to `CHAR` to gain the advantage of working with fixed-width rows. So the strings in memory become **padded out to the maximum length** of your declared `VARCHAR` column.
When your query implicitly generates a temporary table, for instance while sorting or `GROUP BY`, this can use a lot of memory. If you use a lot of `VARCHAR(255)` fields for data that doesn't need to be that long, this can make the temporary table very large.
You may also like to know that this "padding out" behavior means that a string declared with the utf8 character set pads out to three bytes per character even for strings you store with single-byte content (e.g. ascii or latin1 characters). And likewise utf8mb4 character set causes the string to pad out to four bytes per character in memory.
So a `VARCHAR(255)` in utf8 storing a short string like "No opinion" takes 11 bytes on disk (ten lower-charset characters, plus one byte for length) but it takes 765 bytes in memory, and thus in temp tables or sorted results.
I have helped MySQL users who unknowingly created 1.5GB temp tables frequently and filled up their disk space. They had lots of `VARCHAR(255)` columns that in practice stored very short strings.
It's best to define the column based on the type of data that you intend to store. It has benefits to enforce application-related constraints, as other folks have mentioned. But it has the physical benefits to avoid the memory waste I described above.
It's hard to know what the longest postal address is, of course, which is why many people choose a long `VARCHAR` that is certainly longer than any address. And 255 is customary because it is the maximum length of a `VARCHAR` for which the length can be encoded with one byte. It was also the maximum `VARCHAR` length in MySQL older than 5.0.
|
In addition to the size and performance considerations of setting the size of a varchar (and possibly more important, as storage and processing get cheaper every second), the disadvantage of using varchar(255) "just because" is reduced *data integrity*.
Defining maximum limits for strings is a **good thing to do** to prevent longer than expected strings from entering the RDBMS and causing buffer overruns or exceptions/errors later when retrieving and parsing values from the database that are longer (more bytes) than expected.
For example, if you have a field that accepts two-character strings for country abbreviations then you have no conceivable reason to expect your users (in this context, programmers) to input full country names. Since you don't want them to enter "Antigua and Barbuda" (AG) or "Heard Island and McDonald Islands" (HM), you don't allow it at the database layer. Also, it is likely some programmers have not yet RTFMed the design documentation (*which surely exists*) to know not to do this.
Set the field to accept two characters and let the RDBMS deal with it (either gracefully by truncating or ungracefully by rejecting their SQL with an error).
Examples of real data that has no reason to exceed a certain length:
* [Canadian Postal Codes](http://en.wikipedia.org/wiki/Canadian_postal_code) are of the format A1A1A1 and are always 6 characters in length, *even for Santa Claus* (6 characters excludes the space that can be specified for legibility).
* [email addresses](https://www.rfc-editor.org/rfc/rfc5322) - up to 64 bytes before the @, up to 255 bytes after. Never more, lest you break the Internet.
* North American Phone Numbers are never more than 10 digits (excluding the country code).
* Computers running (recent versions of) Windows cannot have [computer names longer than 63 bytes](http://technet.microsoft.com/en-us/library/cc757496(WS.10).aspx), though more than 15 is not recommended and will break your Windows NT server farm.
* State abbreviations are 2 characters (like the country codes exampled above)
* [UPS tracking numbers](http://www.ups.com/content/us/en/tracking/help/tracking/tnh.html) are either 18-, 12-, 11-, or 9-characters long. The 18-character numbers start with "1Z" and the 11-character numbers start with "T" which makes you wonder how they deliver all those packages if they don't know the difference between letters and numbers.
And so on...
Take the time to think about your data and its limits. If you're a architect, developer, or programmer, it's your *job*, after all.
**By using a varchar(n) instead of varchar(255) you eliminate the problem where users (end-users, programmers, other programs) enter unexpectedly long data *that will* come back to haunt your code later.**
And I didn't say you shouldn't also implement this restriction in the business logic code used by your application.
|
Are there disadvantages to using a generic varchar(255) for all text-based fields?
|
[
"",
"mysql",
"sql",
""
] |
I am making a program in C# to connect to a webcam and do some image manipulation with it.
I have a working application that uses win32 api (avicap32.dll) to connect to the webcam and send messages to it that sends it to the clipboard. The problem is that, while accessible from paint, reading it from the program results in null pointers.
This is the code I use to connect the webcam:
```
mCapHwnd = capCreateCaptureWindowA("WebCap", 0, 0, 0, 320, 240, 1024, 0);
SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0);
SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0);
```
And this is what I use to copy the image to the clipboard:
```
SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);
SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);
tempObj = Clipboard.GetDataObject();
tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap);
```
There's some error checking which I have removed from the code to make it shorter.
|
I've recently started doing some hobby work in this area.
We settled on using the [OpenCV](http://sourceforge.net/projects/opencv/) library with the [opencvdotnet](http://code.google.com/p/opencvdotnet/) wrapper. It supports capturing frames from a webcam:
```
using (var cv = new OpenCVDotNet.CVCapture(0))
{
var image = cv.CreateCompatibleImage();
// ...
cv.Release();
}
```
And if you're doing image manipulation, OpenCV's image processing algorithms have been wrapped within the OpenCVDotNet.Algs assembly.
If you decide to go this route be sure to install OpenCV version 1.0 (and install it to "c:\program files\opencv" if you are on Vista 64-bit, or "mklink OpenCV 'c:\program files (x86)\OpenCV`" from the correct directory or else opencvdotnet will not install).
|
There are really two ways to get camera data into your application, DirectShow and WIA. Microsoft recommends that you use [WIA](http://msdn.microsoft.com/en-us/library/ms630368.aspx), and the interface for WIA is fairly simple to wrap your brain around. I created and published an open source [WIA desktop library](http://blog.opennetcf.com/ctacke/2007/12/21/WIADesktopLibrary.aspx) based on work I did a while ago.
Now the problem with WIA in some cases is that it's too simple. For example, if you want to adjust camera properties (like frame rate, resolution, etc) then WIA falls down. Microsoft deprecated DirectShow, but they really didn't give us any replacement that has all of its capabilities, and I've found that it continues to work fine on all existing platforms (it's very entrenched, so I can't imagine support going away any time soon).
There is a very good [DirectShow library over at SourceForge](http://directshownet.sourceforge.net/). The only "problem" with it is it's really complex and that stems from the fact that DShow is just so damned complex and confusing in the first place. There are lots of things that the wrapper can do that just aren't easy to work out, but they do provide samples for a lot of common use cases like showing video or capturing a frame. If you want to add overlays, or insert other filters, it can do it, but be forewarned that it's not at all straightforward.
|
Webcam usage in C#
|
[
"",
"c#",
"clipboard",
"webcam",
""
] |
I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a `°` character - [Unicode U+00B0](http://en.wikipedia.org/wiki/Degree_symbol) (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a `UnicodeDecodeError`.
My first attempt to fix the issue simply caught that error (because the app apparently does send *some* bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the `wxTextCtrl` can display?
|
pdc got it right, the following works fine (but fails without the `decode`):
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
app = wx.PySimpleApp()
app.TopWindow = wx.Frame(None)
field = wx.TextCtrl(app.TopWindow)
field.Value += '°'.decode('ISO8859-1')
app.TopWindow.Show()
app.MainLoop()
```
|
I can't say mych about wxPython itself, but I am guessing that it is trying to convert the text to Unicode before displaying it, If you have a string like `'123\xB0'` and try to convert it to Unicode with teh default encoding (ASCII) then it will throw `UnicodeDecodeError`. You can probably fix this by replacing
```
s = message.get_string()
```
with
```
s = message.get_string().decode('ISO8859-1')
```
(where I am assuming a function `get_string()` that gets the message as a string). The difference here is that by handong the conversion to Unicode yourself you get to specify the encoding.
|
How do I safely decode a degrees symbol in a wxPython app?
|
[
"",
"python",
"unicode",
"wxpython",
"decode",
"textctrl",
""
] |
What's the most appropriate type used to store the duration time information of a video in sql server?
|
There are [several options](http://www.sqlteam.com/article/working-with-time-spans-and-durations-in-sql-server), including using the builtin DateTime or Time data type with offset from a particular fixed zero (which will allow you to use the built-in date/time function to get hours, minutes and seconds, etc.
If you were on pre-SQL Server 2005, you could combine it with a [user-defined data type technique](http://weblogs.sqlteam.com/jeffs/archive/2004/12/02/2959.aspx) (if your spans are less than 24 hours) to constrain the date part to be guaranteed not to wander.
|
It depends on how granular you need and if you have any constraints on a maximum time. For example, would you need to know down to the millisecond of time duration or is 1 second granular enough? The other thing to consider is how much data do you (or can you) store.
For SQL Server 2005, you have these constraints:
tinyint
* min = 0
* max =255
* Size = 1 byte
smallint
* min = -2^15 (-32,768)
* max= 2^15 - 1 (32,767)
* Size = 2 bytes
int
* min = -2^31 (-2,147,483,648)
* max = 2^31 - 1 (2,147,483,647)
* Size = 4 bytes
bigint
* min = -2^63
(-9,223,372,036,854,775,808)
* Max = 2^63 - 1
(9,223,372,036,854,775,807)
* Size = 8 bytes
|
Storing video duration time in sql server
|
[
"",
"sql",
"sql-server",
"database",
"sql-server-2005",
""
] |
i have a class with a static public property called "Info".
via reflection i want to get this properties value, so i call:
```
PropertyInfo pi myType.GetProperty("Info");
string info = (string) pi.GetValue(null, null);
```
this works fine as long as the property is of type string. but actually my property is of type IPluginInfo and a PluginInfo type (implementing IPluginInfo) is instatiated and returned in the Info properties get accessor, like this:
```
public static IPluginInfo PluginInfo
{
get
{
IPluginInfo Info = new PluginInfo();
Info.Name = "PluginName";
Info.Version = "PluginVersion";
return Info;
}
}
```
like this when i call:
```
IPluginInfo info = pi.GetValue(null, null) as IPluginInfo;
```
info is always null, whiel PropertyInfo pi is still valid. am i missing something obvious here?
|
Could you create a short but complete program that demonstrates the problem?
Given that you're talking about plugins, my *guess* is that you've got the problem of having IPluginInfo defined in two different assemblies. See if [this article](http://pobox.com/~skeet/csharp/plugin.html) helps at all.
The easiest way to verify it is to call `pi.GetValue` and store the result in an `object` variable first, then do the cast or "as" in another line. That way you can break the debugger and look at the return value before it's lost.
|
ok, thanks for all the answers.
i indeed already had the plugininterface in a separate .dll but had placed this .dll in the pluginhosts directory as well as in the directory with all the plugins.
|
PropertyInfo.GetValue(null, null) returns null
|
[
"",
"c#",
""
] |
I've successfully used the Windows SendMessage method to help me do various things in my text editor, but each time I am just copying and pasting code suggested by others, and I don't really know what it means. There is always a cryptic message number that is a parameter. How do I know what these code numbers mean so that I can actually understand what is happening and (hopefully) be a little more self-sufficient in the future? Thanks.
Recent example:
```
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,UIntPtr wParam, IntPtr lParam);
SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));
```
|
This is the windows message code.
They are defined in the header files, and generally available translated as an include of some sort with different languages.
example:
WM\_MOUSEMOVE = &H200
MK\_CONTROL = &H8
MK\_LBUTTON = &H1
MK\_MBUTTON = &H10
MK\_RBUTTON = &H2
MK\_SHIFT = &H4
MK\_XBUTTON1 = &H20
MK\_XBUTTON2 = &H40
see <http://msdn.microsoft.com/en-us/library/ms644927(VS.85).aspx#windows_messages>.
|
Each message in Windows is signified by a number. When coding using the Windows SDK in native code, these are provided by defines such as WM\_CHAR, WM\_PAINT, or LVM\_GETCOUNT, but these defines are not carried over to the .NET framework because in the most part, the messages are wrapped by .NET events like OnKeyPressed and OnPaint, or methods and properties like ListView.Items.Count.
On the occasion where there is no wrapped event, property or method, or you need to do something that isn't supported at the higher level, you need the message numbers that Windows uses underneath the .NET framework.
The best way to find out what a particular number actually means is to look in the Windows SDK headers and find the definition for that number.
|
Explanation of SendMessage message numbers?
|
[
"",
"c#",
"winforms",
"interop",
""
] |
I'm attempting to fulfill a rather difficult reporting request from a client, and I need to find away to get the difference between two DateTime columns in minutes. I've attempted to use trunc and round with various [formats](http://www.ss64.com/orasyntax/fmt.html) and can't seem to come up with a combination that makes sense. Is there an elegant way to do this? If not, is there **any** way to do this?
|
```
SELECT date1 - date2
FROM some_table
```
returns a difference in days. Multiply by 24 to get a difference in hours and 24\*60 to get minutes. So
```
SELECT (date1 - date2) * 24 * 60 difference_in_minutes
FROM some_table
```
should be what you're looking for
|
By default, oracle date subtraction returns a result in # of days.
So just multiply by 24 to get # of hours, and again by 60 for # of minutes.
Example:
```
select
round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
(
select
to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
from
dual
) test_data
```
|
Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?
|
[
"",
"sql",
"oracle",
"datediff",
""
] |
I'm using the [freeodbc++](http://libodbcxx.sourceforge.net/) library to access data on a MS SQL Server 2000 database (SP3? SP4?). In particular, I'm running a particularly long and nasty stored procedure. I can watch the procedure execute in SQL Profiler, however, it tends to stop processing at a certain point. No error codes or exceptions thrown. If I comment out the nested statement that is always the last statement, it just ends slightly before the comment. I haven't tried radically commenting out the whole darn thing... I'm setting the query timeout to 300 seconds. The callable statement usually returns in under 1 sec, without actually finishing the SP.
Any ideas?
**UPDATE0:** If I run the SP via Query Analyzer or some other tool... it works. It's just via my ODBC connection that it fails.
**UPDATE1:** As I comment out code, the execution ends further into the SP. Makes me think there is a timeout or buffer limit that I'm running into.
|
Have you tried profiling on the SQL Server side, to see what is happening with your SPID?
Also, I have not used freeodbc++, but maybe there is a PRINT statement in there that it does not like. You could also SET NOCOUNT ON to suppress the row count messages. Again, this depends upon how freeodbc++ reacts to these "informational" messages.
It sounds like a bug in freeodbc++, based on this "freezing" style of behavior that you describe. Start with examining the process on the SQL side to see if it is really hung, or if your library just "died" on you.
|
Adding "::Sleep(30000);" immediately after I call execute on the ODBC statement object (and before the statement close command) keeps the server process from exiting prematurely. Must be a bug with freeodbc++ or a configuration error on my part.
Thanks for the troubleshooting/debugging tips.
|
Why does the Store Procedure I'm calling over ODBC fail at the same location?
|
[
"",
"sql",
"sql-server",
"sql-server-2000",
"odbc",
""
] |
I am declaring an array of void pointers. Each of which points to a value of arbitary type.
`void **values; // Array of void pointers to each value of arbitary type`
Initializing values as follows:
```
values = (void**)calloc(3,sizeof(void*));
//can initialize values as: values = new void* [3];
int ival = 1;
float fval = 2.0;
char* str = "word";
values[0] = (void*)new int(ival);
values[1] = (void*)new float(fval);
values[2] = (void*)str;
//Trying to Clear the memory allocated
free(*values);
//Error: *** glibc detected *** simpleSQL: free(): invalid pointer: 0x080611b4
//Core dumped
delete[] values*;
//warning: deleting 'void*' is undefined
//Similar Error.
```
Now how do I free/delete the memory allocated for values ( the array of void pointers)?
|
You have 3 things that are dynamically allocated that need to be freed in 2 different ways:
```
delete reinterpret_cast<int*>( values[0]);
delete reinterpret_cast<float*>( values[1]);
free( values); // I'm not sure why this would have failed in your example,
// but it would have leaked the 2 items that you allocated
// with new
```
Note that since `str` is not dynamically allocated it should not (actually **cannot**) be freed.
A couple of notes:
* I'm assuming that the `sizeof(void)`
was meant to be `sizeof(void*)`
since what you have won't compile
* I'm not going to say anything about
your seemingly random casting except
that it looks like code that ready
for disaster in general
|
I suspect the issue is with the way that you allocated `values`: `values = (void*)calloc(3,sizeof(`**`void`**`))`. That should be `sizeof(void *)` rather than just `sizeof(void)`.
sizeof(void) may be zero or something else that makes no sense, so you're not really allocating any memory to begin with... it's just dumb luck that the assignments work, and then the error pops up when you try to deallocate the memory.
EDIT: You're also asking for trouble by alternating between C++-style `new`/`delete` with C-style `malloc`/`free`. It is okay to use them both as long as you don't `delete` something you `malloc`'ed or `free` something you `new`'ed, but you're going to mix them up in your head if you go like this.
|
Freeing memory allocated to an array of void pointers
|
[
"",
"c++",
"c",
"memory-management",
""
] |
Is there a way to hide private data members of a C++ class away from its users, in the cpp file? I think of the private members as part of the implementation and it seems a little backwards to declare them in the header file.
|
The "pimpl" idiom is how this is generally handled.
See
* <http://www.gotw.ca/gotw/024.htm>
* <http://www.gotw.ca/gotw/028.htm>
* <http://herbsutter.com/gotw/_100/> (updated for C++11)
|
you want to use something like the PIMPL idiom
<http://en.wikipedia.org/wiki/Opaque_pointer>
|
Hiding private data members? (C++)
|
[
"",
"c++",
"class",
"private",
""
] |
I've recently gotten my hobby java project embedded into a page [thanks to this very site](https://stackoverflow.com/questions/138157/java-console-like-web-applet), but now I'm having some security issues.
I have the include:
```
import java.sql.*;
```
and the line:
```
Class.forName("com.mysql.jdbc.Driver").newInstance();
```
as well as a mysql .jar file in my src directory, it works from the console, and in the applet works fine from the applet - up until that forName() line in my code, where it throws the exception:
```
Exception: com.mysql.jdbc.Driverjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.-1)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkExit(Unknown Source)
at java.lang.Runtime.exit(Unknown Source)
at java.lang.System.exit(Unknown Source)
at applet.Database.connectDB(Database.java:80)
etc...
```
I think I may be able to fix it with a client.policy file, otherwise I might need to write an abstraction layer which uses a server-client network connection to query from the server-side...
I'm sure the Java gurus here probably know the best way about it.
|
I think the security exception is actually from a System.exit() call in your applet, after the Class.forName(). Generally you are not allowed to call System.exit() in unsigned applets as it shuts the whole JVM down. Have you checked if line 80 is actually the Class.forName() line, or does line 80 have some kind of exception handler which tries to call System.exit() if the driver does not load?
Anyway, in order to load the mysql jar file in your applet, you need to include it in an ARCHIVE attribute like this:
```
<APPLET ARCHIVE="mysql.jar" CODEBASE="./src/" ...
```
Once you get past this stage, you will still need to host the mysql server at the same IP number/hostname as the webserver, and open it to all the same people who can access your applet. As Tony said, this isn't how people normally do it, for security reasons. Better to write something on the server side, if you have control of the app server, and use XML or some other data exchange method to get the data out to the applet. Of course if you are just experimenting to learn about applets, then it's probably fine - but do take care to keep mysql behind your firewall if possible.
|
If you're trying to use the a JDBC driver from the applet, then the applet needs to be signed with a certificate, and your server needs to deliver this certificate when the applet is loaded on the client side.
|
How do I permit my Java applet to use MySQL?
|
[
"",
"java",
"mysql",
"security",
"applet",
""
] |
When using `__import__` with a dotted name, something like: `somepackage.somemodule`, the module returned isn't `somemodule`, whatever is returned seems to be mostly empty! what's going on here?
|
From the python docs on `__import__`:
> ```
> __import__( name[, globals[, locals[, fromlist[, level]]]])
> ```
>
> ...
>
> When the name variable is of the form
> package.module, normally, the
> top-level package (the name up till
> the first dot) is returned, not the
> module named by name. However, when a
> non-empty fromlist argument is given,
> the module named by name is returned.
> This is done for compatibility with
> the bytecode generated for the
> different kinds of import statement;
> when using "import spam.ham.eggs", the
> top-level package spam must be placed
> in the importing namespace, but when
> using "from spam.ham import eggs", the
> spam.ham subpackage must be used to
> find the eggs variable. As a
> workaround for this behavior, use
> getattr() to extract the desired
> components. For example, you could
> define the following helper:
>
> ```
> def my_import(name):
> mod = __import__(name)
> components = name.split('.')
> for comp in components[1:]:
> mod = getattr(mod, comp)
> return mod
> ```
**To paraphrase:**
When you ask for `somepackage.somemodule`, `__import__` returns `somepackage.__init__.py`, which is often empty.
It will return `somemodule` if you provide `fromlist` (a list of the variable names inside `somemodule` you want, which are not actually returned)
You can also, as I did, use the function they suggest.
Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.
|
python 2.7 has importlib, dotted paths resolve as expected
```
import importlib
foo = importlib.import_module('a.dotted.path')
instance = foo.SomeClass()
```
|
Python's __import__ doesn't work as expected
|
[
"",
"python",
"python-import",
""
] |
How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and write the results to a text box.
|
```
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "YOURBATCHFILE.bat";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
```
Code is from [MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx).
|
Here's a quick sample:
```
//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = strCommand;
//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = strCommandParameters;
pProcess.StartInfo.UseShellExecute = false;
//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;
//Optional
pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;
//Start the process
pProcess.Start();
//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();
//Wait for process to finish
pProcess.WaitForExit();
```
|
How To: Execute command line in C#, get STD OUT results
|
[
"",
"c#",
"command-line",
""
] |
We are looking to provide two **custom Platform switches** (the **platform dropdown** in the configuration manager) for our projects **in Visual Studio**.
For example one for 'Desktop' and one for 'Web'. The target build tasks then compile the code in a custom way based on the platform switch. We don't want to add to the Debug Release switch because we would need those for each Desktop and Web platforms.
We found one way to attempt this, is to modify the .csproj file to add something like this
```
<Platform Condition=" '$(Platform)' == '' ">Desktop</Platform>
```
and add propertygroups like,
```
<PropertyGroup Condition=" '$(Platform)' == 'Web' ">
<DefineConstants>/define Web</DefineConstants>
<PlatformTarget>Web</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'Desktop' ">
<DefineConstants>/define Desktop</DefineConstants>
<PlatformTarget>Desktop</PlatformTarget>
</PropertyGroup>
```
But still this doesn't work, and compiler throws an error
*Invalid option 'Desktop' for /platform; must be anycpu, x86, Itanium or x64*
So does it have to be one of those options and can't we add our custom platforms?
Has anyone been able to do this? any pointers would be helpful.
Update: Using DebugDesktop and ReleaseDesktop will make it more complicated for users. Because 'desktop' and 'web' are actually platforms and also there is ability to add new platforms in the dropdown (i.e. ), I believe 'platform' switch should be used for the exact same purpose.
|
You should be able to use the Configuration Manager dialog to create new platforms.
|
May be this subject will be interesting for somebody after three years. I had similar difficulties with configuring build platforms and resolved them.
The error you gave was thrown because the PlatformTarget property was set with Desctop, not because the Platform property. These two properties have a little bit different meaning. The first one really eventually instructs all participants of build process which process architecture should be utilized, while the second one allows customize build circumstances inside IDE.
When project is created in the Visual Studio, the ProcessTarget property may be set by default with AnyCPU under PropertyGroups that have conditional restrictions like this "**'...|$(Platform)' == '...|AnyCPU'**". But it doesn't enforce you to do the same. The ProcessTarget property can easily be set with AnyCPU for Platform property having other values.
Considering described above, your sample may looks like this:
```
<PropertyGroup Condition=" '$(Platform)' == 'Web' ">
<DefineConstants>Web</DefineConstants>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'Desktop' ">
<DefineConstants>Desktop</DefineConstants>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
```
it must be working.
Hope it's useful for you.
|
How to add and compile for custom 'Platform' switch for visual studio projects?
|
[
"",
"c#",
"visual-studio",
"visual-studio-2008",
""
] |
In VS2008 I have written a C# service, an installer, and have created a setup package to install it. The service needs to load an xml file to operate. Where is the best place to put this file in the various filesystem folders offered by the VS setup project, and how do I then refer to these paths from my code?
I should point out the the service runs as `LocalService`, which means that the ApplicationData folder offered by the "User's Application Data Folder" item in the VS setup project is not accessible, even when "Install for all users" is used during installation. I could easily hack around this, but would like to understand best practice.
|
I am not sure which place is better to store the XML file. I don't think it will matter alot. But if you need to get special folder path in the system you can use Environment class to do so. The following line of code get the path of the Program Files:
```
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
```
|
To read installation path used by installer created from setup project:
1) Open "Custom Actions" editor in your setup project
2) Add custom action from your assembly where your installer class is located (If you haven't done so already)
3) Select this custom action and add `/myKey="[TARGETDIR]\"` to CustomActionData in property grid
4) In your Installer class you may access your value as follows: `Context.Parameters["myKey"]` in your method override dependent on your choice in step 2
|
Locating installer paths in c#
|
[
"",
"c#",
"visual-studio-2008",
"installation",
"service",
""
] |
I'm looking for a lightweight, easy to setup CI server that I can run on my laptop along with Visual Studio & Resharper. I'm obviously looking at all the big names like CruiseControl, TeamCity etc etc but the biggest consideration to me is ease of setup and to a lesser extent memory footprint.
Edit: I'd also like some suggestions for other solutions outside the big 2/3...
Edit: I'm about to accept an answer if no one else has anything to add?
|
I use [TeamCity](http://www.jetbrains.com/teamcity/), and is really, really easy to setup and get it running.
Check the [Demos and Documentation](http://www.jetbrains.com/teamcity/documentation/index.html). You will have it up and running in less than one hour!
|
I have just started to use CruiseControl.NET.
With no prior knowlege I was able to get it up and running with a single test project using MSBuild, MSTest and Team Foundation Server (i.e. CodePlex) in a couple of hours. I posted a bunch of links to useful resources here [Devsta 2008 Day 0: Source Control and CI](http://codermike.com/devsta-2008-day-0-source-control-and-ci)
I can't help on memory footprint as my project was pretty small. I can tell you that while it's not doing anything (i.e. most of the time) it is using ~5MB on my system. In fact the Tray Icon notifier that comes with it takes up more memory than the service at about 6MB. That goes up when it does stuff of course.
|
Best Continuous Integration Setup for a solo developer (.NET)
|
[
"",
"c#",
".net",
"asp.net",
"continuous-integration",
""
] |
I have a problem when an unhandeld exception occurs while debugging a WinForm VB.NET project.
The problem is that my application terminates and I have to start the application again, instead of retrying the action as was the case in VS2003
The unhandeld exception is implemented in the new My.MyApplication class found in ApplicationEvents.vb
```
Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim handler As New GlobalErrorHandler()
handler.HandleError(e.Exception)
e.ExitApplication = False
End Sub
```
Note: handler.HandleError just shows a dialog box and logs the error to a log file.
I also tried the following code that used to work in VS2003 but it results in the same behaviour when run in VS2008:
```
AddHandler System.Windows.Forms.Application.ThreadException, AddressOf OnApplicationErrorHandler
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf OnUnhandledExceptionHandler
```
OnApplicationErrorHandler and OnUnhandledExceptionHandler does the same as handle.HandleError
Running the application outside VS2008 results in the expected behaviour (the application doesn't terminate) but it is increasing our test cycle during debugging.
**Update:** I have added sample code in my answer to demonstrate this problem in C#
|
Ok I found the answer to this issue in this blog post: [Handling "Unhandled Exceptions" in .NET 2.0](http://www.julmar.com/blog/mark/PermaLink,guid,f733e261-5d39-4ca1-be1a-c422f3cf1f1b.aspx)
Thank you Mark!
The short answer is:
```
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
```
This causes the same behaviour during debug and run mode. Resulting in VS not closing while debugging
|
OK I have done more work on this but still don't have an answer.
I found that this problem is not only related to VB.NET but also to C#
Here is simple C# program that demonstrates the problem:
```
using System;
using System.Windows.Forms;
namespace TestCSharpUnhandledException
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show("Oops an unhandled exception, terminating:" + e.IsTerminating);
}
void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show("Oops an unhandled thread exception");
}
private void button1_Click(object sender, EventArgs e)
{
throw new Exception("Dummy unhandled exception");
}
}
}
```
What I found interesting is debugging in **VS the UnhandledException** event is thrown but running the application outside VS causes the **ThreadException** to fire.
Also inside VS the e.IsTerminating is set to true, ultimately I want this to be false. (This is a read only property)
|
Visual Studio 2008 - Application closes when unhandled exception occurs
|
[
"",
"c#",
"vb.net",
"visual-studio-2008",
"debugging",
""
] |
I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).
What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.
I know that `<a href="url" target="_blank">` is out. I also know that `<a href="#" onclick="window.open(url);">` isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like `<span onclick="window.open(url);">` and then style the SPAN to look like a link.
One solution I'm leaning towards is `<a href="url" rel="external">` and using JavaScript to set all targets to '\_blank' on those anchors marked 'external'.
Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.
UPDATE: I say target="\_blank" is a no no, because I've read in [several places](http://www.sitepoint.com/article/standards-compliant-world/3/) that the target attribute is going to be phased out of XHTML.
|
I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:
```
$(document).ready(function() {
$('a[rel*=external]').click(function(){
window.open($(this).attr('href'));
return false;
});
});
```
I find this the best method because:
* it is very clear semantically: you have a link to an external resource
* it is standards-compliant
* it degrades gracefully (you have a very simple link with regular `href` attribute)
* it still allows user to middle-click the link and open it in new tab if they wish
|
Why is `target="_blank"` a bad idea?
It's supposed to do exactly what you want.
edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)
|
What's the best way to open new browser window?
|
[
"",
"javascript",
"html",
"browser",
""
] |
I have a public static class in which I would like to have a ToString() method.
I have defined it as public static string ToString(), but get the following warning:
> 'Class.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
If I add the override keyword I get this error instead:
> A static member 'Class.ToString()' cannot be marked as override, virtual, or abstract
How do I get rid of that warning and let my static class have the ToString() method.
Thank you,
Keith
|
Yes, using the "new" modifier will effectively silence the compiler warning but you are **explicitly hiding** an instance method with a static method. (This is different than overriding the method.) Typically you don't want to hide an instance method except with very good reasons and you really shouldn't hide it with a static method as that really changes the behavior semantics of the call. Every object in .NET has an instance method named ToString() that has specific behavior that developers expect; by hiding that behavior with a new static method you are changing that expectation which can lead to a lot of confusion.
What are you "to stringing"? Static classes typically don't hold internal state so there really shouldn't be any internal data to provide as the logical output of a ToString() call. You may want to rethink your class design or provide a different method name that more clearly indicates the purpose of the method without hiding the instance ToString().
|
In a static class you cannot override ToString. .ToString is an instance method and by definition a static class can only have static members.
Also why would you want to override .ToString()? There is no way to get an instance of the class and hence no way to call the function.
Note: Using the new syntax will not override .ToString. It will create a new member that is completely unrelated to the Object.ToString() method.
|
How do you override ToString in a static class?
|
[
"",
"c#",
".net",
"static",
"overriding",
""
] |
I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?
The concept I'm looking for is this:
```
public class MyClass<T> where T : //[is serializable/has the serializable attribute]
```
|
Nope, I'm afraid not. The only things you can do with constraints are:
* `where T : class` - T must be a reference type
* `where T : struct` - T must be a non-nullable value type
* `where T : SomeClass` - T must be SomeClass or derive from it
* `where T : ISomeInterface` - T must be ISomeInterface or implement it
* `where T : new()` - T must have a public parameterless constructor
Various combinations are feasible, but not all. Nothing about attributes.
|
What I know; you can not do this.
Have you though about adding an 'Initialize' method or something similar?
```
public void Initialize<T>(T obj)
{
object[] attributes = obj.GetType().GetCustomAttributes(typeof(SerializableAttribute));
if(attributes == null || attributes.Length == 0)
throw new InvalidOperationException("The provided object is not serializable");
}
```
I haven't tested this code, but I hope that you get my point.
|
Can you use "where" to require an attribute in c#?
|
[
"",
"c#",
"generics",
"attributes",
"constraints",
"where-clause",
""
] |
This might be a old question: Why does `IEnumerable<T>` inherit from `IEnumerable`?
This is how .NET do, but it brings a little trouble. Every time I write a class implements `IEumerable<T>`, I have to write two `GetEnumerator()` functions, one for `IEnumerable<T>` and the other for `IEnumerable`.
And, `IList<T>` doesn't inherit from IList.
I don't know why `IEnumerable<T>` is designed in other way.
|
[Straight from the horse's mouth](https://learn.microsoft.com/en-us/archive/blogs/brada/why-does-ienumerable-inherits-from-ienumerable) (Hejlsberg):
> Ideally all of the generic collection interfaces (e.g. `ICollection<T>`, `IList<T>`) would inherit from their non-generic counterparts such that generic interface instances could be used both with generic and non-generic code. For example, it would be convenient if an `IList<T>` could be passed to code that expects an `IList`.
> As it turns out, the only generic interface for which this is possible is `IEnumerable<T>`, because only `IEnumerable<T>` is contra-variant: In `IEnumerable<T>`, the type parameter T is used only in "output" positions (return values) and not in "input" positions (parameters). `ICollection<T>` and `IList<T>` use T in both input and output positions, and those interfaces are therefore invariant. (As an aside, they would have been contra-variant if T was used only in input positions, but that doesn't really matter here.)
> <...snip...>
So, to answer your question, `IEnumerable<T>` inherits from `IEnumerable` because it can! :-)
|
The answer for `IEnumerable` is: "because it can without affecting type safety".
`IEnumerable` is a "readonly" interface - so it doesn't matter that the generic form is more specific than the nongeneric form. You don't break anything by implementing both. `IEnumerator.Current` returns `object`, whereas `IEnumerator<T>.Current` returns `T` - that's okay, as you can always legitimately convert to `object`, although it may mean boxing.
Compare this with `IList<T>` and `IList` - you can call `Add(object)` on an `IList`, whereas that may well be invalid for any particular `IList<T>` (anything other than `IList<object>` in fact).
Brad Abram's [blogged with Anders' answer](https://learn.microsoft.com/en-us/archive/blogs/brada/why-does-ienumerable-inherits-from-ienumerable) about this very question.
|
Why does IEnumerable<T> inherit from IEnumerable?
|
[
"",
"c#",
"generics",
"ienumerable",
""
] |
I have a function that automatically exports a table into a CSV file, then I try to attach that same file into a function that will email it. I have sent attachments using html mime mail before, but I was wondering if that created CSV file needs to be stored on the server first before attaching it to the email?
|
It depends on your functions, if you have a function that can export the table as CSV into a string and then the mail functions support creating attachments from a string then I think you have what you need...
|
In theory you could embed it yourself by writing the appropriate tags and handcrafing the email yourself.
Or you can go the easy way and save it to a temporary location, use a tool like PHPMailer (which might also support string attachment) to attach the file, send the mail and then remove the temp file.
|
When attaching a file to an email, does it need to be stored on the server first?
|
[
"",
"php",
"mysql",
""
] |
What are the best ways of dealing with UTC Conversion and daylight saving times conversion. What are the problems and their solutions. All in C# .Net 2.0. Also any existing problems with this in .Net 2.0.
|
If you use UTC times you shouldn't worry about clients timezones or daylight saving... (if they have set a standard)
|
You really don't need to worry about it much with .NET if you're using UTC everywhere. If you're interested in seeing this sort of stuff in action you might check out the [TimeZoneInfo](http://msdn.microsoft.com/en-us/library/system.timezoneinfo_members.aspx) class.
|
Best ways to deal with UTC and daylight saving times
|
[
"",
"c#",
".net",
""
] |
What is the best way to approach removing items from a collection in C#, once the item is known, but not it's index. This is one way to do it, but it seems inelegant at best.
```
//Remove the existing role assignment for the user.
int cnt = 0;
int assToDelete = 0;
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
if (spAssignment.Member.Name == shortName)
{
assToDelete = cnt;
}
cnt++;
}
workspace.RoleAssignments.Remove(assToDelete);
```
What I would really like to do is find the item to remove by property (in this case, name) without looping through the entire collection and using 2 additional variables.
|
If you want to access members of the collection by one of their properties, you might consider using a `Dictionary<T>` or `KeyedCollection<T>` instead. This way you don't have to search for the item you're looking for.
Otherwise, you could at least do this:
```
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
if (spAssignment.Member.Name == shortName)
{
workspace.RoleAssignments.Remove(spAssignment);
break;
}
}
```
|
If RoleAssignments is a `List<T>` you can use the following code.
```
workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);
```
|
Best way to remove items from a collection
|
[
"",
"c#",
"collections",
""
] |
every time i create a FileInfo object and access it's lastaccesstime property, it's always a few minutes off. the file property window remains constant, however the application shows that it is usually a few minutes after the property window time.
Also, i noticed that if i drag the file to the cmd window to pass the filename as an argument, the access time updates most of the time, but not always.
What could be causing this ?
below is an example:
```
static void Main(string[] args)
{
if (args.Length > 0)
{
FileInfo fi = new FileInfo(args[0].ToString());
Console.WriteLine(args[0]);
if (fi.Exists)
{
Console.Write("Current: " + DateTime.Now + "\n");
Console.Write("LAT: " + fi.LastAccessTime + "\n");
Console.Write("LWT: " + fi.LastWriteTime + "\n");
Console.Write("CT: " + fi.CreationTime + "\n");
}
Console.ReadKey();
}
}
```
[alt text http://img407.imageshack.us/img407/4728/propertiesox6.png](http://img407.imageshack.us/img407/4728/propertiesox6.png)
[alt text http://img380.imageshack.us/img380/7752/appgt0.png](http://img380.imageshack.us/img380/7752/appgt0.png)
|
In my experience, last access time is notoriously unreliable. According to <http://technet.microsoft.com/en-us/library/cc781134.aspx>...
> The Last Access Time on disk is not always current because NTFS looks for a one-hour interval before forcing the Last Access Time updates to disk. NTFS also delays writing the Last Access Time to disk when users or programs perform read-only operations on a file or folder, such as listing the folder’s contents or reading (but not changing) a file in the folder.
Apparently, the in-memory copy will be correct, but in my experience, you may get a cached value which may be out of date. Also, note that last access time may be turned off by the user, and is turned off by default in Vista and 2008.
|
[The MSDN article with basic info about file times](http://msdn.microsoft.com/en-us/library/ms724290(VS.85).aspx) has this to say about file time resolution and Last Access times:
> For example, on FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). NTFS delays updates to the last access time for a file by up to one hour after the last access.
This would imply that on both FAT and NTFS, the Last Write Time will generally not be very precise, although I'm not sure the exact values they quote are correct.
|
LastAccess Time is incorrect
|
[
"",
"c#",
"fileinfo",
"lastaccesstime",
""
] |
I am a little confused by the multitude of ways in which you can import modules in Python.
```
import X
import X as Y
from A import B
```
I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the `__init__.py` or in the module code itself?
My question is not really answered by "[Python packages - import by class, not file](https://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file)" although it is obviously related.
|
In production code in our company, we try to follow the following rules.
We place imports at the beginning of the file, right after the main file's docstring, e.g.:
```
"""
Registry related functionality.
"""
import wx
# ...
```
Now, if we import a class that is one of few in the imported module, we import the name directly, so that in the code we only have to use the last part, e.g.:
```
from RegistryController import RegistryController
from ui.windows.lists import ListCtrl, DynamicListCtrl
```
There are modules, however, that contain dozens of classes, e.g. list of all possible exceptions. Then we import the module itself and reference to it in the code:
```
from main.core import Exceptions
# ...
raise Exceptions.FileNotFound()
```
We use the `import X as Y` as rarely as possible, because it makes searching for usage of a particular module or class difficult. Sometimes, however, you have to use it if you wish to import two classes that have the same name, but exist in different modules, e.g.:
```
from Queue import Queue
from main.core.MessageQueue import Queue as MessageQueue
```
As a general rule, we don't do imports inside methods -- they simply make code slower and less readable. Some may find this a good way to easily resolve cyclic imports problem, but a better solution is code reorganization.
|
Let me just paste a part of conversation on django-dev mailing list started by Guido van Rossum:
> [...]
> For example, it's part of the Google Python style guides[1] that all
> imports must import a module, not a class or function from that
> module. There are way more classes and functions than there are
> modules, so recalling where a particular thing comes from is much
> easier if it is prefixed with a module name. Often multiple modules
> happen to define things with the same name -- so a reader of the code
> doesn't have to go back to the top of the file to see from which
> module a given name is imported.
**Source:** <http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a>
1: <http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports>
|
What are good rules of thumb for Python imports?
|
[
"",
"python",
"python-import",
""
] |
Is there anyway to automatically run `javascript:window.print()` when the page finishes loading?
|
`<body onload="window.print()">`
or
`window.onload = function() { window.print(); }`
|
The following code must be put at the **end** of your HTML file so that once the content has loaded, the script will be executed and the window will print.
```
<script type="text/javascript">
<!--
window.print();
//-->
</script>
```
|
Auto start print html page using javascript
|
[
"",
"javascript",
"html",
"printing",
""
] |
After staring at [this 3D cube](http://maettig.com/code/javascript/3d_dots.html) and [these triangles](http://www.uselesspickles.com/triangles/demo.html) for a while I started wondering if there's any good reliable Javascript graphics library with basic 3D support.
Any suggestion?
|
John Resig's port of the Processing library to Javascript:
<http://ejohn.org/blog/processingjs>
|
I'm very psyched about [Raphaël](http://raphaeljs.com/). I've used it in one project and it works like a charm.
|
Are there any good Javascript graphics libraries?
|
[
"",
"javascript",
"graphics",
"3d",
""
] |
I'm having problems with Iterator.remove() called on a HashSet.
I've a Set of time stamped objects. Before adding a new item to the Set, I loop through the set, identify an old version of that data object and remove it (before adding the new object). the timestamp is included in hashCode and equals(), but not equalsData().
```
for (Iterator<DataResult> i = allResults.iterator(); i.hasNext();)
{
DataResult oldData = i.next();
if (data.equalsData(oldData))
{
i.remove();
break;
}
}
allResults.add(data)
```
The odd thing is that i.remove() silently fails (no exception) for some of the items in the set. I've verified
* The line i.remove() is actually called. I can call it from the debugger directly at the breakpoint in Eclipse and it still fails to change the state of Set
* DataResult is an immutable object so it can't have changed after being added to the set originally.
* The equals and hashCode() methods use @Override to ensure they are the correct methods. Unit tests verify these work.
* This also fails if I just use a for statement and Set.remove instead. (e.g. loop through the items, find the item in the list, then call Set.remove(oldData) after the loop).
* I've tested in JDK 5 and JDK 6.
I thought I must be missing something basic, but after spending some significant time on this my colleague and I are stumped. Any suggestions for things to check?
EDIT:
There have been questions - is DataResult truly immutable. Yes. There are no setters. And when the Date object is retrieved (which is a mutable object), it is done by creating a copy.
```
public Date getEntryTime()
{
return DateUtil.copyDate(entryTime);
}
public static Date copyDate(Date date)
{
return (date == null) ? null : new Date(date.getTime());
}
```
FURTHER EDIT (some time later):
For the record -- DataResult was not immutable! It referenced an object which had a hashcode which changed when persisted to the database (bad practice, I know). It turned out that if a DataResult was created with a transient subobject, and the subobject was persisted, the DataResult hashcode was changed.
Very subtle -- I looked at this many times and didn't notice the lack of immutability.
|
I was very curious about this one still, and wrote the following test:
```
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
public class HashCodeTest {
private int hashCode = 0;
@Override public int hashCode() {
return hashCode ++;
}
public static void main(String[] args) {
Set<HashCodeTest> set = new HashSet<HashCodeTest>();
set.add(new HashCodeTest());
System.out.println(set.size());
for (Iterator<HashCodeTest> iter = set.iterator();
iter.hasNext();) {
iter.next();
iter.remove();
}
System.out.println(set.size());
}
}
```
which results in:
```
1
1
```
If the hashCode() value of an object has changed since it was added to the HashSet, it seems to render the object unremovable.
I'm not sure if that's the problem you're running into, but it's something to look into if you decide to re-visit this.
|
Under the covers, HashSet uses HashMap, which calls HashMap.removeEntryForKey(Object) when either HashSet.remove(Object) or Iterator.remove() is called. This method uses both hashCode() and equals() to validate that it is removing the proper object from the collection.
If both Iterator.remove() and HashSet.remove(Object) are not working, then something is definitely wrong with your equals() or hashCode() methods. Posting the code for these would be helpful in diagnosis of your issue.
|
HashSet.remove() and Iterator.remove() not working
|
[
"",
"java",
"collections",
""
] |
I think questions like this are the reason why I don't like working with PHP. The manual is good, if you can find what you are looking for. After reading through the [Array Functions](https://www.php.net/array), I didn't see one that provides the functionality I need.
I have an array (in my case, numerically indexed) that I want to scan for a particular value and, if it's there, remove it. And then, when all instances of that value have been removed, I want to rearrange the array using [array\_values](https://www.php.net/manual/en/function.array-values.php).
|
[`array_diff`](http://de.php.net/array_diff) is what you want.
```
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
```
Result: `"blue"`.
|
Just to add to this...
array\_diff appears to show elements in the first array which don't appear in the second array. It doesn't show those elements which only appear in one or the other array.
e.g.
```
<?
$test = "hello";
$array1 = array("a" => "green", "red", "bicycle", "red");
$array2 = array("b" => "green", "yellow", "red", "blue", "yellow", "pink");
$result = array_diff($array1, $array2);
print_r ($result);
?>
```
returns
```
Array
(
[1] => bicycle
)
```
|
Is there a PHP function to remove any/all key/value pairs that have a certain value from an array?
|
[
"",
"php",
"arrays",
""
] |
I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely **different parts of the DOM** and mostly positioned using float.
All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever").
Best would be something like this:
```
var distance = getDistance(element1, element2);
```
or in jQuery notation:
```
var distance = $(element1).distanceTo($(element2));
```
|
I never used jQuery, just looked up API, so I can assume you can do the following:
```
var o1 = $(element1).offset();
var o2 = $(element2).offset();
var dx = o1.left - o2.left;
var dy = o1.top - o2.top;
var distance = Math.sqrt(dx * dx + dy * dy);
```
|
Using pure javascript.
```
var dx = obj1.offsetLeft - obj2.offsetLeft;
var dy = obj1.offsetTop - obj2.offsetTop;
var distance = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2));
```
|
Get relative position between 2 DOM elements using JavaScript
|
[
"",
"javascript",
"jquery",
"dom",
""
] |
In the spirit of [Best Practices: Always return a \_\_\_\_, never a \_\_\_\_](https://stackoverflow.com/questions/171156/best-practices-always-return-a-never-a), I face a similar question in my upcoming [migration from JDK1.4.2 to JDK5 and more](https://stackoverflow.com/questions/219164/generics-in-legacy-code). (Yes, I *know*, [JDK1.4.2 is EOL!](http://java.sun.com/products/archive/eol.policy.html) ;-) ).
For functions returning a collection (which are not simple [property collections](https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property)), I always prefer (in JDK1.4.2) returning an Array instead of a generic List, because:
* it enforces the returning type (`MyObject[]` instead of List of Objects, much more ***type-safe*** on a static -- as in 'compilation' -- level)
* it *suggests* a 'read-only' character to the returned collection (it is more complicated to add an element to the collection, even though this is not as rigorous as the 'read-only' keyword in c#). This is not the same as saying it is 'immutable' since the references inside the array can still be modified...
Of course, I do always *create* this returned array (I do not expose any 'internal' array)
Now, In JDK5 and more, I could use `List<MyObject>` if I want to.
**What are the good reasons for choosing to return `MyObject[]` instead of List or `Collection<MyObject>` when coding in java5 ?**
Bonus, if `Collection<MyObject>` is used, is it possible to:
* enforce a read-only attribute on the returned collection ? (no `add()` or `remove()` possible)
* enforce an immutable aspect to the returned collection ? (even the references of that collection can not be modified)
PS: The [JavaGenericFAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) did not quite have that one.
|
Prefer Collection (or List, or Set as appropriate) to an array. With generics you get the type-checking that was lacking pre-Java 5. Also, by exposing only the interface, you are free to change the implementation later (e.g. switch an ArrayList for a LinkedList).
Arrays and generics don't mix very well. So, if you want to take advantage of generics, you should *usually* avoid arrays.
I.e: You can't generically create an array. For example, if T is a generic type then "new T[0]" doesn't compile. You'd have to do something like "(T[]) new Object[0]", which generates an unchecked cast warning. For the same reason, you can't use generic types with varargs without warnings.
Using [Collections.unmodifiableCollection](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#unmodifiableCollection(java.util.Collection)) (and similar methods), you get the read-only constraint (which you can't achieve with an array - you would have to return a clone of the array).
You can't enforce immutability of members, but then you can't do that with an array either.
|
Actually arrays still have one advantage over Collections/Lists. Due to the way that Java implements Generics through type erasure, you cannot have two methods that take Collections as arguments yet only differ by the Collection's generic type.
Ex:
```
public void doSomething(Collection<String> strs) { ... }
public void doSomething(Collection<Integer> ints) { ... }
```
The two above methods will not compile because the javac compiler uses type erasure and thus cannot pass the type information to the JVM. The JVM will only see two methods that take a Collection as its argument.
In the above cases, the best work-around is to make the methods take arrays as their arguments and use the Collection/List's toArray() method when passing the arguments to them. If you still want to use Collection/List's inside the above methods, just use java.util.Arrays.asList() method to get your List back.
Ex:
```
public void doSomething(String[] strs) {
List<String> strList = Arrays.asList(strs);
...
}
public void doSomething(Integer[] ints) {
List<Integer> intList = Arrays.asList(ints);
...
}
public static void main(String[] args) {
List<String> strs = new ArrayList<String>();
List<Integer> ints = new ArrayList<Integer>();
obj.doSomething(strs.toArray());
obj.doSomething(ints.toArray());
}
```
|
API java 5 and more: should I return an array or a Collection?
|
[
"",
"java",
"arrays",
"api",
"generics",
"collections",
""
] |
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..
For example, compared to..
* [phpUnderControl](http://phpundercontrol.org/about.html)
* [Jenkins](http://jenkins-ci.org/content/about-jenkins-ci)
+ [Hudson](http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson)
* [CruiseControl.rb](http://cruisecontrolrb.thoughtworks.com/)
..and others, [BuildBot](http://buildbot.python.org/stable/) looks rather.. archaic
I'm currently playing with Hudson, but it is very Java-centric (although with [this guide](http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html), I found it easier to setup than BuildBot, and produced more info)
Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?
---
**Update:** Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with [Jenkins](http://jenkins-ci.org) is different.
***Update:*** After trying a few alternatives, I think I'll stick with Hudson. [Integrity](http://integrityapp.com/) was nice and simple, but quite limited. I think [Buildbot](http://buildbot.net/trac) is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.
Setting Hudson up for a Python project was pretty simple:
* Download Hudson from <http://hudson-ci.org/>
* Run it with `java -jar hudson.war`
* Open the web interface on the default address of `http://localhost:8080`
* Go to Manage Hudson, Plugins, click "Update" or similar
* Install the Git plugin (I had to set the `git` path in the Hudson global preferences)
* Create a new project, enter the repository, SCM polling intervals and so on
* Install `nosetests` via `easy_install` if it's not already
* In the a build step, add `nosetests --with-xunit --verbose`
* Check "Publish JUnit test result report" and set "Test report XMLs" to `**/nosetests.xml`
That's all that's required. You can setup email notifications, and [the plugins](http://wiki.hudson-ci.org/display/HUDSON/Plugins) are worth a look. A few I'm currently using for Python projects:
* [SLOCCount plugin](http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin) to count lines of code (and graph it!) - you need to install [sloccount](http://www.dwheeler.com/sloccount/) separately
* [Violations](http://wiki.hudson-ci.org/display/HUDSON/Violations) to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)
* [Cobertura](http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin) can parse the coverage.py output. Nosetest can gather coverage while running your tests, using `nosetests --with-coverage` (this writes the output to `**/coverage.xml`)
|
You might want to check out [Nose](http://somethingaboutorange.com/mrl/projects/nose/) and [the Xunit output plugin](http://nose.readthedocs.org/en/latest/plugins/xunit.html). You can have it run your unit tests, and coverage checks with this command:
```
nosetests --with-xunit --enable-cover
```
That'll be helpful if you want to go the Jenkins route, or if you want to use another CI server that has support for JUnit test reporting.
Similarly you can capture the output of pylint using the [violations plugin for Jenkins](https://wiki.jenkins-ci.org/display/JENKINS/Violations)
|
Don't know if it would do : [Bitten](http://bitten.edgewall.org/) is made by the guys who write Trac and is integrated with Trac. [Apache Gump](http://gump.apache.org/) is the CI tool used by Apache. It is written in Python.
|
"Pretty" Continuous Integration for Python
|
[
"",
"python",
"jenkins",
"continuous-integration",
"buildbot",
""
] |
I know that you can use a dummy "int" parameter on `operator++` and `operator--` to override the postfix versions of those operators, but I vaguely recall something about a dummy parameter that you could declare on a destructor. Does anyone know anything about that, and if so, what that dummy parameter did?
This was in my old Turbo C++ tutorial books, which I read when I was a teenager (i.e. a *long* time ago), so I might be completely misremembering it. That was also very early C++, before it was standardized, so it's possible that it was something Turbo C++-specific.
|
You're possibly thinking of the placement and nothrow forms of operator delete, which have the signatures:
```
void operator delete(void *, void *) throw();
void operator delete(void *, const std::nothrow_t&) throw();
void operator delete[](void *, void *) throw();
void operator delete[](void *, const std::nothrow_t&) throw();
```
These are never called during normal operation, but would be used in the case where the constructor for an object being constructed with [placement new](http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10) throws an exception. Generally you don't have to define them, since the compiler already called the destructor(s) on the dead object's bases and members, and for placement new there's no memory to be freed. But can exist if you are overloading placement new and need a corresponding operator.
The second argument is not really used, and just distinguishes the signature for the ordinary:
```
void operator delete(void *)
```
These aren't special dummy arguments the way the operator++ ones are, though. They're just an instance of the general rule that call to new with extra arguments, such as:
```
obj = new(x,y,z) Object(a,b,c)
```
will generate implicit code to clean up from constructor errors that passes those same additional arguments to the operator delete, which will function (approximately) like:
```
void *raw = operator new(sizeof(Object), x,y,z)
try {
obj = new(raw) Object(a,b,c);
} catch(...) {
operator delete(raw,x,y,z);
throw;
}
```
|
Either you are misremembering, or you should try to forget it. Destructors don't have parameters, return types and they shouldn't throw exceptions.
|
C++ class member functions that use dummy parameters
|
[
"",
"c++",
"parameters",
"destructor",
""
] |
Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what's wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same result.
```
public static void main(String[] args) {
String x = "10000000";
long l = new Long(x).longValue();
System.out.println("Long value: " + l);
Calendar c = new GregorianCalendar();
c.setTimeInMillis(l);
System.out.println("Calendar time in Millis: " + c.getTimeInMillis());
String origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in YYYY-MM-DD format: " + origDate);
x = "1000000000000";
l = new Long(x).longValue();
System.out.println("\nLong value: " + l);
c.setTimeInMillis(l);
System.out.println("Calendar time in Millis: " + c.getTimeInMillis());
origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
System.out.println("Date in YYYY-MM-DD format: " + origDate);
}
```
> Long value: 10000000
>
> Calendar time in Millis: 10000000
>
> Date in YYYY-MM-DD format: 1969-11-31
>
> Long value: 1000000000000
>
> Calendar time in Millis: 1000000000000
>
> Date in YYYY-MM-DD format: 2001-8-8
|
The dates you print from `Calendar` are local to your timezone, whereas the epoch is defined to be midnight of 1970-01-01 in UTC. So if you live in a timezone west of UTC, then your date will show up as 1969-12-31, even though (in UTC) it's still 1970-01-01.
|
First, `c.get(Calendar.MONTH)` returns 0 for Jan, 1 for Feb, etc.
Second, use `DateFormat` to output dates.
Third, your problems are a great example of how awkward Java's Date API is. Use Joda Time API if you can. It will make your life somewhat easier.
Here's a better example of your code, which indicates the timezone:
```
public static void main(String[] args) {
final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
long l = 10000000L;
System.out.println("Long value: " + l);
Calendar c = new GregorianCalendar();
c.setTimeInMillis(l);
System.out.println("Date: " + dateFormat.format(c.getTime()));
l = 1000000000000L;
System.out.println("\nLong value: " + l);
c.setTimeInMillis(l);
System.out.println("Date: " + dateFormat.format(c.getTime()));
}
```
|
Java.util.Calendar - milliseconds since Jan 1, 1970
|
[
"",
"java",
"calendar",
""
] |
How do I tell if my application (compiled in Visual Studio 2008 as *Any CPU*) is running as a 32-bit or 64-bit application?
|
```
if (IntPtr.Size == 8)
{
// 64 bit machine
}
else if (IntPtr.Size == 4)
{
// 32 bit machine
}
```
|
If you're using [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 4.0, it's a one-liner for the current process:
```
Environment.Is64BitProcess
```
Reference: *[Environment.Is64BitProcess Property](http://msdn.microsoft.com/en-us/library/system.environment.is64bitprocess.aspx)* (MSDN)
|
How do I tell if my application is running as a 32-bit or 64-bit application?
|
[
"",
"c#",
"64-bit",
"32-bit",
""
] |
I've got a Excel VSTO 2005 application I need to debug, I've tried attaching to the process EXCEL.EXE in Visual Studio 2005 to no avail.
Does anyone know what to do in order to debug managed code running in a VSTO Excel Application?
|
I haven't worked with Excel, but with VSTO in Word, attaching the debugger to the WINWORD process works, but makes it impossible to debug startup code, as it has already ran before you can attach. In this case you can insert
```
Debugger.Launch();
```
which will stop your code and ask to attach a debugger. It's about the best solution I could find.
|
I usually include a "StopSwitch" which launches the debugger when the stop-switch is enabled in the app.config file.
* *StopSwitch Stops Execution for Just-In-Time Debugging* at <http://missico.spaces.live.com/blog/cns!7178D2C79BA0A7E3!309.entry>)
After enabling the `StopSwitch`, sometimes the JIT Debugger is not launch because the problem occurs before the .NET Framework loads the assembly and executes the `Stop` statement.
|
How to I attach to a VSTO Excel Application Process to Debug?
|
[
"",
"c#",
"excel",
"vsto",
""
] |
How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)?
I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked.
I've been searching a lot but couldn't find a solution.
I guess this is a quite common question, how do you do that?
|
For normal DateTimes, if you don't initialize them at all then they will match `DateTime.MinValue`, because it is a value type rather than a reference type.
You can also use a nullable DateTime, like this:
```
DateTime? MyNullableDate;
```
Or the longer form:
```
Nullable<DateTime> MyNullableDate;
```
And, finally, there's a built in way to reference the default of any type. This returns `null` for reference types, but for our DateTime example it will return the same as `DateTime.MinValue`:
```
default(DateTime)
```
or, in more recent versions of C#,
```
default
```
|
If you're using .NET 2.0 (or later) you can use the nullable type:
```
DateTime? dt = null;
```
or
```
Nullable<DateTime> dt = null;
```
then later:
```
dt = new DateTime();
```
And you can check the value with:
```
if (dt.HasValue)
{
// Do something with dt.Value
}
```
Or you can use it like:
```
DateTime dt2 = dt ?? DateTime.MinValue;
```
You can read more here:
<http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx>
|
DateTime "null" / uninitialized value?
|
[
"",
"c#",
"datetime",
"null",
"initialization",
""
] |
I am building a fun little app to determine if I should bike to work.
I would like to test to see if it is either Raining or Thunderstorm(ing).
```
public enum WeatherType : byte
{ Sunny = 0, Cloudy = 1, Thunderstorm = 2, Raining = 4, Snowing = 8, MostlyCloudy = 16 }
```
I was thinking I could do something like:
```
WeatherType _badWeatherTypes = WeatherType.Thunderstorm | WeatherType.Raining;
if(currentWeather.Type == _badWeatherTypes)
{
return false;//don't bike
}
```
but this doesn't work because \_badWeatherTypes is a combination of both types. I would like to keep them separated out because this is supposed to be a learning experience and having it separate may be useful in other situations (IE, Invoice not paid reason's etc...).
I would also rather not do: (this would remove the ability to be configured for multiple people)
```
if(WeatherType.Thunderstorm)
{
return false; //don't bike
}
etc...
```
|
Your current code will say whether it's *exactly* "raining and thundery". To find out whether it's "raining and thundery and possibly something else" you need:
```
if ((currentWeather.Type & _badWeatherTypes) == _badWeatherTypes)
```
To find out whether it's "raining *or* thundery, and possibly something else" you need:
```
if ((currentWeather.Type & _badWeatherTypes) != 0)
```
EDIT (for completeness):
It would be good to use the `FlagsAttribute`, i.e. decorate the type with `[Flags]`. This is not necessary for the sake of this bitwise logic, but affects how `ToString()` behaves. The C# compiler ignores this attribute (at least at the moment; the C# 3.0 spec doesn't mention it) but it's generally a good idea for enums which are effectively flags, and it documents the intended use of the type. At the same time, the convention is that when you use flags, you pluralise the enum name - so you'd change it to `WeatherTypes` (because any actual value is effectively 0 or more weather types).
It would also be worth thinking about what "Sunny" really means. It's currently got a value of 0, which means it's the absence of everything else; you couldn't have it sunny and raining at the same time (which is physically possible, of course). Please don't write code to prohibit rainbows! ;) On the other hand, if in your real use case you genuinely want a value which means "the absence of all other values" then you're fine.
|
I'm not sure that it should be a flag - I think that you should have an range input for:
* Temperature
* How much it's raining
* Wind strength
* any other input you fancy (e.g. thunderstorm)
you can then use an algorithm to determine if the conditions are sufficiently good.
I think you should also have an input for how likely the weather is to remain the same for cycling home. The criteria may be different - you can shower and change more easliy when you get home.
If you really want to make it interesting, collect the input data from a weather service api, and evaulate the decision each day - Yes, I should have cycled, or no, it was a mistake. Then perhaps you can have the app learn to make better decisions.
Next step is to "socialize" your decision, and see whether other people hear you are making the same decisions.
|
Determining if enum value is in list (C#)
|
[
"",
"c#",
".net",
"enums",
""
] |
I've made a Django site, but I've drank the Koolaid and I want to make an *IPhone* version. After putting much thought into I've come up with two options:
1. Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.
2. Find some time of middleware that reads the user-agent, and changes the template directories dynamically.
I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation [discourages changing settings on the fly](http://docs.djangoproject.com/en/dev/topics/settings/). I found a [snippet](http://www.djangosnippets.org/snippets/1098/) that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.
Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?
**Update**
I went with a combination of middleware and tweaking the template call.
For the middleware, I used [minidetector](http://code.google.com/p/minidetector/). I like it because it detects a [plethora](http://www.youtube.com/watch?v=b6E682C7Jj4) of mobile user-agents. All I have to do is check request.mobile in my views.
For the template call tweak:
```
def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
```
I use this for any view that I know I have both versions.
**TODO:**
* Figure out how to access *request.mobile* in an extended version of render\_to\_response so I don't have to use check\_mobile('template\_name.html')
* Using the previous automagically fallback to the regular template if no mobile version exists.
|
Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render\_to\_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone.
|
Detect the user agent in middleware, switch the url bindings, profit!
How? Django request objects have a .urlconf attribute, which can be set by middleware.
From django docs:
> Django determines the root URLconf
> module to use. Ordinarily, this is the
> value of the ROOT\_URLCONF setting, but
> if the incoming HttpRequest object has
> an attribute called urlconf (set by
> middleware request processing), its
> value will be used in place of the
> ROOT\_URLCONF setting.
1. In yourproj/middlware.py, write a class that checks the http\_user\_agent string:
```
import re
MOBILE_AGENT_RE=re.compile(r".*(iphone|mobile|androidtouch)",re.IGNORECASE)
class MobileMiddleware(object):
def process_request(self,request):
if MOBILE_AGENT_RE.match(request.META['HTTP_USER_AGENT']):
request.urlconf="yourproj.mobile_urls"
```
2. Don't forget to add this to MIDDLEWARE\_CLASSES in settings.py:
```
MIDDLEWARE_CLASSES= [...
'yourproj.middleware.MobileMiddleware',
...]
```
3. Create a mobile urlconf, yourproj/mobile\_urls.py:
```
urlpatterns=patterns('',('r'/?$', 'mobile.index'), ...)
```
|
Change Django Templates Based on User-Agent
|
[
"",
"python",
"django",
"django-templates",
"mobile-website",
"django-middleware",
""
] |
Developing a website and just trying to get back into the swing of (clever) SQL queries etc, my mind had totally gone tonight!
There is a website <http://www.ufindus.com/> which has a textbox allowing you to enter either a place name or a postcode/zipcode. I am trying to do something similiar but I am rubbish at SQL - so how do you construct an SQL statement that could potentially look at 2 columns (i.e. place and postcode) because you can't query both fields for the same value e.g
```
place = 'YORK' AND postcode = 'YORK'
```
or
```
place = 'YO21 5EA' AND postcode = 'YO21 5EA'
```
so do you have to put some logic in to be intelligent enough to detect whether it looks like a place name or a postcode - that just seems too complicated to me!! Any help would be much appreciated.
|
You could use an "OR" to get the job done. For example,
place = 'YORK' or postcode = 'YORK'
You might also do better using the LIKE statement, as in
WHERE place LIKE 'YORK%' or postcode LIKE 'YORK%'
(this assumes both place and postcode are character-based columns)
|
why not use OR instead of AND?
```
place = @textboxvalue OR post = @textboxvalue
```
|
SQL - querying via a textbox which could take different values
|
[
"",
"asp.net",
"sql",
"sql-server",
""
] |
I'm trying to get this piece of code working a little better. I suspect it's the loop reading one byte at a time. I couldn't find another way of doing this with gzip decompression. Implementing a `StreamReader` is fine, but it returns a string which I can't pass to the decompression stream.
Is there a better way?
```
byte[] bufffer = null;
List<byte> resourceBytes = new List<byte>();
int byteValue = 0;
WebResource resource = new WebResource();
HttpWebResponse webResponse = null;
try {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(resourceUri);
webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
webRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
webRequest.UserAgent = agent;
webRequest.Accept = "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1";
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Referer = resourceUri.OriginalString;
webRequest.Timeout = 5000;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream webStream = webResponse.GetResponseStream();
if (!string.IsNullOrEmpty(webResponse.ContentEncoding)) {
if (webResponse.ContentEncoding.ToLower().Contains("gzip")) {
webStream = new GZipStream(webStream, CompressionMode.Decompress);
}
else if (webResponse.ContentEncoding.ToLower().Contains("deflate")) {
webStream = new DeflateStream(webStream, CompressionMode.Decompress);
}
}
do {
byteValue = webStream.ReadByte();
if (byteValue != -1) {
resourceBytes.Add((byte)byteValue);
}
} while (byteValue != -1);
//Free up resources
webStream.Close();
webResponse.Close();
bufffer = resourceBytes.ToArray();
```
|
I'd agree with jmcd that WebClient would be far simpler, in particular WebClient.DownloadData.
re the actual question, the problem is that you are reading single bytes, when you should probably have a fixed buffer, and loop - i.e.
```
int bytesRead;
byte[] buffer = new byte[1024];
while((bytesRead = webStream.Read(buffer, 0, buffer.Length)) > 0) {
// process "bytesRead" worth of data from "buffer"
}
```
[edit to add emphasis] The important bit is that you *only* process "bytesRead" worth of data each time; everything beyond there is garbage.
|
Is the [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx) class no use for what you want to do?
|
C# downloading a webpage. A better way needed, CPU usage high
|
[
"",
"c#",
"url",
"download",
"uri",
""
] |
Using the client-side ASP.NET AJAX library, I have created an instance of a client component with the $create shortcut-method (<http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx>). The object is attached to a DOM element. Now I need to get a reference to the instance, but it is neither registered on window or on the DOM element, and I cannot find it anywhere.
Does someone know how you can obtain a reference to the instance?
Best regards,
JacobE
|
Does the $find() routine find it?
|
According to MSDN, Sys.Component.Create should return the object that it just created. And, $create is just a shortcut for Sys.Component.create.
```
Returns: A new instance of a component that uses the specified parameters.
```
So, try:
```
var instance = $create(someType);
```
|
ASP.NET AJAX: How to get a client instance created with the $create method?
|
[
"",
"asp.net",
"javascript",
"ajax",
"asp.net-ajax",
"client-side",
""
] |
I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks
|
Since Twisted is event driven, you don't need a timeout per se. You simply need to set a state variable (like datagramRecieved) when you receive a datagram and register a [looping call](http://twistedmatrix.com/projects/core/documentation/howto/time.html) that checks the state variable, stops the reactor if appropriate then clears state variable:
```
from twisted.internet import task
from twisted.internet import reactor
datagramRecieved = False
timeout = 1.0 # One second
# UDP code here
def testTimeout():
global datagramRecieved
if not datagramRecieved:
reactor.stop()
datagramRecieved = False
l = task.LoopingCall(testTimeout)
l.start(timeout) # call every second
# l.stop() will stop the looping calls
reactor.run()
```
|
I think `reactor.callLater` would work better than `LoopingCall`. Something like this:
```
class Protocol(DatagramProtocol):
def __init__(self, timeout):
self.timeout = timeout
def datagramReceived(self, datagram):
self.timeout.cancel()
# ...
timeout = reactor.callLater(5, timedOut)
reactor.listenUDP(Protocol(timeout))
```
|
Is it possible to set a timeout on a socket in Twisted?
|
[
"",
"python",
"networking",
"sockets",
"twisted",
""
] |
Trends data from Twitter Search API in JSON.
Grabbing the file using:
```
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
```
How do I work with data from this object. As an array? Only really need to extract data from the [name] values.
JSON object contains:
```
stdClass Object
(
[trends] => Array
(
[0] => stdClass Object
(
[name] => Vote
[url] => http://search.twitter.com/search?q=Vote
)
[1] => stdClass Object
(
[name] => Halloween
[url] => http://search.twitter.com/search?q=Halloween
)
[2] => stdClass Object
(
[name] => Starbucks
[url] => http://search.twitter.com/search?q=Starbucks
)
[3] => stdClass Object
(
[name] => #flylady
[url] => http://search.twitter.com/search?q=%23flylady
)
[4] => stdClass Object
(
[name] => #votereport
[url] => http://search.twitter.com/search?q=%23votereport
)
[5] => stdClass Object
(
[name] => Election Day
[url] => http://search.twitter.com/search?q=%22Election+Day%22
)
[6] => stdClass Object
(
[name] => #PubCon
[url] => http://search.twitter.com/search?q=%23PubCon
)
[7] => stdClass Object
(
[name] => #defrag08
[url] => http://search.twitter.com/search?q=%23defrag08
)
[8] => stdClass Object
(
[name] => Melbourne Cup
[url] => http://search.twitter.com/search?q=%22Melbourne+Cup%22
)
[9] => stdClass Object
(
[name] => Cheney
[url] => http://search.twitter.com/search?q=Cheney
)
)
[as_of] => Mon, 03 Nov 2008 21:49:36 +0000
)
```
|
You mean something like this?
```
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}
```
|
If you use `json_decode($string, true)`, you will get no objects, but everything as an associative or number indexed array. Way easier to handle, as the stdObject provided by PHP is nothing but a dumb container with public properties, which cannot be extended with your own functionality.
```
$array = json_decode($string, true);
echo $array['trends'][0]['name'];
```
|
Handling data in a PHP JSON Object
|
[
"",
"php",
"json",
""
] |
I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?
```
def by_tag(tag):
return '''
function(doc) {
if (doc.tags.length > 0) {
for (var tag in doc.tags) {
if (doc.tags[tag] == "%s") {
emit(doc.published, doc)
}
}
}
};
''' % tag
```
|
*Disclaimer: I didn't test this and don't know if it can perform better.*
Create a single perm view:
```
function(doc) {
for (var tag in doc.tags) {
emit([tag, doc.published], doc)
}
};
```
And query with
\_view/your\_view/all?startkey=['your\_tag\_here']&endkey=['your\_tag\_here', {}]
Resulting JSON structure will be slightly different but you will still get the publish date sorting.
|
You can define a single permanent view, as Bahadir suggests. when doing this sort of indexing, though, *don't* output the doc for each key. Instead, emit([tag, doc.published], null). In current release versions you'd then have to do a separate lookup for each doc, but SVN trunk now has support for specifying "include\_docs=True" in the query string and CouchDB will automatically merge the docs into your view for you, without the space overhead.
|
How to build "Tagging" support using CouchDB?
|
[
"",
"python",
"couchdb",
"tagging",
"document-oriented-db",
""
] |
By default, objects (tables, stored procedures, etc) are set up with the dbo owner/schema (I think ms sql 2000 calls it owner, while ms sql 2005 calls it schema)
The owner/schema is really a role or user in the database. I've always left the default of dbo, but I've recently seen some examples in microsoft training books where some of their tables & stored procedures had different owners/schemas. When is it beneficial to do this and why?
|
The use of schemas is exceptionally beneficial when you have security concerns.
If you have multiple applications that access the database, you might not want to give the Logistics department access to Human Resources records. So you put all of your Human Resources tables into an hr schema and only allow access to it for users in the hr role.
Six months down the road, Logistics now needs to know internal expense accounts so they can send all of these palettes of blue pens to the correct location people. You can then create a stored procedure that executes as a user that has permission to view the hr schema as well as the logistics schema. The Logistics users never need to know what's going on in HR and yet they still get their data.
You can also use schemas the way cfeduke has suggested and just use them to group things in the object browser. If you are doing this, just be careful because you might end up creating Person.Address and Company.Address when you really just need a single dbo.Address (I'm not knocking your example, cfeduke, just using it to illustrate that both address tables might be the same or they might be different and that YMMV).
|
I've used schemas in the past sort of like namespaces so you could have multiple entities named Address (`[Person].[Address]`, `[Company].[Address]`). The advantage to this is visual organization in SQL Management Studio, you can get the same thing by putting everything under one schema and naming tables with a single identifier (i.e. `[dbo].[PersonAddress]`).
I've also used them for developer vs. developer development prior to running SQL Server Developer Edition on all our dev machines (back when we had a centralized development database earlier in my career).
|
Schema, Owner for objects in MS SQL
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
"sql-server-2000",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.