Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
My PHP app uses 404 Documents to generate HTML files so that multiple queries to the same HTML file only cause the generation to run once.
I'd like to intercept requests to the HTML files so that the user needs to have an established PHP Session in order to pull up the files.
In the best case, SESSION ID would be used in the URL and force it could be used as a further authentication. For example, logging in would issue you a SessionID and make only certain HTML files accessible to you.
I'm aware that by changing my cookies I could spoof a request, but that's fine.
How would I go about doing this? | Something like this could work (I haven't tested it):
```
RewriteCond %{HTTP_COOKIE} PHPSESSID=([a-zA-Z0-9]+)
RewriteCond %{REQUEST_FILENAME} %{REQUEST_FILENAME}-%1.html
RewriteRule ^ %{REQUEST_FILENAME}-%1.html
```
It assumes that you append `"-$session_id.html"` to filenames (`$session_id` is PHP's session ID).
It should be safe, and the benefit is that files are served by the web server directly without invoking PHP at all. | ```
SetEnvIf HTTP_COOKIE "PHPSESSID" let_me_in
<Directory /www/static/htmls>
Order Deny,Allow
Deny from all
Allow from env=let_me_in
</Directory>
```
Of course user can manually create such cookie in his browser (there are extensions which do that for Firefox, and you can always edit your browser's cookie store). | Protecting HTML files with .htaccess | [
"",
"php",
"html",
"security",
".htaccess",
""
] |
I'm looking to do a presentation in a couple of weeks and was wondering: What are the top ten Javascript incompatibilities that you look out for when developing? What trips you up? I can start with one:
```
var somevar = {
'internet': 'explorer',
'hates': 'trailing',
'commas': 'in',
'json': 'code', // oh noes!
}
```
What are some other common gotchas that can't or aren't fixed by using a framework like jQuery or base? | var x = new Boolean(false); if (x) ... else...;
Is the 'if' or 'else' branch taken?
var x = "hi", y = new String("hi");
what is the typeof(x) and typeof(y) ?
Edit:..
parseInt("017") produces 15 (octal) instead of 17
The 'Error' object is a different signature from IE to Firefox.
When using objects as hashmap's, you need to use object.hasOwnProperty(key) to ensure that the property is not inherited through the prototype chain. | With HTML markup like
```
<div id="foo">
<a href="#">Link 1</a>
</div>
```
If you obtain a reference to the outer div, it will have one child node in some browsers, and three child nodes in others, depending on how whitespace is treated. Some will have text nodes with the newline and whitespace as children of `div#foo` before and after the link element. | Javascript Incompatibilities/Inconsistencies | [
"",
"javascript",
""
] |
I'm learning a bit about function programming, and I'm wondering:
1) If my `ForEach` extension method is pure? The way I'm calling it seems violate the "don't mess with the object getting passed in", right?
```
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach ( var item in source )
action(item);
}
static void Main(string[] args)
{
List<Cat> cats = new List<Cat>()
{
new Cat{ Purring=true,Name="Marcus",Age=10},
new Cat{ Purring=false, Name="Fuzzbucket",Age=25 },
new Cat{ Purring=false, Name="Beanhead",Age=9 },
new Cat{Purring=true,Name="Doofus",Age=3}
};
cats.Where(x=>x.Purring==true).ForEach(x =>
{
Console.WriteLine("{0} is a purring cat... purr!", x.Name);
});
// *************************************************
// Does this code make the extension method impure?
// *************************************************
cats.Where(x => x.Purring == false).ForEach(x =>
{
x.Purring = true; // purr,baby
});
// all the cats now purr
cats.Where(x=>x.Purring==true).ForEach(x =>
{
Console.WriteLine("{0} is a purring cat... purr!", x.Name);
});
}
public class Cat {
public bool Purring;
public string Name;
public int Age;
}
```
2) If it is impure, is it bad code? I personally think it makes cleaner looking code than the old `foreach ( var item in items) { blah; }`, but I worry that since it might be impure, it could make a mess.
3) Would it be bad code if it returned `IEnumerable<T>` instead of `void`? I'd say as long as it is impure, yes it would be very bad code as it would encourage chaining something that would modify the chain. For example, is this bad code?
```
// possibly bad extension
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach ( var item in source )
action(item);
return source;
}
``` | Impurity doesn't necesarily mean bad code. Many people find it easy and useful to use side effects to solve a problem. The key is first knowing how to do it in a pure way, so you'll know when impurity is appropriate :).
.NET doesn't have the concept of purity in the type system, so a "pure" method that takes in arbitrary delegates can always be impure, depending on how it's called. For instance, "Where", aka "filter", would usually be considered a pure function, since it doesn't modify its arguments or modify global state.
But, there's nothing stopping you from putting such code inside the argument to Where. For example:
```
things.Where(x => { Console.WriteLine("um?");
return true; })
.Count();
```
So that's definately an impure usage of Where. Enumerables can do whatever they want as they iterate.
**Is your code bad?** No. Using a foreach loop is just as "impure" -- you're still modifying the source objects. I write code like that all the time. Chain together some selects, filters, etc., then execute a ForEach on it to invoke some work. You're right, it's cleaner and easier.
Example: ObservableCollection. It has no AddRange method for some reason. So, if I want to add a bunch of things to it, what do I do?
```
foreach(var x in things.Where(y => y.Foo > 0)) { collection.Add(x)); }
```
or
```
things.Where(x => x.Foo > 0).ForEach(collection.Add);
```
I prefer the second one. At a minimum, I don't see how it can be construed as being worse than the first way.
When is it bad code? When it does side effecting code in a place that's not expected. This is the case for my first example using Where. And even then, there are times when the scope is very limited and the usage is clear.
**Chaining ForEach**
I've written code that does things like that. To avoid confusion, I would give it another name. The main confusion is "is this immediately evaluated or lazy?". ForEach implies that it'll go execute a loop right away. But something returning an IEnumerable implies that the items will be processed as needed. So I'd suggest giving it another name ("Process", "ModifySeq", "OnEach"... something like that), and making it lazy:
```
public static IEnumerable<T> OnEach(this IEnumerable<T> src, Action<T> f) {
foreach(var x in src) {
f(x);
yield return x;
}
}
``` | It is not pure, as it can call impure methods. I think by typical definitions, purity is a transitive closure - a function is pure only if all the functions it calls (directly or indirectly) are also pure, or if the effects of those functions are encapsulated (e.g. they only mutate a non-escaping local variable). | Is this C# extension method impure and if so, bad code? | [
"",
"c#",
"functional-programming",
"extension-methods",
""
] |
These days with Visual C# (Visual C# 2008 specifically) it seems that the default color for menustrips and menus is blue, which to me looks really strange and is something that I'd really like to override. I'm guessing that Visual Studio is picking up this blue color from my selected system theme or something, however no other Windows app running on my system has this blue color so I don't know why my .NET apps would have to have it. ;)
Anyway, I noticed that if I create an application using an older version of Visual Studio (Visual Studio.NET), the default background color for menustrips and menus is the standard gray that you'd expect to see. This is one solution to the problem I suppose, but it seems like kind of a stupid one and I'd really like to find a way to override it in the current version of Visual C#. | DotNet 1.x didn't have a MenuStrip, and used a standard Windows menu.
DotNet versions 2.0 and up have the MenuStrip, and VS 7 and up removes the MainMenu from the toolbox and replaces it with a MenuStrip, which uses the Office ~~Xp~~ 2003 theme, hence the blue color scheme for the MenuStrip and ToolStrip.
The MainMenu can still be added to the toolbox for a standard Windows menu. | Set the "**RenderMode**" option of the MenuStrip to "**System**" instead of "managerRenderMode"
:) | How do you change the default background color for menustrips and menus in .NET? | [
"",
"c#",
".net",
"visual-studio",
"menu",
""
] |
I am using the standard `FindFirst` and `FindNext` to retrieve all files in a directory
but I need the results to come back sorted ( in the same order that clicking on the name column in explorer would sort them basically )
How can I achive this
This has to be done via Win32
Thanks | You can use the [Indexing Service](http://msdn.microsoft.com/en-us/library/ms692260(VS.85).aspx) for this, but I would recommend just to handle the sorting yourself while using FindFirstFile.
Sorting is not possible with the FindFirstFile Win32 API. There is a slightly more advanced [FindFirstFileEx](http://msdn.microsoft.com/en-us/library/aa364419(VS.85).aspx), but even that does not allow sorting.
There is a Raymond Chen [post on The Old New Thing about FindFirstFile's limitations](http://blogs.msdn.com/oldnewthing/archive/2005/07/21/441330.aspx).
Your best bet is probably to load all results into a vector, and then sort that. | As everyone has pointed out, `FindFirstFile()` does not and can not sort the files it returns. It operates at a fairly low level, and returns files in an order that relates to file system's natural order of directory entries in a directory.
On a disk formatted with FAT and FAT32, that order will strongly relate to the order in which the files were created, modified by file deletions and possible re-use of now empty directory entry slots. This is because FAT directories are (as on many unix filesystems) simply a packed array of fixed-size directory entry structs, along with an ugly hack to fit long file names written in Unicode into a directory structure designed for 8.3 names written in ASCII. Unlike Unix, Win32 API calls are required to read the directory entries, but that doesn't affect the order in which the entries are read.
On NTFS (as I understand it) directories are represented in some variant of a B-Tree and the natural order of files seen by the Win32 API is therefore related to the indexing natural to that data structure.
You can see the differences with the `DIR` command at the command prompt. On a FAT32 volume, `DIR` shows the files in a different order than it will if that same folder is copied to an NTFS volume. `DIR /ON` should list files in the same order regardless of the underlying file system in use.
Neither unsorted order produced by DIR is the same as the order produced by Windows Explorer when you sort by Name. (For that matter, `DIR /ON` isn't the same, either.)
Windows Explorer uses a case-independent sort, that also seems to ignore some punctuation marks in the sort, and tries to be clever about numbers. In particular, a simple use of `qsort()` with `stricmp()` won't get the same answer as Explorer. It isn't clear if the actual sort order used by either Explorer or DIR is documented anywhere.
For example, the following names sort like this in DIR:
```
C:\temp\test> dir/on/b
aoli.txt
a-one.txt
atwo.txt
b1.txt
b10.txt
b2.txt
b-20.txt
b21.txt
b3.txt
b-4.txt
```
but transcribing from Explorer sorted in the Name column they are in this order:
```
aoli.txt
a-one.txt
atwo.txt
b1.txt
b2.txt
b3.txt
b10.txt
b21.txt
b-4.txt
b-20.txt
```
I'm having trouble imagining the simple to apply in a comparison function to get the latter effect. | How can I get FindFirstFile to sort files | [
"",
"c++",
"c",
"winapi",
""
] |
I have asked to use singleton pattern implemented DAL, but I think its difficult to pool the connections,use transactions..etc
I would like to know the pros and cons and also would like to know the best way to pool the connections as there can be more than 500 concurrent users for the site I am developing.
DB Server is Oracle 10g.
DAL uses Enterprise library 3.1 | The singleton pattern is great for a DAL -- I use this in my own enterprise web application (hundreds of users and over 2,000 methods in 20-some singleton classes). The connection pooling is indeed handled best by ado.net and the sql server itself. If you are wanting to have multiple types of back-end server, that's not a problem. Even with a singleton pattern, you probably want a centralized data-access class that handles the specifics of actually making direct calls to the database (with parameters, text/procedure names, credentials/connection string all passed in).
In my situation, each method on a single corresponds 1:1 with a stored procedure in my database. This essentially makes a C# "front end" hook for each stored procedure, so that they can be called almost like native C# code, syntactically speaking. It makes calls to the DAL very straightforward. I have multiple singletons because of the massive number of SPs in question. Each SP has a prefix, like Development\_, or Financial\_, or Organization\_ or whatever. Then I have a singleton class that corresponds to each, like Development, Financial, or Organization. So the sp Organization\_ViewData would in C# be a method named ViewData on a singleton class named Organization.
That's just one way of doing it, of course, but I've found that to work very well with multiple developers and a large amount of code over the last six years. The main thing is that consistency is key. If a front-end programmer is looking at the name of a method on one of your singleton brokers, that should tell them exactly where it is going into the database end. That way if there's a problem, or if someone's having to search through code to try to understand it, there's less tracing that has to be done. | The best practice for connection pooling is to not implement it yourself, but instead let the ADO.NET framework take care of it.
You can set connection pooling options as parameters within the connection string. Then, every connection that is opened with that string will be supplied from the connection pool that is implemented and managed by the framework. When you close or dispose of the OracleConnection, the underlying connection is not destroyed but will instead go back onto the pool.
This is described here:
[<http://msdn.microsoft.com/en-us/library/ms254502.aspx>](http://msdn.microsoft.com/en-us/library/ms254502.aspx)
About the use of Singletons in general: I've used them to wrap the data access layer, and it has always worked well.
Note that transactions only apply to specific connections, not the database as a whole. This means you can have several threads running, and each thread can read and write to the database through independent transactions, providing each thread uses a separate OracleConnection instance. | Pros and Cons of using Singleton Pattern in DAL | [
"",
"c#",
"singleton",
"data-access-layer",
""
] |
I must customize .NET `ListView` control.
`ListViewItem` must have following structure:
[alt text http://img257.imageshack.us/img257/1575/85834837.jpg](http://img257.imageshack.us/img257/1575/85834837.jpg)
Is there any good tutorial which will help me to make this customization?
I am using Visual Studio 2008, C#. | Scott Guthrie has some great tutorials covering the listview control
<http://weblogs.asp.net/scottgu/archive/2007/08/10/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui.aspx> | Create your own listviewitem based on the normal Listviewitem and and do your own drawing | Custom ListViewItem | [
"",
"c#",
"visual-studio",
"listviewitem",
""
] |
Is it possible to declare a variable in Python, like so?:
```
var
```
so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?
EDIT: I want to do this for cases like this:
```
value
for index in sequence:
if value == None and conditionMet:
value = index
break
```
### Related Questions
* [Why can a function modify some arguments as perceived by the caller, but not others?](https://stackoverflow.com/questions/575196/)
* [Python Variable Declaration](https://stackoverflow.com/questions/11007627/)
### See Also
* [Python Names and Values](https://nedbatchelder.com/text/names1.html)
* [Other languages have "variables"](http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables) | Why not just do this:
```
var = None
```
Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.
This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with *incorrectly* initialized variables. If you init something to `None`, make sure that's what you really want, and assign something more meaningful if you can. | In Python 3.6+ you could use Variable Annotations for this:
<https://www.python.org/dev/peps/pep-0526/#abstract>
PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:
```
# 'captain' is a string (Note: initial value is a problem)
captain = ... # type: str
```
PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:
```
captain: str # Note: no initial value!
```
It seems to be more directly in line with what you were asking "Is it possible only to declare a variable without assigning any value in Python?"
Note: The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. | Is it possible only to declare a variable without assigning any value in Python? | [
"",
"python",
"variable-assignment",
"variable-declaration",
""
] |
Ideally I want to do this:
```
UPDATE TOP (10) messages SET status=10 WHERE status=0 ORDER BY priority DESC;
```
In English: I want to get the top 10 available (status=0) messages from the DB and lock them (status=10). A message with a higher priority should be gotten first.
unfortunately MS SQL doesn't allow an order by clause in the update.
Anyway how to circumvent this? | You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:
```
UPDATE messages
SET status=10
WHERE ID in (SELECT TOP (10) Id
FROM Table
WHERE status=0
ORDER BY priority DESC);
``` | ```
;WITH q AS
(
SELECT TOP 10 *
FROM messages
WHERE status = 0
ORDER BY
priority DESC
)
UPDATE q
SET status = 10
``` | How to update and order by using ms sql | [
"",
"sql",
"sql-server",
"t-sql",
"sql-order-by",
"sql-update",
""
] |
Let's say I have a list like:
```
my_list = [[1,2,3],[4,5,6],[7,8,9]]
```
How do I alter every value in the list without doing?:
```
for x in range(0, 3):
for y in range(0, 3):
my_list[x][y] = -my_list[x][y]
```
I have tried to simplify this by doing
```
my_list = [[[-a, -b, -c] for [a, b, c] in d] for d in my_list]
```
but the values remain the same. | Many answers are about creating altered *copy* of list, but literal meaning of question is about in-place modification of list.
Here is my version of best-of-breed in-place list altering solution:
```
def alter_elements(lst, func):
for i, item in enumerate(lst):
if isinstance(item, list):
alter_elements(item, func)
else:
lst[i] = func(item)
```
Test run:
```
>>> sample = [[1,2,3],[4,5,6],[7,8,9]]
>>> alter_elements(sample, lambda x: -x)
>>> print sample
>>> [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]]
```
No list copies. No hardcoded bounds. No list comprehensions with side-effects. | Another option is to use the built-in `map` function:
```
>>> my_list = [[1,2,3],[4,5,6],[7,8,9]]
>>> neg = lambda x: -x
>>> f = lambda x: map(neg, x)
>>> map(f, my_list)
[[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]]
``` | Alter all values in a Python list of lists? | [
"",
"python",
""
] |
What is the most important use of AppDomains in C#? | The **single most important** use is that your code *has to have one* - i.e. everything you write in C# executes in an `AppDomain`. That is quite important ;-p
If you mean *additional* app-domains:
When using plugins and other untrusted code, it allows you both isolation, and the ability to unload them (you can't unload assemblies - only entire app-domains).
I'm using it currently to load dynamically generated dlls, so that I can unload them.
They also allow you to set different configuration files, trust levels, etc - but have associated costs of complexity and remoting.
MSDN has a section on app-domains, [here](http://msdn.microsoft.com/en-us/library/yb506139.aspx). | I can't tell you what the most important use is, since that depends on the situation.
AppDomains are useful for sandboxing parts of your application. You can load extensions in an AppDomain and unload them again - something you cannot otherwise do. You can assign specific rights to AppDomains. Per default objects in different AppDomains cannot access each other.
AppDomains can be viewed as lightweight processes as they give you many of the same features. However, unlike a Process new AppDomains do not have their own thread per default. You have to manage AppDomains and threads yourself.
Also, AppDomains all share the same managed heap. This is usually not a problem, but it may have surprising effects as some instances like strings are shared among AppDomains. For regular use this is not an issue, but if you use strings for locking, threads in different AppDomain can affect each other. | Usage of AppDomain in C# | [
"",
"c#",
"remoting",
"appdomain",
""
] |
I'm a jQuery newb. I'm building a Online Shop and I'm using jQuery plugin 'Thickbox' (<http://jquery.com/demo/thickbox>). The Online Shop is set up to display a 'Enlarged Image' which runs the Thickbox JS script and shows an image.
A problem occurs as the data is placed on the page thru a CMS system (using Ajax I believe?). When you choose another product from the 'Choose Type' select drop down new data from the CMS system is placed on the page and the Thickbox script isn't applied as it can't see the new data.
I've been playing around with a fix I've found (<http://www.codynolden.com/blog/2009/01/thickbox-and-ajax-using-livequery>) but I can't seem to apply it to my website?
A live example of my site: <http://madisonlane.businesscatalyst.com/_product_36331/AAA-_Autumn_Dress>
Any ideas? | in thickbox.js:
```
$(domChunk).click(function(){
```
was replaced with this:
```
$(domChunk).live(click, function(){
``` | Stuart got it right: thank you so much!
I was stuck with a similar problem issue: in my case, the target of an appended link (through jQuery `.append()` method ) was not loaded in a thickbox.
My jQuery code was executed in a `document.ready()` function:
```
$("#subpages").append('','<a href="..." class="thickbox" [...]');
```
Simply adding:
```
tb_init('.thickbox'); //required to reinitialize thickbox as DOM was manipulated
```
just after the last line fixed the problem. | jQuery Thickbox Issue | [
"",
"javascript",
"jquery",
"ajax",
""
] |
I have the following dojo codes to create a surface graphics element under a div:
```
....
<script type=text/javascript>
....
function drawRec(){
var node = dojo.byId("surface");
// remove all the children graphics
var surface = dojox.gfx.createSurface(node, 600, 600);
surface.createLine({
x1 : 0,
y1 : 0,
x2 : 600,
y2 : 600
}).setStroke("black");
}
....
</script>
....
<body>
<div id="surface"></div>
....
```
`drawRec()` will draw a rectangle graphics first time. If I call this function again in an anchor href like this:
```
<a href="javascript:drawRec();">...</a>
```
it will draw another graphics again. What I need to clean all the graphics under the div and then create again. How can I add some dojo codes to do that? | ```
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
``` | ```
node.innerHTML = "";
```
Non-standard, but fast and well supported. | Remove all the children DOM elements in div | [
"",
"javascript",
"dojox.gfx",
""
] |
Why do we need Reader/Writer Streams while Using TCPListner in C# networking?
example :
```
TcpClient client = server.AcceptTcpClient();
client.ReceiveTimeout = 75000;
Stream s = client.GetStream();
StreamReader reader = new StreamReader(s);
StreamWriter writer = new StreamWriter(s);
writer.AutoFlush = true;
``` | You only need `StreamReader`/`StreamWriter` if you want to deal with text instead of binary data.
Sockets deal with binary data naturally, which is why `TcpClient` exposes a Stream. Stream is a binary abstraction, hence its Read/Write methods deal in byte arrays. `TextReader`/`TextWriter` (from which `StreamReader`/`StreamWriter` are derived) deal with text - their methods deal with strings and char arrays.
`StreamReader`/`StreamWriter` basically wrap a stream and do the conversion (via an `Encoding`) between text and binary data for you. | You don't need them. You can use raw sockets if you don't like the Tcp wrapper classes. Take a look at `System.Net.Sockets.` | Why do we need Reader/Writer Streams while Using TCPListner in C# networking? | [
"",
"c#",
""
] |
I use vim as my editor but I would like to get some of the same power of the IDE's for java when it comes to refactoring. Are there any commandline tools for refactoring java? I could probably hack something together using perl or vim scripting but if there is something already out there I'd rather use that. | Check out [jrefactory](http://jrefactory.sourceforge.net/csrefactory.html), and its [command line option](http://jrefactory.sourceforge.net/csr-commandline.html). | You could try [Eclim](http://eclim.org/). The goal of Eclim is to expose the functionality of Eclipse within Vim. In particular, there are a few [commands for refactoring](http://eclim.org/vim/java/refactor.html) that are supported. | Are there any open source command line tools to refactor java code? | [
"",
"java",
"command-line",
"refactoring",
"automated-refactoring",
""
] |
I read somewehere (I thought on codinghorror) that it is bad practice to add strings together as if they are numbers, since like numbers, strings cannot be changed. Thus, adding them together creates a new string. So, I was wondering, what is the best way to add two strings together, when focusing on performance?
Which of these four is better, or is there another way which is better?
```
//Note that normally at least one of these two strings is variable
$str1 = 'Hello ';
$str2 = 'World!';
$output1 = $str1.$str2; //This is said to be bad
$str1 = 'Hello ';
$output2 = $str1.'World!'; //Also bad
$str1 = 'Hello';
$str2 = 'World!';
$output3 = sprintf('%s %s', $str1, $str2); //Good?
//This last one is probaply more common as:
//$output = sprintf('%s %s', 'Hello', 'World!');
$str1 = 'Hello ';
$str2 = '{a}World!';
$output4 = str_replace('{a}', $str1, $str2);
```
Does it even matter? | You are always going to create a new string whe concatenating two or more strings together. This is not necessarily 'bad', but it can have performance implications in certain scenarios (like thousands/millions of concatenations in a tight loop). I am not a PHP guy, so I can't give you any advice on the semantics of the different ways of concatenating strings, but for a single string concatenation (or just a few), just make it readable. You are not going to see a performance hit from a low number of them. | String Concatenation with a dot is definitely the fastest one of the three methods. You will always create a new string, whether you like it or not.
Most likely the fastest way would be:
```
$str1 = "Hello";
$str1 .= " World";
```
Do not put them into double-quotes like `$result = "$str1$str2";` as this will generate additional overhead for parsing symbols inside the string.
If you are going to use this just for output with echo, then use the feature of echo that you can pass it multiple parameters, as this will not generate a new string:
```
$str1 = "Hello";
$str2 = " World";
echo $str1, $str2;
```
For more information on how PHP treats interpolated strings and string concatenation [check out Sarah Goleman's blog](http://blog.libssh2.org/index.php?/archives/28-How-long-is-a-piece-of-string.html). | What is the best way to add two strings together? | [
"",
"php",
"performance",
"string",
""
] |
I'm creating a very simple PHP templating system for a custom CMS/news system. Each article has the intro and the full content (if applicable). I want to have a conditional of the form:
```
{continue}click to continue{/continue}
```
So if it's possible to continue, the text "click to continue" will display, otherwise, don't display this whole string. So far, it works like this: if we can continue, remove the {continue} tags; otherwise, remove the whole thing.
I'm currently using `preg_match_all` to match the string in the second case. What is the best function for removing the matched text? A simple `str_replace`, or something else?
Or is there a better way to implement this overall? | Why not use [preg\_replace\_callback](http://au.php.net/preg_replace_callback)?
Specifically:
```
preg_replace_callback('!\{continue\}(.*)\{/continue\}!Us', 'replace_continue', $html);
function replace_continue($matches) {
if (/* can continue */) {
return $matches[1];
} else {
return '';
}
}
```
I find preg\_replace\_callback to be incredibly useful. | Sorry I know people have been ridiculing this kind of answer, but just use Smarty. Its simple, stable, clever, free, small and cheap. Spend an hour learning how to use it and you will never look back.
Go to [www.smarty.net](http://www.smarty.net) | Best way to implement conditional in a PHP templating system? | [
"",
"php",
"regex",
"string",
"templates",
""
] |
I am making an old-school 2d game, and I want to animate a specific color in my texture.
Only ways I know are:
1. opengl shaders.
2. animating one color channel only.
3. white texture under the color-animated texture.
But I don't want to use shaders, I want to make this game as simple as possible, not many extra openGL functions etc..
And the color channel animating doesnt fit this because I need all color channels in my textures.
Currently I am doing it with 2 textures: white texture under the other texture, translated the specific pixel color into transparent, then I change white texture color with glColor3f() function to what ever I want, and I see the "palet animation" on that specific color.
But that style sounds pretty hacky, so I am wondering if there is some better trick to this? | How about just using paletted textures? There are [extensions](http://personal.redestb.es/jmovill/opengl/openglonwin-20.html) to do just that. If using extensions is out of question you can just make palette handling by your own. Just do your palette tricks, there are lot of them, and just write RGB texture using palette. Ofcourse this limits number of colors, but thats whole point of using palette.
Paint programs that are good for palette handling are nowadays rare. That's why I will not remove Deluxe Paint from my drive. | While I am unfamiliar with the palette texture extension I still recommend using a fragment shader for this sort of effect. It is almost trivial to do a color-key replacement with a shader, versus the other methods you mentioned, and will be way faster than writing the palette functionality yourself.
Here's an example GLSL fragment shader that would replace the color white in a texture for whatever color is passed in.
```
uniform vec4 fvReplaceColor;
uniform sampler2D baseMap;
varying vec2 Texcoord;
void main( void )
{
vec4 fvBaseColor = texture2D( baseMap, Texcoord);
if(fvBaseColor == vec4(1.0, 1.0, 1.0, 1.0))
fvBaseColor = fvReplaceColor;
gl_FragColor = fvBaseColor;
}
```
Yes, it does take a little bit extra to set up shader, but but what it sounds like you are trying to do I feel it's the best approach. | Palette Animation in OpenGL | [
"",
"c++",
"c",
"opengl",
""
] |
I am looking to 'extending' an interface by providing set accessors to properties in that interface. The interface looks something like this:
```
interface IUser
{
string UserName
{
get;
}
}
```
I want something like this:
```
interface IMutableUser : IUser
{
string UserName
{
get;
set;
}
}
```
I need the inheritence. I cannot copy the body of `IUser` into `IMutableUser` and add the set accessors.
Is this possible in C#? If so, how can it be accomplished? | I don't see any reason why what you have posted shouldn't work? Just did a quick test and it compiles alright, but gives a warning about hiding. This can be fixed by adding the new keyword, like this:
```
public interface IMutableUser : IUser
{
new string Username { get; set; }
}
```
An alternative would be to add explicit set methods; eg:
```
public interface IMutableUser : IUser
{
void SetUsername(string value);
}
```
Of course, I'd prefer to use setters, but if it's not possible, I guess you do what you have to. | You could use an abstract class:
```
interface IUser
{
string UserName
{
get;
}
}
abstract class MutableUser : IUser
{
public virtual string UserName
{
get;
set;
}
}
```
Another possibility is to have this:
```
interface IUser
{
string UserName
{
get;
}
}
interface IMutableUser
{
string UserName
{
get;
set;
}
}
class User : IUser, IMutableUser
{
public string UserName { get; set; }
}
``` | Add 'set' to properties of interface in C# | [
"",
"c#",
"inheritance",
"interface",
""
] |
I've inherited a Java web-services code-base (BEA/Oracle Weblogic) and need to start/launch an external background application from a web-service.
I've already tried:
```
ProcessBuilder pb = new ProcessBuilder(arg);
pb.start();
```
as well as:
```
Runtime.exec(cmdString);
```
But am experiencing strange behaviors when launching applications in this manner (i.e. the launched application stops working even though the process is still active. -- The application works fine when manually run from a normal command line).
Is there a better way to launch an external processes?
**EDIT: ----------------------**
I have some additional information that may help shed some light on the problem.
* The process we are trying to start will require hours to complete so waiting for completion (using `waitfor()`) in the webservice will not be an ideal scenario.
* Yes, the process we are trying to start from the webservice was created by a fellow team member [cue: your eyes roll... now]
*I have had success* when I use process builder to start a bash script, where the external application is launched as a *background process* (using "&").
```
#!/bin/bash
java -jar myApp.jar &
```
This obviously creates an orphaned process but at least the application does continue to execute. | Simply put: if the launched application writes to SDTOUT/STDIN and you don't flush them frequently (see Process.getErrorStream/Process.getInputStream) then the process will block when the buffer is full (that is really small, 4KB or less).
I recommend you to invoke ProcessBuilder.redirectErrorStream() before starting the process. Then, after that, create a thread with the run() method along the lines of:
```
public void run() {
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
``` | Firstly, is this happening on Windows or on Linux? Also, what is the launched application supposed to more or less do? (is it a script? is it a binary? is it *your* binary?)
**EDIT**
OK, so starting a `bash` script (using `ProcessBuilder`) which in turns spawns a new JVM (`java -jar myApp.jar`) works.
What happens exactly when you try to spawn the new JVM *directly* using `ProcessBuilder`? You originally said:
> the launched application stops working
1. By launched application do you mean "java -jar myApp.jar", when invoked directly, *not* via an intermediate `bash` script?
2. What are the exact and complete parameters (and their values) you pass to the various `ProcessBuilder` methods (and in which order) when you try to launch Java directly and this new JVM stops working? (e.g. provide annotated code)
3. If you install `lsof` on your \*nix machine, what file is shown to be associated with file descriptor 2 (look at the `FD` column) when running: `lsof -p 1234` (where `1234` is the process ID of the "hung" JVM?) It might be interesting to attach the entire output of the `lsof` command here.
4. What is appended to the file you have identified in step 3 above (for file descriptor 2), up to several seconds after you issue the command: `kill -QUIT 1234` (where `1234` is the process ID of the "hung" JVM?) | Best Way to Launch External Process from Java Web-Service? | [
"",
"java",
"web-services",
"weblogic",
""
] |
I know that the following is case sensitive:
```
if (StringA == StringB) {
```
So is there an operator which will compare two strings in an insensitive manner? | Try this:
```
string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
``` | **The best way** to compare 2 strings ignoring the case of the letters is to use the [String.Equals](http://msdn.microsoft.com/en-us/library/t4411bks.aspx) static method specifying an ordinal ignore case string comparison. This is also the fastest way, much faster than converting the strings to lower or upper case and comparing them after that.
I tested the performance of both approaches and the ordinal ignore case string comparison was **more than 9 times faster**! It is also more reliable than converting strings to lower or upper case (check out the Turkish i problem). So always use the [String.Equals](http://msdn.microsoft.com/en-us/library/t4411bks.aspx) method to compare strings for equality:
```
String.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);
```
If you want to perform a culture specific string comparison you can use the following code:
```
String.Equals(string1, string2, StringComparison.CurrentCultureIgnoreCase);
```
Please note that the second example uses the the string comparison logic of the current culture, which makes it slower than the "ordinal ignore case" comparison in the first example, so if you don't need any culture specific string comparison logic and you are after maximum performance, use the "ordinal ignore case" comparison.
For more information, [read the full story on my blog](http://www.pvladov.com/2012/09/case-insensitive-string-comparison.html). | Is there a C# case insensitive equals operator? | [
"",
"c#",
".net",
"string",
"operators",
"case-insensitive",
""
] |
How can I change the local system's date & time programmatically with C#? | [Here is where I found the answer.](http://www.codeguru.com/forum/archive/index.php/t-246724.html); I have reposted it here to improve clarity.
Define this structure:
```
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public short wYear;
public short wMonth;
public short wDayOfWeek;
public short wDay;
public short wHour;
public short wMinute;
public short wSecond;
public short wMilliseconds;
}
```
Add the following `extern` method to your class:
```
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);
```
Then call the method with an instance of your struct like this:
```
SYSTEMTIME st = new SYSTEMTIME();
st.wYear = 2009; // must be short
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;
SetSystemTime(ref st); // invoke this method.
``` | A lot of great viewpoints and approaches are already here, but here are some specifications that are currently left out and that I feel might trip up and confuse some people.
1. On **Windows Vista, 7, 8 OS** this will *require* a UAC Prompt in order to obtain the necessary administrative rights to successfully execute the `SetSystemTime` function. The reason is that calling process needs the **SE\_SYSTEMTIME\_NAME** privilege.
2. The `SetSystemTime` function is expecting a `SYSTEMTIME` struct in coordinated universal time **(UTC)**. It will not work as desired otherwise.
Depending on where/ how you are getting your `DateTime` values, it might be best to play it safe and use [`ToUniversalTime()`](http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime%28v=vs.110%29.aspx) before setting the corresponding values in the `SYSTEMTIME` struct.
Code example:
```
DateTime tempDateTime = GetDateTimeFromSomeService();
DateTime dateTime = tempDateTime.ToUniversalTime();
SYSTEMTIME st = new SYSTEMTIME();
// All of these must be short
st.wYear = (short)dateTime.Year;
st.wMonth = (short)dateTime.Month;
st.wDay = (short)dateTime.Day;
st.wHour = (short)dateTime.Hour;
st.wMinute = (short)dateTime.Minute;
st.wSecond = (short)dateTime.Second;
// invoke the SetSystemTime method now
SetSystemTime(ref st);
``` | Change system date programmatically | [
"",
"c#",
"datetime",
"date",
"time",
"system",
""
] |
I know I can use Awk, but I am on a Windows box, and I am making a function for others that may not have Awk. I also know I can write a C program, but I would love not to have something that requires compilation and maintenance for a little Vim utility I am making.
The original file might be:
```
THE DAY WAS LONG
THE WAY WAS FAST
```
and after the transposition, it should become:
```
TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
```
### Update
* Golf rules apply to selecting correct answer.
* Python fans should check out [Charles Duffy’s answer below](https://stackoverflow.com/a/704139/254635). | Here is a command in Vim language. So you don't have to compile Vim with +python support.
```
function! s:transpose()
let maxcol = 0
let lines = getline(1, line('$'))
for line in lines
let len = len(line)
if len > maxcol
let maxcol = len
endif
endfor
let newlines = []
for col in range(0, maxcol - 1)
let newline = ''
for line in lines
let line_with_extra_spaces = printf('%-'.maxcol.'s', line)
let newline .= line_with_extra_spaces[col]
endfor
call add(newlines, newline)
endfor
1,$"_d
call setline(1, newlines)
endfunction
command! TransposeBuffer call s:transpose()
```
Put this in newly created .vim file inside vim/plugin dir or put this to your [.\_]vimrc.
Execute `:TransposeBuffer` to transpose current buffer | Vim support for a number of scripting languages built in -- see [the Python interface](http://www.vim.org/htmldoc/if_pyth.html) as an example.
Just modify `vim.current.buffer` appropriately and you're set.
To be a little more specific:
```
function! Rotate()
python <<EOF
import vim, itertools
max_len = max((len(n) for n in vim.current.buffer))
vim.current.buffer[:] = [
''.join(n) for n in itertools.izip(
*( n + ' ' * (max_len - len(n))
for n in vim.current.buffer))]
EOF
endfunction
``` | How to transpose the contents of lines and columns in a file in Vim? | [
"",
"python",
"vim",
"text-files",
"text-parsing",
""
] |
I need to pass a function as a parameter to another function and then call the passed function from within the function...This is probably easier for me to explain in code..I basically want to do something like this:
```
function ($functionToBeCalled)
{
call($functionToBeCalled,additional_params);
}
```
Is there a way to do that.. I am using PHP 4.3.9
Thanks! | I think you are looking for [`call_user_func`](https://www.php.net/function.call-user-func).
An example from the PHP Manual:
```
<?php
function barber($type) {
echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>
``` | ```
function foo($function) {
$function(" World");
}
function bar($params) {
echo "Hello".$params;
}
$variable = 'bar';
foo($variable);
```
Additionally, you can do it this way. See [variable functions](http://us.php.net/manual/en/functions.variable-functions.php). | PHP pass function name as param then call the function? | [
"",
"php",
"function",
"parameters",
""
] |
I was reading about volatile member function and came across an affirmation that member function can be both **const and volatile together**. I didn't get the real use of such a thing. Can anyone please share their experience on **practical usage** of having member function as const and volatile together.
I wrote small class to test the same:
```
class Temp
{
public:
Temp(int x) : X(x)
{
}
int getX() const volatile
{
return X;
}
int getBiggerX()
{
return X + 10;
}
private:
int X;
};
void test( const volatile Temp& aTemp)
{
int x = aTemp.getX();
}
int main(int argc, char* argv[])
{
const volatile Temp aTemp(10);
test(aTemp);
return 0;
}
``` | You asked for a practical example of volatile member functions. Well i can't think of one because the only situations i *could* imagine are so low-level that i would not consider using a member function in the first place, but just a plain struct with data-members accessed by a volatile reference.
However, let's put a const volatile function into it just for the sake of answering the question. Assume you have a port with address 0x378h that contains 2 integers, 4 bytes each. Then you could write
```
struct ints {
int first;
int second;
int getfirst() const volatile {
return first;
}
int getsecond() const volatile {
return second;
}
// note that you could also overload on volatile-ness, just like
// with const-ness
};
// could also be mapped by the linker.
ints const volatile &p = *reinterpret_cast<ints*>(0x378L);
```
You are stating
> **I'm** not changing them, but another thing outside this abstract semantics could change it. So always do a real load from its address.
Actually, *volatile* signals that the value of an object might not be the value last stored into it but is actually unknown and might have been changed in between by external (not observable by the compiler) conditions. So when you read from a volatile object, the compiler has to emulate the exact abstract semantics, and perform no optimizations:
```
a = 4;
a *= 2;
// can't be optimized to a = 8; if a is volatile because the abstract
// semantics described by the language contain two assignments and one load.
```
The following already determines what `volatile` does. Everything can be found in `1.9` of the Standard. The parameters it talks about are implementation defined things, like the sizeof of some type.
> The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below. [...]
>
> A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible execution sequences of the corresponding instance of the abstract machine with the same program and the same input. [...]
>
> The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions. | The *cv* qualification distilled means:
> I won't change the value, but there is something out there that can.
You are making a promise to yourself that you won't change the value (`const` qualification) and requesting the compiler to keep its slimy hands off of this object and turn off all optimization (`volatile` qualification). Unfortunately, there is little standard among the compiler vendors when it comes to treating `volatile` fairly. And `volatile` is a *hint* to the compiler after all.
A practical use case of this is a system clock. Supposing 0xDEADBEEF was your system specific address of a hardware clock register you'd write:
```
int const volatile *c = reinterpret_cast<int *>(0xDEADBEEF);
```
You can't modify that register value, but each time you read it, it is likely to have a different value.
Also, can use this to model [UARTs](http://en.wikipedia.org/wiki/16550_UART). | when should a member function be both const and volatile together? | [
"",
"c++",
"constants",
"volatile",
""
] |
I want to get, given a character, its `ASCII` value.
For example, for the character `a`, I want to get `97`, and vice versa. | Use [`chr()`](http://docs.python.org/library/functions.html#chr) and [`ord()`](http://docs.python.org/library/functions.html#ord):
```
>>> chr(97)
'a'
>>> ord('a')
97
``` | ```
>>> ord('a')
97
>>> chr(97)
'a'
``` | How can I convert a character to a integer in Python, and viceversa? | [
"",
"python",
"integer",
"char",
"type-conversion",
""
] |
I am using expat parser to parse an XML file of around 15 GB . The problem is it throws an "Out of Memory" error and the program aborts .
I want to know has any body faced a similar issue with the expat parser or is it a known bug and has been rectified in later versions ? | I've used expat to parse large files before and never had any problems. I'm assuming you're using SAX and not one of the expat DOM wrappers. If you are using DOM, then that's your problem right there - it would be essentially trying to load the whole file into memory.
Are you allocating objects as you parse the XML and maybe not deallocating them? That would be the first thing I would check for. One way to check if the problem is really with expat or not - if you reduce the program to a simple version that has empty tag handlers (i.e. it just parses the file and does nothing with the results) does it still run out of memory? | I don't know expat at all, but I'd guess that it's having to hold too much state in memory for some reason. Is the XML mal formed in some way? Do you have handlers registered for end tags of large blocks?
I'm thinking that if you have a handler registered for the end of a large block, and expat is expected to pass the block to the handler, then expat could be running out of memory before it's able to completely gather that block. As I said, I don't know expat, so this might not be possible, I'm just asking.
Alternately, are you sure that expat is where the memory loss is? I could imagine a situation where you were keeping some information about the contents of the XML file, and your own data structures, either because the data was so large, or because of memory leaks in your code, caused the out of memory condition. | expat parser: memory consumption | [
"",
"c++",
"xml",
"large-files",
"out-of-memory",
"expat-parser",
""
] |
I am sure it's possible to be able to drag files onto a Flash movie inside a browser, but is it possible to achieve the same functionality with Javascript?
I have seen a site (can't remember) that did this, but I never checked if it was a pure Javascript solution compared to a Flash solution.
I am leaning towards the **not** side, I believe that breaks the limitations of Javascript, although if there is any solution I would love to hear it. My only worry is it won't be supported that well across different browsers. | I don't think it's possible to drag a file into a page as such.
Though some browsers may allow you to drag a file into a file upload input box. If this is the cease, perhaps you could stretch such an input via CSS and make it transparent/overlay on background to provide a "pretty" drop target. | You can do this with ActiveX, though it would only work in IE.. and here is an article describing how to do a drag/drop upload in Firefox <http://straxus.javadevelopersjournal.com/creating_a_mozillafirefox_drag_and_drop_file_upload_script_p.htm>
There isn't a generic way of doing this that will work for all browsers with javascript - but you could use a java applet like this: <http://www.zackgrossbart.com/hackito/2007/11/28/drag-and-drop-file-uploading-made-easy/> | Drop Files From Window To Javascript | [
"",
"javascript",
"uploading",
""
] |
I'm writing a Ruby on Rails app. The following jQuery code is included in the head tag of the index.html.erb file, which is the template for all pages on the site.
```
<script>
$(document).ready(function() {
$("#select_mailshot").click(function () {
alert('mailshot');
document.location.href = "/products/1";
});
$("#select_blog").click(function () {
alert('blog');
document.location.href = "/messages";
});
$("#select_contact").click(function () {
alert('contact');
document.location.href = "/contacts/1";
});
});
</script>
```
(the alert steps are in there for debugging)
The following html code in index.html.erb
```
<ul>
<li id="select_mailshot">Mailshot</li>
<li id="select_blog">Blog</li>
<li id="select_contact">Contact us</li>
</ul>
```
The intention is that this effectively creates 3 buttons.
When clicking on any button from <http://myurl.com/> it all works.
When clicking on any button from <http://myurl.com/messages> (get to this via the middle button) it all works
When starting from <http://myurl.com/products/1> it all stops working (the alerts do not trigger). In fact when starting from <http://myurl.com/anything/id> it stops working.
I've been trying to solve this for hours now and the only difference between the working and non-working conditions is the url as far as I can see.
Can anyone shed any light as to what's going on here? | What does firebug tell you? Do you have javascript errors on the page? if so, what are they? Are you sure the jQuery library is included correctly in the deeper pages ( i.e. is it a relative path? ) | Is this javascript inlined?
If not, then maybe the link is relative so when you try to load it from messages/40 you need **../script.js**. Another solution is to use absolute URLs (<http://myurl/script.js>) or virtual (/script.js). | JQuery isn't recognising a #id selector, seems to be dependent on the URL | [
"",
"javascript",
"jquery",
""
] |
I know that file\_get\_contents can be used to retrieve the source of a webpage, but I want to know the most efficient way.
I have an old class I made a long time ago that uses something like this:
```
$this->socket = fsockopen($this->host, 80);
fputs($this->socket, 'GET ' . $this->target . ' HTTP/1.0' . "\n");
fputs($this->socket, 'Host: ' . $this->host . "\n");
fputs($this->socket, 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5' . "\n");
fputs($this->socket, 'Connection: close' . "\n\n");
$this->source = '';
while(!feof($this->socket))
{
$this->source .= fgets($this->socket, 128);
}
fclose($this->socket);
```
Is this the best way? By most efficient I mean returns the fastest results. | `file_get_contents()` is the best and most efficient way. But, either way, there is not much difference because the bottleneck is the network, not the processor. Code readability should also be a concern.
Consider this benchmark as well: <http://www.ebrueggeman.com/php_benchmarking_fopen.php> | The code you have is probably the fastest and simplest way of doing what you're talking about. However, it isn't very flexible if you want to do more complex tasks (like posting, or supporting HTTP 1.1 stuff like Content-Encoding and Transfer-Encoding).
If you want something that will handle more complex cases and such, use php [cURL](http://php.net/curl). | Most efficient way to retrieve the source of a website through PHP? (GET Request) | [
"",
"php",
"http",
"sockets",
"fgets",
""
] |
Modern computers have more and more cores. We want to change our current linear algorithm to use these cores.
A splitting of any algorithm to use different threads only makes sense if there is a free processor.
Are there any good libraries that can help to parallelize some steps if there are free processors?
I will give some examples.
* If there is only one processor it makes no sense to create multiple threads. It will reduce the speed.
* If there run 2 processes (requests on a server) on a core duo it make also no sense to start threads.
* If there only one process on a core duo it make sense.
The abstract algorithm has 4 steps A, B, C and D. Steps A, B and C can execute parallel. Step D needs the results from A, B and C.
Edit: I means an mathematic algorithm. No IO, No events, etc | I think you need a ConcurrentContext from Javolution. See at <http://javolution.org/target/site/apidocs/javolution/context/ConcurrentContext.html> | This isn't necessarily true.
Depending on the algorithm, it often makes sense to split it into multiple threads even if there is only a single core available. If there is any waiting on sockets, IO, etc, you can get benefits from this. If there are 2 processes, the "other" process may not be using 100% of the other core, so threading can help here. Trust your OS in this case to handle it correctly.
You can always check the processor count with Runtime.availableProcessors() to determine how to split it into separate threads. Alternatively, you can use a threadpool, which should scale correctly with more processors.
In general, though, I would design your algorithm to use more than one processor if the algorithm makes sense to parallelize. Most systems will have more cores/processors available, and you can always tweak your implementation later if you find it needs it. If the process is long running, the overhead of generating the thread will be worth it - if it's already fast, it may be more worthwhile looking at other places to optimize. | How can I implement an algorithm for multicore in Java? | [
"",
"java",
"algorithm",
"multithreading",
"multicore",
""
] |
While reading about the function [InterlockedIncrement](http://msdn.microsoft.com/en-us/library/ms683614(VS.85).aspx#) I saw the remark that the variable passed must be aligned on a 32-bit boundary. Normally I have seen the code which uses the InterlockedIncrement like this:
```
class A
{
public:
A();
void f();
private:
volatile long m_count;
};
A::A() : m_count(0)
{
}
void A::f()
{
::InterlockedIncrement(&m_count);
}
```
Does the above code work properly in multi-processor systems or should I take some more care for this? | It depends on your compiler settings. However, by default, anything eight bytes and under will be aligned on a natural boundary. Thus an "int" we be aligned on a 32-bit boundary.
Also, the "#pragma pack" directive can be used to change alignment inside a compile unit.
I would like to add that the answer assumes Microsoft C/C++ compiler. Packing rules might differ from compiler to compiler. But in general, I would **assume** that most C/C++ compilers for Windows use the same packing defaults just to make working with Microsoft SDK headers a bit easier. | Strictly speaking, it really depends on your usage of A - for instance, if you pack an "A" object within a shell ITEMIDLIST, or a struct with a bad "pragma pack" the data may not be properly aligned. | InterlockedIncrement usage | [
"",
"c++",
"multithreading",
"winapi",
"multicore",
"interlocked",
""
] |
In my project I often encounter Java heap space errors, i.e., there isn't enough space to run the program any more. Is there any way I can increase virtual memory?
I am not using the command-line. I am using Net Beans. | In NetBeans, you can add command line options using the Properties of the Project, the Run option. There is an option for the JVM command line there. Look at the -Xms and -Xmx options.
This works for JRuby projects as well, incidentally. | Under Netbeans you can set the VM options for a project, in the project properties. Under Properties > Run the last box should be VM Options. Netbeans will use those when running the app. | Is there a way to increase virtual memory in an application started from NetBeans? | [
"",
"java",
"netbeans",
"virtual-memory",
"out-of-memory",
""
] |
I have an application that I want to (eventually) convert to ASP.NET MVC. I want to do an all out service upgrade (to ASP.NET) but want to use current asp stuff to run the current functionality so I can upgrade small pieces while making incremental upgrades to the new framework. This site is heavily dependent on a VB6 DLL that is not very mature, so we will also want to upgrade this eventually too, potentially replacing the current functionality with web services. Is there a quick fix or is this task a 3 month + task? Also, I am sure it has been thought of before, the beauty of the MVC is that I would think there is a way to tackle this, though I am unsure of where to start. What would be the quickest way to convert this application (in 40 or so hours), where I can just make small configuration changes and have this working in ASP.NET MVC? | The short answer is... You can't. The differences between classic asp and asp.net are fairly drastic not just in syntax but in overall design. MVC is not just a similar implementation to classic asp although it may look that way. Any conversion will take time, thought and effort to get it completely working.
The good news though, is that you can run them SxS so you can actually have classic asp code running under a site that is setup as an ASP.NET or ASP.NET MVC site. So with some duct tape you can peice together your upgraded solution part by part. | Rewrite your VB6 DLL as a COM callable .NET assembly. Then, you can reference it both from ASP and ASP.NET.
Hopefully, most of the heavy lifting is in the VB6 DLLs. If so, you can then start migrating pages over to ASP.NET MVC as you want. You have to watch out for page-to-page communication - things like Session and Cookies. Cookies will pretty much work as is, but you'll need to move Session to something shareable between MVC and ASP like Sql Server. Unfortunately, that requires rewriting your Session calls in ASP to something else (possibly a COM wrapper around a .NET component again). Search and replace should do the trick, though.
As for the timeline and amount of work this entails - that's pretty context dependent on the amount of spaghetti in your existing app, how much logic is in the DLL vs. ASP, and how many pages you're migrating.
I don't think 40 hours is a reasonable amount of time to get up to speed with .NET, MVC, and rewrite - though I think 2-3 months could be. | Classic ASP in ASP.NET MVC (C#) | [
"",
"c#",
"asp.net-mvc",
"vb6",
"asp-classic",
""
] |
Is it possible to have any control over the class names that get generated with the .Net XSD.exe tool? | As far as I'm aware I don't think this is possible, the class names match almost exactly to whats in the schema.
Personally I would change the class names after XSD has generated the code, but to be honest I usually just stick with what XSD generates. Its then easier for someone else reading the code to understand what classes map to what parts of the XML.
Alternatively, if you have control over the schema you could update that? | Basically, no. If you were writing the classes manually, you could have:
```
[XmlType("bar")]
class Foo {}
```
however, you can't do this with the xsd-generated classes. Unfortunately, one of the things you *can't* do with a `partial class` is rename it. Of course, you could use `xsd` to generate it, change the .cs file **and don't generate it again**, but that is not ideal for maintenance. | Classes Generated with XSD.exe Custom Class Names | [
"",
"c#",
".net",
"xsd.exe",
""
] |
Is it possible to echo or print the entire contents of an array without specifying which part of the array?
The scenario: I am trying to echo everything from:
```
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
```
Without specifying "id" and instead outputting the complete contents of the array. | If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:
```
while ($row = mysql_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '<br />';
}
}
```
Or if you don't care about the formatting, use the print\_r function recommended in the previous answers.
```
while ($row = mysql_fetch_array($result)) {
echo '<pre>';
print_r ($row);
echo '</pre>';
}
```
print\_r() prints only the keys and values of the array, opposed to var\_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types - use var\_dump() over print\_r(). | For nice & readable results, use this:
```
function printVar($var) {
echo '<pre>';
var_dump($var);
echo '</pre>';
}
```
The above function will preserve the original formatting, making it (more)readable in a web browser. | Output (echo/print) everything from a PHP Array | [
"",
"php",
"arrays",
""
] |
I am taking over some applications from a previous developer. When I run the applications through Eclipse, I see the memory usage and the heap size increase a lot. Upon further investigation, I see that they were creating an object over-and-over in a loop as well as other things.
I started to go through and do some clean up. But the more I went through, the more questions I had like "will this actually do anything?"
For example, instead of declaring a variable outside the loop mentioned above and just setting its value in the loop... they created the object in the loop. What I mean is:
```
for(int i=0; i < arrayOfStuff.size(); i++) {
String something = (String) arrayOfStuff.get(i);
...
}
```
versus
```
String something = null;
for(int i=0; i < arrayOfStuff.size(); i++) {
something = (String) arrayOfStuff.get(i);
}
```
Am I incorrect to say that the bottom loop is better? Perhaps I am wrong.
Also, what about after the second loop above, I set "something" back to null? Would that clear out some memory?
In either case, what are some good memory management best practices I could follow that will help keep my memory usage low in my applications?
**Update:**
I appreciate everyones feedback so far. However, I was not really asking about the above loops (although by your advice I did go back to the first loop). I am trying to get some best practices that I can keep an eye out for. Something on the lines of "when you are done using a Collection, clear it out". I just really need to make sure not as much memory is being taken up by these applications. | Don't try to outsmart the VM. The first loop is the suggested best practice, both for performance and maintainability. Setting the reference back to null after the loop will not guarantee immediate memory release. The GC will do its job best when you use the minimum scope possible.
Books which cover these things in detail (from the user's perspective) are [Effective Java 2](http://java.sun.com/docs/books/effective/) and [Implementation Patterns](https://rads.stackoverflow.com/amzn/click/com/0321413091).
If you care to find out more about performance and the inners of the VM you need to see talks or read books from [Brian Goetz](http://www.briangoetz.com/). | Those two loops are equivalent except for the scope of `something`; see [this question](https://stackoverflow.com/questions/110083/which-loop-has-better-performance-why) for details.
General best practices? Umm, let's see: don't store large amounts of data in static variables unless you have a good reason. Remove large objects from collections when you're done with them. And oh yes, "Measure, don't guess." Use a profiler to see where the memory is being allocated. | What are some Java memory management best practices? | [
"",
"java",
"memory-management",
""
] |
I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it? | With bash:
```
while true ; do
run_proc &
PID=$!
sleep 3600
kill $PID
sleep 30
done
```
The `$!` bash variable expands to the PID of the most recently started background process. The `sleep` just waits an hour, then the `kill` shuts down that process.
The `while` loop just keeps doing it over and over. | This is in Perl, but you should be able to translate it to Python.
```
#!/usr/bin/perl
use strict;
use warnings;
#set times to 0 for infinite times
my ($times, $wait, $program, @args) = @ARGV;
$times = -1 unless $times;
while ($times--) {
$times = -1 if $times < 0; #catch -2 and turn it back into -1
die "could not fork" unless defined(my $pid = fork);
#replace child with the program we want to launch
unless ($pid) {
exec $program, @args;
}
#parent waits and kills the child if it isn't done yet
sleep $wait;
kill $pid;
waitpid $pid, 0; #clean up child
}
```
Because I am trying to teach myself Python, here it is in Python (I do not trust this code):
```
#!/usr/bin/python
import os
import sys
import time
times = int(sys.argv[1])
wait = int(sys.argv[2])
program = sys.argv[3]
args = []
if len(sys.argv) >= 4:
args = sys.argv[3:]
if times == 0:
times = -1
while times:
times = times - 1
if times < 0:
times = -1
pid = os.fork()
if not pid:
os.execvp(program, args)
time.sleep(wait)
os.kill(pid, 15)
os.waitpid(pid, 0)
``` | How do I schedule a process' termination? | [
"",
"python",
"bash",
"unix",
"process",
"kill",
""
] |
Given the following code:
```
#pragma once
class B
{
public:
B(void)
{
}
~B(void)
{
}
};
```
I know I can also write this:
```
#pragma once
class B
{
public:
B()
{
}
~B()
{
}
};
```
What is the purpose of having `void` in the first example? Is it some type of practice that states the constructor take **zero** parameters? | The two are same, at least in C++. In C, providing an empty pair of parentheses typically means an unspecified parameter list (as opposed to an empty parameter list). C++ does not have this problem.
***How can a correct answer get downvoted so many times? Yet another SO bug?*** | A long time ago you did something like this in C (my pre-ISO C is rusty :) ):
```
void foo(a, b)
int a,
int b
{
}
```
while C++ was being created the name mangling required the types of the arguments, so for C++ it was changed to:
```
void foo(int a, int b)
{
}
```
and this change was brought forward to C.
At this point, I believe to avoid breaking existing C code this:
```
void foo()
```
and this:
```
void foo(void)
```
meant two very different things, `()` means *do not check for the argument number or type*, and `(void)` means *takes no arguments*. For C++ `()` meaning *not to check anything* was not going to work so `()` and `(void)` mean the same thing in C++.
So, for C++ `()` and `(void)` were always the same thing.
At least that is how I remember it... :-) | What is the meaning of having void in the constructor definition? | [
"",
"c++",
""
] |
I've got a regular expression (javascript) which is something like...
/(x)(y)+(z)/gi
The problem is that I'll always get exactly 3 captures from those parens, even if the (y)+ matched multiple times. If it does match multiple times, it just returns the last match. I've no way of knowing ahead of time how many times y will match on any given run, but I want to capture all of them.
Any ideas? | I would use
```
/(x)(y+)(z)/gi
```
then take the text that matched the second group and parse it further. | I take it you can't use
```
/(x)((?:y)+)(z)/gi
```
because this is part of a "larger regex"? | Multiple captures with one set of parens in a larger regex | [
"",
"javascript",
"regex",
""
] |
The situation is: there is a file with 14 294 508 unsigned integers and 13 994 397 floating-point numbers (need to read `double`s). Total file size is ~250 MB.
Using `std::istream` takes ~30sec. Reading the data from file to memory (just copying bytes, without formatted input) is much faster. Is there any way to improve reading speed without changing file format? | Do you need to use STL style i/o? You must check out [this](http://www.dietmar-kuehl.de/cxxrt/cxxrt-1.0.4.tar.gz) excellent piece of work from one of the experts. It's a specialized `iostream` by Dietmar Kuhl.
I hate to suggest this but take a look at the C formatted i/o routines. Also, are you reading in the whole file in one go? | Parsing input by yourself (atoi & atof), usually boosts speed at least twice, compared to "universal" read methods. | How to perform fast formatted input from a stream in C++? | [
"",
"c++",
"performance",
"stl",
"file-io",
""
] |
I'm an experienced C# developer but a WPF newbie. Basic question (I think) that I can't find an answer to by web searching. Here's the simplified use case...
I want to display a string in a WPF TextBlock. So I write some C# code in codebehind of my XAML control...
```
public class MyCoolControl : UserControl
{
public void InitializeMyCoolControl()
{
this.DataContext = "SomeStringOnlyAvailableAtRuntime"; // Perhaps from a database or something...
}
}
```
And I set up my XAML like this:
```
<UserControl ... snip...>
<!-- Bind the textblock to whatever's in the DataContext -->
<TextBlock Text="{Binding}"></TextBlock>
</UserControl>
```
Works great, I can see the value "SomeStringOnlyAvailableAtRuntime" when I execute my application. However, I don't see anything at Design Time using Visual Studio 2008's XAML Designer.
How can I see a placeholder value (anything) for the textblock at design time?
Thanks!
-Mike | I often use `FallbackValue` on the binding to have something to look at while I design user controls. For example:
```
<TextBlock Text={Binding Path=AverageValue, FallbackValue=99.99} />
```
However, since `FallbackValue` is not just applied at design time, this might not be appropriate if you want to use `FallbackValue` at run time for other reasons. | In your example you might need to use `TargetNullValue`, not `FallbackValue` as the binding expression is likely to be `null` as the `DataContext` is `null` at design time.
`FallBackValue` is used if the `Path` given in the binding does not exist, but as no path is specified I'd assume the `DataContext` would then be evaluated as `null`.
```
<UserControl ... snip...>
<!-- Bind the textblock to whatever's in the DataContext -->
<TextBlock Text="{Binding TargetNullValue=Nothing to see}"></TextBlock>
</UserControl>
```
Also note that .NET Framework 3.5 SP1 is needed as these two additional properties were added in SP1. | How to display placeholder value in WPF Visual Studio Designer until real value can be loaded | [
"",
"c#",
"wpf",
"visual-studio",
"designer",
""
] |
I've just built an SVG map of New Zealand for use with the excellent javascript library [Raphael](http://raphaeljs.com), but unfortunately have stumbled upon what I can only imagine is a bug or syntactic variation in IE's javascript interpreter.
In Firefox and other browsers the onlick and onmouseover events work perfectly - however they do not fire in IE (tested in IE 7). Unfortunately there is no javascript error to help me debug this, so I can only assume IE handles these events in some fundamentally different way.
```
<script type="text/javascript" charset="utf-8">
window.onload = function() {
var R = Raphael("paper", 450, 600);
var attr = {
fill: "#3f3f40",
stroke: "#666",
"stroke-width": 1,
"stroke-linejoin": "round"
};
var nz = {};
nz.northland = R.path(attr, "M 193.34222,3.7847503 C 194.65463");
// SVG data stripped for sake of brevity
var current = null;
for (var region in nz) {
nz[region].color = Raphael.getColor();
(function(rg, region) {
rg[0].style.cursor = "pointer";
rg[0].onmouseover = function() {
current && nz[current].animate({ fill: "#3f3f40", stroke: "#666" }, 500) && (document.getElementById(current).style.display = "");
rg.animate({ fill: rg.color, stroke: "#ccc" }, 500);
rg.toFront();
R.safari();
document.getElementById(region).style.display = "block";
current = region;
};
rg[0].onclick = function() {
alert("IE never gets this far.");
//window.location.href = "my-page.aspx?District=" + region;
};
rg[0].onmouseout = function() {
rg.animate({ fill: "#3f3f40", stroke: "#666" }, 500);
};
if (region == "northland") {
rg[0].onmouseover();
}
})(nz[region], region);
}
};
</script>
```
Many thanks :) | The fix appears to be using the onmousedown event instead of onclick.
Changing:
```
rg[0].onclick = function() {
alert("IE never gets this far, but Firefox is happy.");
};
```
to
```
rg[0].onmousedown = function() {
alert("This works in IE and Firefox.");
};
```
resolved the issue. Thanks for everyone's input - got there in the end. If anyone actually knows why IE doesn't like **onclick**, I'd be interested to hear! | Have you tried attaching the events?
```
if (rg[0].attachEvent)
rg[0].attachEvent("onclick", function(){ /* IE */ });
else
rg[0].addEventListener("click", function(){ /* other */ }, false);
``` | Events work in Firefox/Chrome but fail in IE | [
"",
"javascript",
"internet-explorer",
"raphael",
""
] |
I just started writing a small application in C++ using Visual Studio C++ 2008 Express. I installed the Boost Library using the Windows installer. While compiling the program I get the following error :
> Compiling...
> stdafx.cpp
> Compiling...
> websave.cpp
> GoogleAuthenticate.cpp
> Generating Code...
> Compiling manifest to resources...
> Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
> Copyright (C) Microsoft Corporation. All rights reserved.
> Linking...
> LINK : fatal error LNK1104: cannot open file 'libboost\_system-vc90-mt-gd-1\_38.lib'
// GoogleAuthenticate.h
```
#pragma once
#include <boost/asio.hpp>
class GoogleAuthenticate
{
public:
GoogleAuthenticate(void);
virtual ~GoogleAuthenticate(void);
};
```
// GoogleAuthenticate.cpp
```
#include "StdAfx.h"
#include "GoogleAuthenticate.h"
GoogleAuthenticate::GoogleAuthenticate(void)
{
}
GoogleAuthenticate::~GoogleAuthenticate(void)
{
}
```
// websave.cpp
```
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "hello" << endl;
return 0;
}
```
I checked the boost/boost-1.38/lib folder and the libboost\_system-vc90-mt-gd-1\_38.lib is present there. Also added the path in "Additional Include Directories" in Configuration Properties of the project.
Is there anything that is being missed here ? | Forgot to add this :
In Configuration Properties > Linker > Additional Library Directories, enter the path to the Boost binaries, e.g. C:\Program Files\boost\boost\_1\_38\_0\lib.
Should have RTFM. <http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#link-from-within-the-visual-studio-ide>
Fixed. | You can also add it to the library directories for that specific project. Right click on the project, properties -> Linker -> General -> Additional Library Directories.
We do this because we can have different versions of boost with different projects in our configuration management structure. If you just want to use whatever version is installed on your PC, use the setting from the tools menu: Tools -> Options -> Projects and Solutions -> VC++ Directories -> Library Files. | Linker Error while building application using Boost Asio in Visual Studio C++ 2008 Express | [
"",
"c++",
"visual-studio",
"boost",
"linker",
""
] |
I'm working on a stereoscopy application in C++ and OpenGL (for medical image visualization). From what I understand, the technology was quite big news about 10 years ago but it seems to have died down since. Now, many companies seem to be investing in the technology... [Including nVidia it would seem](http://www.nvidia.co.uk/object/force_within_uk.html).
Stereoscopy is also known as "3D Stereo", primarily by nVidia (I think).
Does anyone see stereoscopy as a major technology in terms of how we visualize things? I'm talking in both a recreational and professional capacity. | With [nVidia's 3D kit](http://www.nvidia.com/object/GeForce_3D_Vision_Main.html) you don't need to "make a stereoscopy application", drivers and video card take care of that. 10 years ago there was good quality stereoscopy with polarized glasses and extremely expensive monitors and low quality stereoscopy with [red/cyan glasses](http://en.wikipedia.org/wiki/Anaglyph_image). What you have now is both cheap and good quality. Right now all you need is 120Hz LCD, entry level graphics card and $100 [shutter glasses](http://en.wikipedia.org/wiki/LCD_shutter_glasses).
So no doubt about it, it will be the next big thing. At least in entertainment. | One reason why it is probably coming back is due to the fact that we know have screens with high enough refreshrate so that 3D is possible. I think I read that you will need somewhere around 100Hz for 3D-TV. So, no need for bulky glasses anymore.
**Edit**: To reiterate: You no longer need glasses in order to have 3D TV. This article was posted in a swedish magazine a few weeks ago: [<http://www.nyteknik.se/nyheter/it_telekom/tv/article510136.ece>](http://www.nyteknik.se/nyheter/it_telekom/tv/article510136.ece).
What it says is basically that instead of glasses you use a technique with vertical lenses on the screen. Problem with CRT is that they are not flat. Our more modern flat screens obviously hasn't got this problem.
The second problem is that you need high frequency (at least 100 Hz as that makes the eye get 50 frames per second) and a lot of pixels, since each eye only gets half the pixels.
TV sets that support 3D **without glasses** have been sold by various companies since 2005. | Is stereoscopy (3D stereo) making a come back? | [
"",
"c++",
"opengl",
"nvidia",
"stereo-3d",
"stereoscopy",
""
] |
Any one a idea how to simply create a form with Zend\_Form and jquery? I want to use Zend\_Form to validate the form so I don't have to dual script the form in JavaScript and PHP.
Thank you,
Ivo Trompert | No problem there.
Add ZendX\_JQuery to your library if you use autoload.
Then extend ZendX\_JQuery\_Form to your needs.
Do your stuff in the init() method of your class.
For example, I was able to create an AutoComplete field which has regular Zend\_Form validation plus JQuery behavior like this:
```
$elem = new ZendX_JQuery_Form_Element_AutoComplete(
'query',
array('Label' => 'Search',
'required'=>true,
'filters'=>array('StripTags'),
'validators'=>array(
array('validator'=>'StringLength',
'options'=>array('min'=>'3'),
'breakChainOnFailure'=>true
),
array('Alnum')
)
)
);
$elem->setJQueryParams(array('data' => array(),
'url' => 'my_autocomplete_callback.php',
'minChars' => 1,
'onChangeInterval' => 500,
)
);
```
Then I even changed the default decorators like this:
```
$elementDecorators = array(
array('UiWidgetElement', array('tag' => '')),
array('Errors', array('tag' => 'div', 'class'=>'error')),
array('Label'),
array('HtmlTag', array('tag' => 'div')),
);
$elem->setDecorators($elementDecorators);
```
And finally add to my form (remember I'm in the init() so I'll address it via $this):
```
$this->addElement($elem);
```
There you are, the magic is done.
PS: don't forget to add the following in your bootstrap:
```
$view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');
``` | Well, Zend\_Form will not generate any client-side JavaScript validators for you, if that's what you mean.
BUT: You can just do all the validation on the server, and use jQuery to hook into the fields' change events, and to AJAX-ify the form validation.
Check [that](http://www.whitewashing.de/blog/articles/92) for a sample. | Zend Framework form with jquery | [
"",
"php",
"jquery",
"validation",
"zend-framework",
"zend-form",
""
] |
This is an odd one. Note this is cut down example code, and misses out destructors deliberately).
```
template <class f, class g> class Ptr;
class RealBase
{
};
template <class a, class b, class c = Ptr<a,b> >
class Base : public RealBase
{
public:
Base(){};
};
template <class d, class e>
class Derived : public Base <d,e>
{
public:
Derived(){};
void DerivedMethod(){};
};
typedef Derived<double,double> D_Derived;
template <class f, class g>
class Ptr
{
public:
Ptr(){};
Ptr(Base<f,g,Ptr<f,g> >* a){in = a;};
Base<f,g,Ptr<f,g> >* operator->()
{
return in;
};
Base<f,g,Ptr<f,g> >& operator*()
{
return *in;
};
private:
Base<f,g,Ptr<f,g> >* in;
};
```
I'm using the Ptr class from this example in a vector, as a pointer to a Derived class.
As we can see, the Ptr takes a `Base<>*` as it's constructor argument.
Unfortunately I need a constructor that takes a const Base<>\*, and I cannot simply do this:
```
Ptr(const Base<>* a) { in = const_cast<Base<>*>(a)};
```
Any ideas how I can make this class accept a `const Base<>*` as it's constructor?
---
Edit:
Ok, turns out I can fix this by making changes to unrelated code, so it's a bit of a non-problem now =] Took me about a day to fix it though =[ | I think you need to define a separate class to wrap pointers to const, since not only the arguments of the constructor, but also the return types of the operators should be changed to const versions. If you make the `ConstPtr` a `friend` of `Ptr`, this should work out quite nicely:
```
template<...>
class ConstPtr {
const Base<...> *in;
ConstPtr(Base<...>* a) { in = a; }
ConstPtr(const Base<...>* a) { in = a; }
ConstPtr(const Ptr<...> &a) { in = a.in; }
...
};
```
To construct wrappers from raw pointers you could add an overloaded function, more or less like this:
```
template<..., class P>
P make_ptr(Base<...> *t);
template<...>
Ptr<...> make_ptr< ..., Ptr<...> >(Base<...> *t) {
return Ptr(t);
}
template<...>
ConstPtr<...> make_ptr< ..., ConstPtr<...> >(const Base<...> *t) {
return ConstPtr(t)
}
``` | Your `Ptr` class has a non-const pointer member. You will not be able to assign a `const Base*` without some unsafe casts. Do you want that? Try this instead:
```
template <class f, class g>
class Ptr
{
public:
Ptr(){};
Ptr(Base<f,g,Ptr<f,g> > const* a) { in = *a; }
Base<f,g,Ptr<f,g> >* operator->()
{
return ∈
};
Base<f,g,Ptr<f,g> >& operator*()
{
return in;
};
private:
Base<f,g,Ptr<f,g> > in;
};
``` | const pointer as a constructor argument | [
"",
"c++",
""
] |
How can I easily detect when a variable changes value? I would like the execution of the program to break on the debugger whenever a specified variable changes value. Right now I'm using Eclipse's debugger. | For a class or instance variable
1. right-click on the variable in the outline view
2. select "Toggle Watchpoint"
3. Then, in the breapkoints view, you can right-click on the resulting
entry
4. select "breakpoint properties"
5. deselect "Field Access". | OR
Toggle Breakpoint on the line where the variable is declared, then right-click on the resulting entry, select "breakpoint properties" and deselect "Field Access". | How to detect when a variable changes value | [
"",
"java",
"eclipse",
"debugging",
"variables",
""
] |
please see the following code.
```
String s = "Monday";
if(s.subString(0,3).equals("Mon"){}
String s2 = new String(s.subString(0,3));
String s3 = s.subString(0,3);
```
I know that line 2 will still point to "Monday" and have a new String object with the offset and count set to 0,3.
The line 4 will create a new String "Mon" in string pool and point to it.
But not sure what about line 5 whether it will behave like line 2 or line 4.
If i am wrong for line 2 or 4 also please correct.. | > I know that line 2 will still point to "Monday" and have a new String object with the offset and count set to 0,3.
That is currently true of the Sun JRE implementation. I seem to recall that was not true of the Sun implementation in the past, and is not true of other implementations of the JVM. Do not rely on behaviour which is not specified. GNU classpath might copy the array (I can't remember off hand what ratio is uses to decide when to copy, but it does copy if the copy is a small enough fraction of the original, which turned one nice O(N) algorithm to O(N^2)).
> The line 4 will create a new String "Mon" in string pool and point to it.
No, it creates a new string object in the heap, subject to the same garbage collection rules as any other object. Whether or not it shares the same underlying character array is implementation dependant. Do not rely on behaviour which is not specified.
The [`String(String)`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#String(java.lang.String)) constructor says:
> Initializes a newly created String object so that it **represents the same sequence of characters** as the argument; in other words, the newly created string is a copy of the argument string.
The [`String(char[])`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#String(char[])) constructor says:
> Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. The **contents of the character array** are copied; subsequent modification of the character array does not affect the newly created string.
Following good OO principles, no method of `String` actually requires that it is implemented using a character array, so no part of the specification of `String` requires operations on an character array. Those operations which take an array as input specify that the **contents** of the array are copied to whatever internal storage is used in the String. A string could use UTF-8 or LZ compression internally and conform to the API.
However, if your JVM doesn't make the small-ratio sub-string optimisation, then there's a chance that it does copy only the relevant portion when you use `new String(String)`, so it's a case of trying it a seeing if it improves the memory use. Not everything which effects Java runtimes is defined by Java.
To obtain a string in the string pool which is `equal` to a string, use the [`intern()`](http://java.sun.com/javase/6/docs/api/java/lang/String.html#intern()) method. This will either retrieve a string from the pool if one with the value already has been interned, or create a new string and put it in the pool. Note that pooled strings have different (again implementation dependent) garbage collection behaviour. | **As pointed out by Pete Kirkham, this is implementation specific. My answer is only correct for the Sun JRE, and only prior to Java 7 update 6.**
You're right about a normal `substring` call just creating a new string referring to the same character array as the original string. That's what happens on line 5 too. The fact that the new string object reference happens to be assigned to a variable doesn't change the behaviour of the method.
Just to be clear, you say that in line 2 the new string will still point to "Monday" - the char array reference inside the string will be to the same char array as one used for "Monday". But "Monday" is a string in itself, not a char array. In other words, by the time line 2 has finished (and ignoring GC) there are two string objects, both referring to the same char array. One has a count of 6 and the other has a count of 3; both have an offset of 0.
You're wrong about line 4 using a "string pool" though - there's no pooling going on there. However, it is different to the other lines. When you call the `String(String)` constructor, the new string takes a *copy* of the character data of the original, so it's completely separate. This can be very useful if you only need a string which contains a small part of a very large original string; it allows the original large char array to be garbage collected (assuming nothing else needs it) while you hold onto the copy of the small portion. A good example of this in my own experience is reading lines from a line. By default, `BufferedLineReader` will read lines using an 80-character buffer, so every string returned will use a char array of at least 80 characters. If you're reading lots of very short lines (single words) the difference in terms of memory consumption just through the use of the odd-looking
```
line = new String(line);
```
can be very significant.
Does that help? | how the subString() function of string class works | [
"",
"java",
"string",
""
] |
Is it ok to define tables primary key with 2 foreign key column that in combination must be unique? And thus not add a new id column (Guid or int)?
Is there a negative to this? | Yes, it's completely OK. Why not? The downside of composite primary keys is that it can be long and it might be harder to identify a single row uniquely from the application perspective. However, for a couple integer columns (specially in junction tables), it's a good practice. | Natural versus Artificial primary keys is one of those issues that gets widely debated and IMHO the discussion only seems to see the positions harden.
In my opinion both work so long as the developer knows how to avoid the downside of both. A natural primary key (whether composite or single column) more nearly ensures that duplicate rows are not added to the DB. Whereas with artificial primary keys it is necessary to first check the record is unique (as opposed to the primary key, which being artificial will always be unique). One effective way to achieve this is to have a unique or candidate index on the fields that make the record unique (e.g. the fields that make a candidate for a primary key)
Meanwhile an artificial primary key makes for easy joining. Relations can be made with a single field to single field join. With a composite key the writer of the SQL statement must know how many fields to include in the join. | Should I use Natural Identity Columns without GUID? | [
"",
"sql",
"primary-key",
""
] |
How can I log a user out from my facebook connect website, without using the fb-login button? I would like to do it from codebehind (c#)? | I found out that there was only an option to do it from Javascript by `FB.logout()`. It seems kinda wird that there is no API from codebehind to do the same. | If you just want a simple link to log out the user, you can form a url like this:
`https://www.facebook.com/logout.php?access_token=ACCESS_TOKEN&confirm=1&next=REDIRECT`
Just replace `ACCESS_TOKEN` and `REDIRECT` with the appropriate values. Facebook changes this every now and then, so you have to watch out for that. This only works in the browser, but the nice thing about doing it this way is that the user doesn't have to wait for the JavaScript library to load. | Logout with facebook | [
"",
"c#",
".net",
"facebook",
""
] |
I'm attempting to create a concrete instance of the IAudioEvents COM interface (available in Vista and later). This is my first foray into COM programming, so I'm probably just doing something stupid here. Anyway, the following code fails to compile with "C2259: 'AudioEndpointVolumeNotifierImpl' : cannot instantiate abstract class".
Class Definiton (AudioEndpointVolumeNotifierImpl.h):
```
class AudioEndpointVolumeNotifierImpl : public IAudioSessionEvents
{
private:
LONG _cRef;
public:
AudioEndpointVolumeNotifierImpl() : _cRef(1){}
~AudioEndpointVolumeNotifierImpl(){}
HRESULT STDMETHODCALLTYPE OnSimpleVolumeChanged(float NewVolume, BOOL NewMute,LPCGUID EventContext);
HRESULT STDMETHODCALLTYPE OnChannelVolumeChanged(DWORD ChannelCount, float NewChannelVolumeArray[], DWORD ChangedChannel, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnDisplayNameChanged(LPCWSTR NewDisplayName, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnGroupingParamChanged(LPCGUID NewGroupingParam, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPWCHAR NewIconPath, LPCGUID EventContext){return S_OK;}
HRESULT STDMETHODCALLTYPE OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason){return S_OK;}
HRESULT STDMETHODCALLTYPE OnStateChanged(AudioSessionState NewState){ return S_OK; }
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&_cRef);
}
ULONG STDMETHODCALLTYPE Release()
{
ULONG ulRef = InterlockedDecrement(&_cRef);
if (0 == ulRef)
{
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface)
{
if (IID_IUnknown == riid)
{
AddRef();
*ppvInterface = (IUnknown*)this;
}
else if (__uuidof(IAudioSessionEvents) == riid)
{
AddRef();
*ppvInterface = (IAudioSessionEvents*)this;
}
else
{
*ppvInterface = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
};
```
Corresponding .cpp:
```
HRESULT STDMETHODCALLTYPE AudioEndpointVolumeNotifierImpl::OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext)
{
PostStatusChange(NewVolume);
return S_OK;
}
```
Fails in an IClassFactory instance on the following code:
```
...
AudioEndpointVolumeNotifierImpl* pObject = new AudioEndpointVolumeNotifierImpl();
if (pObject == NULL)
{
return E_OUTOFMEMORY ;
}
...
```
A good portion of this code IS lifted from some tutorials (the IUnknown stuff in particular). I'm not expecting this code to work just yet, but I can't see why it doesn't compile.
Thanks. | Oddly, although `OnIconPathChanged` is described as taking an `LPWCHAR` parameter here:
<http://msdn.microsoft.com/en-us/library/dd370939(VS.85).aspx>
It is shown taking an `LPCWSTR` in the example here:
<http://msdn.microsoft.com/en-us/library/dd370797(VS.85).aspx>
One of these is probably wrong; if we assume it is the former, and that the method actually takes an `LPCWSTR` (which makes more sense given the context anyway), that would explain your error. I would try changing your declaration to
```
HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPCWSTR NewIconPath, LPCGUID EventContext){return S_OK;}
``` | In addition to Eric Melski's answer (since you said you were a beginner, i assumed his answer would not be clear to you):
The reason why you get this error is because AudioEndpointVolumeNotifierImpl is an abstract class, which means that it has pure virtual methods, either directly defined in the class, or inherited from base class.
In your case, it's clearly the latter.
What you want to do is implement inherited pure virtual methods, which you have tried to do, but if the signature of the methods are not the same, you are simply defining an overload, and leaving the base pure virtual method unchanged. And your class is still abstract. Hence the error message. | Beginning C++ problem; cannot instantiate abstract class (C2259 in VS) | [
"",
"c++",
"windows",
"com",
""
] |
Scenario: over 1.5GB of text and csv files that I need to process mathematically. I tried using SQL Server Express, but loading the information, even with BULK import takes a very long time, and ideally I need to have the entire data set in memory, to reduce hard disk IO.
There are over 120,000,000 records, but even when I attempt to filter the information to just one column (in-memory), my C# console application is consuming ~3.5GB of memory to process just 125MB (700MB actually read-in) of text.
It seems that the references to the strings and string arrays are not being collected by the GC, even after setting all references to null and encapsulating IDisposables with the using keyword.
I think the culprit is the String.Split() method which is creating a new string for each comma separated value.
You may suggest that I shouldn't even read the unneeded\* columns into a string array, but that misses the point: How can I place this *entire* data set in memory, so I can process it in parallel in C#?
I could optimize the statistical algorithms and coordinate tasks with a sophisticated scheduling algorithm, but this is something I was hoping to do before I ran into memory problems, and not because of.
I have included a full console application that simulates my environment and should help replicate the problem.
Any help is appreciated. Thanks in advance.
```
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace InMemProcessingLeak
{
class Program
{
static void Main(string[] args)
{
//Setup Test Environment. Uncomment Once
//15000-20000 files would be more realistic
//InMemoryProcessingLeak.GenerateTestDirectoryFilesAndColumns(3000, 3);
//GC
GC.Collect();
//Demostrate Large Object Memory Allocation Problem (LOMAP)
InMemoryProcessingLeak.SelectColumnFromAllFiles(3000, 2);
}
}
class InMemoryProcessingLeak
{
public static List<string> SelectColumnFromAllFiles(int filesToSelect, int column)
{
List<string> allItems = new List<string>();
int fileCount = filesToSelect;
long fileSize, totalReadSize = 0;
for (int i = 1; i <= fileCount; i++)
{
allItems.AddRange(SelectColumn(i, column, out fileSize));
totalReadSize += fileSize;
Console.Clear();
Console.Out.WriteLine("Reading file {0:00000} of {1}", i, fileCount);
Console.Out.WriteLine("Memory = {0}MB", GC.GetTotalMemory(false) / 1048576);
Console.Out.WriteLine("Total Read = {0}MB", totalReadSize / 1048576);
}
Console.ReadLine();
return allItems;
}
//reads a csv file and returns the values for a selected column
private static List<string> SelectColumn(int fileNumber, int column, out long fileSize)
{
string fileIn;
FileInfo file = new FileInfo(string.Format(@"MemLeakTestFiles/File{0:00000}.txt", fileNumber));
fileSize = file.Length;
using (System.IO.FileStream fs = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(fs))
{
fileIn = sr.ReadToEnd();
}
}
string[] lineDelimiter = { "\n" };
string[] allLines = fileIn.Split(lineDelimiter, StringSplitOptions.None);
List<string> processedColumn = new List<string>();
string current;
for (int i = 0; i < allLines.Length - 1; i++)
{
current = GetColumnFromProcessedRow(allLines[i], column);
processedColumn.Add(current);
}
for (int i = 0; i < lineDelimiter.Length; i++) //GC
{
lineDelimiter[i] = null;
}
lineDelimiter = null;
for (int i = 0; i < allLines.Length; i++) //GC
{
allLines[i] = null;
}
allLines = null;
current = null;
return processedColumn;
}
//returns a row value from the selected comma separated string and column position
private static string GetColumnFromProcessedRow(string line, int columnPosition)
{
string[] entireRow = line.Split(",".ToCharArray());
string currentColumn = entireRow[columnPosition];
//GC
for (int i = 0; i < entireRow.Length; i++)
{
entireRow[i] = null;
}
entireRow = null;
return currentColumn;
}
#region Generators
public static void GenerateTestDirectoryFilesAndColumns(int filesToGenerate, int columnsToGenerate)
{
DirectoryInfo dirInfo = new DirectoryInfo("MemLeakTestFiles");
if (!dirInfo.Exists)
{
dirInfo.Create();
}
Random seed = new Random();
string[] columns = new string[columnsToGenerate];
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= filesToGenerate; i++)
{
int rows = seed.Next(10, 8000);
for (int j = 0; j < rows; j++)
{
sb.Append(GenerateRow(seed, columnsToGenerate));
}
using (TextWriter tw = new StreamWriter(String.Format(@"{0}/File{1:00000}.txt", dirInfo, i)))
{
tw.Write(sb.ToString());
tw.Flush();
}
sb.Remove(0, sb.Length);
Console.Clear();
Console.Out.WriteLine("Generating file {0:00000} of {1}", i, filesToGenerate);
}
}
private static string GenerateString(Random seed)
{
StringBuilder sb = new StringBuilder();
int characters = seed.Next(4, 12);
for (int i = 0; i < characters; i++)
{
sb.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * seed.NextDouble() + 65))));
}
return sb.ToString();
}
private static string GenerateRow(Random seed, int columnsToGenerate)
{
StringBuilder sb = new StringBuilder();
sb.Append(seed.Next());
for (int i = 0; i < columnsToGenerate - 1; i++)
{
sb.Append(",");
sb.Append(GenerateString(seed));
}
sb.Append("\n");
return sb.ToString();
}
#endregion
}
}
```
\*These other columns will be needed and accessed both sequentially and randomly through the life of the program, so reading from disk each time is a tremendously taxing overhead.
\*\*Environment Notes: 4GB of DDR2 SDRAM 800, Core 2 Duo 2.5Ghz, .NET Runtime 3.5 SP1, Vista 64. | Yes, String.Split creates a new String object for each "piece" - that's what it's meant to do.
Now, bear in mind that strings in .NET are Unicode (UTF-16 really), and with the object overhead the cost of a string in bytes is approximately `20 + 2*n` where `n` is the number of characters.
That means if you've got a lot of small strings, it'll take a lot of memory compared with the size of text data involved. For example, an 80 character line split into 10 x 8 character strings will take 80 bytes in the file, but 10 \* (20 + 2\*8) = 360 bytes in memory - a 4.5x blow-up!
I doubt that this is a GC problem - and I'd advise you to remove extra statements setting variables to null when it's not necessary - just a problem of having too much data.
What I *would* suggest is that you read the file line-by-line (using `TextReader.ReadLine()` instead of `TextReader.ReadToEnd()`). Clearly having the whole file in memory if you don't need to is wasteful. | I would suggest reading line by line instead of the entire file, or a block of up to 1-2mb.
**Update:**
From Jon's comments I was curious and experimented with 4 methods:
* StreamReader.ReadLine (default and custom buffer size),
* StreamReader.ReadToEnd
* My method listed above.
Reading a 180mb log file:
* ReadLine ms: 1937
* ReadLine bigger buffer, ascii ms: 1926
* ReadToEnd ms: 2151
* Custom ms: 1415
The custom StreamReader was:
```
StreamReader streamReader = new StreamReader(fileStream, Encoding.Default, false, 16384)
```
StreamReader's buffer by default is 1024.
For memory consumption (the actual question!) - ~800mb used. And the method I give still uses a StringBuilder (which uses a string) so no less memory consumption. | Why can't I leverage 4GB of RAM in my computer to process less than 2GB of information in C#? | [
"",
"c#",
"performance",
"memory",
"string",
"garbage-collection",
""
] |
When I read the xml through a URL's InputStream, and then cut out everything except the url, I get "<http://cliveg.bu.edu/people/sganguly/player/%20Rang%20De%20Basanti%20-%20Tu%20Bin%20Bataye.mp3>".
As you can see, there are a lot of "%20"s.
I want the url to be unescaped.
Is there any way to do this in Java, without using a third-party library? | This is not unescaped XML, this is URL encoded text. Looks to me like you want to use the following on the URL strings.
```
URLDecoder.decode(url);
```
This will give you the correct text. The result of decoding the like you provided is this.
```
http://cliveg.bu.edu/people/sganguly/player/ Rang De Basanti - Tu Bin Bataye.mp3
```
The %20 is an escaped space character. To get the above I used the URLDecoder object. | # Starting from Java 11 use
# [`URLDecoder.decode(url, StandardCharsets.UTF_8)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URLDecoder.html#decode(java.lang.String,java.nio.charset.Charset)).
for Java 7/8/9 use [`URLDecoder.decode(url, "UTF-8")`](https://docs.oracle.com/javase/8/docs/api/java/net/URLDecoder.html#decode-java.lang.String-java.lang.String-).
`URLDecoder.decode(String s)` has been deprecated since **Java 5**
Regarding the chosen encoding:
> Note: The [World Wide Web Consortium Recommendation](http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars) states that **UTF-8** should be used. Not doing so may introduce incompatibilites. | How do you unescape URLs in Java? | [
"",
"java",
"url-encoding",
""
] |
Im trying to generate a small square 32 by 32 pixels with a 10 by 10 squareish transparent gap in the middle.
This is what I have so far:
```
private Image CreatePicture(){
// Create a new Bitmap object, 32 x 32 pixels in size
Bitmap canvas = new Bitmap(32,32,System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
for(int i=10;i<21;i++){
for(int p=10;p<21;p++){
canvas.SetPixel(i,p,Color.Lime);
}
}
canvas.MakeTransparent(Color.Lime);
// return the picture
return canvas;
}
```
Its a it rough and not going to be the final "optimized version" its just a rough demo script. The problem is the returned image does not transparency instead its just a grey box :(.
Any help appreciated.
Michael
UPDATE:
I have updated the script with the PixelFormat set to an Alpha RGB format which it actually accepts without erroring on runtime. Now though if I remove the "canvas.MakeTransparent(Color.Lime);" line it shows a lime box in the middle with it it just shows a grey box the same colour as the grey background; so it seems as if transparency is being recognised just not implimenting the transparency!
```
private Bitmap CreatePicture(){
// Create a new Bitmap object, 50 x 50 pixels in size
Bitmap canvas = new Bitmap(82,82,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
for(int i=10;i<71;i++){
for(int p=10;p<71;p++){
canvas.SetPixel(i,p,Color.Lime);
}
}
canvas.MakeTransparent(Color.Lime);
// return the picture
return canvas;
}
``` | It depends on how your going to use or display the image. PNG and Gif are the two file formats that support transparency.
For the bitmap setting of transparency, i used:
Graphics.FromImage(bitmap).FillRectangle(Brushes.Transparent, ...) to set the area I wanted as transparent, then I saved the file out as a PNG to get an image with transparency.
I also tried the MakeTransparent method and ran into problems and the Brushes.Transparent was the solution that worked for my situation.
Hope this gives you a direction to look into.
One last note, I create the Bitmap object with width and height only, I don't specify the pixel format or whatever that's called i.e. bitmap = New Bitmap(width, height); | ```
[...]Format16bppRgb555
```
Try to use some format with an alpha channel (...Rgba) here. Also, if the output will be an image later, make sure you use an image format like PNG that supports alpha channels. | Generate image with some transparent parts | [
"",
"c#",
"image",
"bitmap",
""
] |
I am having a problem running Ant with JDK 1.6 on Mac OS X. Even though Java application versions is set to Java SE 6 in OS X's Java Preference, executing `java -version` in Terminal also shows `java version "1.6.0_07"`, Ant still seems to use JDK 1.5 to be using JDK 1.5 as it does not see JDK 1.6 classes when compiling my code.
I understand that Ant relies on `JAVA_HOME` environment variable to specify which JDK to use. However, I do not quite understand how this variable can be set on Mac OS X.
Hence, my question is how to make Ant runs with JDK 1.6 on Mac OS X. If the correct way is still to set `JAVA_HOME` environment variable, how to set the variable on OS X. | The JAVA\_HOME environment variable is set in your home directory's .profile file. (/Users/ejel/.profile ?) Edit it and set it to what you want it to be. E.g.:
```
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
```
From this point onward, every time you open a new terminal window it will have JAVA\_HOME set to this new value. It will not have changed with any existing open windows.
If you are truly aghast to putting this in the profile, or if it conflicts with other software, the export statement could always be run in the terminal manually or go into a script (eg: setj6ev.sh) that is run once before you start running ant tasks. | I've added the line
```
export JAVA_HOME=`/usr/libexec/java_home`
```
To my .zshrc file, it seems to do the trick (.bash\_profile or whatever if you use bash). | Running Ant with JDK 1.6 on Mac OS X | [
"",
"java",
"macos",
"ant",
""
] |
I seem to be confused about PHP output buffering. I have code like this:
```
function return_json($obj) {
ob_get_clean();
ob_start();
header("Content-Type: application/json");
echo json_encode($obj);
exit;
}
```
But it doesn't seem to like the ob\_get\_clean(). I do that because some HTML might accidentally get generated before it gets to that point but I thought this was how you were meant to do it.
What am I missing? | Use the [`ob_get_level()` function](http://docs.php.net/ob_get_level) to see if an output buffer is active and quit it:
```
while (ob_get_level()) {
ob_end_clean();
}
``` | To use ob\_get\_clean (), you have to be sure, that at some point you have ob\_start ()'ed earlier. Otherwise, there’s no buffer to clean, everything is already flushed to the user agent. | Output buffering in PHP? | [
"",
"php",
"output-buffering",
""
] |
I know there are a number of threads on here about how to use the using statement and calling the Dispose() method. I have read the majority of these threads.
If I call Dispose(), does it call Close()?
If I want to use an object (say SqlDataReader), but then use it again in another code block, should I not call Dispose()? Which also means to omit the using statement.
Also, to clarify, if a FileStream is wrapping a StreamWriter and I call dispose on the FileStream, this will call Flush(), Close() and Dispose() (depending on whether Dispose() calls Close()) on the StreamWriter, right? Likewise, if I call Close on the FileStream, this will only call Flush() and Close() on the FileStream.
Is checking IL a good way to answer these questions about what is happening under the hood? | > If I call Dispose(), does it call Close()?
Calling [`Dispose`](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) should take any required actions to dispose of the resource, which should be similar, if not identical to, calling [`Close`](http://msdn.microsoft.com/en-us/library/system.io.stream.close.aspx). This, however, is an implementation detail and not necessarily guaranteed (though we can expect that the BCL follows this guideline).
> If I want to use an object (say SqlDataReader), but then use it again in another code block, should I not call Dispose()? Which also means to omit the using statement.
If you want to use the object again, you definitely should not dispose it. However, you should typically use two separate connections if you're going to the database two separate times. It's generally not a good idea to keep an [IDataReader](http://msdn.microsoft.com/en-us/library/system.data.idatareader.aspx) around an longer than is needed to grab your needed data.
> Also, to clarify, if a FileStream is wrapping a StreamWriter and I call dispose on the FileStream, this will call Flush(), Close() and Dispose() (depending on whether Dispose() calls Close()) on the StreamWriter, right? Likewise, if I call Close on the FileStream, this will only call Flush() and Close() on the FileStream.
Disposing an object that wraps another disposable object should call `Dispose` on the interior object. Calling `Close` on a `FileStream` will call its `Dispose` method under the good, so it will also act on both streams.
> Is checking IL a good way to answer these questions about what is happening under the hood?
Checking IL will definitely answer most of these questions definitively. As [@Rich](https://stackoverflow.com/questions/667111/some-advanced-questions-on-the-using-statement/667123#667123) says, you can also just try debugging your own Dispose implementations. There is also, of course, MSDN documentation to start with before you try to figure it out yourself, and Reflector if you don't want to muck around in IL. | "If I call Dispose(), does it call Close()?"
In theory, it should. The BCL classes all do this, but it is up to the library author to correctly handle this. If the library you are using is done correctly, Dispose() should also Close() [and Close() will Dispose() - the calls should be interchangable].
"If I want to use an object (say SqlDataReader), but then use it again in another code block, should I not call Dispose()? Which also means to omit the using statement."
Correct. If you use the using statement, it will always call Dispose(). This will close the data reader before your other block can use it.
"Also, to clarify, if a FileStream is wrapping a StreamWriter and I call dispose on the FileStream, this will call Flush(), Close() and Dispose() (depending on whether Dispose() calls Close()) on the StreamWriter, right? Likewise, if I call Close on the FileStream, this will only call Flush() and Close() on the FileStream."
If you are wrapping a FileStream around a StreamWriter, I highly recommend treating them consistently. Use a single using statement with both members, so they are both disposed of at the end of the block. This is the safest, most clean approach.
"Is checking IL a good way to answer these questions about what is happening under the hood?"
It is a way - although a more difficult way. Read up on MSDN about using and streams, and the documentation will explain it in simpler terms than trying to parse the IL. The IL will tell you EXACTLY what happens, though, if you are curious. | Some advanced questions on the using statement | [
"",
"c#",
".net",
"idisposable",
""
] |
I want to add a VC++ DLL reference into my C# Visual Studio project. But when I try to add it I see, "It is not a valid assembly or COM component".
Please suggest how I can use the VC++ DLL as a reference in a C# project. | There are two options for using a C++ DLL from C#: either COM interop, or P/Invoke. COM Interop involves creating a COM object in your C++ DLL, and then adding it as a reference. You can use the COM object like a C# object (for the most part) at this point.
P/Invoke allows you to call exported functions from C# (think calling standard Win32 API functions from C#). This is likely easier to set up, since all you need to do is export a function, however that could cause you to refactor your code in the C++ DLL, since it's not a very OOP way of doing things. | You can only use C++ components in C# when they have been prepared for use, for example by being written in C++/CLI or being written as a COM server.
If your component is a plain C++ dll you'll need to write some wrapper code, probably best is C++/Cli | How can I add a VC++ DLL as a reference in my C# Visual Studio project? | [
"",
"c#",
".net",
"visual-studio",
"interop",
""
] |
I have a web application that once signed in, personalizes almost all pages.
I want to be able to have some very specific pages locked down with SSL that may have sensitive information. From what I have been able to find, once you sign in via an SSL sign in page (area of the web site), the session information which I use to store a lot of personalization and user credentials is not available to the non SSL portion of the web site since they are considered 2 seperate applications.
This MSDN document pretty much says what I am talking about: [MSDN Doc](http://msdn.microsoft.com/en-us/library/ms998310.aspx)
> Note: If you use this type of site structure, your application must not rely on the user's identity on the non-SSL pages. In the preceding configuration, no forms authentication ticket is sent for requests for non-SSL pages. As a result, the user is considered anonymous. This has implications for related features, such as personalization, that require the user name.
I am also not using forms authentication. When a user signs in a session object is made storing their credentials including their IP. If this session object exists for a particular user with the same IP then they are considered 'signed in' and the personalization features are enabled.
So my question is, are there any work arounds to this so that say my sign in page and some other page are using SSL, the reset of the site is not, and all pages have access to the same session variables?
If not can anyone suggest any other methods of accomplishing the same type of personalization features? | We have decided to not go with SSL in those few pages that required them. We looked at other web applications that did similar things and they do not use SSL. We are not really protecting anything that would be all that useful for a malicious user to go through the trouble of stealing anyways.
One option I did consider before the decision was made to remove the SSL was to store a user's session on the application's web service interface. Every page call would access the web service to access the session information. This would be enforced on every page call to ensure the session stayed active. I didn't do too much investigation into using this solution before the SSL decision was made so there could be many draw backs to this solution, especially having to make extra calls to the web service with every server hit. | Since there are no comments, I thought I'd offer an inelegent but practical solution.
Leave the RequireHTTPS off in your forms authentication configuration block.
Next, you create a custom class that implements IHttpModule. This interface has an Init method that takes a HTTPApplication instance as an argument. You can then attach to the "AuthenticateRequest" event on this instance.
From here, you can 302-redirect any requests that come in without SSL when they should do. You'd probably want to drive which pages require SSL from a custom configuration section in your web.config.
To use this class for your requests, you have to add a line to the HttpModules section of the web.config. | Is it possible to have a personalized ASP.NET web app with only some SSL pages? | [
"",
"c#",
"asp.net",
"security",
"web-applications",
""
] |
I was trying to figure out why a debug build was blowing up with the "dependent assembly microsoft.vc80.debugcrt could not be found" event error.
After deleting everything (anything not .cpp or .h) and recreating the solution - I still had the problem.
A google search was fruitless and a re-install of VS didn't produce any change.
I did have the dlls in C:\WINDOWS\WinSxS\x86\_Microsoft.VC80.DebugCRT\_1fc8b3b9a1e18e3b\_8.0.50727.42\_x-ww\_f75eb16c.
I opened the \debug\.exe.intermediate.manifest file and it had 2 (dependentAssembly) entries:
1st: name='Microsoft.VC80.DebugCRT' version='8.0.50608.0'
2nd: name='Microsoft.VC80.DebugCRT' version='8.0.50727.762'
If I delete one and change the other one to
name='Microsoft.VC80.DebugCRT' version='8.0.50727.42'
I can get a build that will start.
Granted I did have VS2008 installed - but what is controlling the versions ? or How can I get the right debug dll version to "stick".
VS2008 was de-installed through the control panel.
EDIT: Found nothing in the registry if DebugCRT is searched for.
the environment path points to the VS8 folders .
There is only 1 DebugCRT folder in the c:\windows\winsxs\policies folder
(8.0.50.727.42)
The c:\windows\winsxs\manifests folder only has the .42 version of .cat and .manifest
The .manifest file (in above manifest folder) has version="8.0.50727.42"
Clarification: the manifest file has 2 "dependentAssembly" entries each with different versions and not the .42. I can delete 1 entry and change the version on the other to match the .42 to get a debug build that starts.
EDIT2:I'm also using boost and inside the DLLs there is the .762 version | The version was picked up by from the Boost DLLs which were a download, pre-compiled version of Boost. Once the libraries were re-compiled (and re-installed) a re-build of the solution produced a manifest with a single version and the program linked and ran.
So -Check the libs and dlls that are imported into the solution for version used. | VS 2008 is VC90 not VC80, so that's not part of the problem. The relation between manifest-requested assembly and SxS-loaded assenbly is found in C:\WINDOWS\WinSxS\Policies. IIRC, "8.0.50608.0" is generated by VS2005 pre-SP1. It's wrong, and should have been 8.0.50727.42, but this is caught by the policy.
I'm not sure how you're getting two manifests. What are your manifest settings? | Visual Studio 2005 - C++ - What controls the manifest creation | [
"",
"c++",
"visual-studio",
"assemblies",
"version",
"manifest",
""
] |
Coming from a C++ background I have to master the complexity of the Java
world and its frameworks. Looking at the spring framework for DI I am
finding it difficult to believe that I have to make each setter function
which will be subject for DI public. Doesn't that requirement break the
principle of information hiding?
Of course I want spring to be able to set some private parts of my
classes, but I certainly do NOT want every client class to be able to do
the same.
What am I missing here? | If you *code to interfaces*, you only need to expose setters on the implementations. As you inject the interfaces into other parts of the system, they cannot access the implementation details or state of the objects. | I agree with your point - that's why I prefer constructor injection. | Doesn't Spring's dependency injection break information hiding? | [
"",
"java",
"spring",
"dependency-injection",
"encapsulation",
""
] |
I'm new to python programming.
I have this problem: I have a list of text files (both compressed and not) and I need to :
- connect to the server and open them
- after the opening of the file, I need to take his content and pass it to another python function that I wrote
```
def readLogs (fileName):
f = open (fileName, 'r')
inStream = f.read()
counter = 0
inStream = re.split('\n', inStream) # Create a 'list of lines'
out = "" # Will contain the output
logInConst = "" # log In Construction
curLine = "" # Line that I am working on
for nextLine in inStream:
logInConst += curLine
curLine = nextLine
# check if it is a start of a new log && check if the previous log is 'ready'
if newLogRegExp.match(curLine) and logInConst != "":
counter = counter + 1
out = logInConst
logInConst = ""
yield out
yield logInConst + curLine
def checkFile (regExp, fileName):
generatore = readLogs(fileName)
listOfMatches=[]
for i in generatore: #I'm now cycling through the logs
# regExp must be a COMPILE regular expression
if regExp.search(i):
listOfMatches.append(i)
return listOfMatches
```
in order to elaborate the info contained in those files.
The function has the aim of write in just 1 line the logs that are stored in those files using 3 lines ... The function is working fine on files read from my local machine but I cannot figure out how to connect to a remote server and create these one-line logs without storing the content of each file into a string and then working with the string ... The command that I use to connect to the remote machine is :
```
connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0]
```
retList[0] and retList[2] are the user@remote and the folder name that I have to access
Thanks to all in advance !
**UPDATE:**
My problem is that I have to establish an ssh connection first :
```
pr1=Popen(['ssh', 'siatc@lgssp101', '*~/XYZ/AAAAA/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0]
```
All the files that I need to open are stored in a list, fileList[], part of them are compressed (.gz) and part are just text files !! I have tried all the procedures that u showed before bot nothing worked ... I think that I mus modify the third argument of the Popen function but I cannot figure out how to do it ! Is there anyone that can help me ??? | You do not have to split the stream/file into lines yourself. Just iterate:
```
for ln in f:
# work on line in ln
```
This should work equally well for files (using open() for file()) and pipes (using Popen). Use the `stdout` property of the popen object to access the pipe connected to stdout of the subprocess
**Example**
```
from subprocess import Popen, PIPE
pp = Popen('dir', shell=True, stdout=PIPE)
for ln in pp.stdout:
print '#',ln
``` | Remove InStream and just use the file object.
So that your code would read:
```
for nextLine in f.readlines():
.
.
.
```
Ber has it right.
To clarify, the default iteration behavior of a file object is to return the next line. so "**for nextLine in f**" will give you the same results as "**for nextLine in f.readlines()**".
See the file object documentation for details: <http://docs.python.org/library/stdtypes.html#bltin-file-objects> | Python, redirecting the stream of Popen to a python function | [
"",
"python",
"stream",
"subprocess",
"yield",
"popen",
""
] |
I'm coming from the .Net camp where virtualization was much more prevalent do to the need to run on server software and system-wide entities such as the GAC.
Now that I'm doing Java development, does it make sense to continue to employ virtualization? We were using VirtualPC which, IMO, wasn't the greatest offering. If we were to move forward, we would, hopefully, be using VMWare.
We are doing web development and wouldn't use virtualization to test different flavors of server deployment.
Pros:
* Allows development environments to be
identical across the team
* Allows for isolation from the host
* Cross-platform/browser testing
Cons:
* Multiple monitor support is lacking (not in VMWare?)
* Performance degradation - mostly I/O
* Huge virtual disks | One possible advantage is that you could technically test out the same program on a variety of operating systems and on a vartiety of JVMs.
Contrary to popular opinion, Java is not 100% portable, and it is very possible to write nonportable code. In addition, there are subtle versions between libraries. If you work with different JVMs, there could also be differences.
However, since Java IDEs are heavyweight, running an IDE within the VM may not be fun.
Java does support some forms of remote deployment, might be beneficial to explore those while still doing the IDE work locally. | I don't like developing in a VM. The good thing is, in contrast to what you're writing as cons, that multiple monitors are supported by VMWare and the huge disk thing isn't really a problem since VMWare runs surprisingly smoothly from USB hard disks.
Running the heavyweight IDEs for Java, as Uri said, won't be much fun in a VM. But then, running Visual Studio in a VM isn't really fun as well. So if you were happy with VS in a VM, then give it a try for Java, because the cons aren't as strong as you might think :) | Are there any benefits to developing Java in a virtual machine? | [
"",
"java",
"virtualization",
""
] |
I know this question has been asked before, but many answers don't give clear samples with codes on how to do this using ASP.NET 2.0. A simple C# is preferred, but I can also accept VB.NET or F#.
This [third party cookies question](https://stackoverflow.com/questions/390219/why-wont-asp-net-create-cookies-in-localhost) is a sample of a self answered question with the same topic, but it didn't give any clues about reading/getting the third party cookies. | This is basically a [cross site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting) "feature". What you need to do is run code on the client which reads the cookies and somehow transfer the contents to somewhere else. This is typically done via a query.
But before you do that, please think about this for a moment. There's a reason you shouldn't be able to read cookies from third parties in the first place. | It is a security feature that one can only read cookies from the same domain that created the cookies. Trying to read "foreign" cookies is a sign of malicious intentions. | How to read third party cookies works across different domains? | [
"",
"c#",
"asp.net",
"c#-2.0",
"cookies",
""
] |
I'd like to parse REXX source so that I can analyse the structure of the program from Java.
I need to do things like normalise equivalent logic structures in the source that are syntactically different, find duplicate variable declarations, etc. and I already have a Java background.
Any easier ways to do this than writing a load of code? | If you have [BNF](http://en.wikipedia.org/wiki/Backus-Naur_form) Rexx grammar, then **[javacc](https://javacc.dev.java.net/)** can help you build an [AST](http://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree) representation of that Rexx code.
More accurately, javacc will build the *Java classes* which will :
* parse Rexx code and
* actually builds the AST.
There would still be "load of code", but you would not to be the one doing the writing of the classes for that Rexx code parser. Only its generation. | REXX is not an easy language to parse with common tools, especially those that expect a BNF grammar. Unlike most languages designed by people exposed to C, REXX doesn't have any reserved words, making the task somewhat complicated. Every term that looks like a reserved word is actually only resolved in its specific context (*e.g.*, "PULL" is only reserved as the first word of a `PULL` instruction or the second word of a `PARSE PULL` instruction - you can also have a variable called PULL ("`PULL = 1 + 2`")). Plus there are some very surprising effects of comments. But the [ANSI REXX standard](http://www.rexxla.org/rexxlang/standards/j18pub.pdf) has the full syntax and all the rules. | How can I parse REXX code in Java? | [
"",
"java",
"parsing",
"rexx",
""
] |
i was wondering if there was a way to do this in C++?
```
void func1(const std::string& s)
{
std::cout << s << std::endl;
}
void func2(int me)
{
std::cout << me << std::endl;
}
int main()
{
std::map<std::string, boost::function< ??? > > a_map;
a_map["func1"] = &func1;
a_map["func1"]("HELLO");
}
```
Is there any way to do what i have above using boost function and a map? | There are ways to store the functions, the problem is, in order to be able to call the function with the desired argument you'd have to know the calling signature of the function anyways, and if you have that information, you might as well use separate maps, or use a more complicated object than boost::function.
If you're willing to do a bit of work and have a finite number of signatures, you could just do something like this:
```
class MultiFunc
{
protected:
MultiFunc() {}
public:
typedef void (*stringFunc)(const std::string&);
typedef void (*intFunc)(int);
static MultiFunc *Create(stringFunc function);
static MultiFunc *Create(intFunc function);
virtual void operator()(const string &) { throw exception(); }
virtual void operator()(int) { throw exception(); }
virtual ~MultiFunc();
};
class MultiFuncString : public MultiFunc
{
private:
stringFunc Function;
public:
MultiFuncString(stringFunc function) : Function(function) {}
virtual void operator()(const string &arg) { Function(arg); }
};
class MultiFuncInt : public MultiFunc
{
private:
intFunc Function;
public:
MultiFuncInt(intFunc function) : Function(function) {}
virtual void operator()(int arg) { Function(arg); }
};
MultiFunc *MultiFunc::Create(MultiFunc::stringFunc function)
{
return new MultiFuncString(function);
}
MultiFunc *MultiFunc::Create(MultiFunc::intFunc function)
{
return new MultiFuncInt(function);
}
void func1(const std::string& s)
{
std::cout << s << std::endl;
}
void func2(int me)
{
std::cout << me << std::endl;
}
int main()
{
map<string, MultiFunc *> a_map;
a_map["func1"] = MultiFunc::Create(&func1);
(*a_map["func1"])("Hello");
a_map["func2"] = MultiFunc::Create(&func2);
(*a_map["func2"])(3);
// Remember to delete the MultiFunc object, or use smart pointers.
}
```
This outputs:
```
Hello
3
```
Unfortunately, you can't make templated virtual functions or you easily generalize this all. | You probably can't use the `std::map` since it is a homogenous container. Try, something like [`boost::variant`](http://www.boost.org/doc/libs/1_38_0/doc/html/variant.html) (they support the visitor pattern) or [`boost::tuple`](http://www.boost.org/doc/libs/1_38_0/libs/tuple/doc/tuple_users_guide.html) | Map of boost function of different types? | [
"",
"c++",
"boost",
""
] |
In Visual Studio (C#) I have a form created as part of a project and need to have access to another form that should be created through another project and have both forms reference each other when necessary.. How do I go about doing that? | You can right click on the project name in project explorer window. And choose Add Reference. In the Add Reference window, choose "Projects" tab and select the project you wish to reference to. Do the same for another project. They should now can reference each other. | Right click on References in your project and select "Add Reference", then add another project as reference. | Adding a project | [
"",
"c#",
"visual-studio",
""
] |
I want to use IE8 as a WebBrowser control in a C# application. How can I disable "quirks mode" and force IE into standards compliance (as far as it is implemented)? | I think the issue you're facing is described in [IEBlog: WebBrowser Control Rendering Modes in IE8](http://blogs.msdn.com/ie/archive/2008/03/18/webbrowser-control-rendering-modes-in-ie8.aspx):
> While webmasters can easily alter
> their site to render properly in the
> new version of IE, many software
> vendors do not have the resources to
> instantly push out new versions of
> their applications with updated
> internal pages.
> In order to ensure that these existing
> applications remain in working order,
> **IE8 renders pages running within
> instances of the WebBrowser control in
> IE7 Standards Mode by default.**
Here I should note that the comments on the page say the above is incorrect, and that "**IE8 renders pages running within instances of the WebBrowser control in IE7 Strict Mode OR Quirks mode by default**, depending on the page's doctype."
The solution is as follows:
> When an executable loads an instance
> of the WebBrowser control it scans the
> registry to check whether the
> executable wants IE7 Standards or IE8
> Standards mode.
>
> ...
>
> To run in IE8 Standards Mode insert
> the following registry value:
>
> `[HKEY_CURRENT_USER\Software\Microsoft\Internet
> Explorer\Main\FeatureControl\FEATURE_NATIVE_DOCUMENT_MODE]`
>
> `"MyApplication.exe"=dword:13880`
>
> In both of these instances,
> MyApplication.exe should be replaced
> with the name of the executable that
> will be running WebBrowser controls in
> a specified mode.
So it sounds like the "programmatic" solution is to write a key in the registry saying you want IE8 Standards mode for `WebBrowser` controls in your specific application. | If you don't want to use the registry key technique, you could insert the following tag:
`<meta http-equiv="X-UA-Compatible" content="IE=8" />`
The "content" attribute forces rendering in various modes. | How to programmatically turn off quirks mode in IE8 WebBrowser control? | [
"",
"c#",
"internet-explorer-8",
"webbrowser-control",
"standards-compliance",
"quirks-mode",
""
] |
I am trying to run a php script on my remote Virtual Private Server through the command line. The process I follow is:
1. Log into the server using PuTTY
2. On the command line prompt, type> php myScript.php
The script runs just fine. BUT THE PROBLEM is that the script stops running as soon as I close the PuTTY console window.
I need the script to keep on running endlessly. How can I do that? I am running Debian on the server.
Thanks in advance. | I believe that Ben has the correct answer, namely use the nohup command. nohup stands for nohangup and means that your program should ignore a hangup signal, generated when you're putty session is disconnected either by you logging out or because you have been timed out.
You need to be aware that the output of your command will be appended to a file in the current directory named nohup.out (or $HOME/nohup.out if permissions prevent you from creating nohup.out in the current directory). If your program generates a lot of output then this file can get very large, alternatively you can use shell redirection to redirect the output of the script to another file.
```
nohup php myscript.php >myscript.output 2>&1 &
```
This command will run your script and send all output (both standard and error) to the file myscript.output which will be created anew each time you run the program.
The final & causes the script to run in the background so you can do other things whilst it is running or logout. | An easy way is to run it though nohup:
```
nohup php myScript.php &
``` | How to run a php script through the command line (and keep it running after logging out) | [
"",
"php",
"debian",
"putty",
"remote-server",
""
] |
Lets say I have a custom data type that looks something like this:
```
public class MyDataType
{
public string SimpleProp1;
public string SimpleProp2;
public List<SomeType> ComplexProp;
}
```
now I hava a data bound control (i.e. ItemsControl or DataGrid), that is created dynamically.
How would the binding defined in xaml code look like to acces a subproperty of the complex property? I thought it should look something like this:
```
<TextBox Text="{Binding simpleSubProp, path=ComplexProp[0]}" />
```
or
```
<TextBox Text="{Binding path=ComplexProp[0].simpleSubProp}" />
```
but both of those give me xml parse errors. How should it look correctly? Is it even possible to refer to a specific item of a collection property in souch a way? If it is not, what other options do I have?
EDIT, The scenario doesn't seem to be clear enough:
I have an
```
IEnumberable<MyDataType>
```
that is bound to an ItemsControl, inside the DataTemplate I have multiple TextBoxes that need to refer to subproperties of an object in the List of the complex property. | Looks like poperty path indexers are broken in Silverlight [Indexers in property paths are broken](http://silverlight.net/forums/p/44151/120984.aspx). The way to get around it is as suggested in the post and to use an IValueConverter.
XAML
```
<UserControl x:Class="Silverlight.Mine.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="System"
xmlns:sm="clr-namespace:Silverlight.Mine;assembly=Silverlight.Mine"
Width="400" Height="300">
<UserControl.Resources>
<sm:SomeTypeConverter x:Key="MySomeTypeConverter" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="myTextBlock" Text="{Binding Path=SomeDates, Converter={StaticResource MySomeTypeConverter}}" />
</Grid>
</UserControl>
```
C# Page.xaml.cs
```
namespace Silverlight.Mine
{
public partial class Page : UserControl
{
private SomeType m_mySomeType = new SomeType();
public Page()
{
InitializeComponent();
myTextBlock.DataContext = m_mySomeType;
}
}
}
```
C# SomeType.cs
```
namespace Silverlight.Mine
{
public class SomeType
{
public List<DateTime> SomeDates { get; set; }
public SomeType()
{
SomeDates = new List<DateTime>();
SomeDates.Add(DateTime.Now.AddDays(-1));
SomeDates.Add(DateTime.Now);
SomeDates.Add(DateTime.Now.AddDays(1));
}
}
public class SomeTypeConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
if (value != null)
{
List<DateTime> myList = (List<DateTime>)value;
return myList[0].ToString("dd MMM yyyy");
}
else
{
return String.Empty;
}
}
public object ConvertBack(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
if (value != null)
{
return (List<DateTime>)value;
}
return null;
}
}
}
``` | I do this kind of thing all the time, there are two ways I would approach this problem depending on what you want out of it.
If you really want only the one specific member of the list, you can use a converter. The XAML would look something like this:
```
<TextBox Text="{Binding MyDataTypeInstance, Converter={StatacResources SpecificInstanceConverter}}" />
```
That's not usually what I need though, usually I need one control to display the whole comlex object, if that's the case the way to do it is more like as follows:
```
<StackPanel>
<Textblock Text="{Binding SimpleProp1}"/>
<TextBlock Text="{Bidning SimpleProp2}"/>
<ItemsControl ItemsSource="{Binding ComplexProp}>
<ItemsControl.ItemsTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding ComplexPropertyName}/>
<InputToolkit:NumericUpDown Value="{Binding ComplexPropertyValue}/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemsTemplate>
</ItemsControl>
</StackPanel>
```
I like this method because my GUI matches my business objects, and as a result it usually ends up a lot cleaner than if I'm checking for specific indexes in code-behind. | Binding complex properties in Silverlight/WPF | [
"",
"c#",
"silverlight",
"data-binding",
"xaml",
"silverlight-2.0",
""
] |
Google is sponsoring an Open Source project to increase the speed of Python by 5x.
[Unladen-Swallow](http://code.google.com/p/unladen-swallow/) seems to have a [good project plan](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)
Why is concurrency such a hard problem?
Is LLVM going to solve the concurrency problem?
Are there solutions other than Multi-core for Hardware advancement? | [LLVM](http://llvm.org/) is several things together - kind of a virtual machine/optimizing compiler, combined with different frontends that take the input in a particular language and output the result in an intermediate language. This intermediate output can be run with the virtual machine, or can be used to generate a standalone executable.
The problem with concurrency is that, although it was used for a long time in scientific computing, it has just recently has become common in consumer apps. So while it's widely known how to program a scientific calculation program to achieve great performance, it is completely different thing to write a mail user agent/word processor that can be good at concurrency. Also, most of the current OS's were being designed with a single processor in mind, and they may not be fully prepared for multicore processors.
The benefit of LLVM with respect to concurrency is that you have an intermediate output, and if in the future there are advances in concurrency, then by updating your interpreter you instantly gain those benefits in all LLVM-compiled programs. This is not so easy if you had compiled to a standalone executable. So LLVM doesn't solve the concurrency problem per se but it leaves an open door for future enhancements.
Sure there are more possible advances for the hardware like quantum computers, genetics computers, etc. But we have to wait for them to become a reality. | The switch to LLVM itself isn't solving the concurrency problem. That's being solved separately, by getting rid of the [Global Interpreter Lock](http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock).
I'm not sure how I feel about that; I use threads mainly to deal with blocking I/O, not to take advantage of multicore processors (for that, I would use the `multiprocessing` module to spawn separate processes).
So I kind of like the GIL; it makes my life a lot easier not having to think about tricky synchronization issues. | What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x? | [
"",
"python",
"multicore",
"llvm",
"unladen-swallow",
""
] |
Why is that the single parameter constructor of `std::list<T>` requires `T` to be a default-constructible type? I mean the following code does not compile.
```
struct Foo { // does not have default constructor.
Foo (int i) {}
}
int main(void) {
std::list<Foo> l(10);
}
```
It seems possible to use the [construct and destroy idioms](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Generic_Container_Idioms) as they have already done in the std::vector, albeit with more book-keeping the list class.
On a related note, why not have the capacity function in list? You can argue that such a function would pay memory allocation cost up-front and eliminate the overhead later on as you `push_back` objects. At least it will make the interfaces of two STL sequence containers slightly more consistent. | std::list doesn't have a capacity function because it makes no sense; it never has to resize like a vector does. It's capacity is only limited by the available memory, which is not easily determined.
From what you asked for, I think you actually want reserve(). That's a one-off for vector because it (badly) needs such a thing; there's no particular requirement to make all functions consistent across all STL containers, especially when they make little sense for others.
You can accomplish the same effect using a custom allocator. As Manuel suggested, look at boost. | There is no general requirement that the type be default constructible - it must be copyable and assignable. Your code does not work because you try to create a list of 10 items - they have to be constructed somehow and so the default constructor must be used - but only in this specific case. If you created an empty list and added to it, there would be no such requirement.
The same is true for other containers - try compiling the following:
```
#include <vector>
struct A {
A( int x ) : z(x) {}
int z;
};
std::vector <A> a(10);
```
Regarding the second part of your question, I'd just observe that consistency of interface was not a prime design criterion for the standard containers - there is no intention, for example, that one type of container is a "drop-in" replacement for another. There is a good discussion of this in items 1 and 2 of Scott Meyers' book "Effective STL". | C++ standard list and default-constructible types | [
"",
"c++",
"list",
"stl",
"default-constructor",
""
] |
I always wondered why automatic setting of the pointer to NULL after *delete* is not part of the standard. If this gets taken care of then many of the crashes due to an invalid pointer would not occur. But having said that I can think of couple of reasons why the standard would have restricted this:
> 1. Performance:
>
> An additional instruction could slow down the `delete` performance.
> 2. Could it be because of `const` pointers.
>
> Then again standard could have done something for this special case I guess.
Does anyone know exact reasons for not allowing this? | [Stroustrup himself](http://www.stroustrup.com/bs_faq2.html#delete-zero) answers. An excerpt:
> C++ explicitly allows an
> implementation of delete to zero out
> an lvalue operand, and I had hoped
> that implementations would do that,
> but that idea doesn't seem to have
> become popular with implementers.
But the main issue he raises is that delete's argument need not be an lvalue. | First, setting to null would require a memory stored variable. It's true, that you usually have a pointer in a variable but sometimes you might want to *delete* an object at a just calculated address. That would be impossible with "nullifying" delete.
Then comes performance. You might have written code in such a way that the pointer will go out of scope immediately after *delete* is done. Filling it with null is just a waste of time. And C++ is a language with "don't need it? then you don't have to pay for it" ideology.
If you need safety there's a wide range of smart pointers at you service or you can write your own - better and smarter. | Why doesn't delete set the pointer to NULL? | [
"",
"c++",
"memory-management",
"delete-operator",
""
] |
```
Group group = new Group(parent, SWT.NONE);
StyledText comment = new StyledText(group, SWT.BORDER_DASH);
```
This creates a group with a text area inside.
How can I later delete the text (remove it from the screen so that I can replace it with something else)? | Use Widget.dispose.
```
public class DisposeDemo {
private static void addControls(final Shell shell) {
shell.setLayout(new GridLayout());
Button button = new Button(shell, SWT.PUSH);
button.setText("Click to remove all controls from shell");
button.addSelectionListener(new SelectionListener() {
@Override public void widgetDefaultSelected(SelectionEvent event) {}
@Override public void widgetSelected(SelectionEvent event) {
for (Control kid : shell.getChildren()) {
kid.dispose();
}
}
});
for (int i = 0; i < 5; i++) {
Label label = new Label(shell, SWT.NONE);
label.setText("Hello, World!");
}
shell.pack();
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
addControls(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
``` | Another option is to use a [StackLayout](http://www.java2s.com/Tutorial/Java/0280__SWT/UseaStackLayouttoswitchbetweenComposites.htm) to switch between underlying controls. This prevents you from running into a "widget is disposed" error. | SWT/JFace: remove widgets | [
"",
"java",
"swt",
"jface",
""
] |
I've developed an Excel 2003 addin in C#, using VSTO and VS 2008. The addin works just fine on my machine (HP NC6320 laptop, 3gb RAM T5600 1.8ghz Core2 cpu), however when it is tested on another users machine (HP nc6710b laptop 2gb RAM, T7200 2ghz Core2 cpu), it is substantially slower. I've also tried it on another laptop the same type as mine, and it is also fast
I've been through the obvious things, like applications running, Antivirus stuff, etc. The machines are both fully patched, and up to date.
Basically, what the addin does is:
1. Read data from a SQL Server 2005 database
2. Do some manipulation on it
3. Display it on a worksheet, and format it appropriately
The slow bit is the displaying on the worksheet.
I'm stumped as to why it would be slower on a newer machine.. Just to really confuse myself, I tried it on a VM (VMware Workstation v6.5) with 256mb RAM, and 1 cpu, running xp and only Office 2003 installed on it, and it was substantially quicker than the new laptop.
So in summary, an Excel Addin performs quickly on a low spec VM, and on an older laptop, but on a newer spec laptop it is slower.
Any suggestions would be gratefully recieved ?
Many thanks
Nick
**edit:**
Ok,
I've checked the printer drivers, they are the same...
I've checked the fragmentation levels, and if anything, the faster machine is less fragmented than the slower one..
Am looking at the events settings.. | You can also add
```
Application.EnableEvents = False
```
to your code before starting dumping your data to spreadsheet to stop any other Excel Add-Ins or any VBA code waiting for applciation level change/update events.
Don't forget to re-enable events after your are done!! | Check that the slow machine does not have any XLA or COM addins installed (ie Google Office Addin) or any other potentially event-trapping code in Personal.XLS etc
Presumably you are already doing all the standard speedup things such as:
- turning off automatic calculation and screenupdating before writing to XL
- writing and formatting cells in a single large block rather than cell-by-cell
- ... | Why does an Excel VSTO addin run slower on a higher spec machine? | [
"",
"c#",
"performance",
"excel",
"vsto",
""
] |
I'm trying to find the missing letter in the alphabet from the list with the least lines of code.
If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.
If I know there are only one missing letter.
(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically) | Some questions:
* Are all the letters upper or lower case? (a/A)
* Is this the only alphabet you'll want to check?
* Why are you doing this so often?
Least lines of code:
```
# do this once, outside the loop
alphabet=set(string.ascii_lowercase)
# inside the loop, just 1 line:
missingletter=(alphabet-set(yourlist)).pop()
```
The advantage of the above is that you can do it without having to sort the list first. If, however, the list is *always* sorted, you can use bisection to get there faster. On a simple 26-letter alphabet though, is there much point?
Bisection (done in ~4 lookups):
```
frompos, topos = 0, len(str)
for i in range(1,100): #never say forever with bisection...
trypos = (frompos+topos+1)/2
print "try:",frompos,trypos,topos
if alphabet[trypos] != str[trypos]:
topos = trypos
else:
frompos = trypos
if topos-frompos==1:
if alphabet[topos] != str[topos]:
print alphabet[frompos]
else:
print alphabet[topos]
break
```
This code requires fewer lookups, so is by far the better scaling version O(log n), but may still be slower when executed via a python interpreter because it goes via python `if`s instead of `set` operations written in C.
(Thanks to J.F.Sebastian and Kylotan for their comments) | Using a list comprehension:
```
>>> import string
>>> sourcelist = 'abcdefghijklmnopqrstuvwx'
>>> [letter for letter in string.ascii_lowercase if letter not in sourcelist]
['y', 'z']
>>>
```
The [string](http://docs.python.org/library/string.html) module has some predefined constants that are useful.
```
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.digits
'0123456789'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>>
``` | python: finding a missing letter in the alphabet from a list - least lines of code | [
"",
"python",
""
] |
I'm working on a web application for which I'm attempting to implement a full featured windowing system. Right now it's going very well, I'm only running into one minor issue. Sometimes when I go to drag a part of my application (most often the corner div of my window, which is supposed to trigger a resize operation) the web browser gets clever and thinks I mean to drag and drop something. End result, my action gets put on hold while the browser does its drag and drop thing.
Is there an easy way to disable the browser's drag and drop? I'd ideally like to be able to turn it off while the user is clicking on certain elements, but re-enable it so that users can still use their browser's normal functionality on the contents of my windows. I'm using jQuery, and although I wasn't able to find it browsing the docs, if you know a pure jQuery solution it would be excellent.
In short: I need to disable browser text selection and drag-and-drop functions while my user has the mouse button down, and restore that functionality when the user releases the mouse. | Try preventing default on mousedown event:
```
<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>
```
or
```
<div onmousedown="return false">asd</div>
``` | This works. Try it.
```
<BODY ondragstart="return false;" ondrop="return false;">
``` | Disable Drag and Drop on HTML elements? | [
"",
"javascript",
"css",
""
] |
Im using Console.ReadKey() to choose from a number of options that varies from time to time.
Before this initial code snippet there is a for loop that counts occurances into counter variable of type int.
The point is to use Console.ReadKey() to get an int.
```
int choice = ReadKey();
Console.WriteLine("");
if (choice < counter)
{
mail.to = result[counter-1].email;
}
```
By using the following methods
```
static int ReadKey()
{
ConsoleKeyInfo choice = Console.ReadKey();
char convertedchoice = choice.KeyChar;
string convertedchoice2 = convertedchoice.ToString();
int result = TryInt(convertedchoice2);
return result;
}
static int TryInt(string totry)
{
while (true)
{
int result;
if (int.TryParse(totry, out result))
{
return result;
}
Console.WriteLine("Sorry, you need to enter a number. Try again.");
}
}
```
I tried using ToString() but this was the way that it would let me do it in the end.
So this looks kind of inneffective to me and hence I would really appreciate some guidance as what to do differently?
Edit:
I ended up with a combination of all the good answers below. Thanks alot guys.
```
static int ReadKey()
{
while (true)
{
ConsoleKeyInfo choice = Console.ReadKey();
if (char.IsDigit(choice.KeyChar))
{
int answer = Convert.ToInt32(choice.KeyChar);
return answer - 48; //-48 because 0 is represented in unicode by 48 and 1 by 49 etc etc
}
Console.WriteLine("\nSorry, you need to input a number");
}
}
``` | For a menu system with choices 0..9 this is reasonably OK. Not for reading larger numbers though.
Your whole checking logic can be made a lot easier with char.IsDigit() :
```
if char.IsDigit(convertedchoice)
{
int result = convertedchoice - '0'; // char1 - char2 = int, in this case in 0..9
return result;
}
else ...
``` | You can just call `Convert.ToInt32(choice.KeyChar);` directly.
That would simplify it a bit. | Is there a good way to use Console.ReadKey for choosing between values without doing a lot of conversion between types? | [
"",
"c#",
"types",
"console",
""
] |
I'm starting a new Winforms app, and I intend to use an IoC/DI framework (probably Ninject, but I'm also thinking about StructureMap and LinFu).
It seems like nearly everyone who is using IoC/DI is doing so in a web based environment and have found virtually nothing on using Winforms with it.
I'd like to know if anyone is using IoC/DI with Winforms and what approaches you used to deal with Winforms related issues (for instance, how do you make the container available in various parts of the app, do you use the framework to instantiate your forms, etc..)
If anyone knows of any open source Winforms based projects that use IoC/DI (doesn't matter which framework, I should be able to translate concepts) I would like links to those as well.
EDIT:
Are people just not writing Smart Clients anymore?
EDIT:
If you could point me to some real-world code that uses IoC/DI in a Winforms or even console type application (ie, something that is not Web based) I'd appreciate it.
EDIT:
I've been using Ninject and discovered that Ninject will happily inject an instance of it's common kernel interface if you specify an IKernel constructor parameter. This has been working out pretty well, but I'd still like to hear other approaches people use. | I just recently started writing a new WinForms application from scratch using StructureMap for IoC. I've previously looked at SCSF and CAB, but found those overly complex.
I wrote some fluent APIs on top of StructureMaps registry so our modules can register commands, presenters and views.
From my experience it has been worth the effort in all regards, I would never want to write a WinForms app without using these tools and the highly structured modular approach again. | The Microsoft patterns and practices team which maintains the [Unity](http://www.codeplex.com/unity) injection container also created the [Smart Client - Composite UI Application Block](http://msdn.microsoft.com/en-us/library/aa480450.aspx) for winforms, which I believe uses Unity. I know the new WPF version called [Composite Client Application Guidance (codename Prism)](http://msdn.microsoft.com/en-us/library/cc707819.aspx) uses Unity | IoC/DI frameworks with Smart Client Winform apps: How should I approach this? | [
"",
"c#",
"winforms",
"dependency-injection",
"inversion-of-control",
""
] |
Most of my SPs can simply be executed (and tested) with data entered manually. This works well and using simple PRINT statements allows me to "debug".
There are however cases where more than one stored procedure is involved and finding valid data to input is tedious. It's easier to just trigger things from within my web app.
I have a little experience with the profiler but I haven't found a way to explore what's going on line by line in my stored procedures.
What are your methods?
Thank you, as always.
Note: I'm assuming use of SQL Server 2005+ | Profiler is very handy, just add SP:StmtStarting events, and filter the activity down to just your process by setting SPID=xxx. Once you have it set up, it's a breeze to see what's going on. | You can actually attach a debugger to your sql server :) - from vs, given you have configured that on your sql server.
Check this link for more info, notice you can set break points :) <https://web.archive.org/web/20090303135325/http://dbazine.com/sql/sql-articles/cook1>.
Check this link for a more general set of info: <http://msdn.microsoft.com/en-us/library/zefbf0t6.aspx>
**Update:** Regarding *"There are however cases where more than one stored procedure is involved and finding valid data to input is tedious. It's easier to just trigger things from within my web app."*
I suggest you set up integration tests, focused on the specific methods that interact with those procedures. If the procedures are being driven by the web app, it is a great place to have valid tests + inputs you can run at any time. If there are multiple apps that interact with the procedures, I would look at unit testing the procedures instead. | What's your favored method for debugging MS SQL stored procedures? | [
"",
"sql",
"sql-server",
"debugging",
"stored-procedures",
""
] |
I'd like to do this:
```
MyClass mc = MyClass("Some string" << anotherString);
```
Thanks for your answers, I have decided to re-write this question based on what you've told me, as it's gotten a little messy. Eventually, I read [C++ format macro / inline ostringstream](https://stackoverflow.com/questions/303562/c-format-macro-inline-ostringstream), and decided to use a macro, as it's not really possible to do this using a constructor. Some answers my no longer be relevant.
Now, what I can actually, do is:
```
MY_CLASS("Some string" << anotherString << " more string!");
```
Using this macro:
```
#include <sstream>
#define MY_CLASS(stream) \
MyClass( ( dynamic_cast<std::ostringstream &> ( \
std::ostringstream() . seekp( 0, std::ios_base::cur ) << stream ) \
) . str() )
```
Where the MyClass constructor takes a string:
```
MyClass::MyClass(string s) { /* ... */ }
``` | I think you should look at [this](https://stackoverflow.com/questions/303562/303675#303675) question for some hints as to what will be required to get the behavior you want.
This sort of thing seems to a bit difficult. | redesign your solution. if your c-tor needed string it should accept string.
also in this and similar cases will better if your constructor will accept const reference.
```
no matching function for call to ‘MyClass(std::basic_ostream <..>&)
```
error happened because operator<< defined for and returns std::basic\_ostream not std::stringstream object. ofcourse you could use
```
dynamic_cast< const std::stringstream& >( s << "hello" << "world" )
```
but your team lead could fire you for this code:)
**BTW:**
```
MyClass mc = MyClass("Some string" << anotherString);
```
could be rewriten as
```
MyClass mc("Some string" << anotherString);
``` | Can I pass C++ strings into a method in the style of a stream? | [
"",
"c++",
"string",
"stringstream",
""
] |
I have this code:
```
private static $dates = array(
'start' => mktime( 0, 0, 0, 7, 30, 2009), // Start date
'end' => mktime( 0, 0, 0, 8, 2, 2009), // End date
'close' => mktime(23, 59, 59, 7, 20, 2009), // Date when registration closes
'early' => mktime( 0, 0, 0, 3, 19, 2009), // Date when early bird discount ends
);
```
Which gives me the following error:
> Parse error: syntax error, unexpected '(', expecting ')' in /home/user/Sites/site/registration/inc/registration.class.inc on line 19
So, I guess I am doing something wrong... but how can I do this if not like that? If I change the mktime stuff with regular strings, it works. So I know that I can do it *sort of* like that..
Anyone have some pointers? | PHP can't parse non-trivial expressions in initializers.
I prefer to work around this by adding code right after definition of the class:
```
class Foo {
static $bar;
}
Foo::$bar = array(…);
```
or
```
class Foo {
private static $bar;
static function init()
{
self::$bar = array(…);
}
}
Foo::init();
```
---
[PHP 5.6](https://wiki.php.net/rfc/const_scalar_exprs) can handle some expressions now.
```
/* For Abstract classes */
abstract class Foo{
private static function bar(){
static $bar = null;
if ($bar == null)
bar = array(...);
return $bar;
}
/* use where necessary */
self::bar();
}
``` | If you have control over class loading, you can do static initializing from there.
Example:
```
class MyClass { public static function static_init() { } }
```
in your class loader, do the following:
```
include($path . $klass . PHP_EXT);
if(method_exists($klass, 'static_init')) { $klass::staticInit() }
```
A more heavy weight solution would be to use an interface with ReflectionClass:
```
interface StaticInit { public static function staticInit() { } }
class MyClass implements StaticInit { public static function staticInit() { } }
```
in your class loader, do the following:
```
$rc = new ReflectionClass($klass);
if(in_array('StaticInit', $rc->getInterfaceNames())) { $klass::staticInit() }
``` | How to initialize static variables | [
"",
"php",
"class",
"static-members",
""
] |
I'm working on a small little thing here for school. After hours of researching, and a ton of errors and logic reworking I've almost completed my little program here.
I'm trying to take user input, store it into the string, get a character array from the string ( dont ask why, I just have to put this into a character array ), then get the reversed order of the phrase that the user entered. Here is my code:
```
#include "stdafx.h"
#include <iostream>
#include <String>
#include <cstring>
using namespace std;
using namespace System;
#pragma hdrstop
char* getCharArray(string);
string reversePhrase( int, char* );
void main(void)
{
string sPhrase = "";
int sSize = 0;
string sReversed = "";
char* cPhrase = NULL;
cout << "Welcome to the You Type It & We'll Reverse it! [Version 1.0] " << endl;
cout << "This program will reverse your phrase, and count how many characters are in it!" << endl;
cout << "To begin just enter a phrase." << endl;
cout << "Enter a phrase: ";
getline( cin, sPhrase);
sSize = sPhrase.length();
cout << endl;
cPhrase = getCharArray(sPhrase);
sReversed = reversePhrase( sSize, cPhrase );
cout << sReversed;
system("pause");
}
string reversePhrase(int size , char* cPhrase)
{
string sReversed = "";
int place = size;
for ( int i = 0; i < size ; i ++ )
{
sReversed.append(1, cPhrase[place]);
cout << "Current string: " << sReversed << endl;
cout << "Current character: " << cPhrase[place] << endl;
place--;
}
return sReversed;
}
char* getCharArray(string sPhrase)
{
int size = 1;
size = sPhrase.length();
char* cArray = NULL;
cArray = new char[size];
for (int i = 0 ; i < size ; i++)
{
cArray[size] = sPhrase.at(i);
}
return cArray;
}
```
When I type in "ownage" into the program, this is what I get returned:

It is almost like my Character Array is getting garbage collected before it can use all of the characters. This is probably an easy fix but, I just don't see how I can get around this one. | Try rewriting getCharArray like this
```
char* getCharArray(string sPhrase)
{
int size = 1;
size = sPhrase.length();
char* cArray = NULL;
cArray = new char[size+1]; // NOTE
for (int i = 0 ; i < size ; i++)
{
cArray[i] = sPhrase.at(i); // NOTE
}
}
cArray[size]=0; // NOTE
return cArray;
}
```
Note that the assignment in the loop now uses the index variable. Also, you need to allocate one extra char in the array to set the null terminator for the string and then you need to set it at the end.
You'll also need to think about deallocating the array at some point | The bug is in this line:
```
cArray[size] = sPhrase.at(i);
```
That `size` should be your loop index.
You should probably look at using `std::string` more, and not poke around with character arrays when there's no need to. | I am trying to return a Character Array but, I'm only getting the first letter returned | [
"",
"c++",
"arrays",
"string",
"pointers",
"return-value",
""
] |
I'm working on an iPhone app that will upload images to a web server. I was wondering if anyone had any tips on how to generate unique names for each image file that gets uploaded.
I'm sure there are a million ways to do this, but if anyone has any suggestions I'd really appreciate it! Thanks. | you could create a GUID and save the image as that name ..
Thanks | The simplest solution (assuming you're storing these in a database) is to have an auto-increment field in the database, and use that to rename the file as it's uploaded. That way you'll end up with image00000001.jpg, image00000002.jpg, etc. | iPhone Uploading unique images to a server running PHP / MYSQL | [
"",
"php",
"iphone",
"mysql",
""
] |
Please consider the following snippet:
```
public interface MyInterface {
public int getId();
}
public class MyPojo implements MyInterface {
private int id;
public MyPojo(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public ArrayList<MyInterface> getMyInterfaces() {
ArrayList<MyPojo> myPojos = new ArrayList<MyPojo>(0);
myPojos.add(new MyPojo(0));
myPojos.add(new MyPojo(1));
return (ArrayList<MyInterface>) myPojos;
}
```
The return statement does a casting that doesn't compile. How can I convert the myPojos list to the more generic list, **without having to go through each item of the list**?
Thanks | Change your method to use a wildcard:
```
public ArrayList<? extends MyInterface> getMyInterfaces() {
ArrayList<MyPojo> myPojos = new ArrayList<MyPojo>(0);
myPojos.add(new MyPojo(0));
myPojos.add(new MyPojo(1));
return myPojos;
}
```
This will prevent the caller from trying to add *other* implementations of the interface to the list. Alternatively, you could just write:
```
public ArrayList<MyInterface> getMyInterfaces() {
// Note the change here
ArrayList<MyInterface> myPojos = new ArrayList<MyInterface>(0);
myPojos.add(new MyPojo(0));
myPojos.add(new MyPojo(1));
return myPojos;
}
```
As discussed in the comments:
* Returning wildcarded collections can be awkward for callers
* It's usually better to use interfaces instead of concrete types for return types. So the suggested signature would probably be one of:
```
public List<MyInterface> getMyInterfaces()
public Collection<MyInterface> getMyInterfaces()
public Iterable<MyInterface> getMyInterfaces()
``` | Choosing the right type from the start is best, however to answer your question you can use type erasure.
`return (ArrayList<MyInterface>) (ArrayList) myPojos;` | How can I cast a list using generics in Java? | [
"",
"java",
"generics",
"casting",
""
] |
I'm trying to access a WebService using nuSOAP (because I'm bound to PHP4 here) that uses more than 1 namespace in a message. Is that possible?
An example request message would look like this:
```
<soapenv:Envelope ...
xmlns:ns1="http://domain.tld/namespace1"
xmlns:ns2="http://domain.tld/namespace2">
<soapenv:Header/>
<soapenv:Body>
<ns1:myOperation>
<ns2:Person>
<ns2:Firstname>..</ns2:Firstname>
..
</ns2:Person>
<ns1:Attribute>..</ns1:Attribute>
</ns1:myOperation>
</soapenv:Body>
</soapenv:Envelope>
```
I tried to following:
```
$client = new nusoap_client("my.wsdl", true);
$params = array(
'Person' => array(
'FirstName' => 'Thomas',
..
),
'Attribute' => 'foo'
);
$result = $client->call('myOperation', $params, '', 'soapAction');
```
in the hope that nuSOAP would try to match these names to the correct namespaces and nodes. Then I tried to use soapval() to generate the elements and their namespace - but if I call an operation, nuSOAP creates the following request:
```
<SOAP-ENV:Envelope ...>
<SOAP-ENV:Body>
<queryCCApplicationDataRequest xmlns="http://domain.tld/namespace1"/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
```
So something goes wrong during the "matching" phase. | After trying around with the matching, I found two possible solutions:
1) Don't use the WSDL to create the nusoap\_client and soapval() to create the message
This has the disadvantage that the message contains a lot of overhead (the namespace is defined in each element). Not so fine.
2) Instead of relying on the matching of parameters, construct your reply in xml and put all the definition for prefixes in the first element - e.g.
```
$params = "<ns1:myOperation xmlns:ns1="..." xmlns:ns2="...">
<ns2:Person>
<ns2:Firstname>..</ns2:Firstname>
..
</ns2:Person>
<ns1:Attribute>..</ns1:Attribute>
</ns1:myOperation>";
```
Still not a very nice solution, but it works :-) | Building on Irwin's post, I created the xml manually and had nusoap do the rest. My webhost does not have the php soap extension, so I had to go with nusoap, and the web service I'm trying to consume required the namespaces on each tag (e.g. on username and password in my example here).
```
require_once('lib/nusoap.php');
$client = new nusoap_client('https://service.somesite.com/ClientService.asmx');
$client->soap_defencoding = 'utf-8';
$client->useHTTPPersistentConnection(); // Uses http 1.1 instead of 1.0
$soapaction = "https://service.somesite.com/GetFoods";
$request_xml = '<?xml version="1.0" encoding="utf-8" ?>
<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<n1:GetFoods xmlns:n1="https://service.somesite.com">
<n1:username>banjer</n1:username>
<n1:password>theleftorium</n1:password>
</n1:GetFoods>
</env:Body>
</env:Envelope>
';
$response = $client->send($request_xml, $soapaction, '');
echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
```
Then I had an error that said:
```
Notice: Undefined property: nusoap_client::$operation in ./lib/nusoap.php on line 7674
```
So I went the lazy route and went into nusoap.php and added this code before line 7674 to make it happy:
```
if(empty($this->operation)) {
$this->operation = "";
}
``` | How to use nuSOAP for messages with multiple namespaces | [
"",
"php",
"soap",
"php4",
"nusoap",
""
] |
I'm trying to move a project from an old linux platform to a kubunutu 9.04. Now I get this error when compiling with gcc 4.3.3:
```
/usr/src/linux-headers-2.6.28-11-generic/include/linux/cpumask.h:600:37: error: "and" may not appear in macro parameter list
```
If I understand the message right, it is not allowed to use "and" as a macro parameter, since it is a "reserved command". Two questions about that:
1. How is this possible? I cannot imagine that there is such a mistake in the linux header files... Did I do something wrong before? I tried an #undef and but this won't help.
2. How do I fix this error? It cannot be true that I have to change the linux header files, can it?
Thanks for help. | I believe the problem is that `and` is a [keyword in C++ but not C](http://www.georgehernandez.com/h/xComputers/Cs/ReservedKeywords.asp) (they use `&&`).
The kernel guys sometimes macros as an alternative to inline functions. Sometimes, however, they need macros because what they want to do has to be done in the scope of the calling function, and defining a function to do that won't work (for instance a macro to find out the name of the current function).
Assuming the macros in question are really fake inlined functions, it would be possible to write your own .c file full of nothing but functions calling these macros, compile it, and refer to those functions via an `extern "C"` header. You would get the same behavior, but slightly worse performance (which is unlikely to be a problem).
If the macros actually have to be macros, then your best bet is to hand edit them to be C++ compliant. | The linux headers are C headers, not C++. | compile error: cpumask.h: "and" may not appear in macro parameter list | [
"",
"c++",
"gcc",
""
] |
I realize that it seems to be a duplicate of [What is the difference between a Field and a Property in C#?](https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c) but my question has a slight difference (from my point of view):
Once I know that
* I will not use my class with "techniques that only works on properties" and
* I will not use validation code in the getter/setter.
Is there any difference (except the style/future development ones), like some type of control in setting the property?
Is there any additional difference between:
```
public string MyString { get; set; }
```
and
```
public string myString;
```
(I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.) | Encapsulation.
In the second instance you've just defined a variable, in the first, there is a getter / setter around the variable. So if you decide you want to validate the variable at a later date - it will be a lot easier.
Plus they show up differently in Intellisense :)
**Edit:** Update for OPs updated question - if you want to ignore the other suggestions here, the other reason is that it's simply not good OO design. And if you don't have a very good reason for doing it, **always** choose a property over a public variable / field. | Fields and properties look the same, but they are not. Properties are methods and as such there are certain things that are not supported for properties, and some things that may happen with properties but never in the case of fields.
Here's a list of differences:
* Fields can be used as input to `out/ref` arguments. Properties can not.
* A field will always yield the same result when called multiple times (if we leave out issues with multiple threads). A property such as `DateTime.Now` is not always equal to itself.
* Properties may throw exceptions - fields will never do that.
* Properties may have side effects or take a really long time to execute. Fields have no side effects and will always be as fast as can be expected for the given type.
* Properties support different accessibility for getters/setters - fields do not (but fields can be made `readonly`)
* When using reflection the properties and fields are treated as different `MemberTypes` so they are located differently (`GetFields` vs `GetProperties` for example)
* The JIT Compiler may treat property access very differently compared to field access. It may however compile down to identical native code but the scope for difference is there. | Difference between Property and Field in C# 3.0+ | [
"",
"c#",
"properties",
"c#-3.0",
"field",
"automatic-properties",
""
] |
For some reason neither the accepted answer nor any others work for me for "[Sending email in .NET through Gmail](https://stackoverflow.com/questions/32260/sending-email-in-c-net-through-gmail)". Why would they not work?
UPDATE: I have tried all the answers (accepted and otherwise) in the other question, but none of them work.
I would just like to know if it works for anyone else, otherwise Google may have changed something (which has happened before).
When I try the piece of code that uses `SmtpDeliveryMethod.Network`, I quickly receive an SmtpException on Send(message). The message is
> The SMTP server requires a secure connection or the client was not authenticated.
The server response was:
> 5.5.1 Authentication Required. Learn more at" <-- seriously, it ends there.
**UPDATE:**
This is a question that I asked a long time ago, and the accepted answer is code that I've used many, many times on different projects.
I've taken some of the ideas in this post and other EmailSender projects to create an [EmailSender project at Codeplex](http://emailsender.codeplex.com/). It's designed for testability and supports my favourite SMTP services such as GoDaddy and Gmail. | CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.
Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
}
}
```
I also got it working using a combination of web.config, <http://msdn.microsoft.com/en-us/library/w355a94k.aspx> and code (because there is no matching `EnableSsl` in the configuration file :( ).
### 2021 Update
By default you will also need to enable access for "less secure apps" in your gmail settings page: google.com/settings/security/lesssecureapps. This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. – thanks to @Ravendarksky | In addition to the other troubleshooting steps above, I would also like to add that if you have enabled two-factor authentication (also known as [two-step verification](http://googleblog.blogspot.com/2011/02/advanced-sign-in-security-for-your.html)) on your GMail account, you **must generate an application-specific password and use that newly generated password to authenticate via SMTP**.
To create one, visit: <https://www.google.com/settings/> and choose *Authorizing applications & sites* to generate the password. | Sending email through Gmail SMTP server with C# | [
"",
"c#",
".net",
"email",
"smtp",
"gmail",
""
] |
I would like to be able to parse vb.net code files, so I can examine the collection of Subs, Functions (and their contents, including comments), private variables, etc.
I **can** be open the actual source code files.
So for example, if I have:
```
Public Function FunctionOne(arg1 As String, arg2 as String) as Integer
here is some code
''//here are some comments
End Function
Public Sub FunctionOne(arg1 As integer, arg2 as integer)
here is some code
''//here are some comments
End Sub
```
I would like to be able to parse out all of the subs and functions and all of the code between the Public Function and End Function (actually, it would be nice to have the option to either include just the code within, or the entire function definition.
This would seem to call for some sort of a parsing library, or else fairly decent regex skills.
Any suggestions?
UPDATE:
The main thing I'm trying to achieve is the parsing of the source code, so reflection is just fine perhaps for getting the list of functions and what not and I know how to do that, but it is a proper way of **parsing the source code** I am trying to figure out. | This code is crude but more or less accomplishes what I was intending to do:
```
Private _SourceCode As String = Nothing
Private ReadOnly Property SourceCode() As String
Get
If _SourceCode = Nothing Then
Dim thisCodeFile As String = Server.MapPath("~").ToString & "\" & Type.GetType(Me.GetType.BaseType.FullName).ToString & ".aspx.vb"
_SourceCode = My.Computer.FileSystem.ReadAllText(thisCodeFile)
End If
Return _SourceCode
End Get
End Property
Private Function extractProcedureDefinition(ByVal procedureName As String) As String
Return extractStringContents(Me.SourceCode, "Sub " & procedureName & "()", "End Sub", True)
End Function
Private Function extractFunctionDefinition(ByVal procedureName As String) As String
'TODO: This works now, but wouldn't if we wanted includeTags = False, as it does not properly handle the "As xxxxx" portion
Return extractStringContents(Me.SourceCode, "Function " & procedureName, "End Sub", True)
End Function
Private Function extractStringContents(ByVal body As String, ByVal openTag As String, ByVal closeTag As String, ByVal includeTags As Boolean) As String
Dim iStart As Integer = body.IndexOf(openTag)
Dim iEnd As Integer = body.IndexOf(closeTag, iStart)
If includeTags Then
iEnd += closeTag.Length
Else
iStart += openTag.Length
End If
Return body.Substring(iStart, iEnd - iStart)
End Function
``` | What about compiling those at runtime from your program, and then using reflection on the compiled library?
look at [this microsoft thread](http://support.microsoft.com/?scid=kb%3Ben-us%3B304655&x=15&y=8) for details on how to do that ! | .Net string parsing library, or regex for parsing .Net code files | [
"",
"c#",
".net",
"vb.net",
"regex",
"parsing",
""
] |
If I have a class with two constructors as follows:
```
class Foo
{
public Foo(string name)
{...}
public Foo(Bar bar): base(bar.name)
{...}
}
```
is there some way that I can check if bar is null before I get a null reference exception? | You can use a **static** method to do this:
```
class Foo
{
public Foo(string name) {
...
}
public Foo(Bar bar): base(GetName(bar)) {
...
}
static string GetName(Bar bar) {
if(bar == null) {
// or whatever you want ...
throw new ArgumentNullException("bar");
}
return bar.Name;
}
}
``` | ```
class Foo
{
public Foo(Bar bar): base(bar == null ? default(string) : bar.name)
{
// ...
}
}
```
alternatively let the bar-class handle with an object of the bar-class and throw an ArgumentNullException if you'd like | Can you check for null when a constructor call another constructor using the object given to the first constructor? | [
"",
"c#",
"constructor",
""
] |
When page is to be posted back to the server, browser collects the current values of each control and pastes it together into a string. This postback data is then sent back to the server via HTTP POST.
Q1 - Besides control’s Text attributes and SelectedIndexchanged ( thus besides user input data), are there other attributes/values of a control which are saved by a browser as postback data?
Q2 - In case of GridView, which values are saved by a browser on a postback? Only those in a row which the user chooses to edit?
byte | The values of `textarea`, `select`, `input` and `button` fields are returned in the post. Each value is a key-value pair where the key is the `name` property of the element.
I think that I have got all the elements that include data in the post:
* `textarea`: The `value` propery is included, i.e. what's typed in the textarea.
* `select`: The `value` property of the selected option is included. If the selected option doesn't have a `value` property specified, the text of the option is used.
* `input type="text"`: The `value` property is included, i.e. what's typed in the input field.
* `input type="password"`: The `value` property is included, i.e. what's typed in the input field.
* `input type="submit"`: If the button was used to send the form, the `value` property is included, i.e. the text of the button.
* `input type="image"`: If the button was used to send the form, the coordinates of the mouse click within the image is sent in the post. Names for the x and y coordinates are created by adding ".x" and ".y" to the name of the element.
* `input type="checkbox"`: If the checkbox is checked, the `value` property is included. If the element has no `value` property specified, the value "on" is used.
* `input type="radio"`: The `value` property is included from the selected item from each group. (A group is all radio buttons with the same name.)
* `input type="file"`: The content of the selected file is included, along with the original file path (or only the file name, depending on browser and security settings).
* `input type="hidden"`: The `value` property is included.
* `button`: If the button was used to send the form, the `innerText` property is included, i.e. the text of the button with any html markup removed.
A `TextBox` control is rendered either as an `input type="text"`, an `input type="password"` or a `textarea`, depending on the `TextMode` property. A `DropDownList` control is rendered as a `select` element. A `Button` control is rendered as an `input type="submit"`. A `CheckBox` control is rendered as an `input type="checkbox"`. And so on... check the rendered html code to see what the actual html elements rendered are.
A GridView only includes any data in the post if it contains any editable form fields, or if it causes a postback (by navigating in the list for example). When doing a postback there is some information stored in a pair of hidden fields, so any control that causes a postback but doesn't send any form data by itself (like a LinkButton for example) does include information about what caused the postback.
Controls may also put data in the ViewState, which is kept in a hidden field in the form. This is also included in the post, but it's just sent to the browser and back again without being changed by the browser. | I'm not asp programmer, so i can't give exact answer, but I'd suggest you to use firefox with addons Live Http Headers, and Firebug (console section).
With this setup you will be able to see exact data sended by browser to your server. | Which values browser collects as a postback data? | [
"",
"c#",
"asp.net",
"ado.net",
""
] |
I'm dealing with the same sort of problem as "[Zombie http.proxyHost settings for JVM on OSX](https://stackoverflow.com/questions/619567/zombie-http-proxyhost-settings-for-jvm-on-osx)" except I'm on Kubuntu 8.04 and Eclipse 3.4.2. I had to use a proxy for work but have migrated off it. I've reset everything in my environment I can find inside and outside Eclipse to get rid of setting the proxy. However when I try to use the Software Update feature I find it's still using the proxy. In the error log I can see:
> !ENTRY org.eclipse.core.net 1 0 2009-03-17 10:49:50.137 !MESSAGE System property http.proxyHost has been set to netproxy.blah.com by an external source. This value will be overwritten using the values from the preferences
>
> !ENTRY org.eclipse.core.net 1 0 2009-03-17 10:49:50.164 !MESSAGE System property http.proxyPort has been set to 3128 by an external source. This value will be overwritten using the values from the preferences
Any ideas as to what the external source might be that's setting this property? | It's a bug in the preferences panel. You can see it if you tail your workspace/.metadata/.log file.
The workaround (at least in Eclipse 3.4.2) is:
* Open **Window > Preferences**, then **General > Network Connections**
* Select **Manual proxy configuration**
* Click the **Add Host...** button to add a 'No Proxy' entry
* Enter a random entry, say 'localhost' and click **OK**
* Click **Direct connection to the Internet**
* Close the property panel with the **OK** button. | Or go to your *eclipse.ini* file and check if there are some parameters like :
```
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1
```
OR same parameters but the first one finishes in 4 like below:
```
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4
```
Since release of Eclipse Kepler (4.3)
With this parameters you can disable the HttpClient provider and have ECF use the JRE URLConnection-based provider instead(line 1). And set proxy settings. | Eclipse still using http.proxyHost settings when no longer set | [
"",
"java",
"eclipse",
"proxy",
"jvm",
""
] |
What are the most suitable equivalent C# data types for the date datatypes in SQL Server? I'm specifically looking for
* `date`
* `time`
* `datetimeoffset` | Here are the equivalent CLR data types for `date`, `time` and `datetimeoffset` SQL Server data types:
**date** - `DateTime`, `Nullable<DateTime>`
**time** - `TimeSpan`, `Nullable<TimeSpan>`
**datetimeoffset** - `DateTimeOffset`, `Nullable<DateTimeOffset>`
Note that you can find a listing of all SQL Server data types and their CLR equivalents here, [Mapping CLR Parameter Data](http://msdn.microsoft.com/en-us/library/ms131092.aspx) | In C# you could use
* Date
* TimeSpan
* [DateTimeOffset Structure](http://msdn.microsoft.com/en-us/library/system.datetimeoffset(VS.95).aspx) | What are equivalent C# data types for SQL Server's date, time and datetimeoffset? | [
"",
"c#",
"sql-server-2008",
"types",
""
] |
Assume there is a table named "myTable" with three columns:
```
{**ID**(PK, int, not null),
**X**(PK, int, not null),
**Name**(nvarchar(256), not null)}.
```
Let {4, 1, аккаунт} be a record on the table.
```
select * from myTable as t
where t.ID=4
AND t.X = 1
AND ( t.Name = N'аккаунт' )
select * from myTable as t
where t.ID=4
AND t.X = 1
AND ( t.Name LIKE N'%аккаунт%' )
```
The first query return the record, however, the second does not? Why?
Systems where this issues are experienced:
\*Windows XP - Professional - Version 2002 - SP3
*Server Collation:* Latin1\_General\_CI\_AS
*Version:* 9.00.3073.00
*Level:* SP2
*Edition:* Developer Edition
*Sever Collation:* SQL\_Latin1\_General\_CP1\_CI\_AS
*Version:* 9.00.3054.00
*Level:* SP2
*Edition:* Enterprise Edition
Results:
```
SELECT SERVERPROPERTY('SQLCharSetName')
iso_1
Using OSQL.exe
0x30043A043A04300443043D04420400000000000000000000000000000000
0x3F3F3F3F3F3F3F0000000000000000000000000000000000000000000000
0x253F3F3F3F3F3F3F25000000000000000000000000000000000000000000
SELECT CAST(name AS BINARY),
CAST(N'аккаунт' AS BINARY),
CAST(N'%аккаунт%' AS BINARY)
FROM myTable t
WHERE t.ID = 4
AND t.X = 1
CAST(name AS BINARY)
0x30043A043A04300443043D04420400000000000000000000000000000000
CAST(N'аккаунт' AS BINARY)
0x3F3F3F3F3F3F3F0000000000000000000000000000000000000000000000
CAST(N'%аккаунт%' AS BINARY)
0x253F3F3F3F3F3F3F25000000000000000000000000000000000000000000
``` | Alright, after a great deal of research, I found it is indeed a problem found on the following versions of SQL Server 2005:
Windows XP - Professional - Version 2002 - SP3
Version: 9.00.3073.00
Level: SP2
Edition: Developer Edition
Version: 9.00.3054.00
Level: SP2
Edition: Enterprise Edition
..may be other versions as well.
FIX: Upgrade to SP3. | Could you please post the result of the following query:
```
SELECT CAST(name AS BINARY),
CAST(N'аккаунт' AS BINARY),
CAST(N'%аккаунт%' AS BINARY)
FROM myTable t
WHERE t.ID = 4
AND t.X = 1
```
This will help to narrow the problem down.
**UPDATE:**
As I can see from the results of your query, you have a problem with encoding.
The Cyrillic literals from your string constants are being converted to the question marks (`0x3F`).
Unfortunately, I cannot reproduce this behavior with `Management Studio` on my test server.
I reckon there is some problem with `OS` settings, as Cyrillic characters most probably don't even reach `SQL Server`.
Could you please answer three more questions:
1. What `OS` are you using (version, language, `MUI` if any)
* What does this query return:
SELECT SERVERPROPERTY('SQLCharSetName')
* Connect to your server using `osql.exe` and issue this query:
SELECT CAST(name AS BINARY),
CAST(N'аккаунт' AS BINARY),
CAST(N'%аккаунт%' AS BINARY)
FROM myTable t
WHERE t.ID = 4
AND t.X = 1
GO
What does it return being run in `osql.exe`? | Weird SQL Behavior, why is this query returning nothing? | [
"",
"sql",
"sql-server-2005",
"unicode",
"unicode-string",
""
] |
In Qt, if I right-click on a toolbar the menu will be shown that allows me to hide the toolbar. I need to disable this functionality because I don't want the toolbar to possible to hide. Is there a way to do this? | Inherit QToolbar and reimplement `contextMenuEvent()`. | I was able to set the ContextMenuPolicy directly on the *toolbar* (not the main window), as long as I used either `Qt::PreventContextMenu` or `Qt::ActionsContextMenu`. `Prevent` eliminated the context menu and made right-click have no effect on the toolbar, while `Actions` made a nice context menu composed of the actions already in my toolbar. `Qt::NoContextMenu` didn't seem to have any effect.
`toolbar->setContextMenuPolicy(Qt::PreventContextMenu);` | Is there a way to prevent the hide operation of a toolbar? | [
"",
"c++",
"qt",
"qtoolbar",
""
] |
What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
```
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
```
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above? | Hmmm... seems more suited to [Adapter](http://en.wikipedia.org/wiki/Adapter_pattern).
```
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
```
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using. | Check out the [Visitor](https://stackoverflow.com/questions/42587/double-dispatch-in-c) pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
```
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
``` | C# - using polymorphism in classes I didn't write | [
"",
"c#",
"architecture",
"inheritance",
"polymorphism",
""
] |
I've been using C++ for a short while, and I've been wondering about the `new` keyword. Simply, should I be using it, or not?
1. With the `new` keyword...
```
MyClass* myClass = new MyClass();
myClass->MyField = "Hello world!";
```
2. Without the `new` keyword...
```
MyClass myClass;
myClass.MyField = "Hello world!";
```
From an implementation perspective, they don't seem that different (but I'm sure they are)... However, my primary language is C#, and of course the 1st method is what I'm used to.
The difficulty seems to be that method 1 is harder to use with the std C++ classes.
Which method should I use?
### Update 1:
I recently used the `new` keyword for *heap* memory (or *free store*) for a large array which was going out of scope (i.e. being returned from a function). Where before I was using the stack, which caused half of the elements to be corrupt outside of scope, switching to heap usage ensured that the elements were intact. Yay!
### Update 2:
A friend of mine recently told me there's a simple rule for using the `new` keyword; every time you type `new`, type `delete`.
```
Foobar *foobar = new Foobar();
delete foobar; // TODO: Move this to the right place.
```
This helps to prevent memory leaks, as you always have to put the delete somewhere (i.e. when you cut and paste it to either a destructor or otherwise). | **Method 1 (using `new`)**
* Allocates memory for the object on the [**free store**](http://www.gotw.ca/gotw/009.htm) (This is frequently the same thing as the **heap**)
* Requires you to explicitly `delete` your object later. (If you don't delete it, you could create a memory leak)
* Memory stays allocated until you `delete` it. (i.e. you could `return` an object that you created using `new`)
* The example in the question will [leak memory](http://en.wikipedia.org/wiki/Memory_leak) unless the pointer is `delete`d; and it **should always be deleted**, regardless of which control path is taken, or if exceptions are thrown.
**Method 2 (not using `new`)**
* Allocates memory for the object on the **stack** (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
* You won't need to `delete` it later.
* Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't `return` a pointer to an object on the stack)
As far as which one to use; you choose the method that works best for you, given the above constraints.
**Some easy cases:**
* If you don't want to worry about calling `delete`, (and the potential to cause [memory leaks](http://en.wikipedia.org/wiki/Memory_leak)) you shouldn't use `new`.
* If you'd like to return a pointer to your object from a function, you must use `new` | There is an important difference between the two.
Everything not allocated with `new` behaves much like value types in C# (and people often say that those objects are allocated on the stack, which is probably the most common/obvious case, but not always true). More precisely, objects allocated without using `new` have *automatic storage duration*
Everything allocated with `new` is allocated on the heap, and a pointer to it is returned, exactly like reference types in C#.
Anything allocated on the stack has to have a constant size, determined at compile-time (the compiler has to set the stack pointer correctly, or if the object is a member of another class, it has to adjust the size of that other class). That's why arrays in C# are reference types. They have to be, because with reference types, we can decide at runtime how much memory to ask for. And the same applies here. Only arrays with constant size (a size that can be determined at compile-time) can be allocated with automatic storage duration (on the stack). Dynamically sized arrays have to be allocated on the heap, by calling `new`.
(And that's where any similarity to C# stops)
Now, anything allocated on the stack has "automatic" storage duration (you can actually declare a variable as `auto`, but this is the default if no other storage type is specified so the keyword isn't really used in practice, but this is where it comes from)
Automatic storage duration means exactly what it sounds like, the duration of the variable is handled automatically. By contrast, anything allocated on the heap has to be manually deleted by you.
Here's an example:
```
void foo() {
bar b;
bar* b2 = new bar();
}
```
This function creates three values worth considering:
On line 1, it declares a variable `b` of type `bar` on the stack (automatic duration).
On line 2, it declares a `bar` pointer `b2` on the stack (automatic duration), *and* calls new, allocating a `bar` object on the heap. (dynamic duration)
When the function returns, the following will happen:
First, `b2` goes out of scope (order of destruction is always opposite of order of construction). But `b2` is just a pointer, so nothing happens, the memory it occupies is simply freed. And importantly, the memory it *points to* (the `bar` instance on the heap) is NOT touched. Only the pointer is freed, because only the pointer had automatic duration.
Second, `b` goes out of scope, so since it has automatic duration, its destructor is called, and the memory is freed.
And the `bar`instance on the heap? It's probably still there. No one bothered to delete it, so we've leaked memory.
From this example, we can see that anything with automatic duration is *guaranteed* to have its destructor called when it goes out of scope. That's useful. But anything allocated on the heap lasts as long as we need it to, and can be dynamically sized, as in the case of arrays. That is also useful. We can use that to manage our memory allocations. What if the Foo class allocated some memory on the heap in its constructor, and deleted that memory in its destructor. Then we could get the best of both worlds, safe memory allocations that are guaranteed to be freed again, but without the limitations of forcing everything to be on the stack.
And that is pretty much exactly how most C++ code works.
Look at the standard library's `std::vector` for example. That is typically allocated on the stack, but can be dynamically sized and resized. And it does this by internally allocating memory on the heap as necessary. The user of the class never sees this, so there's no chance of leaking memory, or forgetting to clean up what you allocated.
This principle is called RAII (Resource Acquisition is Initialization), and it can be extended to any resource that must be acquired and released. (network sockets, files, database connections, synchronization locks). All of them can be acquired in the constructor, and released in the destructor, so you're guaranteed that all resources you acquire will get freed again.
As a general rule, never use new/delete directly from your high level code. Always wrap it in a class that can manage the memory for you, and which will ensure it gets freed again. (Yes, there may be exceptions to this rule. In particular, smart pointers require you to call `new` directly, and pass the pointer to its constructor, which then takes over and ensures `delete` is called correctly. But this is still a very important rule of thumb) | When should I use the new keyword in C++? | [
"",
"c++",
"pointers",
"reference",
"new-operator",
"keyword",
""
] |
I am accepting a POST request like so:
```
Socket connection = m_connection;
Byte[] receive = new Byte[1024];
int received = connection.Receive(receive);
Console.WriteLine(received.ToString());
string request = Encoding.ASCII.GetString(receive);
Console.WriteLine(request);
```
The post values end up being weird, if I post text values a lot of times they end up with a lot of +'s behind them. If I post C:\Users\John Doe\wwwroot, it ends up being: C%3A%5CUsers%5John+Doe%5Cwwwroot
index.html becomes index.html++++++++++++++++++++++++++++++++
It seems I am getting the Encoding wrong somehow, however I tried multiple encodings, and they have same weirdness. What is the best way to correctly read a HTTP POST request from a socket byte stream? | You should use System.Web.HttpUtility.UrlDecode not Encoding.ASCII to peform the decoding.
You will probably get away with passing Encoding.Default as the second parameter to this static method.
Your are seeing the result of a HTML form POST which encodes the values as if they were being appended to a URL as a search string. Hence it is a & delimited set of name=value pairs. Any out-of-band characters are encoded to their hex value %xx.
The UrlDecode method will decode all this for you.
As other have stated you really need to chunk the stream in, it may be bigger that 1K.
Strictly speaking you should check the Content-Type header for any ;CharSet= attribute. If present you need to ensure the character encode you pass to UrlDecode is appropriate to that CharSet (e.g., if CharSet=UTF-8 then use Encoding.UTF8). | You need to trim the byte array `receive` that you are passing to the GetString method. Right now, you are passing all 1024 bytes, so the GetString method is trying to encode those as best it can.
You need to use the `received` variable to indicate the bounds for the string you are encoding. | What is the best way to correctly read a HTTP POST request from a socket byte stream? | [
"",
"c#",
"networking",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.