Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm writing a Firefox extension that needs to know what the username of the currently logged in user is in Windows, Mac, or Linux. So if I'm logged into my machine as "brh", it'll return "brh". Any idea how to do that from extension JavaScript? | Firefox extensions play by different rules to normal JavaScript running in the page: finding the current user is absolutely possible.
Open your Error Console (in Tools) and enter this:
```
Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment).get('USER')
```
The environment variables Firefox was started with are available through that [NsIEnvironment XPCOM component](https://developer.mozilla.org/en/NsIEnvironment).
You may have to customise this per platform. If all else fails, you might be able to create an [NsIFile](https://developer.mozilla.org/en/NsIFile) in `~` then look at its `.path`; I'm not sure if shell expressions are honoured there, though... | The flagged correct answer works fine. I use this in our extension on Firefox 38. I also use events so that the page can communicate with the extension and retrieve windows properties from the extension.
getWindowsProperty: function(prop){
return Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment).get(prop);
}, | Finding the currently logged in user from a Firefox extension | [
"",
"javascript",
"firefox",
"xul",
""
] |
I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor.
Right now, I'm controlling this from the view:
```
parent_candidates = list(Category.objects.all())
pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()]
```
where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids.
There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned\_parent\_list to get the options, when I'd really rather just specify a widget.
Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option? | If I understand your predicament correctly, the problem itself lies with the way you're dealing with which categories can be parents and which ones can't. One option to avoid these problems is to actually limit the level of categories which can become parents. For example, let's say you have the following categories:
* Internet
+ Google
+ Yahoo
* Offline
+ MS Office
+ OpenOffice
The way I usually handle this is I obviously have a parent\_id FK on the categories table. For the root elements (Internet, Offline), the parent\_id would be 0. So, when in your view you're trying to retrieve the "parent categories" for the dropdown, you need to decide how far down can they keep nesting. I mostly limit this to the first level, so to choose which categories to show in your dropdown, you'd do something like:
```
parents = Category.objects.filter(parent_id=0)
```
Now obviously, this limits the approach somewhat, but you can increase the level you'd like to include and work out some kind of visual identification system in your template for the dropdown (including extra spaces or dashes for each level in the hierarchy or something).
Anyway, sorry about the long response, and hopefully this addressed your issue somewhat. | Take a look at the [django-treebeard](http://code.google.com/p/django-treebeard/) app. | ForeignKey form restrictions in Django | [
"",
"python",
"django",
"django-forms",
""
] |
If I'm using a `Hashtable`, I can write code like this:
```
object item = hashtable[key] ?? default_value;
```
That works whether or not `key` appears in the `Hashtable`.
I can't do that with a `Dictionary<TKey. TValue>`. If the key's not present in the dictionary, that will throw a `KeyNotFoundException`. So I have to write code like this:
```
MyClass item;
if (!(dict.TryGetValue(key, out item))
{
item = default_value;
}
```
I'm wondering why this is. `Dictionary<TKey, TValue>` is just a wrapper around `Hashtable`. Why has this restriction been added to it?
**Edit:**
For another perspective on PopCatalin's answer (see below), the code I'd written above won't work if the dictionary's values are of a value type. If I'm using a `Dictionary<int, int>`, then the code I would *like* to use looks like this:
```
int i = dict[key] ?? default_value;
```
And that won't compile, because `dict[key]` isn't a nullable or reference type. | The difference between a `Dictionary<T>` and a `Hashtable` is that a `Dictionary<T>` is a generic type that can specialize to store value types along reference types.
The hashtable can only store reference types (a `Object` passed by reference) and only value types that are boxed (also passed by reference).
When a dictionary is specialized with value types, it must return those values 'by value' not by reference.So, therefore, a `Dictionary<T>` can't return null, as null is **not a valid value** for value types. | There is one misconception in your post. Dictionary is not a wrapper around Hashtable. It's a completely different implementation.
The reason why this change was made is mainly justified by one assertion: Null is a valid value for a hashtable. Without this change it's not possible to distinguish between a non-exsistent key and a value key with a null value using the [] method of access. Dictionary clears this up. | Why doesn't a Dictionary access nonexistent keys like a Hashtable does? | [
"",
"c#",
".net",
"dictionary",
"hashtable",
""
] |
```
$pee = preg_replace( '|<p>|', "$1<p>", $pee );
```
This regular expression is from the Wordpress source code (formatting.php, wpautop function); I'm not sure what it does, can anyone help?
Actually I'm trying to port this function to Python...if anyone knows of an existing port already, that would be much better as I'm really bad with regex. | wordpress really calls a variable "pee" ?
I'm not sure what the $1 stands for (there are no braces in the first parameter?), so I don't think it actually does anything, but i could be wrong. | The preg\_replace() function - somewhat confusingly - allows you to use other delimiters besides the standard "/" for regular expressions, so
```
"|<p>|"
```
Would be a regular expression just matching
```
"<p>"
```
in the text. However, I'm not clear on what the replacement parameter of
```
"$1<p>"
```
would be doing, since there's no grouping to map to $1. It would seem like as given, this is just replacing a paragraph tag with an empty string followed by a paragraph tag, and in effect doing nothing.
Anyone with more in-depth knowledge of PHP quirks have a better analysis? | What does this Regular Expression do | [
"",
"php",
"regex",
"wordpress",
""
] |
I've been working with jQuery for a pair of weeks and I've noticed it works fine with objects that are in the original HTML document, but when I generate a new element using jQuery the library doesn't get any of its events.
Let's say I try to run something like this:
```
$('.whatever').click(function() {
alert("ALERT!");
});
```
If the HTML does have something like this:
```
<span class="whatever">Whatever</span>
```
Then clicking on the word `Whatever` gets me a nice alert.
But if the `span` element is added dynamically using jQuery, nothing happens when clicking on it.
Is there a way to make jQuery work with those elements, somehow? | Thats because the :
(corrected)
```
$('.whatever').click(function() {
alert("ALERT!");
});
```
Means, in literal terms:
```
Find all elements currently on the page that have the class ".whatever"
Foreach element in that result set, bind this function to its click event
```
so naturally, adding a new DOM element wont automagically apply the click.
the best way to solve this is create bindings during your insert phase, ie:
```
var x = document.createElement("span");
$(x).click(function(){ }); //etc
$(somcontiner).append(x);
```
### Warning on simply rebinding everything
If done wrong, it can lead to undesired effects, ie, making the number of times the event triggers something increase. To stop this, you may need to first unbind them to delete the previous passes binds.
ie,
```
$(x).click(foo);
$(x).click(bar); //foo and bar should both execute.
```
so to stop this, you need
```
$(x).unbind("click");
$(x).click(foo);
```
in the rebind. | If you have jQuery 1.3 or later, try using [live](http://docs.jquery.com/Events/live) for adding events to dynamically generated elements:
```
$('.whatever').live("click", function() {
alert("ALERT!");
});
``` | jQuery with elements generated dynamically | [
"",
"javascript",
"jquery",
""
] |
I've got a C++ program that's likely to generate a HUGE amount of data -- billions of binary records of varying sizes, most probably less than 256 bytes but a few stretching to several K. Most of the records will seldom be looked at by the program after they're created, but some will be accessed and modified regularly. There's no way to tell which are which when they're created.
Considering the volume of data, there's no way I can store it all in memory. But as the data only needs to be indexed and accessed by its number (a 64-bit integer), I *don't* want the overhead of a full-fledged database program. Ideally I'd like to treat it as an `std::map` with its data stored on disk until requested.
Is there an already-written library that will do what I'm looking for, or do I need to write it myself?
EDIT: After some thought, I realized that Rob Walker's answer had a valid point: I'd be hard-pressed to get anywhere near the same kind of data integrity out of a home-brew class that I'd get from a real database.
Although BerkeleyDB (as suggested by RHM) looks like it would do exactly what we're looking for, the dual-licensing is a headache that we don't want to deal with. When we're done with the code and can prove that it would benefit noticeably from BerkeleyDB (which it probably would), we'll reexamine the issue.
I did look at Ferruccio's suggestion of stxxl, but I wasn't able to tell how it would handle the program being interrupted and restarted (maybe with changes). With that much data, I'd hate to just scrap what it had already completed and start over every time, if some of the data could be saved.
So we've decided to use an SQLite database, at least for the initial development. Thanks to everyone who answered or voted. | I doubt you will find a library that meets your requirements exactly, so you'll have to decide on what 'features' are really important to you and then decide if an existing DB solution comes close enough.
Billions of records is a large dataset by any stretch. What rate are records generated at? How long do they persist? Does the access pattern change over time?
Are updates always with the same amount of data as the original?
I would suggest proving definitively that a DB solution isn't going to work before starting to roll your own, particularly if integrity of the data is paramount (and it usually is...) Maintaining that volume of data on disk reliably can definitely be a challenge. Do you need any kind of transaction semantics when changing the data? Is the client multithreaded? | Take a look at [STXXL](http://stxxl.sourceforge.net/).
`stxxl::map<>` looks like it does exactly what you need. | Store huge std::map, mostly on disk | [
"",
"c++",
"data-structures",
""
] |
My product opens a web browser and points it at an HTML file containing a local Flash application. How do I detect programmatically whether this file loaded successfully and if not what exception was thrown? Is there a way to do this using Javascript?
Checking externally whether the file exists on disk is not enough because I've seen other failures occur (race conditions might be involved). | Answering my own question: <https://sourceforge.net/forum/message.php?msg_id=5929756>
1. Define a Javascript function that should be invoked if Flash loaded.
2. Invoke this method from the top of your Flash file.
3. Use a timer to detect if the callback is never invoked.
4. Prefer invoking Javascript functions from Flash rather than invoking Flash functions from Javascript. Either way you cannot invoke a function that has not been loaded yet. It is far easier to guarantee that the browser has finished loading your Javascript function before invoking it from Flash, than guaranteeing that Flash finished loading your Flash function before invoking it from Javascript.
Here is an example:
* I am using [swfobject](http://code.google.com/p/swfobject/) to embed Flash.
* I use FlashVars to tell Flash which Javascript function to invoke. This is useful if there are multiple Flash objects on the page.
**Flash**
```
var params:Object = LoaderInfo(this.root.loaderInfo).parameters;
if (ExternalInterface.available)
{
var onLoaded:String = params["onLoaded"];
if (onLoaded != null)
ExternalInterface.call(onLoaded, true);
}
```
**Javascript**
```
var flashLoaded = false;
var flashTimer;
function onFlashLoaded()
{
flashLoaded = true;
clearTimeout(flashTimer);
}
function onFlashTimeout()
{
if (!isFlashLoaded)
{
// Remove the Flash object in case it is partially loaded
$("#videoFeed").empty();
$("#videoFeed").append('<div id="flashObject"></div>');
alert("Failed to load video player");
}
clearTimeout(flashTimer);
}
function connectToVideo()
{
var flashvars = {};
flashvars.onLoaded = "onFlashLoaded";
var params = {};
params.menu = false;
var attributes = {};
isFlashLoaded = false;
flashTimer = setTimeout("onFlashTimeout()", 5000);
swfobject.embedSWF("flash/VideoFeed.swf", "flashObject", "800", "600", "11", "expressInstall.swf", flashvars, params, attributes);
}
``` | In cases where you cannot modify the swf and adding an ExternalInterface is not an option, you can still use Javascript to get the status of the swf. For example, you can call document.getElementById(swf\_id).PercentLoaded() from Javascript, and wait for it to be 100.
That won't tell you what exception was thrown if the swf failed to load, but at least you will know for sure whether it loaded. Other useful calls are found here:
<http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html> | Detect if Flash application loaded correctly using Javascript? | [
"",
"javascript",
"flash",
""
] |
I was trying to check out a project from SVN using Eclipse. I tried using "Checkout As" to make it into a "Java project from existing Ant script", but the project wizard requires the file to have already been downloaded. Is there a way to checkout the project into Eclipse as a Java project, without having to download it elsewhere first?
(I am using Eclipse Ganymade 3.4.1 with Subversive.) | If it wasn't checked in as a Java Project, you can add the java nature as shown [here](http://enarion.net/programming/tools/eclipse/changing-general-project-to-java-project/). | Here are the steps:
* Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here:
<http://subclipse.tigris.org/install.html>
* Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
* Select your project's root folder and select checkout as a project in the workspace.
It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature), | How do I check out an SVN project into Eclipse as a Java project? | [
"",
"java",
"eclipse",
"svn",
"ant",
"subversive",
""
] |
Has anyone seen anything in Tix work under python 3.0? I've tried to work through the examples but when creating anything it states that cnf is unsubscriptable.
I also noticed that none of the Dir Select stuff (DirList DirTree) works under 2.6.1.
Why doesn't Python either dump Tix or support it? Its got a lot of good stuff to make easy programs. | Likely what happened is that no one noticed the bug. (It's very hard to automatically test GUI libraries like Tix and Tkinter.) You should report bugs as you find them to <http://bugs.python.org>. | Generally speaking, if you're using third-party modules, you're better off avoiding Python 3.0 for now. If you're working on a third-party module yourself, porting forward to Python 3.0 is a good idea, but for the time being general development in it is just going to be a recipe for pain. | Tix and Python 3.0 | [
"",
"python",
"python-3.x",
"tix",
""
] |
I'm doing a bookmarking system and looking for the fastest (easiest) way to retrieve a page's title with PHP.
It would be nice to have something like `$title = page_title($url)` | ```
<?php
function page_title($url) {
$fp = file_get_contents($url);
if (!$fp)
return null;
$res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches);
if (!$res)
return null;
// Clean up title: remove EOL's and excessive whitespace.
$title = preg_replace('/\s+/', ' ', $title_matches[1]);
$title = trim($title);
return $title;
}
?>
```
Gave 'er a whirl on the following input:
```
print page_title("http://www.google.com/");
```
Outputted: Google
Hopefully general enough for your usage. If you need something more powerful, it might not hurt to invest a bit of time into researching HTML parsers.
EDIT: Added a bit of error checking. Kind of rushed the first version out, sorry. | You can get it without reg expressions:
```
$title = '';
$dom = new DOMDocument();
if($dom->loadHTMLFile($urlpage)) {
$list = $dom->getElementsByTagName("title");
if ($list->length > 0) {
$title = $list->item(0)->textContent;
}
}
``` | Fastest way to retrieve a <title> in PHP | [
"",
"php",
"html",
"parsing",
""
] |
Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()?
Is there a particular use for an empty Guid? | > Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()?
Short answer: Because the language/runtime didn't let the designer of the Guid type define a default constructor.
It's not only conventional that the value of a "default-constructed" struct is zero, you simply cannot define a default constructor for a struct. When you say new Guid() the runtime gives you a new object where all the fields are initialized to their default values: <http://msdn.microsoft.com/en-us/library/ah19swz4%28VS.71%29.aspx>
Some rationale can be found here: <https://web.archive.org/web/20131102220804/http://www.yoda.arachsys.com/csharp/faq/#struct.constructors> | This behavior is consistent with the rest of the value types in the .Net framework. When "newing up" a value type, a default value is used. This just happens to be the default for Guid similar to Int32's default value of 0. | Why does the parameterless Guid constructor generate an empty GUID? | [
"",
"c#",
".net",
"guid",
"default-constructor",
""
] |
I'm working on a Python library that interfaces with a web service API. Like many web services I've encountered, this one requests limiting the rate of requests. I would like to provide an optional parameter, `limit`, to the class instantiation that, if provided, will hold outgoing requests until the number of seconds specified passes.
I understand that the general scenario is the following: an instance of the class makes a request via a method. When it does, the method emits some signal that sets a lock variable somewhere, and begins a countdown timer for the number of seconds in `limit`. (In all likelihood, the lock is the countdown timer itself.) If another request is made within this time frame, it must be queued until the countdown timer reaches zero and the lock is disengaged; at this point, the oldest request on the queue is sent, and the countdown timer is reset and the lock is re-engaged.
Is this a case for threading? Is there another approach I'm not seeing?
Should the countdown timer and lock be instance variables, or should they belong to the class, such that all instances of the class hold requests?
Also, is this generally a bad idea to provide rate-limiting functionality within a library? I reason since, by default, the countdown is zero seconds, the library still allows developers to use the library and provide their own rate-limiting schemes. Given any developers using the service will need to rate-limit requests anyway, however, I figure that it would be a convenience for the library to provide a means of rate-limiting.
Regardless of placing a rate-limiting scheme in the library or not, I'll want to write an application using the library, so suggested techniques will come in handy. | This works out better with a queue and a dispatcher.
You split your processing into two sides: **source** and **dispatch**. These can be separate threads (or separate processes if that's easier).
The **Source** side creates and enqueues requests at whatever rate makes them happy.
The **Dispatch** side does this.
1. Get the request start time, *s*.
2. Dequeues a request, process the request through the remote service.
3. Get the current time, *t*. Sleep for *rate* - (*t* - *s*) seconds.
If you want to run the **Source** side connected directly to the remote service, you can do that, and bypass rate limiting. This is good for internal testing with a mock version of the remote service.
The hard part about this is creating some representation for each request that you can enqueue. Since the Python [Queue](https://docs.python.org/2/library/queue.html) will handle almost anything, you don't have to do much.
If you're using multi-processing, you'll have to [pickle](https://docs.python.org/2/library/pickle.html) your objects to put them into a pipe. | Don't reinvent the wheel, unless it's called for. Check the awesome library [ratelimit](https://pypi.org/project/ratelimit/). Perfect if you just want to rate limit your calls to an rest api for whatever reason and get on with your life.
```
from datetime import timedelta
from ratelimit import limits, sleep_and_retry
import requests
@sleep_and_retry
@limits(calls=1, period=timedelta(seconds=60).total_seconds())
def get_foobar():
response = requests.get('https://httpbin.org/get')
response.raise_for_status()
return response.json()
```
This will *block* the thread if more requests than one per minute is issued. | How to limit rate of requests to web services in Python? | [
"",
"python",
"web-services",
"rate-limiting",
""
] |
I'm working on a small GreaseMonkey script where I would like to embed a jQuery plugin (Markitup) so that the script is fully self contained (images + js) except for jQuery which is served from google.
I found the site <http://www.greywyvern.com/code/php/binary2base64> which says that you can embed javascript with the href if you base64 encode the script, much like serving images as basse64 from CSS.
```
<script type="text/javascript" href="data:text/javascript;base64,dmFyIHNjT2JqMSA9IG5ldyBzY3Jv..."></script>
```
So i tried that but couldn't get it to work at all, using Firefox 3.0.5 on OS X.
I put together a small test page to isolate the problem but couldn't get it to work at that page either.
```
<!DOCTYPE HTML>
<html>
<head>
<title>Title</title>
<meta charset="utf-8">
</head>
<body>
<script href="data:text/javascript;base64,YWxlcnQoJ2FzYWRhc2QnKTsK"></script>
<script>alert('a');</script>
</body>
</html>
```
The base64 string (YWxlcnQoJ2FzYWRhc2QnKTsK) says `alert('asadasd');` so I'm supposed to get two alerts but the only one I see is the second one where the alert is located as text inside the script tag.
Am I doing something wrong or why isn't this working, any ideas? | maybe just a thought but maybe the "href" should be "src" instead. | If you'd check script tag syntax you'd get
```
<script src="..."
^^^
src NOT href
```
Using data URIs here doesn't work in IE 6 btw. | Embed javascript as base64 | [
"",
"javascript",
"embed",
"base64",
""
] |
I'm considering using Annotations to define my Hibernate mappings but have run into a problem: I want to use a base entity class to define common fields (including the ID field) but I want different tables to have different ID generation strategies:
```
@MappedSuperclass
public abstract class Base implements Serializable {
@Id
@Column(name="ID", nullable = false)
private Integer id;
public Integer getId(){return id;}
public void setId(Integer id){this.id = id;}
...
}
@Entity
@Table(name="TABLE_A")
public class TableA extends Base {
// Table_A wants to set an application-defined value for ID
...
}
@Entity
@Table(name="TABLE_B")
public class TableB extends Base {
// How do I specify @GeneratedValue(strategy = AUTO) for ID here?
...
}
```
Is there some way to do this? I've tried including the following into `TableB` but hibernate objected to my having the same column twice and it seems wrong:
```
@Override // So that we can set Generated strategy
@Id
@GeneratedValue(strategy = AUTO)
public Integer getId() {
return super.getId();
}
``` | In the code above, it looks like you're mixing annotations on fields (superclass) and methods (subclass). The Hibernate [reference documentation](http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/#entity-mapping-entity) recommends avoiding this, and I suspect it might be causing the problem. In my experience with Hibernate, it's safer and more flexible to annotate getter/setter methods instead of fields anyway, so I suggest sticking to that design if you can.
As a solution to your problem, I recommend removing the **id** field from your Base superclass altogether. Instead, move that field into the subclasses, and create abstract **getId()** and **setId()** methods in your Base class. Then override/implement the **getId()** and **setId()** methods in your subclasses and annotate the getters with the desired generation strategy.
Hope this helps. | On the method in the child dont add the second @Id tag.
```
@Override // So that we can set Generated strategy
@GeneratedValue(strategy = AUTO)
public Integer getId() {
return super.getId();
}
``` | How do I override the GenerationType strategy using Hibernate/JPA annotations? | [
"",
"java",
"hibernate",
"jpa",
"annotations",
""
] |
Why are static indexers disallowed in C#? I see no reason why they should not be allowed and furthermore they could be very useful.
For example:
```
public static class ConfigurationManager
{
public object this[string name]
{
get => ConfigurationManager.getProperty(name);
set => ConfigurationManager.editProperty(name, value);
}
/// <summary>
/// This will write the value to the property. Will overwrite if the property is already there
/// </summary>
/// <param name="name">Name of the property</param>
/// <param name="value">Value to be wrote (calls ToString)</param>
public static void editProperty(string name, object value)
{
var ds = new DataSet();
var configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);
ds.ReadXml(configFile);
if (ds.Tables["config"] == null)
ds.Tables.Add("config");
var config = ds.Tables["config"];
if (config.Rows[0] == null)
config.Rows.Add(config.NewRow());
if (config.Columns[name] == null)
config.Columns.Add(name);
config.Rows[0][name] = value.ToString();
ds.WriteXml(configFile);
configFile.Close();
}
public static void addProperty(string name, object value) =>
ConfigurationManager.editProperty(name, value);
public static object getProperty(string name)
{
var ds = new DataSet();
var configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);
ds.ReadXml(configFile);
configFile.Close();
if (ds.Tables["config"] == null) return null;
var config = ds.Tables["config"];
if (config.Rows[0] == null) return null;
if (config.Columns[name] == null) return null;
return config.Rows[0][name];
}
}
```
The above code would benefit greatly from a static indexer. However it won't compile because static indexers are not allowed. Why is this so? | Indexer notation requires a reference to `this`. Since static methods don't have a reference to any particular instance of the class, you can't use `this` with them, and consequently you can't use indexer notation on static methods.
The solution to your problem is using a singleton pattern as follows:
```
public class Utilities
{
private static ConfigurationManager _configurationManager = new ConfigurationManager();
public static ConfigurationManager ConfigurationManager => _configurationManager;
}
public class ConfigurationManager
{
public object this[string value]
{
get => new object();
set => // set something
}
}
```
Now you can call `Utilities.ConfigurationManager["someKey"]` using indexer notation. | I believe it was considered not to be terribly useful. I think it's a shame too - an example I tend to use is Encoding, where `Encoding.GetEncoding("foo")` could be `Encoding["Foo"]`. I don't think it would come up *very* often, but aside from anything else it just feels a little inconsistent not to be available.
I would have to check, but I *suspect* it's available in IL (Intermediate Language) already. | Static Indexers? | [
"",
"c#",
".net",
"static",
"indexer",
"static-indexers",
""
] |
What's the best way to handle data entered through dynamically generated controls in ASP.NET?
Currently, I have a group of controls that are generated in the Page\_Load stage, and I need to access the data from them. It seems like it might be possible to just use a hidden field that's read and parsed on postback, but I'd like to know if there's a better way to do it that makes better use of the framework. | The key is recreating the controls on postback.
[Old but good article](https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx) to explain how and why.
You can also use the request.form collection to grab the posted values. | [redsquare](https://stackoverflow.com/users/6440/redsquare) is right. If you can just remember that ASP.Net is a lie wrapped around Http then you will be ok. The browser doesn't really care that MS neatly abstracts the Http Request/Response away from you in the form of Web Controls. It only knows that it needs to wrap up each of the form variables and their respective values and send them back to the server via Http. | Handling dynamically generated controls in asp.net | [
"",
"c#",
"asp.net",
""
] |
When trying to compile my class I get an error:
> The constant `'NamespaceName.ClassName.CONST_NAME'` cannot be marked static.
at the line:
```
public static const string CONST_NAME = "blah";
```
I could do this all of the time in Java. What am I doing wrong? And why doesn't it let me do this? | A `const` object is always `static`. | From the [C# language specification](http://www.ecma-international.org/publications/standards/Ecma-334.htm) *(PDF page 287 - or 300th page of the PDF):*
> Even though constants are considered
> static members, a constant
> declaration neither requires nor
> allows a static modifier. | Why can't I have "public static const string S = "stuff"; in my Class? | [
"",
"c#",
"constants",
""
] |
I am trying to generate some code at runtime using the DynamicMethod class in the Reflection.Emit namespace but for some reason its throwing a "VerificationException". Here is the IL code I am trying to use...
```
ldarg.1
ldarg.0
ldfld, System.String FirstName
callvirt, Void Write(System.String)
ldarg.1
ldarg.0
ldfld, System.String LastName
callvirt, Void Write(System.String)
ldarg.1
ldarg.0
ldfld, Int32 Age
callvirt, Void Write(Int32)
ret
```
I need a way to debug the generated IL code. What options do I have? I am using VS2008 professional. | I have found some more help here...
[DebuggerVisualizer for DynamicMethod (Show me the IL)](http://blogs.msdn.com/haibo_luo/archive/2005/10/25/484861.aspx) It's is a debugger visualizer using which you will be able to see the generated IL at runtime!
And even better is [Debugging LCG](http://blogs.msdn.com/yirutang/archive/2005/05/26/422373.aspx) which allows you to debug the generated code at runtime using Windbg! | Try using the [peverify](http://msdn.microsoft.com/en-us/library/62bwd2yd(VS.80).aspx) tool to check the IL. From MSDN:
> peverify.exe performs comprehensive
> MSIL verification checks based on
> dataflow analysis plus a list of
> several hundred rules on valid
> metadata. For detailed information on
> the checks Peverify.exe performs, see
> the "Metadata Validation
> Specification" and the "MSIL
> Instruction Set Specification" in the
> Tools Developers Guide folder in the
> .NET Framework SDK.
You'll need to save the generated code to disk as an assembly for this to be useful though. | How do I debug IL code generated at runtime using Reflection.Emit | [
"",
"c#",
".net",
"vb.net",
""
] |
Is it possible to create a stored procedure as
```
CREATE PROCEDURE Dummy
@ID INT NOT NULL
AS
BEGIN
END
```
Why is it not possible to do something like this? | Parameter validation is not currently a feature of procedural logic in SQL Server, and NOT NULL is only one possible type of data validation. The CHAR datatype in a table has a length specification. Should that be implemented as well? And how do you handle exceptions? There is an extensive, highly developed and somewhat standards-based methodology for exception handling in table schemas; but not for procedural logic, probably because procedural logic is defined out of relational systems. On the other hand, stored procedures already have an existing mechanism for raising error events, tied into numerous APIs and languages. There is no such support for declarative data type constraints on parameters. The implications of adding it are extensive; especially since it's well-supported, and extensible, to simply add the code:
```
IF ISNULL(@param) THEN
raise error ....
END IF
```
The concept of NULL in the context of a stored procedure isn't even well-defined especially compared to the context of a table or an SQL expression. And it's not Microsoft's definition. The SQL standards groups have spent a lot of years generating a lot of literature establishing the behavior of NULL and the bounds of the definitions for that behavior. And stored procedures isn't one of them.
A stored procedure is designed to be as light-weight as possible to make database performance as efficient as possible. The datatypes of parameters are there not for validation, but to enable the compiler to give the query optimizer better information for compiling the best possible query plan. A NOT NULL constraint on a parameter is headed down a whole nother path by making the compiler more complex for the new purpose of validating arguments. And hence less efficient and heavier.
There's a reason stored procedures aren't written as C# functions. | You could check for its NULL-ness in the sproc and `RAISERROR` to report the state back to the calling location.
```
CREATE proc dbo.CheckForNull @i int
as
begin
if @i is null
raiserror('The value for @i should not be null', 15, 1) -- with log
end
GO
```
Then call:
```
exec dbo.CheckForNull @i = 1
```
or
```
exec dbo.CheckForNull @i = null
``` | How to restrict NULL as parameter to stored procedure SQL Server? | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
On my page I have a drop-down select box, with a default value of (empty). When the user selects an entry, the appropriate form for that entry type is displayed.
Couple of problems..
1. The code is not DRY and seems more verbose than it needs to be, so not easily maintainable / extensible.
2. When a user selects something, fills in the form, goes to the next page, and then hits the Back button, the select field is pre-selected with their choice, but since there has been no `.change()` event, the form box is not displayed. They have to select a different `<option>`, then click back to their original choice to get their forum back.
Here's the code:
```
<script type="text/javascript">
$(document).ready(function(){
$('#select_type').change(function () {
$('fieldset').css('display','none'); # hide all the forms on the page
var selectval = $('#select_type').val();
if (selectval == 'instance')
{
$('#instance').toggle();
}
if (selectval == 'mob')
{
$('#mob').toggle();
}
if (selectval == 'dailyquest')
{
$('#dailyquest').toggle();
}
if (selectval == 'repeatablequest')
{
$('#repeatablequest').toggle();
}
if (selectval == 'zonequest')
{
$('#zonequest').toggle();
}
if (selectval == 'reward')
{
$('#reward').toggle();
}
});
});
</script>
```
Help JS gurus of SO! | Instead of the multiple IF clauses, you can iterate over an array of values. But in this case, if there are no other requirements then simply:
```
$(document).ready(function(){
var select = $('#select_type');
$('#' + select.val()).toggle(); // Toggle the preset value
select.change(function () {
$('fieldset').css('display','none');
$('#' + $(this).val()).toggle();
});
});
```
Should be enough. | ```
$(document).ready(function() {
$("#select_type").change(function () {
$("fieldset").css("display", "none");
$("#" + $(this).val()).toggle();
}).change();
});
``` | How to make this jQuery function more elegant? | [
"",
"javascript",
"jquery",
"html",
"forms",
"html-select",
""
] |
I have a form that is dynamically generated, and has dynamically generated id's (and potentially classes). The forms are the same but they have the related id tacked on to the end.
How can I select each set of inputs and apply code to each one?
I was experimenting with $('input[id^=@id\_airline\_for\_]') but could not get it to fly. I suspect I am missing some fundamental jQuery knowledge that is holding me back since I am sure this is a common problem with dynamic forms.
```
<form method='POST'>
<label for="id_airline_for_8">Airline</label>:
<input id="id_airline_for_8" class="arrival_transfer_toggle_8" type="text" maxlength="30" name="airline_for_8"/>
<label for="id_flight_number_for_8">Flight Number</label>:
<input id="id_flight_number_for_8" class="arrival_transfer_toggle_8" type="text" maxlength="30" name="flight_number_for_8"/>
<label for="id_airline_for_17">Airline</label>:
<input id="id_airline_for_17" class="arrival_transfer_toggle_17" type="text" maxlength="30" name="airline_for_17"/>
<label for="id_flight_number_for_17">Flight Number</label>:
<input id="id_flight_number_for_17" class="arrival_transfer_toggle_17" type="text" maxlength="30" name="flight_number_for_17"/>
-- snip --
</form>
```
EDIT: I should update that i want to be able to perform some action when the input is clicked but only for classes with a matching id at the end.
To make it easy, lets say I want all inputs with a matching id at the end of the #id to disappear when one is clicked (just for arguments sake). | ```
$("input[id^='id_airline_for_']").each(function() {
var id = parseInt(this.id.replace("id_airline_for_", ""), 10);
var airline = $("#id_airline_for_" + id);
var flightNumber = $("#id_flight_number_for_" + id);
// do stuff with airline and flightNumber <input>s
});
``` | You can use `$("input#id_airline_for" + id)` (where `id` is your number, e.g., 8), but it will be faster if you drop the tag name and just use:
```
$("#id_airline_for" + id);
``` | jQuery selection with dynamic id's | [
"",
"javascript",
"jquery",
""
] |
I have a hibernate mapping as follows:
```
<hibernate-mapping>
<class name="kochman.elie.data.types.InvoiceTVO" table="INVOICE">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<property name="date" column="INVOICE_DATE"/>
<property name="customerId" column="CUSTOMER_ID"/>
<property name="schoolId" column="SCHOOL_ID"/>
<property name="bookFee" column="BOOK_FEE"/>
<property name="adminFee" column="ADMIN_FEE"/>
<property name="totalFee" column="TOTAL_FEE"/>
</class>
</hibernate-mapping>
```
where InvoiceTVO has variables defined as:
```
private int id;
private Date date;
private int customerId;
private int schoolId;
private float bookFee;
private float adminFee;
private float totalFee;
```
When I do an insert on this table, I get the following error:
```
Hibernate: insert into INVOICE (INVOICE_DATE, CUSTOMER_ID, SCHOOL_ID, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, ID) values (?, ?, ?, ?, ?, ?, ?)
50156 [AWT-EventQueue-0] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 22001
50156 [AWT-EventQueue-0] ERROR org.hibernate.util.JDBCExceptionReporter - Data truncation: Data truncated for column 'ADMIN_FEE' at row 1
50156 [AWT-EventQueue-0] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
```
I tried changing the type of adminFee to double, and that didn't work either. The problem is, Hibernate did actually perform the insert properly, and future select statements work to return the current set of values, but this error prevents me from doing further processing on this invoice.
The fields bookFee, adminFee, and totalFee are all supposed to be currencies. They are defined in the MySQL database as decimal(5,2).
Any help in how to resolve this would be greatly appreciated. | I would use an integer type (int, long). Never any funny issues with those as long you can avoid overflows. | Using float or double for money is absolutely inacceptable and may even be illegal (as in, breaking laws or at least regulations). That needs to be fixed, then the error will disappear. float has limited precision and cannot accurately represent most decimal fractions at all.
[For money, always, ALWAYS use BigDecimal.](http://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal) | Hibernate and currency precision | [
"",
"java",
"hibernate",
"types",
""
] |
Ok, I have one JavaScript that creates rows in a table like this:
```
function AddRow(text,rowID) {
var tbl = document.getElementById('tblNotePanel');
var row = tbl.insertRow(tbl.rows.length);
var cell = row.insertCell();
var textNode = document.createTextNode(text);
cell.id = rowID;
cell.style.backgroundColor = "gold";
cell.onclick = clickTest;
cell.appendChild(textNode);
}
```
In the above function, I set the cell's `onclick` function to call another JavaScript function called `clickTest`. My question is when I assign the `onclick` event to call `clickTest`, how do I set parameter information to be sent when the `clickTest` method is called on the cell's `onclick` event? Or, how do I access the cell's ID in the `clickTest` function?
Thanks,
Jeff | Try this:
```
cell.onclick = function() { clickTest(rowID); };
```
The idea is that you are binding the onclick handler to the anonymous function. The anonymous function calls clickTest with rowID as the parameter. | In the clickTest function you should have access to a the `this` variable. Try this inside of `clickTest` function:
```
alert(this.id);
```
This will refer to the DOM element that fired the event.
Basically, there isn't really a way to pass parameters to an event handler function. The reason for that is that the browser is executing the function based on an event and you are not actually calling the function.
You can use closures which allow you to access local variables (to the closure) when you assign the event handler function. That would look like this:
```
cell.onclick = function() { alert(this.id); alert(cell.id); };
```
Were `cell.id` is the locally scoped variable that is still considered in scope when the event handler is executed. | How to pass a parameter to a dynamically set JavaScript function? | [
"",
"javascript",
""
] |
In Django, I've got loggers all over the place, currently with hard-coded names.
For module-level logging (i.e., in a module of view functions) I have the urge to do this.
```
log = logging.getLogger(__name__)
```
For class-level logging (i.e., in a class `__init__` method) I have the urge to do this.
```
self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
```
I'm looking for second opinions before I tackle several dozen occurrences of `getLogger("hard.coded.name")`.
Will this work? Anyone else naming their loggers with the same unimaginative ways?
Further, should I break down and write a class decorator for this log definition? | I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple:
```
import logging
LOG = logging.getLogger(__name__)
```
At the top of the module and subsequent:
```
LOG.info('Spam and eggs are tasty!')
```
from anywhere in the file typically gets me to where I want to be. This avoids the need for `self.log` all over the place, which tends to bother me from both a put-it-in-every-class perspective and makes me 5 characters closer to 79 character lines that fit.
You could always use a pseudo-class-decorator:
```
>>> import logging
>>> class Foo(object):
... def __init__(self):
... self.log.info('Meh')
...
>>> def logged_class(cls):
... cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__))
...
>>> logged_class(Foo)
>>> logging.basicConfig(level=logging.DEBUG)
>>> f = Foo()
INFO:__main__.Foo:Meh
``` | For class level logging, as an alternative to a pseudo-class decorator, you could use a metaclass to make the logger for you at class creation time...
```
import logging
class Foo(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
type.__init__(name, bases, attrs)
cls.log = logging.getLogger('%s.%s' % (attrs['__module__'], name))
def __init__(self):
self.log.info('here I am, a %s!' % type(self).__name__)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
foo = Foo()
``` | Naming Python loggers | [
"",
"python",
"django",
"logging",
"python-logging",
""
] |
Below is the command I tried executing, without success:
```
exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess');
```
When you add a die() at the end, it catches that there's an error:
```
exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess') or die('what?!');
```
For the above exec() statement, a permissions problem is causing the error, but PHP isn't displaying it. How do you display from PHP what error is occurring? | You can receive the output result of the [exec function](http://www.php.net/function.exec) by passing an optional second parameter:
```
exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess',$output);
var_dump($output);
``` | The following code will capture both the normal output (from StdOut) and the error output (from SdtErr).
```
exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess 2>&1',$output);
var_dump($output);
``` | How to retrieve PHP exec() error responses? | [
"",
"php",
"shell",
"exec",
""
] |
Is there a way to use verbatim String literals in managed C++? Similar to C#'s
```
String Docs = @"c:\documents and settings\"
``` | in C++11, there is raw string literal:
```
cout<<R"((\"ddd\aa)\n)"<<endl;
cout<<R"delimiter((\"ddd\aa)\n)delimiter"<<endl;
```
output is:
```
(\"ddd\aa)\n
(\"ddd\aa)\n
``` | This is not currently possible. Managed C++ string literals have almost the exact same rules as normal C++ strings. The managed C++ spec is in fact just an augmentation of the ANSI C++ standard.
Currently there is no support for C# style literal syntax in C++ (managed or not). You must manually escape every character.
See Section 9.1.3.3 in the C++/CLI spec for more details. ([Spec Link)](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-372.pdf) | Verbatim Literals in Managed C++? (like C#'s @"blah") | [
"",
".net",
"c++",
".net-2.0",
"string",
"managed-c++",
""
] |
I have a national customer who are currently recruiting dealers by selling each dealer an area for a set fee. They want a 'find a dealer' feature on their website which should point customers to the dealer who has purchased the area the visitor enters. At first we were going to list major cities with the hope that the visitor would click on the nearest city name that they recognised, but it occurred to me that it must be possible to use the maps API to map postcodes or town names to specific areas.
The problem is that it's not quite a "find my nearest dealer" scenario because of the way they're selling specific areas - the dealer for your area might not be the nearest to your postcode/town. I've used the Google maps API in the past, but mainly for plotting things on maps dynamically rather than using it to calculate some geography for help in a database query - can anyone help? I'll be using the PHP API if that makes any difference. | 1. Create your polygons in Google Maps using KML or whatever format you have them in.
2. Use Google Maps to geocode the location that the user enters (in other words, transform postal code and city to lat/long).
3. Use the contains or containsLatLng methods of the GLatLngBounds object in each polygon to determine whether the lat/long is within one of the polygons. | It sounds like you will need polygon regions that represent the dealer's specific area. You can make polygons with the Google Maps API and then you should be able to let user click or mouse over those... | Finding a dealer area via google maps API | [
"",
"php",
"api",
"google-maps",
"geocoding",
""
] |
I've got some code that looks like this:
```
using (DBDataContext dc = new DBDataContext(ConnectionString))
{
Main main = new Main
{
ClientTime = clientTime
};
dc.Mains.InsertOnSubmit(main);
dc.SubmitChanges();
return main.ID;
}
```
If I return from inside a "using", will the using still clean up? | Yes, and that's one of the big advantages of `using` it. | Yes. It really is just the equivalent of a `try/finally` statement - and `finally` blocks get executed however the `try` block exits, whether through an exception, a return statement, or just getting to the end of the block. | Returning from inside the scope of a 'using' statement? | [
"",
"c#",
".net",
""
] |
I am adding items to a `ListBox` like so:
```
myListBox.Items.addRange(myObjectArray);
```
and I also want to select some of the items I add by the following:
```
foreach(MyObject m in otherListOfMyObjects)
{
int index = myListBox.Items.IndexOf(m);
myListBox.SelectedIndices.Add(index);
}
```
however `index` is always `-1`.
Is there a different way to get the index of an object in a `ListBox`? | You should make sure that `MyObject` overrides `Equals()`, `GetHashCode()` and `ToString()` so that the `IndexOf()` method can find the object properly.
Technically, `ToString()` doesn't need to be overridden for equality testing, but it is useful for debugging. | You can use some kind of a key for values in the listbox, like GUIDs. Then you can easily use `myListBox.Items.FindByValue(value)` to find the right item. | How Can I Get the Index of An Item in a ListBox? | [
"",
"c#",
"listbox",
""
] |
Is there any way to access the `<compilation />` tag in a web.config file?
I want to check if the "*debug*" attribute is set to "*true*" in the file, but I can't seem to figure out how to do it. I've tried using the `WebConfigurationManager`, but that doesn't seem to allow me to get to the `<compilation />` section.
**Update:**
I know I could easily just load the file like an XML Document and use XPath, but I was hoping there was already something in the framework that would do this for me. It seems like there would be something since there are already ways to get App Settings and Connection Strings.
I've also tried using the `WebConfigurationManager.GetSection()` method in a few ways:
```
WebConfigurationManager.GetSection("compilation")// Name of the tag in the file
WebConfigurationManager.GetSection("CompilationSection") // Name of the class that I'd expect would be returned by this method
WebConfigurationManager.GetSection("system.web") // Parent tag of the 'compilation' tag
```
All of the above methods return `null`. I'm assuming there is a way to get to this configuration section since there is a class that already exists ('`CompilationSection`'), I just can't figure out how to get it. | Use:
```
using System.Configuration;
using System.Web.Configuration;
```
...
```
CompilationSection configSection =
(CompilationSection) ConfigurationManager.GetSection( "system.web/compilation" );
```
You can then check the `configSection.Debug` property.
**TIP:** if you need to know how to get a value from a config file, check the machine.config file in your `\Windows\Microsoft.net\Framework\<version>\CONFIG` folder. In there you can see how all the configuration section handlers are defined. Once you know the name of the config handler (in this case, CompilationSection), you can look it up in the .Net docs. | The easy way to check if you're running in debug mode is to use the [HttpContext.IsDebuggingEnabled](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.isdebuggingenabled.aspx) property. It gets its answer from the compilation element's debug attribute which is the same thing you're trying to do. | Programmatically access the <compilation /> section of a web.config? | [
"",
"c#",
".net",
"asp.net",
"configuration",
""
] |
I am using the pimpl idiom and want to reference one of the methods of the forward declared class. Below isn't exactly what I'm doing but uses the same concepts.
```
template< typename Class, void (Class::*Method)(void) >
struct Call
{
Call( Class* c )
: m_c(c)
{ }
void operator()( void )
{
(m_c->*Method)();
}
Class* m_c;
};
class A
{
public:
void foo( void )
{
std::cout << "A::foo\n";
}
};
// this works
void do_foo( A* a )
{
Call<A,&A::foo> c(a);
c();
}
class B;
// this doesn't compile
extern void B::bar( void );
// this is what i'd ultimately like to do
void do_bar( B* b )
{
Call<B,&B::bar> c(b);
c();
}
```
Two questions:
* Can this be done?
* Why can't it be done? | You cannot forward declare a member function. I think the reason is that, when you call the function on a pointer to B, the compiler has to pass the this pointer to that method. But it doesn't know the precise class hierarchy of B yet. So possible adjustments of that pointer (due to the method being virtual, for example) would not be possible at that point. The compiler would also not know what visibility that method has. After all, it could be private and you are not allowed to call it from outside. The only way to declare that member function is to define the class, and then declare the function within that definition. Another way to solve your problem is to declare your free function instead:
```
class B;
void do_bar( B* b );
```
Then define do\_bar in a file in which you can safely include the definition of the class B. | It can't compile B::bar() because class B is undefined. But I think you are leaving too much out of the question. At this point:
```
void do_bar( B* b )
{
Call<B,&B::bar> c(b);
c();
}
```
why can't you just say?
```
void do_Bar(B* b) {
b->bar();
}
```
Perhaps if you included that explanation it would be easier to answer your question.
Second, why is this needed when (as seen above) you want to call it through do\_bar()? Why not make do\_bar the extern?
```
extern void B::bar( void );
``` | Forward declare method pointer | [
"",
"c++",
"templates",
""
] |
I have the following use case , lot of code which was tightly coupled on a concrete type (say Concrete1). Later figured out the concrete type needs to be changed, so defined an interface . E.g
```
Class ABC {
virtual int foo() = 0;
virtual int getType() = 0;
}
class Concrete1 : public ABC {
int foo() {
... }
int getType() {
return 1;
}
}
class Concrete2 : public ABC {
int foo() {
... }
int getType() {
return 2;
}
}
```
A static factory pattern was used for creation of the objects. So all places where the object new Concrete1 was created is replaced with ABCFactory::createType().
Now there are a lot of places in code where I need to check if the object returned by createType is whether Concrete1 or Concrete2 and accordingly do the relevant logic (So a lot of if else in the code :( ).
I want to avoid a lot of if else in the code as part of this change. Any suggestions?
The thing which bothers me a lot is
```
if (abc.getType() == 1) {
...
} else if (abc.getType() ==2) {
...
}
``` | the entire point of using interfaces is so that you can use polymorphism which means you should never have to check what type an instance is. doing so is a very big code smell (see Fowlers Refacotring). move the conditional logic to the concrete classes and add te function that will handle it to the interface
EDIT (Adding code example since initial post was done from cell phone):
You are trying to do:
```
void Main(string[] args)
{
Bird bird = BirdFactory.GetPigeon();
if (bird.GetType().Equals(typeof(Duck)))
{
Console.WriteLine("quack");
}
else if (bird.GetType().Equals(typeof(Pigeon)))
{
Console.WriteLine("coo coo");
}
}
```
Instead, try:
```
interface Bird
{
void Speak();
}
class Duck : Bird
{
void Speak()
{
Console.Write("quack");
}
}
class Pigeon : Bird
{
void Speak()
{
Console.Write("coo coo");
}
}
void Main(string[] args)
{
Bird bird = BirdFactory.GetPigeon();
bird.Speak();
}
``` | Put the `...` inside the implementation of yet another virtual method:
```
if (abc.getType() == 1) {
... // A
} else if (abc.getType() == 2) {
... // B
}
```
Put A and B like this:
```
class ABC {
virtual int foo() = 0;
virtual void doIt() = 0; // choose a proper name
};
class Concrete1 : public ABC {
int foo() {
... }
void doIt() {
... // A
}
};
class Concrete2 : public ABC {
int foo() {
... }
void doIt() {
... // B
}
};
```
And change your if to
```
abc.doIt();
```
As another one said, that's exactly the point of dynamic dispatch! Beside being more terse, it also will never "forget" to handle a type. Doing your switch, you could silently not handle a particular type, because you missed updating the code at that place when you introduced a new implementation. Also remember having a virtual destructor in ABC. | Concrete type or Interface? | [
"",
"c++",
""
] |
When a user clicks on an image on a web page, I'd like to trigger the browser's Save Image dialog and to let the user save the image on their hard drive. Is there a cross-browser way to do this with jQuery/Javascript? | Not precisely, but you can do it by hyperlinking to the img file and setting the content-type and content-disposition headers in the server response. Try, e.g., application/x-download, [plus the other headers specified here](http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index3.html). | The only thing that comes to my mind is the document.execCommand("SaveAs") of Internet Explorer, you can open a window or use a hidden iframe with the url of your image, and then call it...
Check (with IE of course) [this example](http://dl.getdropbox.com/u/35146/ieSaveAs.html) I've done. | Open the Save Image dialog using jQuery/Javascript? | [
"",
"javascript",
"jquery",
""
] |
I want to convince the architecture manager to include the [Joda-Time](http://www.joda.org/joda-time/) jar in our product.
Do you know any disadvantages in using it?
I think Joda-Time needs to be constantly updated because of the files that it includes. And that is a disadvantage. Maybe I am wrong.
Could you provide some clarity on the subject? | I've had almost entirely positive experiences with Joda Time. My one problem was when trying to construct my own time zone (for legitimate reasons, I assure you :) I got some very weird exceptions, and the documentation wasn't very good for that particular use case.
However, for the most part it's been a joy to use - immutability makes code a lot easier to reason about, and thread-safety for formatters is hugely useful.
Yes, there are files to keep up to date - but at least you *can* keep them up to date. It's not like they contain things which were unnecessary with Java's built-in stuff, it's just that with Java's mechanism you just couldn't keep information like timezones up to date without significant hackery!
Basically, +1 for using Joda Time. The Java date/time API is one of the worst bits of the Java platform, IMO. | In my opinion, the most important drawback in Joda-Time is about precision: many databases store timestamps with [microsecond](https://en.wikipedia.org/wiki/Microsecond) (or even [nanosecond](https://en.wikipedia.org/wiki/Nanosecond)) precision. Joda-time goes only to [milliseconds](https://en.wikipedia.org/wiki/Millisecond). This is not acceptable to me: all "data model" classes that I use need to reflect the full precision of the data in my database. Approximations or truncations of my data by a library just don't cut it.
Here is the reasoning behind the choice of millisecond precision, taken from the [JSR 310](https://jcp.org/en/jsr/detail?id=310) mailing list:
> *"Joda-Time chose to use milliseconds as it made conversions to Date and Calendar easier."* - S. Colebourne
Easier for whom? The author of the library, one would assume... Incorrect design decision, in my opinion, when almost all databases store times to microsecond/nanosecond precision. The disregard for database values is worrying. | Are there any cons to using Joda-Time? | [
"",
"java",
"jodatime",
""
] |
How can I grab something like ^MM (CTRL + M + M) in .NET, using C#? | Here's a way to do it:
```
bool mSeenCtrlM;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.M)) {
mSeenCtrlM = !mSeenCtrlM;
if (!mSeenCtrlM) {
MessageBox.Show("yada");
}
return true;
}
mSeenCtrlM = false;
return base.ProcessCmdKey(ref msg, keyData);
}
``` | This is just a guess, you could store the key and key modifiers on each key stroke and then next time through check the last keys pressed for a matching sequence.
You could probably implement this in either the ProcessCmdKey or OnKeyPress. | How can I grab a double key stroke in .NET | [
"",
"c#",
".net",
"key",
""
] |
I'm building a C++ application and need to use PDCurses on Windows. I'm compiling with VC++ from MS VS 2005 and I'm getting a link error.
> ```
> error LNK2019: unresolved external
> symbol __imp__GetKeyState@4 referenced
> in function __get_key_count
> ```
There are 11 errors all with the same error code and different symbols. The missing symbols are \_\_imp\_\_MapVirtualKeyA@8, \_\_imp\_\_FindWindowA@8, \_\_imp\_\_wsprintfA, \_\_imp\_\_SendMessageA@16, \_\_imp\_\_GetWindowThreadProcessId@8, \_\_imp\_\_MessageBeep@4. It is almost like the VC++ can't find the appropriate ASCII implementations of these functions. I should also note that the demo programs that come with PDCurses compiled fine, though they are C programs.
In the C++ program, I include the header using
```
extern "C"
{
#include <curses.h>
}
```
I'm sure I'm forgetting to link against some C standard library, but I'm not sure which one. | GetKeyState() is a Windows function in "user32.dll", so you need to be sure you're linking against "user32.lib". You may also need to make sure it comes after the PDCurses library in the list of linker libraries, too. | Did you build PDCurses on your machine - with MS VC++? If so, I'm not sure what's up. If not, then there's a decent chance that what you are using is not compatible with MS VC++. Mixing code from different C++ compilers is fraught. It also depends a bit on what you mean by 'several other errors'. If that's a grotesque understatement for 'hundreds of errors', then that is likely the trouble. If you have just a few (say another half dozen or fewer) similar errors, then it is less likely to be the trouble. | How do I link PDCurses to a C++ application on Windows? | [
"",
"c++",
"windows",
"linker",
"ncurses",
"pdcurses",
""
] |
What is a synthetic class in Java? Why should it be used? How can I use it? | For example, When you have a switch statement, java creates a variable that starts with a $. If you want to see an example of this, peek into the java reflection of a class that has a switch statement in it. You will see these variables when you have at least one switch statement anywhere in the class.
To answer your question, I don't believe you are able to access(other than reflection) the synthetic classes.
If you are analyzing a class that you don't know anything about (via reflection) and need to know very specific and low-level things about that class, you may end up using Java reflection methods that have to do with synthetic classes. The only "use" here is get more information about the class in order to use it appropriately in your code.
(If you're doing this, you're probably building a framework of some sorts that other developers could use. )
Otherwise, if you are not using reflection, there are no practical uses of synthetic classes that I know of. | Java has the ability to create classes at runtime. These classes are known as Synthetic Classes or Dynamic Proxies.
See <http://java.sun.com/j2se/1.5.0/docs/guide/reflection/proxy.html> for more information.
Other open-source libraries, such as [CGLIB](http://cglib.sourceforge.net/) and [ASM](http://asm.objectweb.org/) also allow you to generate synthetic classes, and are more powerful than the libraries provided with the JRE.
Synthetic classes are used by AOP (Aspect Oriented Programming) libraries such as Spring AOP and AspectJ, as well as ORM libraries such as Hibernate. | Synthetic Class in Java | [
"",
"java",
"class",
"synthetic",
""
] |
I have a Visual Studio 2005 C++ program that runs differently in Release mode than it does in Debug mode. In release mode, there's an (apparent) intermittent crash occurring. In debug mode, it doesn't crash. What are some reasons that a Release build would work differently than a Debug build?
It's also worth mentioning my program is fairly complex and uses several 3rd party libraries for XML processing, message brokering, etc...
Thanks in advance! | [**Surviving the Release Version**](https://www.codeproject.com/Articles/548/Surviving-the-Release-Version) gives a good overview.
Things I have encountered - most are already mentioned
**Variable initialization**
by far the most common. In Visual Studio, debug builds explicitly initialize allocated memory to given values, see e.g. [Memory Values](https://community.kde.org/index.php?title=Guidelines_and_HOWTOs/Debugging/MS_Windows&redirect=no#Memory_Values) here. These values are usually easy to spot, cause an out of bounds error when used as an index or an access violation when used as a pointer. An uninitialized boolean is true, however, and may cause uninitialized memory bugs going undetected for years.
In Release builds where memory isn't explicitely initialized it just keeps the contents that it had before. This leads to "funny values" and "random" crashes, but as often to deterministic crashes that require an apparently unrelated command to be executed before the command that actually crashes. This is caused by the first command "setting up" the memory location with specific values, and when the memory locations are recycled the second command sees them as initializations. That's more common with uninitialized stack variables than heap, but the latter has happened to me, too.
Raw memory initialization can also be different in a release build whether you start from visual studio (debugger attached) vs. starting from explorer. That makes the "nicest" kind of release build bugs that never appear under the debugger.
**Valid Optimizations** come second in my exeprience. The C++ standard allows lots of optimizations to take place which may be surprising but are entirely valid e.g. when two pointers alias the same memory location, order of initialization is not considered, or multiple threads modify the same memory locations, and you expect a certain order in which thread B sees the changes made by thread A. Often, the compiler is blamed for these. Not so fast, young yedi! - see below
**Timing** Release builds don't just "run faster", for a variety of reasons (optimizations, logging functions providing a thread sync point, debug code like asserts not executed etc.) also the relative timing between operations change dramatically. Most common problem uncovered by that is race conditions, but also deadlocks and simple "different order" execution of message/timer/event-based code. Even though they are timing problems, they *can* be surprisingly stable across builds and platforms, with reproductions that "work always, except on PC 23".
**Guard Bytes**. Debug builds often put (more) guard bytes around selected instances and allocations, to protect against index overflows and sometimes underflows. In the rare cases where the code relies on offsets or sizes, e.g. serializing raw structures, they are different.
**Other code differences** Some instructions - e.g asserts - evaluate to nothing in release builds. Sometimes they have different side effects. This is prevalent with macro trickery, as in the classic (warning: multiple errors)
```
#ifdef DEBUG
#define Log(x) cout << #x << x << "\n";
#else
#define Log(x)
#endif
if (foo)
Log(x)
if (bar)
Run();
```
Which, in a release build, evaluates to *if (foo && bar)*
This type of error is very very rare with normal C/C++ code, and macros that are correctly written.
**Compiler Bugs** This really never ever happens. Well - it does, but you are for the most part of your career better off assuming it does not. In a decade of working with VC6, I found one where I am still convinced this is an unfixed compiler bug, compared to dozens of patterns (maybe even hundreds of instances) with insufficient understanding of the scripture (a.k.a. the standard). | In debug version often assertions and/or debug symbols are enabled. This can lead to different memory layout. In case of a bad pointer, overflow of an array or similar memory access you access in one case critical bad memory (e.g. function pointer) and in other case maybe just some non-critical memory (e.g. just a doc string is trashed) | What are some reasons a Release build would run differently than a Debug build | [
"",
"c++",
"visual-studio",
"visual-studio-2005",
""
] |
I'm trying to find out if it's possible to develop a key capturing application to analyse writing styles when using the SMS composer for the n73 using S60 2nd Edition, Feature Pack 3 SDK in Java? Originally, I thought that all Java applications would be sand-boxed making it difficult to call the native key capture functions available to symbian, but nobody has been able to clarify this for me. Does it hold any truth?
Thanks,
A | Note: This answer comes from my friend who knows a lot more about these things.
---
As this [J2ME FAQ](http://www.j2meforums.com/wiki/index.php/FAQ#Can_I_access_the_phone.27s_j2me.3F_.28memory.2C_phone_book.2C_inbox.2C_pictures....29_.3F) states,
> **Can I access the phone's j2me?**
> **(memory, phone book, inbox,**
> **pictures...) ?**
> Generally no, this is
> considered a security risk and most
> manufacturers don't allow it. However,
> a very small minority do, so check out
> their developer's site.
So that'd be no. There's no direct way in MIDP libraries to access that data anyway. It may however be possible if you're lucky, but don't count on it. Also according to Sun this may be possible in MIDP3. | I'll be talking as a user:
Opera Mini (a java-based application) is able to read and write user data (phone memory and memory card).
And I've also seen java-based applications that access hardware such as the phone's camera, and seen apps that call system APIs such as vibration or sound notifications.
However, I don't know how they implemented those things.
Note1: Nokia N73 is based on S60 3rd edition not 2nd edition.
Note2: In some cases (such as accessing user data), user authorization is required, unless the application is signed using a certificate. | Developing apps for the nokia n73 in Java? | [
"",
"java",
"symbian",
"nokia",
"n73",
""
] |
I have a common code of serializing a class object in my 3-4 methods ,So I am thinking to create a common function for that code and call function in all the methods
I am doingn this from the following code
```
DataContractJsonSerializer ser = new DataContractJsonSerializer(this.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, this);
json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
```
I want to put this common code in seprate general function which returns Json string and which accept whole class as input parameter as I am converting whole class into a Json object , I tried creating function like
public string GenerateJsonString(class C1)
but this is giving me error on the keyword "class" saying that type is required
Can anyone tell me how can I accept whole class object in seprate method or function | You are confusing a "class" with an "object". You serialize an object, which is an instance of a particular class (aka "Type").
You can create a method taking a parameter of the .NET base type for all objects, "object", like this:
```
public static string GenerateJsonString(object o)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, o);
json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
return json;
}
}
``` | Type the parameter as "object". You can't pass a class as a parameter, only an instance of a class - which in OOP is referred to as an "object"
```
public string GenerateJsonString(object obj)
``` | How to build DataContractJsonSerialize convenience function | [
"",
"c#",
"json",
""
] |
I seem to have a problem with this SQL query:
```
SELECT * FROM appts
WHERE timeStart >='$timeStart'
AND timeEnd <='$timeEnd'
AND dayappt='$boatdate'
```
The time is formatted as military time. The logistics is that a boat rental can be reserved at 7am til 1pm or 9am til 1pm or 9am til 5pm. If there is an appt within that range, it should return appts but it has proven to be inconsistent. If I pick 9am til 1pm, it will ignore appts that started with 7am even though it overlaps 9am-1pm. If I pick 9 to 5, it will return nothing even though it should with the 7am to 1pm. How do I make a SQL statement that includes the whole range from timeStart to timeEnd including those that overlap? | The correct check would look like this:
```
SELECT * FROM appts
WHERE timeStart <='$timeEnd'
AND timeEnd >='$timeStart'
AND dayappt='$boatdate'
```
Other good explanations have been given but I'll go ahead and update it with an alternative explanation of how I visualize this myself. Most people are looking for each possible overlap, considering two time periods, they are trying to think of each combination of start and end that can make an appointment overlap. I think about it as when do two time periods not overlap which for some reason is easier for me.
Say the time period I am checking for is today, I want to find any time period that does not overlap today. There are really only two scenarios for that, either the time period starts after today (PeriodStart > EndOfToday) or the time period ends before today (PeriodEnd < StartOfToday).
Given that we havea simple test for not overlapping:
(PeriodStart > EndOfToday) OR (PeriodEnd < StartOfToday)
A quick flip around and you have a simple test for overlap:
(PeriodStart <= EndOfToday) AND (PeriodEnd >= StartOfToday)
-Shane | Shahkalpesh answered the question with:
> I think you need an OR.
>
> ```
> SELECT * FROM appts
> WHERE (timeStart >='$timeStart'
> OR timeEnd <='$timeEnd')
> AND dayappt='$boatdate'
> ```
I posted a comment that I consider this to be wrong, giving a pair of counter-examples:
> This is plain wrong - @ShaneD is correct. For example, this will pick out a booking between 05:00 and 06:00 because the actual end time is less than any of the end times you ask about. It will also pick up rentals from 18:00 onwards, for the equivalent reason.
In a response to my comment, Shahkalpesh requested:
> Could you post a separate reply with data & input parameters with expected output?
Fair enough - yes. Slightly edited, the question says:
> The logic is that a boat rental can be reserved
* from 7am until 1pm, or
* from 9am until 1pm, or
* from 9am until 5pm.
> If there is an appointment within that range, it should return appointments but it has proven to be inconsistent. If I pick 9am until 1pm, ...
---
Enough background. We can ignore the date of the appointments, and just consider the times. I'm assuming that there is an easy way to limit the times recorded to hh:mm format; not all DBMS actually provide that, but the extension to handle hh:mm:ss is trivial.
```
Appointments
Row timeStart timeEnd Note
1 07:00 13:00 First valid range
2 09:00 13:00 Second valid range
3 09:00 17:00 Third valid range
4 14:00 17:00 First plausibly valid range
5 05:00 06:00 First probably invalid range
6 18:00 22:30 Second probably invalid range
```
Given a search for appointments overlapping the range 09:00 - 13:00, Shahkalpesh's (simplified) query becomes:
```
SELECT * FROM Appointments
WHERE (timeStart >= '09:00' OR timeEnd <= '13:00')
```
This will return all six rows of data. However, only rows 1, 2, 3 overlap the time period 09:00 - 13:00. If rows 1, 2, and 3 are the only valid representative appointment values, then Shahkalpesh's query produces the correct answer. However, if the row 4 (which I think is plausibly valid) is permitted, then it should not be returned. Similarly, rows 5 and 6 - if present - should not be returned. [*Actually, assuming* `timeStart <= timeEnd` *for all rows in the table (and there are no NULL values to mess things up), we can see that Shahkalpesh's query will return ANY row of data for the 09:00-13:00 query because either the start time of the row is greater 09:00 or the end time is less than 13:00 or both. This is tantamount to writing* `1 = 1` *or any other tautology in the WHERE clause.*]
If we consider ShaneD's query (as simplified):
```
SELECT * FROM Appointments
WHERE timeStart <= '13:00' AND timeEnd >= '09:00'
```
we see that it also selects rows 1, 2, and 3, but it rejects rows 4 (because timeStart > '13:00'), 5 (because timeEnd < '09:00') and 6 (because timeStart > '13:00'). This expression is an archetypal example of how to select rows which 'overlap', counting 'meets' and 'met by' (see "[Allen's Interval Algebra](http://www.ics.uci.edu/%7Ealspaugh/foundations/allen.html)", for instance) as overlapping. Changing '>=' and '<=' alters the set of intervals counted as overlapping. | How do I compare overlapping values within a row? | [
"",
"sql",
"mysql",
"overlap",
""
] |
What are the main differences among them? And in which typical scenarios is it better to use each language? | In order of appearance, the languages are `sed`, `awk`, `perl`, `python`.
The `sed` program is a stream editor and is designed to apply the actions from a script to each line (or, more generally, to specified ranges of lines) of the input file or files. Its language is based on `ed`, the Unix editor, and although it has conditionals and so on, it is hard to work with for complex tasks. You can work minor miracles with it - but at a cost to the hair on your head. However, it is probably the fastest of the programs when attempting tasks within its remit. (It has the least powerful regular expressions of the programs discussed - adequate for many purposes, but certainly not PCRE - Perl-Compatible Regular Expressions)
The `awk` program (name from the initials of its authors - Aho, Weinberger, and Kernighan) is a tool initially for formatting reports. It can be used as a souped-up `sed`; in its more recent versions, it is computationally complete. It uses an interesting idea - the program is based on 'patterns matched' and 'actions taken when the pattern matches'. The patterns are fairly powerful (Extended Regular Expressions). The language for the actions is similar to C. One of the key features of `awk` is that it splits the input automatically into records and each record into fields.
Perl was written in part as an awk-killer and sed-killer. Two of the programs provided with it are `a2p` and `s2p` for converting `awk` scripts and `sed` scripts into Perl. Perl is one of the earliest of the next generation of scripting languages (Tcl/Tk can probably claim primacy). It has powerful integrated regular expression handling with a vastly more powerful language. It provides access to almost all system calls and has the extensibility of the CPAN modules. (Neither `awk` nor `sed` is extensible.) One of Perl's mottos is "TMTOWTDI - There's more than one way to do it" (pronounced "tim-toady"). Perl has 'objects', but it is more of an add-on than a fundamental part of the language.
Python was written last, and probably in part as a reaction to Perl. It has some interesting syntactic ideas (indenting to indicate levels - no braces or equivalents). It is more fundamentally object-oriented than Perl; it is just as extensible as Perl.
OK - when to use each?
* Sed - when you need to do simple text transforms on files.
* Awk - when you only need simple formatting and summarisation or transformation of data.
* Perl - for almost any task, but especially when the task needs complex regular expressions.
* Python - for the same tasks that you could use Perl for.
I'm not aware of anything that Perl can do that Python can't, nor vice versa. The choice between the two would depend on other factors. I learned Perl before there was a Python, so I tend to use it. Python has less accreted syntax and is generally somewhat simpler to learn. Perl 6, when it becomes available, will be a fascinating development.
(Note that the 'overviews' of Perl and Python, in particular, are woefully incomplete; whole books could be written on the topic.) | After mastering a few dozen languages, one gets tired of absolute recommendations against tools, like in [this answer](https://stackoverflow.com/a/367082/2057969) regarding `sed` and `awk`.
Sed is the best tool for extremely simple command-line pipelines. In the hands of a sed master, it's suitable for one-offs of arbitrary complexity, but it should not be used in production code except in very simple substitution pipelines. Stuff like 's/this/that/.'
Gawk (the GNU awk) is by far the best choice for complex data reformatting when there is only a single input source and a single output (or, multiple outputs sequentially written). Since a great deal of real-world work conforms to this description, and a good programmer can learn gawk in two hours, it is the best choice. On this planet, simpler and faster is better!
Perl or Python are far better than any version of awk or sed when you have very complex input/output scenarios. The more complex the problem is, the better off you are using python, from a maintenance and readability standpoint. Note, however, that a good programmer can write readable code in any language, and a bad programmer can write unmaintainable crap in any useful language, so the choice of perl or python can safely be left to the preferences of the programmer if said programmer is skilled and clever. | What are the differences between Perl, Python, AWK and sed? | [
"",
"python",
"perl",
"sed",
"awk",
"language-comparisons",
""
] |
I've been using ReSharper for the past months and, advertising aside, I can't see myself coding without it. Since I love living on the bleeding "What the hell just went wrong" edge, I decided to try my luck w/ the latest ReSharper 4.5 nightly builds. It's all nice.
However, I've noticed that the using directives grouping format has changed, and I wanted to know which is closer to the general standards:
[OLD]
```
#region Using directives
using System.X;
using System.Y;
using System.Z;
using System.A;
#region
namespace X { ... }
```
[NEW]
```
namespace X {
#region Using directives
using System.X;
using System.Y;
using System.Z;
using System.A;
#region
...
}
```
Other than just lazy loading references, does it serve any special purpose? (Been reading Scott Hanselman's take on this @ <http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx>)
Thanks; | As Scott proceeds to discover in his post, there is **no runtime difference** between these two cases. Therefore, it does **not** serve the purpose of lazy loading references.
If you read the comments in Scott's blog all the way to the end, you will also see that the developer who passed this rumor to Scott (Mike Brown) says that he had only heard of this and not tested it himself.
That said, it is possible that where you put the using directives might make a difference by giving a compiler error if you set up an alias for a type *inside a namespace*, and you have another type *with the same name* defined in the namespace. But that's no runtime difference of course.
Finally, I believe that MS coding guidelines say to do it as ReSharper 4.5 does. But it's silly to blindly follow this rule "because MS says so", since
1. It has been proved that it offers no benefit.
2. Your team's (or your) usual coding style may very well be different. | Well, the usual is subjective. :) But for me, the usual is the "old" way. | Organizing using directives | [
"",
"c#",
"coding-style",
"using-directives",
""
] |
I can't figure out how to get the SCOPE\_IDENTITY() back to my variables from an SQL2005 Store Procedure.
My sSQL String:
```
sSQL = "EXEC [sp_NewClaim] " & Chr(34) & ClaimNumber & Chr(34) & ", " & Request.Cookies("UserID") & ", " & Request.Cookies("MasterID") & ", " & Chr(34) & strRestaurante & Chr(34) & ", " & Chr(34) & Fecha & Chr(34) & ", " & Chr(34) & Hora & Chr(34) & ", " & Chr(34) & Request("Tiempo") & Chr(34) & ", " & Chr(34) & Request("Luz") & Chr(34) & ", " & Chr(34) & Request("Desc") & Chr(34) & ", " & Chr(34) & Request("incidente") & Chr(34) & ", " & Chr(34) & Request("codigos") & Chr(34) & ", False, 0; SELECT RecordNumber = SCOPE_IDENTITY()"
```
My sSQL Output:
```
EXEC [sp_NewClaim] "W200811", 7, 8, "Otro -- WORK PLEASE", "11/19/2008", "01:19 PM", "Nublado", "Mala", "asdasd", "uyiuyui", "C-Junta", False, 0; SELECT RecordNumber = SCOPE_IDENTITY()
```
Executing my SQL Command:
```
Set rsData= Server.CreateObject("ADODB.Recordset")
rsData.Open sSQL, conDB, adOpenKeyset, adLockOptimistic
```
Trying to Output the SCOPE\_IDENTITY() Produces an Empty Variable (No Output):
```
Response.Write("<br />Record Number: " & rsData("RecordNumber"))
```
The Store Procedure runs correctly. My Information gets stored into my database with out problems. RecordNumber is the Column with the Identity, and the Store Procedure has defined @RecordNumber as an Output:
```
USE [db_clcinsurance_com]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE sp_NewClaim
(
@ClaimNumber nvarchar(50),
@blah............
.................
@RecordNumber INT OUTPUT
)
AS
BEGIN
INSERT INTO Accidente (ClaimNumber,........., RecordNumber)
VALUES (@ClaimNumber,....., @RecordNumber)
SET @RecordNumber = SCOPE_IDENTITY();
END
``` | For your stored procedure, do this:
```
CREATE PROCEDURE sp_NewClaim
(
@ClaimNumber nvarchar(50),
@blah............
.................
)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Accidente (ClaimNumber,........., RecordNumber)
VALUES (@ClaimNumber,....., @RecordNumber)
SELECT SCOPE_IDENTITY()
END
```
And then get the id the same way you'd retrieve any other query result. | I agree with Joel Coehoorn's response, but I wanted to note that you are sending your SCOPE\_IDENTITY() variable back as an output parameter, but not retrieving it that way in your ado call. You cannot retrieve an output parameter using the method you are to call the stored procedure.
If you are curious there are some ado examples [here](http://support.microsoft.com/kb/164485) to call stored procedures. | Classic ASP getting SCOPE_IDENTITY() Value from SQL2005 | [
"",
"sql",
"asp-classic",
"identity",
""
] |
I tried to make the title as clear as possible... here is my scenario:
I have 2 tables (let's call them table A and table B) that have a similar schema. I would like write a stored procedure that would select specific columns of data out of table A, and insert this data as a new record in table B.
Can someone point me in the write direction to make such a query? I am unsure how to "Hold" the values from the first query, so that I may then perform the insert.
I am trying to avoid making a query, processing it with C# and then making another query...
Thanks. | ```
INSERT INTO B (Col1, Col2) SELECT Col1, Col2 FROM A
```
Is this what you mean? | You can do this as a single query from C# like this:
```
Insert into tableB (col1, col2, col3) select col1, col2, col3 from tableA where ...
```
The trick is that column names need to be in the same order and compatible types. | Need SQL help - How can I select rows to perform an insert? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Hullo all,
Wondering if there are any Java hackers who can clue me in at to why the following doesn't work:
```
public class Parent {
public Parent copy() {
Parent aCopy = new Parent();
...
return aCopy;
}
}
public class ChildN extends Parent {
...
}
public class Driver {
public static void main(String[] args) {
ChildN orig = new ChildN();
...
ChildN copy = orig.getClass().cast(orig.copy());
}
}
```
The code is quite happy to compile, but decides to throw a ClassCastException at runtime D=
**Edit:** Whoah, really quick replies. Thanks guys! So it seems I cannot downcast using this method... is there any other way to do downcasting in Java? I did think about having each `ChildN` class overwrite `copy()`, but wasn't enthusiastic about adding the extra boilerplate code. | (Can't add code in a comment, so I'll add here)
Regarding Cloneable: if you're implementing Cloneable, implement it as follows; much cleaner to call...
```
public class Foo implements Cloneable {
public Foo clone() {
try {
return (Foo) super.clone();
} catch (CloneNotSupportedException e) {
return null; // can never happen!
}
}
```
[EDIT: I've also seen other folks use
```
throw new AssertionError("This should never happen! I'm Cloneable!");
```
in the catch block.] | Is like trying to do this:
```
public Object copy(){
return new Object();
}
```
And then attempt to:
```
String s = ( String ) copy();
```
Your *Parent* class and *ChildN* class have the same relationship as *Object* and *String*
To make it work you would need to do the following:
```
public class ChildN extends Parent {
public Parent copy() {
return new ChildN();
}
}
```
That is, override the "copy" method and return the right instance.
---
**EDIT**
As per your edit. That is actually possible. This could be one possible way:
```
public class Parent {
public Parent copy() {
Parent copy = this.getClass().newInstance();
//...
return copy;
}
}
```
That way you don't have to override the "copy" method in each subclass. This is the Prototype design pattern.
However using this implementation you should be aware two checked exceptions. Here's the complete program that compiles and runs without problems.
```
public class Parent {
public Parent copy() throws InstantiationException, IllegalAccessException {
Parent copy = this.getClass().newInstance();
//...
return copy;
}
}
class ChildN extends Parent {}
class Driver {
public static void main(String[] args) throws InstantiationException , IllegalAccessException {
ChildN orig = new ChildN();
ChildN copy = orig.getClass().cast(orig.copy());
System.out.println( "Greetings from : " + copy );
}
}
``` | "Dynamic" Casting in Java | [
"",
"java",
"inheritance",
"casting",
""
] |
I am trying to implement the python logging handler `TimedRotatingFileHandler`.
When it rolls over to midnight it appends the current day in the form `YYYY-MM-DD`.
```
LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s'
LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(
level=logging.DEBUG,
format=LOGGING_MSG_FORMAT,
datefmt=LOGGING_DATE_FORMAT
)
root_logger = logging.getLogger('')
logger = logging.handlers.TimedRotatingFileHandler("C:\\logs\\Rotate_Test",'midnight',1)
root_logger.addHandler(logger)
while True:
daemon_logger = logging.getLogger('TEST')
daemon_logger.info("SDFKLDSKLFFJKLSDD")
time.sleep(60)
```
The first log file created is named `Rotate_Test`, then once it rolls over to the next day it changes the file name to `Rotate_Test.YYYY-MM-DD` where `YYYY-MM-DD` is the current day.
How can I change how it alters the filename? | "How can i change how it alters the filename?"
Since it isn't documented, I elected to read the source. This is what I concluded from reading the source of `logging/handlers.py`
```
handler = logging.handlers.TimedRotatingFileHandler("C:\\isis_ops\\logs\\Rotate_Test",'midnight',1)
handler.suffix = "%Y-%m-%d" # or anything else that strftime will allow
root_logger.addHandler(handler)
```
The suffix is the formatting string. | You can do this by changing the log suffix as suggested above but you will also need to change the extMatch variable to match the suffix for it to find rotated files:
```
handler.suffix = "%Y%m%d"
handler.extMatch = re.compile(r"^\d{8}$")
``` | TimedRotatingFileHandler Changing File Name? | [
"",
"python",
"logging",
""
] |
I'm trying to set a WPF image's source in code. The image is embedded as a resource in the project. By looking at examples I've come up with the below code. For some reason it doesn't work - the image does not show up.
By debugging I can see that the stream contains the image data. So what's wrong?
```
Assembly asm = Assembly.GetExecutingAssembly();
Stream iconStream = asm.GetManifestResourceStream("SomeImage.png");
PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
ImageSource iconSource = iconDecoder.Frames[0];
_icon.Source = iconSource;
```
The icon is defined something like this: `<Image x:Name="_icon" Width="16" Height="16" />` | After having the same problem as you and doing some reading, I discovered the solution - [Pack URIs](http://msdn.microsoft.com/en-us/library/aa970069.aspx).
I did the following in code:
```
Image finalImage = new Image();
finalImage.Width = 80;
...
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
logo.EndInit();
...
finalImage.Source = logo;
```
Or shorter, by using another BitmapImage constructor:
```
finalImage.Source = new BitmapImage(
new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png"));
```
The URI is broken out into parts:
* Authority: `application:///`
* Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: `AssemblyShortName[;Version][;PublicKey];component/Path`
+ AssemblyShortName: the short name for the referenced assembly.
+ ;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.
+ ;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.
+ ;component: specifies that the assembly being referred to is referenced from the local assembly.
+ /Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder.
The three slashes after `application:` have to be replaced with commas:
> Note: The authority component of a pack URI
> is an embedded URI that points to a
> package and must conform to RFC 2396.
> Additionally, the "/" character must
> be replaced with the "," character,
> and reserved characters such as "%"
> and "?" must be escaped. See the OPC
> for details.
And of course, make sure you set the build action on your image to `Resource`. | ```
var uriSource = new Uri(@"/WpfApplication1;component/Images/Untitled.png", UriKind.Relative);
foo.Source = new BitmapImage(uriSource);
```
This will load a image called "Untitled.png" in a folder called "Images" with its "Build Action" set to "Resource" in an assembly called "WpfApplication1". | Setting WPF image source in code | [
"",
"c#",
".net",
"wpf",
"image",
""
] |
If I am assigning an event handler at runtime and it is in a spot that can be called multiple times, what is the recommended practice to prevent multiple assignments of the same handler to the same event.
```
object.Event += MyFunction
```
Adding this in a spot that will be called more than once will execute the handler 'n' times (of course).
I have resorted to removing any previous handler before trying to add via
```
object.Event -= MyFunction;
object.Event += MyFunction;
```
This works but seems off somehow. Any suggestions on proper handling ;) of this scenario. | Baget is right about using an explicitly implemented event (although there's a mixture there of explicit interface implementation and the full event syntax). You can probably get away with this:
```
private EventHandler foo;
public event EventHandler Foo
{
add
{
// First try to remove the handler, then re-add it
foo -= value;
foo += value;
}
remove
{
foo -= value;
}
}
```
That may have some odd edge cases if you ever add or remove multicast delegates, but that's unlikely. It also needs careful documentation as it's not the way that events normally work. | I tend to add an event handler in a path that's executed once, for example in a constructor. | Preventing same Event handler assignment multiple times | [
"",
"c#",
"events",
""
] |
I'm teaching myself some basic scraping and I've found that sometimes the URL's that I feed into my code return 404, which gums up all the rest of my code.
So I need a test at the top of the code to check if the URL returns 404 or not.
This would seem like a pretty straightfoward task, but Google's not giving me any answers. I worry I'm searching for the wrong stuff.
One blog recommended I use this:
```
$valid = @fsockopen($url, 80, $errno, $errstr, 30);
```
and then test to see if $valid if empty or not.
But I think the URL that's giving me problems has a redirect on it, so $valid is coming up empty for all values. Or perhaps I'm doing something else wrong.
I've also looked into a "head request" but I've yet to find any actual code examples I can play with or try out.
Suggestions? And what's this about curl? | If you are using PHP's [`curl` bindings](https://www.php.net/manual/en/ref.curl.php), you can check the error code using [`curl_getinfo`](https://www.php.net/manual/en/function.curl-getinfo.php) as such:
```
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
/* Handle 404 here. */
}
curl_close($handle);
/* Handle $response here. */
``` | If your running php5 you can use:
```
$url = 'http://www.example.com';
print_r(get_headers($url, 1));
```
Alternatively with php4 a user has contributed the following:
```
/**
This is a modified version of code from "stuart at sixletterwords dot com", at 14-Sep-2005 04:52. This version tries to emulate get_headers() function at PHP4. I think it works fairly well, and is simple. It is not the best emulation available, but it works.
Features:
- supports (and requires) full URLs.
- supports changing of default port in URL.
- stops downloading from socket as soon as end-of-headers is detected.
Limitations:
- only gets the root URL (see line with "GET / HTTP/1.1").
- don't support HTTPS (nor the default HTTPS port).
*/
if(!function_exists('get_headers'))
{
function get_headers($url,$format=0)
{
$url=parse_url($url);
$end = "\r\n\r\n";
$fp = fsockopen($url['host'], (empty($url['port'])?80:$url['port']), $errno, $errstr, 30);
if ($fp)
{
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: ".$url['host']."\r\n";
$out .= "Connection: Close\r\n\r\n";
$var = '';
fwrite($fp, $out);
while (!feof($fp))
{
$var.=fgets($fp, 1280);
if(strpos($var,$end))
break;
}
fclose($fp);
$var=preg_replace("/\r\n\r\n.*\$/",'',$var);
$var=explode("\r\n",$var);
if($format)
{
foreach($var as $i)
{
if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$i,$parts))
$v[$parts[1]]=$parts[2];
}
return $v;
}
else
return $var;
}
}
}
```
Both would have a result similar to:
```
Array
(
[0] => HTTP/1.1 200 OK
[Date] => Sat, 29 May 2004 12:28:14 GMT
[Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux)
[Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
[ETag] => "3f80f-1b6-3e1cb03b"
[Accept-Ranges] => bytes
[Content-Length] => 438
[Connection] => close
[Content-Type] => text/html
)
```
Therefore you could just check to see that the header response was OK eg:
```
$headers = get_headers($url, 1);
if ($headers[0] == 'HTTP/1.1 200 OK') {
//valid
}
if ($headers[0] == 'HTTP/1.1 301 Moved Permanently') {
//moved or redirect page
}
```
[W3C Codes and Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html "W3C Codes and Definitions") | Easy way to test a URL for 404 in PHP? | [
"",
"php",
"http",
"validation",
"http-headers",
"http-status-code-404",
""
] |
How does `const` (pointers, references and member functions) help with thread safety in C++? | The main problem with multiple threads is mutability. const restricts this, but since you can cast away the const-ness, it's not foolproof. | Any immutable (that is, unchangable) data is inherently thread safe - there's no risk for multiple threads concurrently reading the same read-only data because it's never going to change!
Marking a variable as const in C++ makes it read-only and thus thread safe. | Thread safety and `const` | [
"",
"c++",
"multithreading",
""
] |
The code below is checking performance of three different ways to do same solution.
```
public static void Main(string[] args)
{
// for loop
{
Stopwatch sw = Stopwatch.StartNew();
int accumulator = 0;
for (int i = 1; i <= 100000000; ++i)
{
accumulator += i;
}
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, accumulator);
}
//Enumerable.Range
{
Stopwatch sw = Stopwatch.StartNew();
var ret = Enumerable.Range(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n);
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret);
}
//self-made IEnumerable<int>
{
Stopwatch sw = Stopwatch.StartNew();
var ret = GetIntRange(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n);
sw.Stop();
Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret);
}
}
private static IEnumerable<int> GetIntRange(int start, int count)
{
int end = start + count;
for (int i = start; i < end; ++i)
{
yield return i;
}
}
}
```
The results are:
```
time = 306; result = 987459712
time = 1301; result = 987459712
time = 2860; result = 987459712
```
It is not surprising that the "for loop" is faster than the other two solutions, because Enumerable.Aggregate takes more method invocations. However, it really surprises me that "Enumerable.Range" is faster than the "self-made IEnumerable". I thought that Enumerable.Range would have more overhead than the simple GetIntRange method.
What are the possible reasons for this? | Why should `Enumerable.Range` be any slower than your self-made `GetIntRange`? In fact, if `Enumerable.Range` were defined as
```
public static class Enumerable {
public static IEnumerable<int> Range(int start, int count) {
var end = start + count;
for(var current = start; current < end; ++current) {
yield return current;
}
}
}
```
then it should be exactly as fast as your self-made `GetIntRange`. This is in fact the reference implementation for `Enumerable.Range`, absent any tricks on the part of the compiler or programmer.
You may want to compare your `GetIntRange` and `System.Linq.Enumerable.Range` with the following implementation (of course, compile in release mode, as Rob points out). This implementation may be slightly optimized with respect to what a compiler would generate from an iterator block.
```
public static class Enumerable {
public static IEnumerable<int> Range(int start, int count) {
return new RangeEnumerable(start, count);
}
private class RangeEnumerable : IEnumerable<int> {
private int _Start;
private int _Count;
public RangeEnumerable(int start, int count) {
_Start = start;
_Count = count;
}
public virtual IEnumerator<int> GetEnumerator() {
return new RangeEnumerator(_Start, _Count);
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
private class RangeEnumerator : IEnumerator<int> {
private int _Current;
private int _End;
public RangeEnumerator(int start, int count) {
_Current = start - 1;
_End = start + count;
}
public virtual void Dispose() {
_Current = _End;
}
public virtual void Reset() {
throw new NotImplementedException();
}
public virtual bool MoveNext() {
++_Current;
return _Current < _End;
}
public virtual int Current { get { return _Current; } }
object IEnumerator.Current { get { return Current; } }
}
}
``` | My guess is that you're running in a debugger. Here are my results, having built from the command line with "/o+ /debug-"
```
time = 142; result = 987459712
time = 1590; result = 987459712
time = 1792; result = 987459712
```
There's still a slight difference, but it's not as pronounced. Iterator block implementations aren't quite as efficient as a tailor-made solution, but they're pretty good. | Why is Enumerable.Range faster than a direct yield loop? | [
"",
"c#",
"performance",
"ienumerable",
"range",
"enumerable",
""
] |
I am trying to test that a particular method throws an expected exception from a method. As per JUnit4 documentation and [this answer](https://stackoverflow.com/questions/156503/how-to-assert-that-a-certain-exception-is-thrown-in-junit45-tests) I wrote the test as:
```
@Test(expected=CannotUndoException.class)
public void testUndoThrowsCannotUndoException() {
// code to initialise 'command'
command.undo();
}
```
However, this code fails the JUnit test, reporting the thrown (and expected) exception as an error.
The method I'm testing has only this in the body:
```
public void undo() {
throw new CannotUndoException();
}
```
Furthermore, the following test passes:
```
public void testUndoThrowsCannotUndoException() {
// code to initialise 'command'
try {
command.undo();
fail();
} catch (CannotUndoException cue){
}
}
```
Meaning that the expected exception is actually thrown.
I am actually planning to change the method to actually do something, rather than just throw the exception, but it's got me curious as to what caused the problem, lest it should happen again in the future.
The following checks have been made:
* the CannotUndoException imported into the test case is the correct one
* version 4 of JUnit is the only one on my classpath
* a clean and build of Eclipse workspace did not change the outcome
I am using JUnit 4.1, and in the same test I am using Mockito.
What could be causing the erroneous failure? | I have found the problem.
The TestRunner I was using was the correct one (JUnit 4), however, I declared my test class as:
```
public class CommandTest extends TestCase
```
Which I assume is causing the test runner to treat it as a JUnit 3 test. I removed `extends TestCase` and received the expected results. | Your test code looks ok to me.
Check that you're running with a junit 4 testrunner, not a junit 3.8 testrunner - this could very well be the culprit here (try launching from the command line or just visually inspect the command line when running your test). *The classpath of your testrunner may not be the same as your project classpath*
This is particularly the case inside IDE's. Alternately you could also try to push to junit 4.4 and see if that solves your problem. (junit 4.5 may cause other problems). | Cause of an unexpected behaviour using JUnit 4's expected exception mechanism? | [
"",
"java",
"unit-testing",
"exception",
"junit4",
""
] |
I decided to change a utility I'm working on to use a tabpage. When I tried to drag various controls from the form to a tab page on top of the form, it made copies of the control, giving it a different name. It's easy enough to just remake the form on top of the tab or just edit the source code in the designer to have everything be added to the tab instead (and this is what I did, which worked), but it seems like there would probably be a better way to do this via the gui. | Have you tried cut and paste. That usually works for me. | The correct tool for this is the Document Outline (CTRL+W, U). Simply drag your set of controls in the outline so that they are under the tab page. Voila.
The document outline dramatically simplifies these types of operations, especially when you are dealing with complex layouts. | C#: Move Controls From Form to tabPage in VS Form Designer | [
"",
"c#",
"winforms",
"visual-studio-2005",
"windows-forms-designer",
""
] |
I've seen several of answers about using [Handle](http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx) or [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx), but I would like to be able to find out in my own code (C#)
which process is locking a file.
I have a nasty feeling that I'm going to have to spelunk around in the win32 API, but if anyone has already done this and can put me on the right track, I'd really appreciate the help.
## Update
### Links to similar questions
* [How does one figure out what process locked a file using c#?](https://stackoverflow.com/questions/860656/how-does-one-figure-out-what-process-locked-a-file-using-c)
* [Command line tool](https://stackoverflow.com/questions/241178/command-line-tool-for-finding-out-who-is-locking-a-file)
* [Across a Network](https://stackoverflow.com/questions/208283/is-it-possible-to-programatically-find-out-what-process-is-locking-a-file-acros)
* [Locking a USB device](https://stackoverflow.com/questions/23197/find-out-which-process-has-an-exclusive-lock-on-a-usb-device-handle)
* [Unit test fails with locked file](https://stackoverflow.com/questions/305843/determining-what-process-has-a-lock-on-a-file)
* [deleting locked file](https://stackoverflow.com/questions/1040/how-do-i-delete-a-file-which-is-locked-by-another-process-in-c) | One of the good things about `handle.exe` is that you can run it as a subprocess and parse the output.
We do this in our deployment script - works like a charm. | Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the [Restart Manager API](http://msdn.microsoft.com/en-us/library/windows/desktop/aa373656%28v=vs.85%29.aspx), that information is now tracked.
I put together code that takes the path of a file and returns a `List<Process>` of all processes that are locking that file.
```
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.Collections.Generic;
public static class FileUtil
{
[StructLayout(LayoutKind.Sequential)]
struct RM_UNIQUE_PROCESS
{
public int dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
const int RmRebootReasonNone = 0;
const int CCH_RM_MAX_APP_NAME = 255;
const int CCH_RM_MAX_SVC_NAME = 63;
enum RM_APP_TYPE
{
RmUnknownApp = 0,
RmMainWindow = 1,
RmOtherWindow = 2,
RmService = 3,
RmExplorer = 4,
RmConsole = 5,
RmCritical = 1000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct RM_PROCESS_INFO
{
public RM_UNIQUE_PROCESS Process;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
public string strAppName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
public string strServiceShortName;
public RM_APP_TYPE ApplicationType;
public uint AppStatus;
public uint TSSessionId;
[MarshalAs(UnmanagedType.Bool)]
public bool bRestartable;
}
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
static extern int RmRegisterResources(uint pSessionHandle,
UInt32 nFiles,
string[] rgsFilenames,
UInt32 nApplications,
[In] RM_UNIQUE_PROCESS[] rgApplications,
UInt32 nServices,
string[] rgsServiceNames);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
[DllImport("rstrtmgr.dll")]
static extern int RmEndSession(uint pSessionHandle);
[DllImport("rstrtmgr.dll")]
static extern int RmGetList(uint dwSessionHandle,
out uint pnProcInfoNeeded,
ref uint pnProcInfo,
[In, Out] RM_PROCESS_INFO[] rgAffectedApps,
ref uint lpdwRebootReasons);
/// <summary>
/// Find out what process(es) have a lock on the specified file.
/// </summary>
/// <param name="path">Path of the file.</param>
/// <returns>Processes locking the file</returns>
/// <remarks>See also:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
/// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
///
/// </remarks>
static public List<Process> WhoIsLocking(string path)
{
uint handle;
string key = Guid.NewGuid().ToString();
List<Process> processes = new List<Process>();
int res = RmStartSession(out handle, 0, key);
if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
try
{
const int ERROR_MORE_DATA = 234;
uint pnProcInfoNeeded = 0,
pnProcInfo = 0,
lpdwRebootReasons = RmRebootReasonNone;
string[] resources = new string[] { path }; // Just checking on one resource.
res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
if (res != 0) throw new Exception("Could not register resource.");
//Note: there's a race condition here -- the first call to RmGetList() returns
// the total number of process. However, when we call RmGetList() again to get
// the actual processes this number may have increased.
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
if (res == ERROR_MORE_DATA)
{
// Create an array to store the process results
RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
pnProcInfo = pnProcInfoNeeded;
// Get the list
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
if (res == 0)
{
processes = new List<Process>((int)pnProcInfo);
// Enumerate all of the results and add them to the
// list to be returned
for (int i = 0; i < pnProcInfo; i++)
{
try
{
processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
}
// catch the error -- in case the process is no longer running
catch (ArgumentException) { }
}
}
else throw new Exception("Could not list processes locking resource.");
}
else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
}
finally
{
RmEndSession(handle);
}
return processes;
}
}
```
**Using from Limited Permission (e.g. IIS)**
This call accesses the registry. If the process does not have permission to do so, you will get ERROR\_WRITE\_FAULT, [meaning](https://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx) `An operation was unable to read or write to the registry`. You *could* selectively grant permission to your restricted account to the necessary part of the registry. It is more secure though to have your limited access process set a flag (e.g. in the database or the file system, or by using an interprocess communication mechanism such as queue or named pipe) and have a second process call the Restart Manager API.
Granting other-than-minimal permissions to the IIS user is a security risk. | How do I find out which process is locking a file using .NET? | [
"",
"c#",
"file-locking",
""
] |
Should Java Objects be reused as often as it can be reused ? Or should we reuse it only when they are "heavyweight", ie have OS resources associated with it ?
All old articles on the internet talk about object reuse and object pooling as much as possible, but I have read recent articles that say `new Object()` is highly optimized now ( 10 instructions ) and Object reuse is not as big a deal as it used to be.
What is the current best practice and how are you people doing it ? | I let the garbage collector do that kind of deciding for me, the only time I've hit heap limit with freshly allocated objects was after running a buggy recursive algorithm for a couple of seconds which generated 3 \* 27 \* 27... new objects as fast as it could.
Do what's best for readability and encapsulation. Sometimes reusing objects may be useful, but generally you shouldn't worry about it. | If you use them very **intensively** and the construction is **costly**, you should try to reuse them as much as you can.
If your objects are very small, and cheap to create ( like Object ) you should create new ones.
For instance connections database are pooled because the cost of creating a new one is higher than those of creating .. mmhh new Integer for instance.
So the answer to your question is, reuse when they are heavy **AND** are used often ( it is not worth to pool a 3 mb object that is only used twice )
**Edit:**
Additionally, this item from Effective Java:[Favor Immutability](http://www.google.com/search?q=Effective+Java+Favor+Immutability+Joshua+Bloch) is worth reading and may apply to your situation. | Java Object Reuse | [
"",
"java",
""
] |
I recently asked this question: [Expose XML or Objects](https://stackoverflow.com/questions/368521/api-design-expose-xml-or-objects "Expose XML or Objects") - thanks all for the responses.
One point to clarify.
* The API will always be accessed remotely (i.e. as a service), most probably via webservices or WCF.
I agree that in theory a strongly typed API exposing objects as the inputs/outputs is the *right* way to go. However, I feel that there is still an argument to be made for exposing XML. As I see it the reasons for using XML are:
1. The business rules can be written by business analysts in Schematron.
2. The interface is weakly typed, but as soon as it is called the data can be validated against data and business rules.
3. The service's implementation will be simpler. There won't be any need to create an domain object model.
4. The XML schema is already defined (we have a data dictionary of schema).
5. Using web services technology means that an XML based API will not need to change as new car 'types' are added, e.g.
```
void AddNewCar( string newCarXml )
string[] GetCars( /* some query conditions */ )
```
If we used an object based API then adding a new type would require a new query method defining the possible derived types that could be returned (see [extending web services](https://stackoverflow.com/questions/374253/extend-webservice-without-impacting-existing-clients-returning-derived-types-fr "extending webservices")). Updating the web service like this would require this services and *all* existing clients to be rebuilt and redeployed.
What does an object based API give us? A strongly typed declarative interface. It does not provide any more abstraction than XML (XML is itself an abstraction). What does the object based API cost? It costs an entire set of domain objects which will need business rules and data validation.
So, what is my question? Give me an un-defeatble, unarguable reason why I should go with objects. | * Objects can perform better (thinking binary serialization here).
* Objects can have stronger simple type validations.
* Objects allow you to put the validation and business rules closer to the data structure definition.
* Objects by their nature allow you to write simpler business rules and validation, since much of that is embedded in the object definition itself.
* **Objects can also define behaviors.**
* .Net makes it simple to turn Objects into Xml and back again via serialization, giving objects most of the same benefits as xml. | If you're looking for an argument in favour of XML (not that I am particularly in favour of XML) are:
* Exposing the XML and providing an XSD is self explanatory when it comes to data. You can pass off all the data in that form, it's self documenting and can be validated reasonably simply.
* I can write a bunch of safe code against my database or code model and I can release the data in a self contained and safe manner to other business units that requires minimal further documentation or explanation.
* It's so easy to read that often you can read it as easily as you could read the documentation or code comments.
The arguments against it however, go on and on...to name the worst offenders:
* Overly verbose.
* Huge network overhead.
* Require an understanding of an extra technology, perhaps needlessly(?).
* The more complex you make something, the greater opportunity for errors there are. | API Design: Expose XML or Objects #2 | [
"",
"c#",
"web-services",
"architecture",
"n-tier-architecture",
""
] |
I would like to use `ON DUPLICATE KEY UPDATE` in Zend Framework 1.5, is this possible?
Example
```
INSERT INTO sometable (...)
VALUES (...)
ON DUPLICATE KEY UPDATE ...
``` | I worked for Zend and specifically worked on Zend\_Db quite a bit.
No, there is no API support for the `ON DUPLICATE KEY UPDATE` syntax. For this case, you must simply use `query()` and form the complete SQL statement yourself.
I do not recommend interpolating values into the SQL as harvejs shows. Use query parameters.
Edit: You can avoid repeating the parameters by using `VALUES()` expressions.
```
$sql = "INSERT INTO sometable (id, col2, col3) VALUES (:id, :col2, :col3)
ON DUPLICATE KEY UPDATE col2 = VALUES(col2), col3 = VALUES(col3)";
$values = array("id"=>1, "col2"=>327, "col3"=>"active");
``` | As a sidebar, you can simplify the `ON DUPLICATE KEY UPDATE` clause and reduce the amount of processing your script needs to do by using `VALUES()`:
```
$sql = 'INSERT INTO ... ON DUPLICATE KEY UPDATE id = VALUES(id), col2 = VALUES(col2), col3 = VALUES(col3)';
```
See <http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html> for more information. | Is there a way to do an "INSERT...ON DUPLICATE KEY UPDATE" in Zend Framework 1.5? | [
"",
"php",
"mysql",
"zend-framework",
"insert-update",
""
] |
I am a bit of a newbie to Reg Ex and don't fully understand the difference between the different flavors. However, I have a basic Reg Ex that works when I try it via the UNIX system (vi and grep) but not when I try to to use it in PHP's ereg functions. I suspect there is something different about the PHP ereg function that is making this not work:
```
<?php
$string = 'Feugiat <em>hendrerit</em> sit iriuredolor aliquam.';
$string = ereg_replace("<em\b[^>]*>(.*?)</em>","\\1",$string);
echo $string;
?>
```
I would like this to output **Feugiat hendrerit sit iriuredolor aliquam.** without the em tags. However it just returns an empty string. | PHP's ereg functions use a very limited regex flavor called [POSIX ERE](http://www.regular-expressions.info/posix.html). My [flavor comparison](http://www.regular-expressions.info/refflavors.html) indicates all that this flavor lacks compared with modern flavors.
In your case, the word boundary \b is not supported. A strict POSIX implementation will flag \b as an error.
Your solution is to use the preg functions instead:
```
preg_replace('!<em\b[^>]*>(.*?)</em>!', '$1', $string);
```
Compared with other answers you've received: Don't escape the backslash in \b, and use $1 for the replacement. preg\_replace uses a different replacement text syntax than ereg\_replace. | You may need to escape the backslash:
```
$string = ereg_replace("<em\\b[^>]*>(.*?)</em>","\\1",$string);
```
This is because `\b` in a PHP string means something different from a `\b` in a regular expression. Using `\\` in the PHP string passes through a single backslash to `ereg_replace()`. This is the same reason you need to use double backslash in the replacement string `"\\1"`.
Depending on your application, you may also want to consider the possibility that your input `$string` does not contain any `<em>` tags. In that case, the above statements would result in an empty string, which is probably not what you intend. | Why won't this standard Reg Ex work in PHP's ereg function | [
"",
"php",
"html",
"regex",
""
] |
I want to do something like this:
page A has a link to page B
page B gets content from a database and processes it
the result from page B is displayed on a div in page A
Please notice that I don't want to leave page A while page B processes the information of the database.
What I'm really trying to do is avoid using frames in the site, and I want to make the pages appear in a `div`. Is this possible?
I'm guessing its kinda of a newbie question, but it's really bugging me and i don't even know where to start looking. | You want AJAX!
AJAX will do that, but the steps will be a little different from what you describe
* page A has a link that calls a javascript function
* the javascript function makes an AJAX call to page B which gets content from a database and processes it
* the result from page B is returned to the javascript function
* page a displays it in a div | What you are looking for is JavaScript and AJAX. | Is it possible to change an HTML element property using its ID with PHP? | [
"",
"php",
"html",
""
] |
Helvetica is available in one form or another on Windows, Mac OS X, and Linux. Under Windows, I can see it from Microsoft Word. On the two UNIX platforms, I can find it with xlsfonts | grep -i helvetica; the name seems to be adobe-helvetica.
But the JDK can't find it! It's not listed from GraphicsEnvironment.getAllFonts(), nor does it come up when I call new Font("Helvetica", ...) [using several name variants, either, like "Adobe Helvetica"]; instead I get defaulted to "Dialog" font and it seems to name it with whatever name I used.
This font is available on every relevant Java target platform today. How do I use it from within Java? | I realize that this isn't actually answering the question, but...
On Windows, Helvetica isn't always installed. My machine at work (the one I'm using now) doesn't, despite having Microsoft Office XP. | ```
Font f = new Font("Helvetica", Font.PLAIN, 10); // make a new font object
ObjectName.setFont(f); // set the objects font using setFont();
```
where "Helvetica" is the font, Font.PLAIN defines the style, and 10 defines the size. Of course it must be installed to work, and you can bundle it using CreateFont().
Try the [Java API for Fonts](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Font.html) for more reference. | How do I use Helvetica in Java? | [
"",
"java",
"fonts",
""
] |
I'm loading an XML document in my C# application with the following:
```
XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);
```
but before that, I do test to make sure the file exists with:
```
File.Exists(myfile);
```
But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file? In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception.
The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say "
Thanks!
-Adeena | It's probably just worth catching the specific exception if you want to show a message to the user:
```
try
{
XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);
}
catch (XmlException exception)
{
ShowMessage("Your XML was probably bad...");
}
``` | **This question confuses "[well-formed](http://www.w3.org/TR/REC-xml/#sec-well-formed)" with "[valid](http://en.wikipedia.org/wiki/Valid_XML_document)" XML document**.
A valid xml document is by definition a well formed document. **Additionally**, it must satisfy a [**DTD**](http://www.w3.org/TR/REC-xml/#dt-doctype) or a schema (an [**xml schema**](http://www.w3.org/TR/xmlschema-0/), a [**relaxng schema**](http://relaxng.org/), [**schematron**](http://www.schematron.com/) or [**other constraints**](http://en.wikipedia.org/wiki/XML_Schema#XML_schema_languages)) to be valid.
Judging from the wording of the question, most probably it asks:
**"How to make sure a file contains a well-formed XML document?".**
The answer is that an XML document is well-formed if it can be parsed successfully by a compliant XML parser. As the [**XDocument.Load()**](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx) method does exactly this, you only need to catch the exception and then conclude that the text contained in the file is not well formed. | How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()? | [
"",
"c#",
"xml",
"linq-to-xml",
""
] |
I'm working with a code base where lists need to be frequently searched for a single element.
Is it faster to use a Predicate and Find() than to manually do an enumeration on the List?
for example:
```
string needle = "example";
FooObj result = _list.Find(delegate(FooObj foo) {
return foo.Name == needle;
});
```
vs.
```
string needle = "example";
foreach (FooObj foo in _list)
{
if (foo.Name == needle)
return foo;
}
```
While they are equivalent in functionality, are they equivalent in performance as well? | They are not equivalent in performance. The Find() method requires a method (in this case delegate) invocation for every item in the list. Method invocation is not free and is **relatively** expensive as compared to an inline comparison. The foreach version requires no extra method invocation per object.
That being said, I wouldn't pick one or the other based on performance until I actually profiled my code and found this to be a problem. I haven't yet found the overhead of this scenario to every be a "hot path" problem for code I've written and I use this pattern a lot with Find and other similar methods. | If searching your list is too slow as-is, you can probably do better than a linear search. If you can keep the list sorted, you can use a binary search to find the element in O(lg n) time.
If you're searching a *whole* lot, consider replacing that list with a Dictionary to index your objects by name. | Find() vs. enumeration on lists | [
"",
"c#",
"performance",
"search",
"list",
""
] |
What's the best way to animate a background image sliding to the left, and looping it? Say I've got a progress bar with a background I want to animate when it's active (like in Gnome or OS X).
I've been playing with the `$(...).animate()` function and trying to modify the relevant CSS property, but I keep hitting a brick wall when trying to figure out how to modify the `background-position` property. I can't just increment its value, and I'm not sure if this is even the best approach.
Any help appreciated! | As soon as I posted this I figured it out. In case it helps anyone else, here's the function I came up with:
```
function animateBar(self) {
// Setup
var bar = self.element.find('.ui-progress-bar');
bar.css('background-position', '0px 0px');
bar.animate({
backgroundPosition: '-20px 0px'
}, 1000, 'linear', function() {
animateBar(self);
});
}
``` | Just a suggestion, but rather than using a standard function and passing in the element as an argument, it would be better to use fn.extend.
```
$.fn.extend({
animateBar: function(){
$(this).find('.ui-progress-bar').css('background-position', '0px 0px');
$(this).find('.ui-progress-bar').animate({
backgroundPosition: '-20px 0px'
}, 1000, 'linear', function() {
animateBar(self);
});
}
});
```
Then you would call the function like this:
```
$(this).animateBar();
```
vs
```
animateBar( $(this) );
```
Just my 2 cents. However @Markus 's Gif solutions is definitely superior, unless you have a specific reason to use an image animated by jQuery. Also your solution will not loop on its own. | Easiest way to animate background image sliding left? | [
"",
"javascript",
"jquery",
"css",
"jquery-animate",
""
] |
I have test database and a production database. When developing I of course work against that test database then when deploying I have to semi-manually update the production database (by running a batch-sql-script). This usually works fine but there's a chance for mistakes where the deployed database isn't the same as the test database.
For tables: Is there any way that I can automatically test all entities that I've mapped using linq2sql against a the production database so that all properties etc. exist? | I use a similar approach during development and I can ensure that the synchronization between the development and production databases can easily become a daunting task if you modify too many tables at once.
I realized that the best approach would be to forget about doing this synchronization manually, it's simply too time consuming and prone to errors, and started using a tool to automate the process.
I've been using the RedGate SQlCompare and I can say that I couldn't live without it anymore. It compares all the structure of the databases, pointing the modifications and applying the changes flawlessly, even in tables with millions of records.
[Link to Redgate SQL Compare](http://www.red-gate.com/products/SQL_Compare/index.htm) | As far as I can tell, there's no way to automatically test before doing a submit. You can however infer it and programmatically check it. I have a controller for each Linq object that I use to marshal the Linq object, and that controller has an IsValid method that goes through and checks the db rules using a technique I saw here:
<http://www.codeproject.com/KB/cs/LinqColumnAttributeTricks.aspx>
I call it with the following code:
```
if (address.City.Length > Utilities.LinqValidate.GetLengthLimit(address, "City"))
throw new ArgumentOutOfRangeException("address.City Max Length Exceeded");
```
Here's a modified version of the utility that I'm using:
```
public static int GetLengthLimit(object obj, string field)
{
int dblenint = 0; // default value = we can't determine the length
Type type = obj.GetType();
PropertyInfo prop = type.GetProperty(field);
// Find the Linq 'Column' attribute
// e.g. [Column(Storage="_FileName", DbType="NChar(256) NOT NULL", CanBeNull=false)]
object[] info = prop.GetCustomAttributes(typeof(ColumnAttribute), true);
// Assume there is just one
if (info.Length == 1)
{
ColumnAttribute ca = (ColumnAttribute)info[0];
string dbtype = ca.DbType;
if (dbtype.StartsWith("NChar") || dbtype.StartsWith("NVarChar") ||
dbtype.StartsWith("Char") || dbtype.StartsWith("VarChar")
)
{
int index1 = dbtype.IndexOf("(");
int index2 = dbtype.IndexOf(")");
string dblen = dbtype.Substring(index1 + 1, index2 - index1 - 1);
int.TryParse(dblen, out dblenint);
}
}
return dblenint;
}
public static bool CanBeNull(object obj, string field)
{
bool canBeNull = false;
Type type = obj.GetType();
PropertyInfo prop = type.GetProperty(field);
object[] info = prop.GetCustomAttributes(typeof(ColumnAttribute), true);
if (info.Length == 1)
{
ColumnAttribute ca = (ColumnAttribute)info[0];
canBeNull = ca.CanBeNull;
}
return canBeNull;
}
``` | Linq2Sql Testing | [
"",
"c#",
".net",
"unit-testing",
"linq-to-sql",
""
] |
I have a variable of type Hashmap`<String,Integer`>.
In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this...
```
Hashmapvariable.put( somestring,
if (flag_variable) {
//manipulation code goes here
new Integer(manipulated value);
} else {
new Integer(non-manipulated value);
}
);
```
But I get an error:
> Syntax error on token(s), misplaced
> constructs.
at the Hashmapvariable.put call.
I also get another error
> Syntax error on token ")", delete this
> token.
at the final ");" line. But I can't delete the ")" - its the closing parentheses for the put method call.
I don't get this. What mistake am I doing? | You cannot place a statement in the method call.
However, one option could be to make an method that returns a `Integer` such as:
```
private Integer getIntegerDependingOnFlag(boolean flag)
{
if (flag)
return new Integer(MANIPULATED_VALUE);
else
return new Integer(NON-MANIPULATED_VALUE);
}
```
Then, you can make a call like this:
```
hashmap.put(someString, getIntegerDependingOnFlag(flag));
``` | ```
new Integer(flag_variable ? manipulated value : non-manipulated value)
```
Does the trick
Edit:
On Java 5, I suppose you can also write
```
hashmap.put(someString, flag_variable ? manipulated value : non-manipulated value)
```
due to auto-boxing. | If construct in hashmap.put call | [
"",
"java",
"hashmap",
""
] |
```
Image.FromFile(@"path\filename.tif")
```
or
```
Image.FromStream(memoryStream)
```
both produce image objects with only one frame even though the source is a multi-frame TIFF file. **How do you load an image file that retains these frames?** The tiffs are saved using the Image.SaveAdd methods frame by frame. They work in other viewers but .NET Image methods will not load these frames, only the first.
**Does this mean that there is no way to return a multi-frame TIFF from a method where I am passing in a collection of bitmaps to be used as frames?** | Here's what I use:
```
private List<Image> GetAllPages(string file)
{
List<Image> images = new List<Image>();
Bitmap bitmap = (Bitmap)Image.FromFile(file);
int count = bitmap.GetFrameCount(FrameDimension.Page);
for (int idx = 0; idx < count; idx++)
{
// save each frame to a bytestream
bitmap.SelectActiveFrame(FrameDimension.Page, idx);
MemoryStream byteStream = new MemoryStream();
bitmap.Save(byteStream, ImageFormat.Tiff);
// and then create a new Image from it
images.Add(Image.FromStream(byteStream));
}
return images;
}
``` | I was able to handle the multi-frame tiff by using the below method.
```
Image multiImage = Image.FromFile(sourceFile);
multiImage.Save(destinationFile, tiff, prams);
int pageCount = multiImage.GetFrameCount(FrameDimension.Page);
for (int page = 1; page < pageCount; page++ )
{
multiImage.SelectActiveFrame(FrameDimension.Page,page);
multiImage.SaveAdd(dupImage,prams);
}
multiImage.SaveAdd(newPage, prams);
multiImage.Dispose();
```
I have not tried the solution in .net 2.0 but MSDN shows the class members to exist. It did fix my problem in .net 4.5.2. | How to open a multi-frame TIFF imageformat image in .NET 2.0? | [
"",
"c#",
"tiff",
"system.drawing",
""
] |
Explanation:
Say package A is always built first and then package B. I need to configure my eclipse workspace such that it mimics the build environment and shows compilation errors when sources in package A refer package B. Is this possible? If yes, how? | Take a look to: [Arquitecture Rules](http://architecturerules.googlecode.com/svn/docs/downloads.html) or [Macker](http://innig.net/macker/)
These tools are able to warn you when some rule is broken. They both support the rule "some package should not invoke some other package".
I do not know if there is an eclipse plugin for any of them, sorry. | You'd need to build them as separate projects, with project B referring to project A but not the other way round. | How do I enforce a package-level build order in eclipse | [
"",
"java",
"eclipse",
"ide",
""
] |
I have following situation. A main table and many other tables linked together with foreign keys. Now when I would like to delete a row in the main table a ConstraintsViolation will occur, which is intended and good.
Now I want to be able to check if the ConstraintsViolation will occur before I trigger the delete row event.
Is this possible? | ```
If Exists ( Select * From OtherTable
Where OtherTableFKColumn = MainTablePrimaryKey)
Begin
Rollback Transaction
RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1)
End
``` | This is a question that on the surface looks good, but has implications.
First of all, you'd need to ensure that after you've read the status of those relations, nobody could change those, so obviously you need to use a transaction and lock the rows in question.
Then you need a way to figure out what relations to check, as I see in a comment here your question about what happens if someone later adds a new relation. So you need to query the schema, or perhaps auto-generate this code from the schema, so that the detection mechanism only needs to run each time you change the schema.
Now, does the exception you get really seem that expensive after this ordeal? | Can I check for constraints before a delete in SQL Server? | [
"",
"sql",
"database",
"sql-server-2005",
"constraints",
""
] |
I would like to compare two dates in javascript. I have been doing some research, but all I can find is how to return the current date. I want to compare 2 separate dates, not related to today. How do I do that.
```
var startDate = Date(document.form1.Textbox2);
``` | ```
if (date1.getTime() > date2.getTime()) {
alert("The first date is after the second date!");
}
```
[Reference to Date object](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date) | ```
new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()
``` | How do I do a Date comparison in Javascript? | [
"",
"javascript",
"datetime",
""
] |
Can anyone link me to a decent c++ tutorial that's actually currently in date? Almost everything I find applies to 2005 and the code examples are riddled with errors which won't run in my 2008 version of the visual compiler. | The book *Accelerated C++* is a good start to learn C++. | Here is a Visual C++ 2008 Express Edition Introdution: [Introduction to Visual C++ 2008 Express (Video)](http://msdn.microsoft.com/en-us/beginner/bb964629.aspx). You will find a good book-list about Standard C++ here: <http://jcatki.no-ip.org:8080/fncpp/Resources#books> (that's the website of the ##c++ irc channel on irc.freenode.org). For an explanation of the difference between C++ and Visual C++ you can read this: <http://www.comeaucomputing.com/techtalk/#vc>. | Is there a tutorial on C++ programming in Visual Studio 2008? | [
"",
"c++",
"windows",
"visual-studio-2008",
""
] |
It seems that
```
if (x=y) { .... }
```
instead of
```
if (x==y) { ... }
```
is a root of many evils.
Why don't *all* compilers *mark it as error* instead of a configurable warning?
I'm interested in finding out cases where the construct `if (x=y)` is useful. | Most of the time, compilers try very hard to remain backward compatible.
Changing their behavior in this matter to throw errors will break existing legitimate code, and even starting to throw warnings about it will cause problems with automatic systems that keep track of code by automatically compiling it and checking for errors and warnings.
This is an evil we're pretty much stuck with at the moment, but there are ways to circumvent and reduce the dangers of it.
Example:
```
void *ptr = calloc(1, sizeof(array));
if (NULL = ptr) {
// Some error
}
```
This causes a compilation error. | One useful construct is for example:
```
char *pBuffer;
if (pBuffer = malloc(100))
{
// Continue to work here
}
```
As mentioned before, and downvoted several times now, I might add this is not specially good style, but I have seen it often enough to say it's useful. I've also seen this with `new`, but it makes more pain in my chest.
Another example, and less controversial, might be:
```
while (pointer = getNextElement(context))
{
// Go for it. Use the pointer to the new segment of data.
}
```
which implies that the function `getNextElement()` returns `NULL` when there is no next element so that the loop is exited. | Inadvertent use of = instead of == | [
"",
"c++",
"c",
"compiler-construction",
"programming-languages",
""
] |
I am working on an in-browser editor within a `textarea`. I have started looking for some information on dealing with `textarea` selection and found [this jQuery plugin, fieldSelection](https://github.com/localhost/jquery-fieldselection) that does some simple manipulation.
However, it doesn't explain what's going on.
I want to understand more on textarea selection in JavaScript, preferably with a description of both pre-DOM3 and post-DOM30 scenarios. | Start with PPK's [introduction to ranges](http://www.quirksmode.org/dom/range_intro.html). Mozilla developer connection has info on [W3C selections](https://developer.mozilla.org/en/DOM/window.getSelection). Microsoft have their system [documented on MSDN](http://msdn.microsoft.com/en-us/library/ms535869(VS.85).aspx). Some more tricks can be found [in the answers here](https://stackoverflow.com/questions/tagged/selection+javascript).
In addition to incompatible interfaces you'll be happy to know that there is extra bizarreness going on with `textarea` nodes. If I remember correctly they behave as any other nodes when you select them in IE, but in other browsers they have an independent selection range which is exposed via the `.selectionEnd` and `.selectionStart` properties on the node.
Additionally, you should really take a look at `.contentEditable` as a means to edit things live. From the release of Firefox3, this is now supported by all browsers. | ```
function get_selection(the_id)
{
var e = document.getElementById(the_id);
//Mozilla and DOM 3.0
if('selectionStart' in e)
{
var l = e.selectionEnd - e.selectionStart;
return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
}
//IE
else if(document.selection)
{
e.focus();
var r = document.selection.createRange();
var tr = e.createTextRange();
var tr2 = tr.duplicate();
tr2.moveToBookmark(r.getBookmark());
tr.setEndPoint('EndToStart',tr2);
if (r == null || tr == null) return { start: e.value.length, end: e.value.length, length: 0, text: '' };
var text_part = r.text.replace(/[\r\n]/g,'.'); //for some reason IE doesn't always count the \n and \r in the length
var text_whole = e.value.replace(/[\r\n]/g,'.');
var the_start = text_whole.indexOf(text_part,tr.text.length);
return { start: the_start, end: the_start + text_part.length, length: text_part.length, text: r.text };
}
//Browser not supported
else return { start: e.value.length, end: e.value.length, length: 0, text: '' };
}
function replace_selection(the_id,replace_str)
{
var e = document.getElementById(the_id);
selection = get_selection(the_id);
var start_pos = selection.start;
var end_pos = start_pos + replace_str.length;
e.value = e.value.substr(0, start_pos) + replace_str + e.value.substr(selection.end, e.value.length);
set_selection(the_id,start_pos,end_pos);
return {start: start_pos, end: end_pos, length: replace_str.length, text: replace_str};
}
function set_selection(the_id,start_pos,end_pos)
{
var e = document.getElementById(the_id);
//Mozilla and DOM 3.0
if('selectionStart' in e)
{
e.focus();
e.selectionStart = start_pos;
e.selectionEnd = end_pos;
}
//IE
else if(document.selection)
{
e.focus();
var tr = e.createTextRange();
//Fix IE from counting the newline characters as two seperate characters
var stop_it = start_pos;
for (i=0; i < stop_it; i++) if( e.value[i].search(/[\r\n]/) != -1 ) start_pos = start_pos - .5;
stop_it = end_pos;
for (i=0; i < stop_it; i++) if( e.value[i].search(/[\r\n]/) != -1 ) end_pos = end_pos - .5;
tr.moveEnd('textedit',-1);
tr.moveStart('character',start_pos);
tr.moveEnd('character',end_pos - start_pos);
tr.select();
}
return get_selection(the_id);
}
function wrap_selection(the_id, left_str, right_str, sel_offset, sel_length)
{
var the_sel_text = get_selection(the_id).text;
var selection = replace_selection(the_id, left_str + the_sel_text + right_str );
if(sel_offset !== undefined && sel_length !== undefined) selection = set_selection(the_id, selection.start + sel_offset, selection.start + sel_offset + sel_length);
else if(the_sel_text == '') selection = set_selection(the_id, selection.start + left_str.length, selection.start + left_str.length);
return selection;
}
``` | Understanding what goes on with textarea selection with JavaScript | [
"",
"javascript",
"textarea",
"selection",
""
] |
```
string str1 = "12345ABC...\\...ABC100000";
// Hypothetically huge string of 100000 + Unicode Chars
str1 = str1.Replace("1", string.Empty);
str1 = str1.Replace("22", string.Empty);
str1 = str1.Replace("656", string.Empty);
str1 = str1.Replace("77ABC", string.Empty);
// ... this replace anti-pattern might happen with upto 50 consecutive lines of code.
str1 = str1.Replace("ABCDEFGHIJD", string.Empty);
```
I have inherited some code that does the same as the snippet above. It takes a huge string and replaces (removes) constant smaller strings from the large string.
I believe this is a very memory intensive process given that new large immutable strings are being allocated in memory for each replace, awaiting death via the GC.
**1. What is the fastest way of replacing these values, ignoring memory concerns?**
**2. What is the most memory efficient way of achieving the same result?**
I am hoping that these are the same answer!
Practical solutions that fit somewhere in between these goals are also appreciated.
Assumptions:
* All replacements are constant and known in advance
* Underlying characters do contain some unicode [non-ascii] chars | *All* characters in a .NET string are "unicode chars". Do you mean they're non-ascii? That shouldn't make any odds - unless you run into composition issues, e.g. an "e + acute accent" not being replaced when you try to replace an "e acute".
You could try using a regular expression with [`Regex.Replace`](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx), or [`StringBuilder.Replace`](http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.replace.aspx). Here's sample code doing the same thing with both:
```
using System;
using System.Text;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] args)
{
string original = "abcdefghijkl";
Regex regex = new Regex("a|c|e|g|i|k", RegexOptions.Compiled);
string removedByRegex = regex.Replace(original, "");
string removedByStringBuilder = new StringBuilder(original)
.Replace("a", "")
.Replace("c", "")
.Replace("e", "")
.Replace("g", "")
.Replace("i", "")
.Replace("k", "")
.ToString();
Console.WriteLine(removedByRegex);
Console.WriteLine(removedByStringBuilder);
}
}
```
I wouldn't like to guess which is more efficient - you'd have to benchmark with your specific application. The regex way may be able to do it all in one pass, but that pass will be relatively CPU-intensive compared with each of the many replaces in StringBuilder. | If you want to be really fast, and I mean really fast you'll have to look beyond the StringBuilder and just write well optimized code.
One thing your computer doesn't like to do is branching, if you can write a replace method which operates on a fixed array (char \*) and doesn't branch you have great performance.
What you'll be doing is that the replace operation is going to search for a sequence of characters and if it finds any such sub string it will replace it. In effect you'll copy the string and when doing so, preform the find and replace.
You'll rely on these functions for picking the index of some buffer to read/write. The goal is to preform the replace method such that when nothing has to change you write junk instead of branching.
You should be able to complete this without a single if statement and remember to use unsafe code. Otherwise you'll be paying for index checking for every element access.
```
unsafe
{
fixed( char * p = myStringBuffer )
{
// Do fancy string manipulation here
}
}
```
I've written code like this in C# for fun and seen significant performance improvements, almost 300% speed up for find and replace. While the .NET BCL (base class library) performs quite well it is riddled with branching constructs and exception handling this will slow down you code if you use the built-in stuff. Also these optimizations while perfectly sound are not preformed by the JIT-compiler and you'll have to run the code as a release build without any debugger attached to be able to observe the massive performance gain.
I could provide you with more complete code but it is a substantial amount of work. However, I can guarantee you that it will be faster than anything else suggested so far. | Memory Efficiency and Performance of String.Replace .NET Framework | [
"",
"c#",
".net",
"string",
""
] |
JTextField has a keyTyped event but it seems that at the time it fires the contents of the cell have not yet changed.
Because of that .length() is always wrong if read here.
There must be a simple way of getting the length as it appears to the user after a key stroke? | This is probably not the optimal way (and it's been a while), but in the past, I have added a DocumentListener to the JTextField and on any of the events (insert, update, remove) I:
```
evt.getDocument().getLength()
```
Which returns the total length of text field's contents. | This may be related to this ["bug" (or rather "feature")](https://bugs.java.com/bugdatabase/view_bug?bug_id=4140413)
> The listeners are notified of the key events prior to processing them to
> allow the listeners to "steal" the events by consuming them. This gives
> compatibility with the older awt notion of consuming events.
> **The "typed"
> event does not mean text was entered into the component**. This is NOT a
> bug, it is intended behavior.
A possible solution is to listen to an [associated Document](http://www.velocityreviews.com/forums/t136479-jtextfield-cant-listen-when-the-text-is-changed.html)
```
// Listen for changes in the text
myTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
// text was changed
}
public void removeUpdate(DocumentEvent e) {
// text was deleted
}
public void insertUpdate(DocumentEvent e) {
// text was inserted
}
});
```
> Note this works no matter how the text gets changed; via a clipboard cut/paste, progamatic "setText()" on the TextField, or the user typing into the field on the UI. | How can I get the length of a JTextField's contents as the user types? | [
"",
"java",
"swing",
"events",
"jtextfield",
""
] |
Is there any way that I can find the container pointed to by an iterator? Specifically, I want to be able to find the `std::vector` pointed to by a particular `std::vector::iterator` so that I can check the range, without having to actually pass references to that vector around.
If (as I suspect) the answer is no, why not?
edit: thanks for a number of quick and (largely) accurate answers. [Evan Teran](https://stackoverflow.com/questions/375598/finding-the-owner-of-an-stl-iterator#375608) nails it. I wasn't thinking about optimization at all, but it's obvious now.
A couple of people asked what I want to do this for. It's nothing terribly important. I have an object which is initialized with a vector and an iterator pointing into the vector. It would be cute and convenient if I could initialize the object just with an iterator because then I could convert `vector::iterator`s directly to this object (this sounds strange but does make sense in the particular case). But it's not crucial at all. | I don't believe so. If iterators had to keep a reference/pointer to their owning container, then it would be impossible for them to be optimized down to a lightweight pointer (which can be done with containers guaranteeing contiguous storage like vectors and such). | There is no way to make that work. The reason is simple: Adding a way to the iterators to get the container to which they are pointing is
* Pointless. Iterators iterate over a collection. As other said, only that, nothing more.
* Not compatible with the iterator requirements. Remember a pointer is a random access iterator. Putting a container pointer into the iterator would be of no use for algorithms, since they intend to be generic, decoupled from specific iterator implementations. A pointer used as an iterator can't have a pointer back to the array it was taken from as a member.
You say you need it for range checking. You can provide an end iterator which points one after the last valid iterator position of a range. Check whether your current position is not at the end. That is all you need to do for range checking. | Finding the owner of an STL iterator | [
"",
"c++",
"stl",
"iterator",
""
] |
I'm trying to parse an array of JSON objects into an array of strings in C#. I can extract the array from the JSON object, but I can't split the array string into an array of individual objects.
What I have is this test string:
```
string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name"
+ ":\"Lorem Ipsum\"},{id:2,name:\"Lorem Ipsum\"}]}";
```
Right now I'm using the following regular expressions right now to split the items into individual objects. For now they're 2 separate regular expressions until I fix the problem with the second one:
```
Regex arrayFinder = new Regex(@"\{items:\[(?<items>[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?<items>\{[^\}]\}),?)+"
, RegexOptions.ExplicitCapture);
```
The `arrayFinder` regex works the way I'd expect it but, for reasons I don't understand, the `arrayParser` regex doesn't work at all. All I want it to do is split the individual items into their own strings so I get a list like this:
> `{id:0,name:"Lorem Ipsum"}`
> `{id:1,name:"Lorem Ipsum"}`
> `{id:2,name:"Lorem Ipsum"}`
Whether this list is a `string[]` array or a `Group` or `Match` collection doesn't matter, but I'm stumped as to how to get the objects split. Using the `arrayParser` and the `json` string declared above, I've tried this code which I assumed would work with no luck:
```
string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name"
+ ":\"Lorem Ipsum\"},{id:2,name:\"Lorem Ipsum\"}]}";
Regex arrayFinder = new Regex(@"\{items:\[(?<items>[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?<items>\{[^\}]\}),?)+"
, RegexOptions.ExplicitCapture);
string array = arrayFinder.Match(json).Groups["items"].Value;
// At this point the 'array' variable contains:
// {id:0,name:"Lorem Ipsum"},{id:1,name:"Lorem Ipsum"},{id:2,name:"Lorem Ipsum"}
// I would have expected one of these 2 lines to return
// the array of matches I'm looking for
CaptureCollection c = arrayParser.Match(array).Captures;
GroupCollection g = arrayParser.Match(array).Groups;
```
Can anybody see what it is I'm doing wrong? I'm totally stuck on this. | Balanced parentheses are literally a textbook example of a language that cannot be processed with regular expressions. JSON is essentially balanced parentheses plus a bunch of other stuff, with the braces replaced by parens. In the [hierarchy of formal languages](http://en.wikipedia.org/wiki/Chomsky_hierarchy), JSON is a context-free language. Regular expressions can't parse context-free languages.
Some systems offer extensions to regular expressions that kinda-sorta handle balanced expressions. However they're all ugly hacks, they're all unportable, and they're all ultimately the wrong tool for the job.
In professional work, you would almost always use an existing JSON parser. If you want to roll your own for educational purposes then I'd suggest starting with a simple arithmetic grammar that supports + - \* / ( ). (JSON has some escaping rules which, while not complex, will make your first attempt harder than it needs to be.) Basically, you'll need to:
1. Decompose the language into an alphabet of symbols
2. Write a context-free grammar in terms of those symbols thatrecognizes the language
3. Convert the grammar into Chomsky normal form, or near enough to make step 5 easy
4. Write a lexer that converts raw text into your input alphabet
5. Write a recursive descent parser that takes your lexer's output, parses it, and produces some kind of output
This is a typical third-year CS assignment at just about any university.
The next step is to find out how complex a JSON string you need to trigger a stack overflow in your recursive parser. Then look at the other types of parsers that can be written, and you'll understand why anyone who has to parse a context-free language in the real world uses a tool like yacc or antlr instead of writing a parser by hand.
If that's more learning than you were looking for then you should feel free to go use an off-the-shelf JSON parser, satisified that you learned something important and useful: the limits of regular expressions. | > Balanced parentheses are literally a textbook example of a language that cannot be processed with regular expressions
bla bla bla ...
check this out:
```
arrayParser = "(?<Key>[\w]+)":"?(?<Value>([\s\w\d\.\\\-/:_]+(,[,\s\w\d\.\\\-/:_]+)?)+)"?
```
this works for me
if you want to match empty values change last '+' to '\*' | Regular expression to parse an array of JSON objects? | [
"",
"c#",
".net",
"regex",
"json",
""
] |
I have to call domain A.com (which sets the cookies with http) from domain B.com.
All I do on domain B.com is (javascript):
```
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = "A.com/setCookie?cache=1231213123";
head.appendChild(script);
```
This sets the cookie on A.com on every browser I've tested, except Safari.
Amazingly this works in IE6, even without the P3P headers.
Is there any way to make this work in Safari? | From the [`Safari Developer FAQ`](http://developer.apple.com/internet/safari/faq.html#anchor6):
> Safari ships with a conservative cookie policy which limits cookie writes to only the pages chosen ("navigated to") by the user. This default conservative policy may confuse frame based sites that attempt to write cookies and fail.
I have found no way to get around this.
If it's worth anything, Chrome doesn't set the cookies either if you use the `<script`> appending method, but if you have a hidden `<img`> with the same source, Chrome works in addition to the rest of the browsers (except, again, Safari) | Here is a solution which works:
<http://anantgarg.com/2010/02/18/cross-domain-cookies-in-safari/> | Setting cross-domain cookies in Safari | [
"",
"javascript",
"safari",
"cookies",
"cross-domain",
"cross-site",
""
] |
I have a solution that is missing a lot of code coverage. I need to refactor this code to decouple to begin to create unit tests. What is the best strategy? I am first thinking that I should push to decouple business logic from data access from businessobjects to first get some organization and then drill down from there. Since many of the classes don't support single responsible principle, it's hard to begin testing them.
Are there are other suggestions or best practices from taking a legacy solution and getting it into shape to be ready for code coverage and unit testing? | Check out [Working Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052). | One of the most important things to do and best ways to approach in legacy code is defects. It is a process that you will continue to do with any code base that you introduce unit testing to, as well. Whenever a defect is reported, write a unit test that will expose the defect. You will quickly find that code that would break on a regular basis (i.e. "Oh, yay. The plugh() method in the xyzzy class is broken *again*!) will start breaking less and less.
Really, just start doing it. You aren't going to have tremendous coverage in a legacy application overnight. Start by hitting the code that is more prone to breakage, and start branching out. Make sure that any new development within the code has a higher code coverage, as well.
Remember the mantra of TDD is "red/green/refactor", and you might want to look into refactoring tools to help do some of the tedious tasks that go along with it. JetBrain's [ReSharper](http://www.jetbrains.com/resharper/features/index.html) is popular, and my personal choice. | Best strategy to get coding prepared for unit testing | [
"",
"c#",
"unit-testing",
"refactoring",
"code-coverage",
""
] |
I need to keep a couple of [Jena](http://jena.sf.net) Models (OntModels, specifically) synchronized across a socket, and I'd like to do this one change at a time (for various reasons -- one being that each Statement added or removed from the OntModels is also adapting a JESS rule base.). I am able to listen to the add/remove events on the OntModels and then create simple event instances that wrap the added / removed Statements along with a ChangeType that indicates that the Statement was added or removed, but serializing the Statement has proven to be a problem.
Unfortunately, all of the JENA serialization documentation that I've found relates to serializing an entire model to xml / rdf / n3 / etc. Since statements are simply triples of Strings (at one level, anyway) it seems like it should be trivial to serialize the data at the Statement level. However, [Jena](http://jena.sf.net) doesn't seem to provide an API for creating Statements with plain strings that "does the right thing". Problems arise with typed literals. eg:
I can create the statement:
```
<http://someuri/myont#foo> <http://someuri/myont#weight> "50.7"^^www.w3.org/2001/XMLSchema#double
```
but the string version that I can get out looks like this:
```
"http://someuri/myont#foo" "http://someuri/myont#weight" "50.7^^www.w3.org/2001/XMLSchema#double"
```
(note the absence of a " before the ^^)
This wouldn't be that much of a problem, since the literal can still be parsed out with a regex, but I've been unable to create a Statement with the proper literal. The obvious approach (ModelCon.createStatement(Resource, Property, String)) generates an untyped string literal with the full value of the String passed in.
Does anyone know how I can reliably serialize (and deserialize, of course) individual Jena Statements? | I would serialize the changes out in N-TRIPLES format. Jena has built-in N-TRIPLES serializer and parser, but the N-TRIPLES syntax is (deliberately) very simple so it would be easy to generate manually in your code.
However, it might be even easier to keep a plain mem model around to hold the changes, have the event handlers write changes into that model, then serialize that model over the wire according to your synchronization schedule. Likewise, at the far end I would read the updates from the sync channel into a temporary mem model, then `yourOntModel.add( changesModel )` should add in the updates very straightforwardly.
Ian | Not an area I've looked at in great depth, but I recalled Talis were doing some research and was able to [follow breadcrumbs](http://n2.talis.com/wiki/Changeset_Protocol) to the relevant vocabulary called "Changeset".
<http://vocab.org/changeset/schema>
I'm surprised you had issues serialising individual statements using JENA, but perhaps if you created a graph according to the changeset schema and serialised the graph you'd have more luck? Alternately, add the statement to a new graph and serialise a graph of one tripple. | Serializing JENA OntModel Changes | [
"",
"java",
"serialization",
"jena",
"ontology",
""
] |
I've got the following Generic usercontrol declared:
```
public partial class MessageBase<T> : UserControl
{
protected T myEntry;
public MessageBase()
{
InitializeComponent();
}
public MessageBase(T newEntry)
{
InitializeComponent();
myEntry = newEntry;
}
}
}
```
But the compiler won't allow me to do this:
```
public partial class MessageControl : MessageBase<Post>
{
public MessageControl()
{
InitializeComponent();
}
}
```
How do I create a generic user control in C#? | Try this
```
public partial class MessageControl : MessageControlBase
{
public MessageControl()
{
InitializeComponent();
}
}
public class MessageControlBase : MessageBase<Post>
{}
```
The key to getting the designer to work is that the base class of the class you are editing must not be generic. | Yes. its possible. See Below link to get an idea.
<https://web.archive.org/web/20130603104810/http://www.hackersbasement.com/csharp/post/2009/08/29/Generic-Control-Builder-in-ASPNet.aspx> | Is it Possible to Make a Generic Control in .Net 3.5? | [
"",
"c#",
".net",
"winforms",
"generics",
"user-controls",
""
] |
Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?
Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. Assume also that templated functions taking these things as parameters do need to manipulate the structure (e.g. calling push\_back), so they can't just take a generic type supporting `[][]`.
What I want to do is:
```
template<typename T>
typedef vector< vector<T> > vecvec;
vecvec<int> intSequences;
vecvec<string> stringSequences;
```
but of course that's not possible, since typedef can't be templated.
```
#define vecvec(T) vector< vector<T> >
```
is close, and would save duplicating the type across every templated function which operates on vecvecs, but would not be popular with most C++ programmers. | You want to have template-typedefs. That is *not* yet supported in the current C++. A workaround is to do
```
template<typename T>
struct vecvec {
typedef std::vector< std::vector<T> > type;
};
int main() {
vecvec<int>::type intSequences;
vecvec<std::string>::type stringSequences;
}
```
In the next C++ (called c++0x, c++1x due to 2010), this would be possible:
```
template<typename T>
using vecvec = std::vector< std::vector<T> >;
``` | I use [Boost.MultiArray](http://www.boost.org/doc/libs/release/libs/multi_array/doc/user.html) which is implemented in the boost library.
HTH | Generic vector of vectors in C++ | [
"",
"c++",
"stl",
""
] |
I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.
My first instinct is to cast inputs as floats from within a try-except block.
```
try:
myinput = float(input)
except:
raise ValueError("input is not a well-formed number")
```
I could also call `isinstance(mydata, (float, int, long) )` but the list of "all these could be numbers" seems a bit inelegant to me.
What's the most pythonic way of going about it? Is there another option I overlooked? | To quote myself from [How much input validation should I be doing on my python functions/methods?](https://stackoverflow.com/questions/367560/how-much-input-validation-should-i-be-doing-on-my-python-functionsmethods#368072):
> For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling add, mul etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working input.
Thus, the best option is to leave the type checking up to Python. If the calculation fails, Python's type checking will give an exception, so if you do it yourself, you just duplicate code which means more work on your behalf. | In Python 2.6 and 3.0, a type hierarchy of numeric abstract data types has been [added](http://www.python.org/dev/peps/pep-3141/), so you could perform your check as:
```
>>> import numbers
>>> isValid = isinstance(myinput , numbers.Real)
```
numbers.Real will match integral or float type, but not non-numeric types, or complex numbers (use numbers.Complex for that). It'll also match rational numbers , but presumably you'd want to include those as well. ie:
```
>>> [isinstance(x, numbers.Real) for x in [4, 4.5, "some string", 3+2j]]
[True, True, False, False]
```
Unfortunately, this is all in Python >=2.6, so won't be useful if you're developing for 2.5 or earlier. | What's the most pythonic way of testing that inputs are well-formed numbers | [
"",
"python",
"idioms",
""
] |
I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website.
1. [cvsweb](http://www.freebsd.org/projects/cvsweb.html) is not what I mean.
2. [doxygen](http://www.doxygen.org) is for a complete project and to browse the self-referencing codes online.I think doxygen is more like web based ctags.
I tried with [rest2web](http://www.voidspace.org.uk/python/rest2web/), it is requires that I write /restweb headers and files to be .txt files and it will interfere with the programming language syntax.
An approach I have thought is:
1) run source-hightlight and create .html pages for all the scripts.
2) now write a script to index those script .htmls and create webpage.
3) Create the website of those pages.
before proceeding, I thought I shall discuss here, if the members have any suggestion.
What do do, when you want to maintain your snippets and notes in cvs and also auto generate it into a good website. I like rest2web for converting notes to html. | I finally settled for [rest2web](http://www.voidspace.org.uk/python/rest2web/). I had to do the following.
1. Use a separate python script to recursively copy the files in the CVS to a separate directory.
2. Added extra files index.txt and template.txt to all the directories which I wanted to be in the webpage.
3. The **best thing** about rest2web is that it supports python scripting within the template.txt, so I just ran a loop of the contents and indexed them in the page.
4. There is still lot more to go to automate the entire process. For eg. Inline viewing of programs and colorization, which I think can be done with some more trials.
I have the completed website here, It is called [uthcode](http://uthcode.sarovar.org). | Run [Trac](http://trac.edgewall.org/) on the server linked to the (svn) repository. The Trac wiki can conveniently refer to files and changesets. You get TODO tickets, too. | Convert CVS/SVN to a Programming Snippets Site | [
"",
"python",
"svn",
"web-applications",
"rest",
"cvs",
""
] |
I have a list box control:
```
<asp:ListBox runat="server" id="lbox" autoPostBack="true" />
```
The code behind resembles:
```
private void Page_Load(object sender, System.EventArgs e)
{
lbox.SelectedIndexChanged+=new EventHandler(lbox_SelectedIndexChanged);
if(!Page.IsPostBack)
{
LoadData();
}
}
private LoadData()
{
lbox.DataSource = foo();
lbox.DataBind();
}
protected void lboxScorecard_SelectedIndexChanged(object sender, EventArgs e)
{
int index = (sender as ListBox).selectedIndex;
}
```
My problem is that when my page receives a post back (when a user makes a selection in the listbox), the selection always "jumps" to the first item in the listbox, so that the index variable in my callback function is always 0.
Seems like this may be a viewstate problem? How can I fix it so that the selection index remains through the postback?
There is no ajax going on, this is .NET 1.0.
Thanks.
**EDIT 1** JohnIdol has gotten me a step closer, If I switch the datasource from my original DataTable to an ArrayList, then everything work properly...what would cause this?
**Edit 2** It turns out that my DataTable had multiple values that were the same, so that the indexes were treated as the same as all items with the same value...thanks to those who helped! | What's the output of the foo() function call?
Populating manually the list box you can set indexes to whatever you want (all 0 for example) - so the same thing can happen setting a given dataSource under certain circumstances (one that specifies indexes I suppose). If all the item indexes are 0 the result is that the SelectedIndexChanged event is not raised (index does not change!) and everything is messed up: on post-back selection will go back to the first item in the list.
This would explain it - I cannot think of anything else - it is working fine for me on .NET 2.0 I am using an ArrayList with strings to populate the listBox.
The only way I can reproduce your issue is setting all indexes to 0.
I'd say add a watch to the ListBox and check the indexes at runtime to make sure they're not all zeroes. | The **real** issue here is order of events. When you databind in page\_load you overwrite the posted data, thats why the selection is not set in the listbox. You can easily overcome this by moving the binding logic to Page\_Init. | selectedIndex is lost during postbacks - ASP.NET | [
"",
"c#",
".net",
"asp.net",
"viewstate",
""
] |
```
typeof(int).Name
```
Will return System.Int32 does anyone know of a way to return "int" | There aren't many types that are C# keywords (int, double, string) ... so perhaps you can write your own mapping function, from the System type name to the corresonding C# keyword. | Yeah, you could write a mapping function. That is just an alias anyway.
Here is a list:
<http://msdn.microsoft.com/en-us/library/86792hfa(VS.71).aspx> | C# type name instead of CLR type name | [
"",
"c#",
"system.type",
""
] |
When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls:
* The valueOf() method on the wrapper
* The wrapper's constructor
* Some other magic? | You can use the `javap` tool to see for yourself. Compile the following code:
```
public class AutoboxingTest
{
public static void main(String []args)
{
Integer a = 3;
int b = a;
}
}
```
To compile and disassemble:
```
javac AutoboxingTest.java
javap -c AutoboxingTest
```
The output is:
```
Compiled from "AutoboxingTest.java"
public class AutoboxingTest extends java.lang.Object{
public AutoboxingTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: aload_1
6: invokevirtual #3; //Method java/lang/Integer.intValue:()I
9: istore_2
10: return
}
```
Thus, as you can see, autoboxing invokes the static method `Integer.valueOf()`, and autounboxing invokes `intValue()` on the given `Integer` object. There's nothing else, really - it's just syntactic sugar. | I came up with a unit test that proves that Integer.valueOf() is called instead of the wrapper's constructor.
```
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import org.junit.Test;
public class Boxing {
@Test
public void boxing() {
assertSame(5, 5);
assertNotSame(1000, 1000);
}
}
``` | What code does the compiler generate for autoboxing? | [
"",
"java",
"autoboxing",
""
] |
I've searched, but I've not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what's its real advantage? What are the problems of static and stack? Could I write an entire application without allocating variables in the heap?
I heard that others languages incorporate a "garbage collector" so you don't have to worry about memory. What does the garbage collector do?
What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?
Once someone said to me that with this declaration:
```
int * asafe=new int;
```
I have a "pointer to a pointer". What does it mean? It is different of:
```
asafe=new int;
```
? | [A similar question](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) was asked, but it didn't ask about statics.
## Summary of what static, heap, and stack memory are:
* A static variable is basically a global variable, even if you cannot access it globally. Usually there is an address for it that is in the executable itself. There is only one copy for the entire program. No matter how many times you go into a function call (or class) (and in how many threads!) the variable is referring to the same memory location.
* The heap is a bunch of memory that can be used dynamically. If you want 4kb for an object then the dynamic allocator will look through its list of free space in the heap, pick out a 4kb chunk, and give it to you. Generally, the dynamic memory allocator (malloc, new, et c.) starts at the end of memory and works backwards.
* Explaining how a stack grows and shrinks is a bit outside the scope of this answer, but suffice to say you always add and remove from the end only. Stacks usually start high and grow down to lower addresses. You run out of memory when the stack meets the dynamic allocator somewhere in the middle (but refer to physical versus virtual memory and fragmentation). Multiple threads will require multiple stacks (the process generally reserves a minimum size for the stack).
## When you would want to use each one:
* Statics/globals are useful for memory that you know you will always need and you know that you don't ever want to deallocate. (By the way, embedded environments may be thought of as having only static memory... the stack and heap are part of a known address space shared by a third memory type: the program code. Programs will often do dynamic allocation out of their static memory when they need things like linked lists. But regardless, the static memory itself (the buffer) is not itself "allocated", but rather other objects are allocated out of the memory held by the buffer for this purpose. You can do this in non-embedded as well, and console games will frequently eschew the built in dynamic memory mechanisms in favor of tightly controlling the allocation process by using buffers of preset sizes for all allocations.)
* Stack variables are useful for when you know that as long as the function is in scope (on the stack somewhere), you will want the variables to remain. Stacks are nice for variables that you need for the code where they are located, but which isn't needed outside that code. They are also really nice for when you are accessing a resource, like a file, and want the resource to automatically go away when you leave that code.
* Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.
## Garbage Collection
I've heard a lot lately about how great Garbage Collectors are, so maybe a bit of a dissenting voice would be helpful.
Garbage Collection is a wonderful mechanism for when performance is not a huge issue. I hear GCs are getting better and more sophisticated, but the fact is, you may be forced to accept a performance penalty (depending upon use case). And if you're lazy, it still may not work properly. At the best of times, Garbage Collectors realize that your memory goes away when it realizes that there are no more references to it (see [reference counting](http://en.wikipedia.org/wiki/Reference_counting)). But, if you have an object that refers to itself (possibly by referring to another object which refers back), then reference counting alone will not indicate that the memory can be deleted. In this case, the GC needs to look at the entire reference soup and figure out if there are any islands that are only referred to by themselves. Offhand, I'd guess that to be an O(n^2) operation, but whatever it is, it can get bad if you are at all concerned with performance. (Edit: Martin B [points out](http://www.hpl.hp.com/personal/Hans_Boehm/gc/complexity.html) that it is O(n) for reasonably efficient algorithms. That is still O(n) too much if you are concerned with performance and can deallocate in constant time without garbage collection.)
Personally, when I hear people say that C++ doesn't have garbage collection, my mind tags that as a feature of C++, but I'm probably in the minority. Probably the hardest thing for people to learn about programming in C and C++ are pointers and how to correctly handle their dynamic memory allocations. Some other languages, like Python, would be horrible without GC, so I think it comes down to what you want out of a language. If you want dependable performance, then C++ without garbage collection is the only thing this side of Fortran that I can think of. If you want ease of use and training wheels (to save you from crashing without requiring that you learn "proper" memory management), pick something with a GC. Even if you know how to manage memory well, it will save you time which you can spend optimizing other code. There really isn't much of a performance penalty anymore, but if you really need dependable performance (and the ability to know exactly what is going on, when, under the covers) then I'd stick with C++. There is a reason that every major game engine that I've ever heard of is in C++ (if not C or assembly). Python, et al are fine for scripting, but not the main game engine. | The following is of course all not quite precise. Take it with a grain of salt when you read it :)
Well, the three things you refer to are **automatic, static and dynamic storage duration**, which has something to do with how long objects live and when they begin life.
---
### Automatic storage duration
You use automatic storage duration for **short lived** and **small** data, that is needed only **locally** within some block:
```
if(some condition) {
int a[3]; // array a has automatic storage duration
fill_it(a);
print_it(a);
}
```
The lifetime ends as soon as we exit the block, and it starts as soon as the object is defined. They are the most simple kind of storage duration, and are way faster than in particular dynamic storage duration.
---
### Static storage duration
You use static storage duration for free variables, which might be accessed by any code all times, if their scope allows such usage (namespace scope), and for local variables that need extend their lifetime across exit of their scope (local scope), and for member variables that need to be shared by all objects of their class (classs scope). Their lifetime depends on the scope they are in. They can have **namespace scope** and **local scope** and **class scope**. What is true about both of them is, once their life begins, lifetime ends at **the end of the program**. Here are two examples:
```
// static storage duration. in global namespace scope
string globalA;
int main() {
foo();
foo();
}
void foo() {
// static storage duration. in local scope
static string localA;
localA += "ab"
cout << localA;
}
```
The program prints `ababab`, because `localA` is not destroyed upon exit of its block. You can say that objects that have local scope begin lifetime **when control reaches their definition**. For `localA`, it happens when the function's body is entered. For objects in namespace scope, lifetime begins at **program startup**. The same is true for static objects of class scope:
```
class A {
static string classScopeA;
};
string A::classScopeA;
A a, b; &a.classScopeA == &b.classScopeA == &A::classScopeA;
```
As you see, `classScopeA` is not bound to particular objects of its class, but to the class itself. The address of all three names above is the same, and all denote the same object. There are special rule about when and how static objects are initialized, but let's not concern about that now. That's meant by the term *static initialization order fiasco*.
---
### Dynamic storage duration
The last storage duration is dynamic. You use it if you want to have objects live on another isle, and you want to put pointers around that reference them. You also use them if your objects are **big**, and if you want to create arrays of size only known at **runtime**. Because of this flexibility, objects having dynamic storage duration are complicated and slow to manage. Objects having that dynamic duration begin lifetime when an appropriate *new* operator invocation happens:
```
int main() {
// the object that s points to has dynamic storage
// duration
string *s = new string;
// pass a pointer pointing to the object around.
// the object itself isn't touched
foo(s);
delete s;
}
void foo(string *s) {
cout << s->size();
}
```
Its lifetime ends only when you call *delete* for them. If you forget that, those objects never end lifetime. And class objects that define a user declared constructor won't have their destructors called. Objects having dynamic storage duration requires manual handling of their lifetime and associated memory resource. Libraries exist to ease use of them. **Explicit garbage collection** for **particular objects** can be established by using a smart pointer:
```
int main() {
shared_ptr<string> s(new string);
foo(s);
}
void foo(shared_ptr<string> s) {
cout << s->size();
}
```
You don't have to care about calling delete: The shared ptr does it for you, if the last pointer that references the object goes out of scope. The shared ptr itself has automatic storage duration. So *its* lifetime is automatically managed, allowing it to check whether it should delete the pointed to dynamic object in its destructor. For shared\_ptr reference, see boost documents: <http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm> | Stack, Static, and Heap in C++ | [
"",
"c++",
"static",
"garbage-collection",
"stack",
"heap-memory",
""
] |
I want to use php in console mode and create an environment to test my functions.
I do not want to be forced to use a web browser and create a new file each time I want to test a function.
I want to access the function in the console and then it return the result.
How do I do this?
**Update:**
Perhaps I have explained this badly. I only want to see what result the function's return.
Maybe I have to learn unit testing but for the moment I only want an interactive console which allows me to test all functions one by one.
In my case I have to load the wordpress functions (I know how do it with a regular `.php` file and then a browser to parse the file) but i don't if it is possible to do it with php from the command line. | I have used [phpsh](http://www.phpsh.org/) in the past and found it very useful. Once you start it you will need to `chdir()` to where your files are and then obviously `require()` any files containing functions you need to test. You can then just test your function calls by typing them into the shell e.g. `var_dump(some_function(1, 2));` | I guess you've to be more specific what kind of functions exactly. Wordpress does not provide something like that out of the box, most PHP apps won't.
I also think you're calling for trouble here when such apps aren't developed in mind for such environments.
Here's an example trying to call "current\_time()" from functions.php and the attempts I had to do just to realize it won't work that way:
```
php -r 'require "functions.php"; var_dump(current_time("mysql"));'
```
gives
```
Fatal error: Call to undefined function apply_filters() in functions.php on line 346
```
Trying
```
php -r 'require "functions.php"; require "plugin.php"; var_dump(current_time("mysql"));'
```
gives
```
Fatal error: Call to undefined function wp_cache_get() in functions.php on line 351
```
Trying
```
php -r 'require "functions.php"; require "plugin.php"; require "cache.php"; var_dump(current_time("mysql"));'
```
gives
```
Fatal error: Call to a member function get() on a non-object in cache.php on line 93
```
Looking at the last error in the source I see
```
function wp_cache_get($id, $flag = '') {
global $wp_object_cache;
return $wp_object_cache->get($id, $flag);
}
```
Using global variables makes testing in other environments a PITA if not impossible.
If this is not what you're trying to do, you've to be more specific/detailed in your question. | Creating a testing environment with php cli | [
"",
"php",
"shell",
"environment",
"command-line-interface",
""
] |
I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious.
Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal? | Not really, or at least not practically.
Subtypes should operate like sets in mathematical set theory. If B is a subset of A, any item in B is also an item in A.
In the same way, if B is a subtype of A, any item in B is also an item of A. Thus, any collection of A must be able to maintain items of B.
That being said, there may be convulted ways that B can override certain operations to explicitly break the ability to use it in a collection or to instantiate it.
I don't think generics will solve that problem. | The question is: why would you want that. If you have a list containing animals, why would you want to fill that list only with the "base animal", but prevent dogs or cats being added to the list. One of the basic concepts of OO is that you use an instance of a subclass everywhere where you need in instance of the base class ([Wikipedia: Liskov substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle)). If that does not apply in your situation, something might be wrong with your class hierarchy. | Java: How to create a collection of a specific parent type and not its subtypes? | [
"",
"java",
"generics",
""
] |
I need assistance finding a delivery method that best fulfills the following requirements:
* We wish to deliver a single file to my clients.
* Clients should be able to launch this file from the operating system shell - much like running an '.exe' on Windows.
* After being launched, the program/script should be able to display a window with HTML content. this may be done using a stand alone program, a runtime or by running within a browser.
* We need the ability to embed a resource within the delivered file, such as an mp3 file, which i can later extract programmatically.
* Optimally, the solution should run on Windows, Mac and Linux machines. Less than perfect cross-platform interoperability is acceptable, but we want as broad a penetration as possible.
* Clients should not need to pre-install anything (unless it is done transparently), pre-configure anything, or approve any thing for this to happen.
For example:
* We could use a regular executable file, written in C++ to do this, but it will not be cross-platform.
* We could use a sliverlight XAP file, an adobe Flex file or a Java JAR, but internet explorer warns users when local content is launched. In addition these approaches mean that we have less than perfect penetration, even though it is acceptable in these cases.
* We could use a python (or equivalent) script, but the installed-base (penetration) of the python interpreter is not good enough.
* Using a standard HTML is not enough because of the difficulty of embedding resources in it. Embedding Silverlight XAML or uuencoded content in HTML causes IE to display a warning.
* Using something along the lines of a jpeg as a delivery method is not rich enough since we need to display HTML. | > *..but internet explorer warns users when local content is launched..*
I don't get it, what's the problem with IE saying "Hey this app is trying to run *your* files!"
I don't mean you don't have a good reason for this, it is just, I don't get it.
IE will only warn the user if the app has not been downloaded and try to access local resources, for instance if running from an applet or a JNLP like this [one:](http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html)(click on the first orange button you see )
But if the users download the jar and run it from the computer ( double click on it ) the app is local and can run without problems.
The jar file is a zip file after all, so you can attach your mp3 file with it. Double click is supported in the desired platform, and the HTML content could be either a local file ( un-packed along with the mp3 file ) or an internet web page.
Java is preinstalled on those OS already. | "internet explorer warns users when local content is launched"
There's a reason for this. How can they distinguish your excellent, well-behaved, polite application from a virus?
Since the line between your app and a virus is very, very blurry, go with any of Silverlight XAP file, an adobe Flex file or a Java JAR.
The IE business is a good thing, not a bad thing. | Cross-platform executable/runtime delivery method | [
"",
"java",
"flash",
"silverlight",
"cross-platform",
""
] |
Suppose I have some per-class data: (AandB.h)
```
class A
{
public:
static Persister* getPersister();
}
class B
{
public:
static Persister* getPersister();
}
```
... and lots and lots more classes. And I want to do something like:
```
persistenceSystem::registerPersistableType( A::getPersister() );
persistenceSystem::registerPersistableType( B::getPersister() );
...
persistenceSystem::registerPersistableType( Z::getPersister() );
```
... for each class.
My question is: is there a way to automate building a list of per-type data so that I don't have to enumerate each type in a big chunk (as in the above example)?
For example, one way you might do this is: (AutoRegister.h)
```
struct AutoRegisterBase
{
virtual ~AutoRegisterBase() {}
virtual void registerPersist() = 0;
static AutoRegisterBase*& getHead()
{
static AutoRegisterBase* head= NULL;
return head;
}
AutoRegisterBase* next;
};
template <typename T>
struct AutoRegister : public AutoRegisterBase
{
AutoRegister() { next = getHead(); getHead() = this; }
virtual void registerPersist()
{
persistenceSystem::registerPersistableType( T::getPersister() );
}
};
```
and use this as follows: (AandB.cxx: )
```
static AutoRegister<A> auto_a;
static AutoRegister<B> auto_b;
```
Now, after my program starts, I can safely do: (main.cxx)
```
int main( int, char ** )
{
AutoRegisterBase* p = getHead();
while ( p )
{
p->registerPersist();
p = p->next;
}
...
}
```
to collect each piece of per-type data and register them all in a big list somewhere for devious later uses.
The problem with this approach is that requires me to add an AutoRegister object somewhere per type. (i.e. its not very automatic and is easy to forget to do). And what about template classes? What I'd really like is for the instantiation of a template class to somehow cause that class to get automatically registered in the list. If I could do this I would avoid having to have the user of the class (rather than the author) to remember to create a:
```
static AutoRegister< SomeClass<X1> > auto_X1;
static AutoRegister< SomeClass<X2> > auto_X2;
...
etc....
```
for each template class instantiation.
For FIW, I suspect there's no solution to this. | You can execute something before main once if a instantiation of a template is made. The trick is to put a static data member into a class template, and reference that from outside. The side effect that static data member triggers can be used to call the register function:
```
template<typename D>
struct automatic_register {
private:
struct exec_register {
exec_register() {
persistenceSystem::registerPersistableType(
D::getPersister()
);
}
};
// will force instantiation of definition of static member
template<exec_register&> struct ref_it { };
static exec_register register_object;
static ref_it<register_object> referrer;
};
template<typename D> typename automatic_register<D>::exec_register
automatic_register<D>::register_object;
```
Derive the class you want to be auto-registered from `automatic_register<YourClass>` . The register function will be called before main, when the declaration of `referrer` is instantiated (which happens when that class is derived from, which will implicitly instantiate that class from the template).
Having some test program (instead of the register function, a function do\_it is called):
```
struct foo : automatic_register<foo> {
static void do_it() {
std::cout << " doit ";
}
};
int main() {
std::cout << " main ";
}
```
Yields this output (as expected):
```
doit main
``` | Register each template at run-time in the constructor. Use a static variable per template to check if the type has already been registered. The following is a quickly hacked together example:
```
#include <iostream>
#include <vector>
using namespace std;
class Registerable {
static vector<Registerable *> registry_;
public:
static void registerFoo(Registerable *p)
{
registry_.push_back(p);
}
static void printAll()
{
for (vector<Registerable *>::iterator it = registry_.begin();
it != registry_.end(); ++it)
(*it)->print();
}
virtual void print() = 0;
};
vector<Registerable *> Registerable::registry_;
template <typename T>
class Foo : public Registerable {
static bool registered_;
public:
Foo()
{
if (!registered_) {
registerFoo(this);
registered_ = true;
}
}
void print()
{
cout << sizeof (T) << endl;
}
};
template <typename T> bool Foo<T>::registered_ = false;
int
main(int argc, char *argv[])
{
Foo<char> fooChar;
Foo<short> fooShort;
Foo<int> fooInt;
Registerable::printAll();
return 0;
}
```
It should output the size of each template parameter in the order the classes were instantiated:
```
1
2
4
```
---
This version removes the registration code from each constructor and puts it in a base class.
```
#include <iostream>
#include <vector>
using namespace std;
class Registerable {
static vector<Registerable *> registry_;
public:
static void registerFoo(Registerable *p)
{
registry_.push_back(p);
}
static void printAll()
{
for (vector<Registerable *>::iterator it = registry_.begin();
it != registry_.end(); ++it)
(*it)->print();
}
virtual void print() = 0;
};
vector<Registerable *> Registerable::registry_;
template <typename T>
class Registerer : public Registerable {
static bool registered_;
public:
Registerer(T *self)
{
if (!registered_) {
registerFoo(self);
registered_ = true;
}
}
};
template <typename T> bool Registerer<T>::registered_ = false;
template <typename T>
class Foo : public Registerer<Foo<T> > {
public:
Foo() : Registerer<Foo<T> >(this) { }
void print()
{
cout << sizeof (T) << endl;
}
};
int
main(int argc, char *argv[])
{
Foo<char> fooChar;
Foo<short> fooShort;
Foo<int> fooInt;
Registerable::printAll();
return 0;
}
```
I added an example of another non-template class using the registry. So, the final output would be:
```
foo: 1
foo: 2
foo: 4
bar
``` | Best way to for C++ types to self register in a list? | [
"",
"c++",
""
] |
I need to make an AJAX request from a website to a REST web service hosted in another domain.
Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.
The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.
Here is the JavaScript code that makes the asynchronous call:
```
var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);
```
How can I have this work in other browsers beside Internet Explorer? | maybe [JSONP](http://en.wikipedia.org/wiki/JSONP) can help.
NB youll have to change your messages to use json instead of xml
Edit
Major sites such as flickr and [twitter](http://apiwiki.twitter.com/Search+API+Documentation) support jsonp with callbacks etc | The post marked as the answer is erroneous: the iframes document is NOT able to access the parent. The same origin policy works both ways.
The fact is that it is not possible in any way to consume a rest based webservice using xmlhttprequest. The only way to load data from a different domain (without any framework) is to use JSONP. Any other solutions demand a serverside proxy located on your own domain, or a client side proxy located on the remote domain and som sort of cross-site communication (like [easyXDM](http://easyxdm.net)) to communicate between the documents. | Cross-site AJAX requests | [
"",
"javascript",
"ajax",
"security",
"xss",
""
] |
How do I get my netbeans drag and drop widget to know whether it is rendering inside the netbeans design view window or the running application?
I'm trying to do some custom rendering. I think it has to do with the root container. | Try [java.beans.Beans.isDesignTime()](http://java.sun.com/javase/6/docs/api/java/beans/Beans.html#isDesignTime()). | This is another method:
```
Component c = javax.swing.SwingUtilities.getRoot(this);
String className = c.getClass().getCanonicalName();
if (!"org.netbeans.core.windows.view.ui.MainWindow"
.equalsIgnoreCase(className)) {
```
Although I think the
```
Beans.isDesignTime()
```
method is better | How do I get my netbeans drag and drop widget to know whether it is rendering inside the netbeans design view window or the running application? | [
"",
"java",
"swing",
"netbeans",
"javabeans",
"designview",
""
] |
In the following code, g++ gives this error :
1.cpp: In member function `void W::test()':
1.cpp:6: error:`int F::glob' is private
1.cpp:19: error: within this context
But, shouldn't the globally declared
variable 'glob' be used here, instead
of the "private" "glob"?
```
#include <iostream.h>
int glob;
class F
{
int glob;
public:
void readIt()
{
cin >> glob;
}
};
class W : public F
{
public:
void test()
{
glob--;
}
};
int main()
{
}
``` | Variables and functions are accessed using scoping rules, not visbility rules. Because `F::glob` is the `glob` in the scope of `W::test()`, it is used. However, `W::test()` does not have access to `F::glob`, and an error results. The compiler does *not* check for `::glob` because something else preceeds it in scope "priority" (not sure for the exact term). | private glob shadows the global glob,so the error is correct
use ::glob to access the global variable if u intent to use global variable | C++ variable with same name, context : global and private, | [
"",
"c++",
"private",
"global",
""
] |
I just started reading Effective C++ today and got to the point where the author talks about the operator new.
The book explains very well how you can catch (with various degrees of elegance) the std::bad\_alloc exception that the operator new can raise if you run out of memory.
My question is: How often do you check for the case when there isn't enough memory to instantiate a object, if at all? and why? Is it worth the hassle? | I catch exceptions when I can answer this question:
> What will you do with the exception once you've caught it?
Most of the time, my answer is, "I have no idea. Maybe my caller knows." So I don't catch the exception. Let it bubble up to someone who knows better.
When you catch an exception and let your function proceed running, you've said to your program, "Never mind. Everything's fine here." When you say that, by golly, everything had better be fine. So, if you've run out of memory, then after you've handled `std::bad_alloc`, you should not be out of memory anymore. You shouldn't just return an error code from your function, because then the caller has to check explicitly for that error code, and you're still out of memory. Your handling of that exception should free some memory. Empty some caches, commit some things to disk, etc. But how many of the functions in your program do you really want to be responsible for reducing your program's memory usage?
If you cannot solve the problem that triggered the exception, then do not handle the exception. | The problem is that when you run out of memory there is generally not much you can do except write to a crash dump and exit the program. It's therefore useless to check every new in your program.
One exception to this is when you allocate memory for e.g. loading a file, in which case you just need to inform the user that not enough memory is available for the requested operation. | How often do you check for an exception in a C++ new instruction? | [
"",
"c++",
"exception",
""
] |
A little background:
* [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow.
* [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to PEP 8.
* [Eclipse](http://www.eclipse.org/) is a great IDE. With the [Pydev](http://pydev.sourceforge.net/) extension, it that can be used to develop Python
I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.
Question is: **How to integrate pep8.py in Eclipse?** | As of PyDev 2.3.0, `pep8` is integrated in PyDev by default, even shipping with a default version of it.
Open Window > Preferences
It must be enabled in PyDev > Editor > Code Analysis > pep8.py
Errors/Warnings should be shown as markers (as other things in the regular code analysis).
In the event a file is not analyzed, see <https://stackoverflow.com/a/31001619/832230>. | I don't know how to integrate it for whole project, but I have used it as an external tool to analyze an individual file.
Note that the [`pycodestyle`](https://pypi.python.org/pypi/pycodestyle/) package is the official replacement for and is the newer version of the [`pep8`](https://pypi.python.org/pypi/pep8/) package. To install it, run:
```
$ sudo pip install --upgrade pycodestyle
```
Next, in Eclipse:
1. Select **Run-External Tools-External Tools Configurations...**
2. Select **Program** root node.
3. Press **New launch configuration** button.
4. Enter **Name** for your launch configuration. I use `pycodestyle`.
5. Fill following fields:
**Location** -- `${system_path:pycodestyle}`
**Working directory** -- `${container_loc}`
**Arguments** -- `"${resource_name}"` (This uses the currently active file.)
Go to **Common** tab and confirm that the **Allocate Console** checkbox is checked.
A benefit of this approach is that you can use a very up-to-date version of the package, and are not limited to the old version included with PyDev. And if you are curious about setting up `pylint` in a similar manner, see [this answer](https://stackoverflow.com/a/39863131/832230). | How to integrate pep8.py in Eclipse? | [
"",
"python",
"eclipse",
"pydev",
"pep8",
""
] |
I'd like to hide a div when user click anywhere on the page outside of that div. How can I do that using raw javascript or jQuery? | Attach a click event to the document to hide the div:
```
$(document).click(function(e) {
$('#somediv').hide();
});
```
Attach a click event to the div to stop clicks on it from propagating to the document:
```
$('#somediv').click(function(e) {
e.stopPropagation();
});
``` | First idea, in raw javascript (from [this post](http://www.webdeveloper.com/forum/showpost.php?p=465274&postcount=4)):
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<style type="text/css">
<!--
#mydiv{
background-color: #999999;
height: 100px;
width: 100px;
}
-->
</style>
<script type="text/javascript">
document.onclick=check;
function check(e)
{
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('mydiv');
if(target!=obj){obj.style.display='none'}
}
</script>
</head>
<body>
<div id="mydiv">my div</div>
</body>
</html>
```
Tested with IE6 and FireFox3.1, it does work as advertised. | Event on a click everywhere on the page outside of the specific div | [
"",
"javascript",
"jquery",
""
] |
My question pertains to multi-threading in Java. I'm translating an app I wrote in Visual Basic 2008 into Java. There is a class in VB called [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker_members.aspx), which allows the coder to perform a task on another thread, a lot like `SwingWorker` in Java. The only distinct difference is that, with the `BackgroundWorker` thread is `run()`, it fires an event called `DoWork()` on the mainline which contains the code to execute in the background. Furthermore, after the code has executed, a `RunWorkerCompleted()` event is fired back on the foreground thread to interpret results.
I have found the `BackgroundWorker` setup quite useful and it seems a little more flexible than `SwingWorker` and I was just wondering whether it was possible (and acceptable) to fire events in the same way in Java? And if so, how would I go about it? Since I've only done a quick scan over `SwingWorker`, it's possible that it has a similar functionality that would work just as well, in which case I would be happy to know about that instead.
Cheers,
Hoopla
EDIT:
Kewl. Cheers guys, thanks for the prompt replies, and apologies for my rather time-lax reply. I'll give your idea a go Oscar, sorry coobird, I didn't quite follow - any further explanation would be welcome (perhaps an example).
Just to recap: I want to have a runnable class, that I instantiate an instance of in my code. The runnable class has two events, one of which is fired from the background thread and contains the code to run in the background (`DoWork()`), and the other event is fired on the foreground thread after the background thread has completed it's task (`RunWorkerCompleted()`).
And if I understand your advice correctly, I can fire the `DoWork()` event from the runnable class' `run()` method so that it will be executed on the background thread, and then I can use the `SwingUtilities.invokeLater()` method to fire the `RunWorkerCompleted()` event on the foreground thread, once the background thread has finished execution.
Yes? | The solely intention of the following code is to show how does it looks like when the SwingUtilities.invokeLater method is used.
The effect is the task is executed in the AWT-Event thread ( the one responsible for component painting ) .
The rest ( creating a new thread , creating a gui etc. ) is just scaffold code.
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InvokeLaterEffect {
static JTextArea text = new JTextArea();
// See the diff by commenting.
static void done() {
SwingUtilities.invokeLater( doneAction );
//doneAction.run();
}
public static void main( String [] args ) {
JFrame frame = new JFrame();
frame.add( text );
frame.pack();
frame.setVisible( true );
bacgroundTask.start();
}
// run a task in the background
static Thread bacgroundTask = new Thread(){
public void run(){
try {
System.out.println( Thread.currentThread().getName() + " Started background task ");
Thread.sleep( 5000 );
System.out.println( Thread.currentThread().getName() + " Finished background task");
done();
} catch ( InterruptedException ie ){}
}
};
// called whtn id done
static Runnable doneAction = new Runnable(){
public void run(){
System.out.println( Thread.currentThread().getName() + " start setting text ");
text.setText("Hello");
System.out.println( Thread.currentThread().getName() + " finish setting text ");
}
};
}
```
The output is like:
```
Thread-2 Started background task
Thread-2 Finished background task
AWT-EventQueue-0 start setting text
AWT-EventQueue-0 finish setting text
``` | What was the mainline again?
Let me see if I get this right.
The background thread fires an event the GUI can intercept to know the data is ready.
Is that correct?
You may use SwingUtilities.invokeLater( Runnable r );
It inserts that runnable instance in the AWT event dispatch thread ( that I guess is the same as the mainline ) after all the events currently in that thread are processed.
This way you can fire an "actionPerformed" event and the registered listener will handle properly.
Let me code something really quickly and you tell me if this was what you wanted.
In the mean time [take a look at here](http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html) | Firing a mainline event from a background thread in Java | [
"",
"java",
"multithreading",
"events",
""
] |
I have a type which I consider use it as struct.
* It represents single value
* It is immutable
But the problem is, it has 6 fields of int.
So which solution I should use for this type?
1. keep using struct?
2. change to class?
3. or pack 6 integers into an array of int, so it has only one field
**EDIT**
Size of struct with 6 integer fields is 24 bytes, which is huge to pass around.
Recommend size for struct is not more than 16 bytes | It depends how you are going to use it?
1. Are you going to allocate a lot of it vs. pass it around a lot?
2. Is it going to be consumed by 3rd party code? In this case, classes typically give you more flexibility.
3. Do you want struct vs. class semantics? For example, non-nullable?
4. Would you benefit from having a couple of pre-created instances of this class that can be re-use to represent special cases? Similar to String.Empty. In this case you would benefit from a class.
It is hard to answer just from the information you provided in your question. | Be careful of boxing. If your struct is going to be consumed by a method which expects an Object, it will be coerced into an object and you'll have a potential performance hit.
Here's a [reference](http://www.c-sharpcorner.com/UploadFile/stuart_fujitani/BoxNUnbox11192005055746AM/BoxNUnbox.aspx) that explains it in more detail.
I'd make it a class (#2) and then you wouldn't have to worry about it.
Using an array of six integers (#3) would probably make your code harder to read. A class with descriptive identifiers for each int would be much better. | Optimal solution for struct with more than 16 bytes | [
"",
"c#",
"optimization",
"class",
"struct",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.