Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a string, such as `hello _there_`. I'd like to replace the two underscores with `<div>` and `</div>` respectively, using **JavaScript**. The output would (therefore) look like `hello <div>there</div>`. The string might contain multiple pairs of underscores.
What I am looking for is a way to **either** run a function on each match, the way Ruby does it:
```
"hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }
```
**Or** be able to reference a matched group, again the way it can be done in ruby:
```
"hello _there_".gsub(/_(.*?)_/, "<div>\\1</div>")
```
Any ideas or suggestions? | ```
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
```
Oh, or you could also:
```
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
``` | You can use `replace` instead of `gsub`.
```
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
``` | Javascript replace with reference to matched group? | [
"",
"javascript",
"regex",
""
] |
I have a GridView which supports deleting. I'd like to add a pop up window with a question like 'Are you sure you want to delete this row?'.
My code:
```
<asp:GridView id="GridAccounts" runat="server" AutoGenerateColumns="False"
ShowFooter="True" DataKeyNames="ID"
DataSourceID="AccountDataSource" onrowcommand="GridAccounts_RowCommand">
<SelectedRowStyle BackColor="Lime" />
<Columns>
<asp:CommandField ButtonType="Image" ShowDeleteButton="True" DeleteImageUrl="~/Pictures/delete.jpg" />
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="LabelAccountIDUpdate" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="ButtonAccountIDInsert" runat="server" CommandName="Insert" Text="Insert" />
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="LabelAccountID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
Code behind:
```
protected void GridPaymentMethod_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton deleteButton = (ImageButton)e.Row.Cells[0].Controls[0];
MyMoney.PaymentMethodRow row = (MyMoney.PaymentMethodRow)((System.Data.DataRowView)e.Row.DataItem).Row;
deleteButton.OnClientClick = string.Format("return confirm('Are you sure you want to delete payment method {0}?');", row.Name.Replace("'", @"\'"));
}
}
```
This renders as:
```
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="return confirm('Are you sure you want to delete payment method Gotovina?');javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
```
If I click OK on confirmation window, postback occurs, but nothing happens. If I comment out RowDataBound code, than delete works OK. Code whithout confirmation pop up:
```
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
```
What am I doing wrong? | In your code you must change ButtonType="Image" to ButtonType="Link" - then onclick="..." will be rendered without javascript:\_\_\_doPostBack(...) part. And in the GridPaymentMethod\_RowDataBound event set something like deleteButton.Text = "<img src=\"path\_to\_image\" ... />" (use html entities instead of <>).
Or you can use ImageButton with ComamndName="delete" and [ConfirmButtonExtender](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ConfirmButton/ConfirmButton.aspx) from ASP.NET AjaxToolkit suite. | I believe [this](http://www.pluralsight.com/community/blogs/fritz/archive/2006/03/22/20514.aspx) is an example of what you are trying to do. It's cleaner and you don't have to go nutz with the code behind. | Confirm delete before deleting dataview's row | [
"",
"asp.net",
"javascript",
"html",
""
] |
Is there any implementation of the [NFS](http://en.wikipedia.org/wiki/Network_File_System_(protocol)) protocol written in C# or a good documentation thats easy to read so I can implement my own..
Both server and Client are needed but the client doesn't have to be C#, there must be some thing out there? | Assuming you weren't looking at this as a learning experience I would have suggested taking a C++/C implementation and wrapping it via C++/CLI.
However the only mention of an open source windows client for NFS 4 is [this project](http://www.citi.umich.edu/projects/nfsv4/windows/) with the financial support of MS and the university who wrote the reference implementation for many other OS's
That that this is their [statement of intent](http://www.citi.umich.edu/projects/nfsv4/windows/CITI-MS-SoW.pdf) and suggests a two year project sorry. | Hi you can check at my open source project <http://code.google.com/p/nekodrive>
You can use directly NekoDrive.NFS c# library that wraps my implementation
of V2 e V3 NFS Protocol (V4.1 is coming).. It doesn't support the full protocol yet but It works for basic browsing/download/upload functions..
hope this helps | Where can I find a C#/.NET NFS implementation? | [
"",
"c#",
"networking",
"nfs",
""
] |
Lets say I have a website with links to various books on my main page.
```
<a href='books.php?id=1'>Book 1</a>
<a href='books.php?id=2'>Book 2</a>
<a href='books.php?id=4'>Book 3</a>
```
Books 1-3 are in my system, however id=3 is apart of another catelog that I'm not showing or authorizing through this section of the site. So if a user clicked on Book 3, then changed the id=4 to id=3, they could simply pull up the record (assuming I don't have proper session checking).
Is there a good way to obscure the get id that you're passing when trying to pull a specific record? it seems by passing just the id would be easy to request pages that, without proper querying and session checking, you would be able to get another result.
Is there a better way to do this?
Cheers | You need to always, always, check that user is able to access the page. That is the only way to verify that you don't show wrong data, because someone can always modify the link they are going to, even if you somehow hide it.
There is just no escaping it. You always need to verify that the record can be accessed. | You probably could hash your id or something using `md5` or whatever to make it harder to manually enter, but that's really not a good idea.
What you should do is to implement server side security in your `books.php` script that will prevent users from unauthorized access. That's the only thing that will keep your site secure. | PHP Security when Passing MySQL Unique ID via Get | [
"",
"php",
"security",
"obfuscation",
""
] |
A shout out to the Swing gurus out there!!
I've been doing Swing programming for several years but have always been unclear on this.
As you know Swing/AWT gives you several ways to execute a particular action when a button is clicked. I've seen it done several different ways in the applications I've worked on. The project I'm currently working on tends to follow this approach:
```
someButton.setActionCommand("mycommand");
someButton.addActionListener(listener);
```
--snip--
```
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("mycommand"))
doThis();
else if (command.equals("someothercommand"))
doThat();
etc.
```
This seems kind of clunky to me - is there any benefit to this style of programming, or is it better to use Swing `Action`s?
Or are there different situations where the different approaches are better/worse? | IMO, it is better to use separate listeners for Actions.
That way you leave the delegating of what action should happen up to Swing. You don't have to compare Strings to decide what to do.
Having one huge `ActionListener` for more than one action feels like breaking the pattern to me. | From a design point of view, I think it is better to have one class to handle one specific action for a component as opposed to one class that is a "lets handle everything for all components here" type of design.
Also, if you use `Action` you can a) apply it to more than one component (e.g. a button and a menu item) b) call `setEnable` to enable/disable it for all components its attached to and c) Also use it to define various settings on the components its attached to (namely, the text label, the tooltip text, the accelerator key, icon, etc.). This last one is done via the `putValue` method and calling this method again will change the settings for all components its attached to.
Specifically, I would advise to subclass `AbstractAction` for your needs. | Action commands vs Action classes? | [
"",
"java",
"user-interface",
"swing",
""
] |
I'm trying to figure out a way to detect groups of files. For instance:
If a given directory has the following files:
* Birthday001.jpg
* Birthday002.jpg
* Birthday003.jpg
* Picknic1.jpg
* Picknic2.jpg
* Afternoon.jpg.
I would like to condense the listing to something like
* Birthday ( 3 pictures )
* Picknic ( 2 pictures )
* Afternoon ( 1 picture )
How should I go about detecting the groups? | Here's one way you can solve this, which is more efficient than a brute force method.
* load all the names into an associative array with key equal to the name and value equal to the name but with digits stripped (`preg_replace('/\d//g', $key)`).
You will have something like `$arr1 = [Birthday001 => Birthday, Birthday002 => Birthday ...]`
* now make another associative array with keys that are values from the first array and value which is a count. Increment the count when you've already seen the key.
* in the end you will end up with a 2nd array that contains the names and counts, just like you wanted. Something like `$arr2 = [Birthday => 2, ...]` | Simply build a histogram whose keys are modified by a regex:
```
<?php
# input
$filenames = array("Birthday001.jpg", "Birthday002.jpg", "Birthday003.jpg", "Picknic1.jpg", "Picknic2.jpg", "Afternoon.jpg");
# create histogram
$histogram = array();
foreach ($filenames as $filename) {
$name = preg_replace('/\d+\.[^.]*$/', '', $filename);
if (isset($histogram[$name])) {
$histogram[$name]++;
} else {
$histogram[$name] = 1;
}
}
# output
foreach ($histogram as $name => $count) {
if ($count == 1) {
echo "$name ($count picture)\n";
} else {
echo "$name ($count pictures)\n";
}
}
?>
``` | How do I detect groups of common strings in filenames | [
"",
"php",
"regex",
""
] |
I am currently hunting a nasty bug in a multi-threaded environment using FutureTasks and Executors. The basic idea is this to have a fixed number of threads execute individual FutureTasks that compute a result that is to be displayed in a a table (never mind the GUI aspect here).
I have been looking at this for so long, I am beginning to doubt my sanity.
Consider this piece of code:
```
public class MyTask extends FutureTask<Result> {
private String cellId;
...
protected void done() {
if (isCancelled()) return;
try {
Result r = get(); // should not wait, because we are done
... // some processing with r
sendMessage(cellId, r);
} catch (ExecutionException e) { // thrown from get
...
} catch (InterruptedException e) { // thrown from get
...
}
}
...
}
```
When `done()` is called by an Executor handling an instance of MyTask, I check if I got there, because the task was cancelled. If so, I skip all remaining activities, especially I do not call `sendMessage()`.
The documentation for FutureTask.done() says:
> Protected method invoked when this task transitions to state isDone (whether normally or via cancellation). The default implementation does nothing. Subclasses may override this method to invoke completion callbacks or perform bookkeeping. Note that you can query status inside the implementation of this method to determine whether this task has been cancelled.
> ([API Reference](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html#done()))
But what I do not get from the documentation of `FutureTask` are the semantics *while* `done()` is being executed. What if I pass the `isCancelled()` check at the beginning, but right after that some other thread calls my `cancel()` method? Will that cause my task to change its mind and reply `isCancelled() == true` from then on?
If so, how would I later know if the the message was sent? Looking at `isDone()` would just tell me that execution of the task was finished, but as `isCancelled()` were true then as well, I could not know if it got to send the message out in time.
Maybe this is obvious, but I do not really see it right now. | From the API (emphasis mine):
> public boolean cancel(boolean mayInterruptIfRunning)
>
> Description copied from interface: Future
>
> Attempts to cancel execution of this task. **This attempt will fail if the task has already completed**, already been cancelled, or could not be cancelled for some other reason.
So FutureTask is working off the assumption that you cannot cancel a task when it has transitioned to the isDone stage. | [`FutureTask#done()`](http://java.sun.com/javase/7/docs/api/java/util/concurrent/FutureTask.html#done%28%29) is called no more than once for any given instance, and it's only called for one reason -- `run()` completed either with or without error, or `cancel()` ran before either of the preceding events occurred. The record of completion by any of these outcomes is *latching*. The reason a `FutureTask` completed can't change, regardless of competing events seemingly happening "at the same time."
Hence, within `FutureTask#done()` only one of `isCancelled()` or `isDone()` will return true then and forever more. It's difficult to distinguish between `isDone()` reporting true by way of error or successful completion. You can't override `set()` or `setException(Throwable)` decisively, as both delegate to the inner [`AQS`](http://java.sun.com/javase/7/docs/api/java/util/concurrent/locks/AbstractQueuedSynchronizer.html) to decide whether the *attempt* to record a successful yielding of a value or encountering an exception should stick. Overriding either method only lets you know that it was called, but you can't observe the decision made by the base implementation. If either event occurs "too late"—say, *after* cancellation—the attempt to record the value or the exception will be ignored.
Studying the implementation, the only way I see to discern a non-canceled successful outcome from an error is to bite the bullet and call `get()`. | Java 5: java.util.concurrent.FutureTask - Semantics of cancel() and done() | [
"",
"java",
"multithreading",
"concurrency",
"executorservice",
"futuretask",
""
] |
Sorry, this looks longer than it probably is but I thought I should include all the information!
I'm using a simple Ajax script to dynamically bring content into a <div> on a page. The first request to load some new content into the div works fine, but if I've got an Ajax "back" link within the content which has just loaded, it seems to throw an error.
Even stranger, it works on my office network, but it fails If I'm on a home or VPN network. If it fails, this error pops up in the JavaScript debugger:
```
Line: 12
Char: 11
Error: Permission Denied
Code: 0
URL: http://www.example.com/about.php
```
The code really isn't that complex, it's just a slightly hacked around version of the stuff on the W3 website, but the fact that the return call is "denied" is confusing me. Would it be something within the server IIS configuration to stop scripting attacks? (Random thought?)
Any help appreciated ;)
**First - the Ajax script**
```
var myHttpRequest = false;
if(window.XMLHttpRequest)
myHttpRequest = new XMLHttpRequest();
else if(window.ActiveXObject)
myHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
function loadContent(source, content)
{
if(myHttpRequest)
{
var data = document.getElementById(content);
myHttpRequest.open("GET",source);
data.innerHTML = '<div class=\"loading_image\"><img src=\"images/loading.gif\" width=\"54px\" height=\"55px\" alt="loading" /></div>';
myHttpRequest.onreadystatechange = function()
{
if(myHttpRequest.readyState==4)
data.innerHTML = myHttpRequest.responseText;
$('#col2_2_content').supersleight();
}
myHttpRequest.send(null);
}
}
```
Then this is a truncated example of the page which calls the Ajax content and has the col2\_2\_content Div where everything gets inserted. The file `ajax.js` is referenced in the head section.
```
<div id="col2_2_content">
<div class="mugshot_container">
<img src="images/mugshot_dh.jpg" onClick="loadContent('about/dh.php?ajax=yes', 'col2_2_content');"/>
</div>
</div>
```
And this is the code from `about/dh.php` which is inserted via Ajax, along with the PHP formatting to decide what should be returned. (It's designed to be called directly too - in which case it gets a header/footer wrapped around).
```
<?php
$home_url = "http://www.example.com/url/";
$content = "
<p>Some Text</p>
<p><a onClick=\"loadContent('$home_url/about/about-main.php?ajax=yes', 'col2_2_content');\">Back</a></p>
";
if (isset($_REQUEST['ajax']) ) {
echo $content;
} else {
include_once 'about-header.php';
echo $content;
include_once 'about-footer.php';
}
?>
``` | You got yourself in cross-domain request situation. AJAX requests basically can be made only to the server that served the page. So if your script page is loaded from `http://website.com/url`, you can make any call to `http://website.com/` but any call to `http://url.com` would fail.
Having said that, it is possible to call `http://s1.example.com` from `http://s2.example.com` if you run `document.domain = "example.com"`.
But if you really need to access data across domains, there's few ways to do that. Simplest one I know is to use `<script>` tag to do the query. You can edit your document to add `<script>` tag with any `src` you like and browser will go there and fetch the script for you. So if you control `http://url.com`, you can just make it create a javascript instead of HTML page and this script would be loaded and executed. This method is used to make JSONP work.
Cross-site scripting might work without security issues in the local network because IE doesn't put that much restrictions in that case. I doubt though it will work in any other browser even in your LAN. | "Permission denied" sounds suspiciously as if you're having [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) issues. | Ajax error - "permission denied" | [
"",
"php",
"ajax",
"iis",
""
] |
I've developed a mini HTTP server in C++, using boost::asio, and now I'm load testing it with multiple clients and I've been unable to get close to saturating the CPU. I'm testing on a Amazon EC2 instance, and getting about 50% usage of one cpu, 20% of another, and the remaining two are idle (according to htop).
Details:
* The server fires up one thread per core
* Requests are received, parsed, processed, and responses are written out
* The requests are for data, which is read out of memory (read-only for this test)
* I'm 'loading' the server using two machines, each running a java application, running 25 threads, sending requests
* I'm seeing about 230 requests/sec throughput (this is *application* requests, which are composed of many HTTP requests)
So, what should I look at to improve this result? Given the CPU is mostly idle, I'd like to leverage that additional capacity to get a higher throughput, say 800 requests/sec or whatever.
Ideas I've had:
* The requests are very small, and often fulfilled in a few ms, I could modify the client to send/compose bigger requests (perhaps using batching)
* I could modify the HTTP server to use the Select design pattern, is this appropriate here?
* I could do some profiling to try to understand what the bottleneck's are/is | boost::asio is not as thread-friendly as you would hope - there is a big lock around the epoll code in boost/asio/detail/epoll\_reactor.hpp which means that only one thread can call into the kernel's epoll syscall at a time. And for very small requests this makes all the difference (meaning you will only see roughly single-threaded performance).
Note that this is a limitation of how boost::asio uses the Linux kernel facilities, not necessarily the Linux kernel itself. The epoll syscall does support multiple threads when using edge-triggered events, but getting it right (without excessive locking) can be quite tricky.
BTW, I have been doing some work in this area (combining a fully-multithreaded edge-triggered epoll event loop with user-scheduled threads/fibers) and made some code available under the [nginetd](http://nginetd.cmeerw.org) project. | As you are using EC2, all bets are off.
Try it using real hardware, and then you might be able to see what's happening. Trying to do performance testing in VMs is basically impossible.
I have not yet worked out what EC2 is useful for, if someone find out, please let me know. | C++ Socket Server - Unable to saturate CPU | [
"",
"c++",
"linux",
"multithreading",
"scalability",
"boost-asio",
""
] |
**An example of this would be:**
```
char str[] = "Hello";
int strLength = strlen(str);
for ( char * pc = str;
pc < str + strLength;
pc++)
{
*pc += 2;
}
```
**Edit:** Accounted for write-protected memory issue. | My one issue is that you'd have a lot of fun if you leave out the \* in \*pc in the for loop. Whoops? More generally, it is slightly harder to tell the difference between reassigning the pointer and modifying the value.
However, (though I don't have it handy), Stroustroup himself endorses(see edit) pointer iteration in the C++ Programming Language book. Basically, you can have a pretty terse implementation of string comparison between two char arrays using pointer arithmetic.
In short, I would recommend using such pointers in a "read only" fashion. If you need to write to the array, I would use the more traditional i.
This is, of course, all my personal preference.
Edit: Stroustroup doesn't endorse pointer iteration OVER integer -- he simply uses it at one point in the book, so my reasoning is that he doesn't think its anethema to good practice. | It's ALWAYS a bad idea to use a construct that you don't fully understand. This extends to the people who will have to read your code after you... (I think this is a corollary to the "Don't be a clever programmer" rule)
In this case, if you DO understand, and are fully comfortable with the construct, then there's nothing inherently wrong with it... But usually, if you have to ask if it's a bad idea, then you're not fully comfortable with it... | Is it a bad idea to use pointers as loop incrementers instead of the usual "int i"? | [
"",
"c++",
"c",
"pointers",
"loops",
""
] |
I have some (C++) functions each containing several calls creating similar arrays of the same basic type on the heap. At various points in these functions, I may need to throw an exception. Keeping track of which arrays have been deleted is a pain, and quite error prone, so I was thinking about just adding the array pointers to a `Set<ArrType*>`, of which I can just delete every item when I catch an exception, like this:
```
try
{
set<ArrType*> sHeap;
ArrType* myArr = new ArrType[5];
sHeap.Add(myArr);
someExternalRoutine(myArr);
...
}
catch(CString s)
{
DeleteAllPointersInMyHeap(sHeap);
throw(s);
}
```
It feels a bit like adding epicycles, but I can't get around the fact that any one of several external calls may throw an exception, and I need to definitely delete all the pointers allocated up to that point.
Is this just foolishness? Should I just add smaller try-catch blocks around the external calls? I'd still end up with little lists of delete A; delete B; delete D; after each one... | You don't have to rely on garbage collection.
You have std::auto\_ptr that provides pointer like syntax and wraps a dynamically allocated object. When destroyed, it automatically destroys the object it points to.
You could implement something similar for arrays. | Why not use a smart pointer like [`boost::shared_array`](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_array.htm) or use a stack-allocated [`std::vector`](http://www.sgi.com/tech/stl/Vector.html)? For single allocations rather than array allocations, you could use [`boost::shared_ptr`](http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/shared_ptr.htm).
These implement the [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) for you. Even if you're re-using a concept like RAII, you're still reinventing the wheel if there's already a concrete implementation out there that satisfies your requirements. | Am I crazy to recreate a tiny garbage collection system inside my functions? | [
"",
"c++",
"garbage-collection",
""
] |
I need to select all rows where `User.site_url` is not null. It's simple enough to do this in a regular **MySQL** query but how is this done in **CakePHP**?
The manual mentions the following:
```
array ("not" => array (
"Post.title" => null
)
)
```
I have tried the following but it's still returning everything
```
$this->User->find('all', array('conditions' => array('not' => array('User.site_url'))));
``` | I think this is what you mean:
```
$this->User->find('all', array(
'conditions' => array('not' => array('User.site_url' => null))
));
``` | Your just missing the null
```
$this->User->find('all', array('conditions' => array('not' => array('User.site_url'=>null))));
``` | CakePHP: Find where field is not null | [
"",
"php",
"cakephp",
""
] |
I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substring probability in the partition.
For example, if the string is 'abc', then there would be probabilities for 'a', 'b', 'c', 'ab, 'bc' and 'abc'. There are four possible partitionings of the string: 'abc', 'ab|c', 'a|bc' and 'a|b|c'. The algorithm needs to find the product of the component probabilities for each partitioning, then sum the four resultant numbers.
Currently, I've written a python iterator that uses binary representations of integers for the partitions (eg 00, 01, 10, 11 for the example above) and simply runs through the integers. Unfortunately, this is immensely slow for strings longer than 20 or so characters.
Can anybody think of a clever way to perform this operation without simply running through every partition one at a time? I've been stuck on this for days now.
In response to some comments here is some more information:
The string can be just about anything, eg "foobar(foo2)" -- our alphabet is lowercase alphanumeric plus all three type of braces ("(","[","{"), hyphens and spaces.
The goal is to get the likelihood of the string given individual 'word' likelihoods. So L(S='abc')=P('abc') + P('ab')P('c') + P('a')P('bc') + P('a')P('b')P('c') (Here "P('abc')" indicates the probability of the 'word' 'abc', while "L(S='abc')" is the statistical likelihood of observing the string 'abc'). | A [Dynamic Programming](http://en.wikipedia.org/wiki/Dynamic_programming) solution (if I understood the question right):
```
def dynProgSolution(text, probs):
probUpTo = [1]
for i in range(1, len(text)+1):
cur = sum(v*probs[text[k:i]] for k, v in enumerate(probUpTo))
probUpTo.append(cur)
return probUpTo[-1]
print dynProgSolution(
'abc',
{'a': 0.1, 'b': 0.2, 'c': 0.3,
'ab': 0.4, 'bc': 0.5, 'abc': 0.6}
)
```
The complexity is O(N2) so it will easily solve the problem for N=20.
How why does this work:
* Everything you will multiply by `probs['a']*probs['b']` you will also multiply by `probs['ab']`
* Thanks to the [Distributive Property](http://en.wikipedia.org/wiki/Multiplication#Properties) of multiplication and addition, you can sum those two together and multiply this single sum by all of its continuations.
* For every possible last substring, it adds the sum of all splits ending with that by adding its probability multiplied by the sum of all probabilities of previous paths. (alternative phrasing would be appreciated. my python is better than my english..) | First, profile to find the bottleneck.
If the bottleneck is simply the massive number of possible partitions, I recommend parallelization, possibly via [`multiprocessing`](http://docs.python.org/library/multiprocessing.html). If that's still not enough, you might look into a [Beowulf](http://www.beowulf.org/) cluster.
If the bottleneck is just that the calculation is slow, try shelling out to C. It's pretty easy to do via [`ctypes`](http://docs.python.org/library/ctypes.html).
Also, I'm not really sure how you're storing the partitions, but you could probably squash memory consumption a pretty good bit by using one string and a [suffix array](http://en.wikipedia.org/wiki/Suffix_array). If your bottleneck is swapping and/or cache misses, that might be a big win. | Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string? | [
"",
"python",
"string",
"partitioning",
""
] |
in my J2EE project I've a couple of dependencies, which are not available in any Maven repository, because they're proprietary libraries. These libraries need to be available at runtime, so that have to be copied to target/.../WEB-INF/lib ...
Right now, I'm listing them as system dependency in my POM, but with this method the problem is, that aren't being copied to the target build during compilation. Also this method is not very elegant.
So which is the best way to integrate them in Maven?
Note: I don't want to create my own Maven repository. | As you've said you don't want to set up your own repository, perhaps this will help.
You can use the [install-file goal](http://maven.apache.org/plugins/maven-install-plugin/install-file-mojo.html) of the maven-install-plugin to install a file to the local repository. If you create a script with a Maven invocation for each file and keep it alongside the jars, you (and anyone else with access) can easily install the jars (and associated pom files) to their local repository.
For example:
```
mvn install:install-file -Dfile=/usr/jars/foo.jar -DpomFile=/usr/jars/foo.pom
mvn install:install-file -Dfile=/usr/jars/bar.jar -DpomFile=/usr/jars/bar.pom
```
or just
```
mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0 -Dpackaging=jar
```
You can then reference the dependencies as normal in your project.
However your best bet is still to set up an internal remote repository and I'd recommend using [Nexus](http://nexus.sonatype.org/) myself. It can run on your development box if needed, and the overhead is minimal. | For people wanting a quick solution to this problem:
```
<dependency>
<groupId>LIB_NAME</groupId>
<artifactId>LIB_NAME</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${basedir}/WebContent/WEB-INF/lib/YOUR_LIB.jar</systemPath>
</dependency>
```
just give your library a unique groupID and artifact name and point to where it is in the file system. You are good to go.
Of course this is a dirty quick fix that will ONLY work on your machine and if you don't change the path to the libs. But some times, that's all you want, to run and do a few tests.
EDIT: just re-red the question and realised the user was already using my solution as a temporary fix. I'll leave my answer as a quick help for others that come to this question. If anyone disagrees with this please leave me a comment. :) | Maven: How to include jars, which are not available in reps into a J2EE project? | [
"",
"java",
"maven-2",
"build-process",
""
] |
What I'm trying to do is draw some glass on a form marked as an mdi container. However as soon as the IsMdiContainer is set, the form adds an MdiClient to it's list of Controls. At this point something happens to the parent form - almost like a dark gray panel is being docked to the entire form onto which the MdiClient is being placed on.
I then do is the following to move the MdiClient control out of the way a bit:
```
foreach(var c in Controls)
{
if(c is MdiClient)
{
var client = (MdiClient)c;
client.BackColor = Color.Red;
client.Dock = DockStyle.None;
client.Size = new Size(this.Width-100, this.Height);
break;
}
}
```
This then makes the actual MdiClient area smaller so we can see what is behind it (the bit which hosts the children forms) and it is blatantly obvious that the parent form is not painting or something.
As can be seen here: <http://img525.imageshack.us/img525/8605/mdiglassproblem.png>
I now need to somehow get the area behind the MdiClient (dark gray part which is rendered white on the glass section) to go away.
Any ideas?
*PS - Glass is being rendered using DwmExtendFrameIntoClientArea method in Vista.* | I managed to get it working. That dark gray area I was talking about, which gets painted over everything was occuring in the OnPaint method of the form. Obviously when there is an MdiContainer present the form is preprogrammed to paint the dark gray area which was obstructing the glass.
So just override the OnPaint method without calling it's base and then take the code that was used to draw the glass in the normal Paint method and stick it in the OnPaint method.
```
protected override void OnPaint(PaintEventArgs e)
{
//base.OnPaint(e);
bool glassEnabled = IsGlassEnabled();
if (glassEnabled) // draw glass if enabled
{
Rectangle rc = picPlaceHolder.ClientRectangle;
IntPtr destdc = e.Graphics.GetHdc(); // hwnd must be the handle of form, not control
IntPtr Memdc = CreateCompatibleDC(destdc);
IntPtr bitmapOld = IntPtr.Zero;
BITMAPINFO dib = new BITMAPINFO();
dib.bmiHeader.biHeight = -(rc.Bottom - rc.Top);
dib.bmiHeader.biWidth = rc.Right - rc.Left;
dib.bmiHeader.biPlanes = 1;
dib.bmiHeader.biSize = Marshal.SizeOf(typeof(BITMAPINFOHEADER));
dib.bmiHeader.biBitCount = 32;
dib.bmiHeader.biCompression = BI_RGB;
if (!(SaveDC(Memdc) == 0))
{
IntPtr bitmap = CreateDIBSection(Memdc, ref dib, DIB_RGB_COLORS, 0, IntPtr.Zero, 0);
if (!(bitmap == IntPtr.Zero))
{
bitmapOld = SelectObject(Memdc, bitmap);
BitBlt(destdc, rc.Left, rc.Top, rc.Right - rc.Left, rc.Bottom - rc.Top, Memdc, 0, 0, SRCCOPY);
}
// remember to clean up
SelectObject(Memdc, bitmapOld);
DeleteObject(bitmap);
ReleaseDC(Memdc, -1);
DeleteDC(Memdc);
}
e.Graphics.ReleaseHdc();
}
}
```
Then just ensure that the MdiContainer is not in the way of the glass and it should draw perfectly. | I think this is perfect enough.
```
foreach (Control ctrl in this.Controls)
{
if (ctrl is MdiClient)
{
ctrl.BackColor = Color.LightGray;
}
}
``` | How to remove gray background on MDI parent form? | [
"",
"c#",
"forms",
"mdi",
"mdiparent",
""
] |
So, I have a snapshot of a video source, which I get into an Image, grab a Graphics object for it, and then draw a timestamp in the bottom right of the image. No problem thus far. However, I cannot guarantee what colour is going to be behind the text, so no matter what brush I use, it will almost certainly clash with some of the images that it is drawn on, making the text unreadable.
I am wondering if anyone knows of a way (either a method in .net, or a nice algorithm), for determining the best colour for a string based on the image behind it.
Cheers | ```
just draw the string 5 times.
One time 1(or2) pixels to the left in black
One time 1(or2) pixels to the right in black
One time 1(or2) pixels above it in black
One time 1(or2) pixels below it in black
and the final time in white on the place where you want it
``` | The only reliable way is to use a contrasting outline. | Drawing a contrasted string on an image | [
"",
"c#",
"string",
"system.drawing",
""
] |
I have a typed array `MyType[] types;`
and i want to make and independant copy of this array. i tried this
```
MyType[] types2 = new MyType[types.Length] ;
types2 = types ;
```
but this create a reference to the first. I then tried
```
Array.Copy( types , types2 , types.Length ) ;
```
but I have the same problem: changing a value in the first array changes the value in the copy as well.
How can I make a completely independent or deep copy of an Array, IList or IEnumerable? | Implement a clone method on MyType, using protected method MemberwiseClone (performs shallow copy) or using a deep cloning technique. You can have it implement an ICloneable then write several extensions methods that will clone the corresponsing collection.
```
interface ICloneable<T>
{
T Clone();
}
public static class Extensions
{
public static T[] Clone<T>(this T[] array) where T : ICloneable<T>
{
var newArray = new T[array.Length];
for (var i = 0; i < array.Length; i++)
newArray[i] = array[i].Clone();
return newArray;
}
public static IEnumerable<T> Clone<T>(this IEnumerable<T> items) where T : ICloneable<T>
{
foreach (var item in items)
yield return item.Clone();
}
}
```
You must do this because while a new array is created when you use Array.Copy it copies the references, not the objects referenced. Each type is responsible for copying itself. | Based on the first post, all he needs is this for "an independent copy of the array". Changes to the `shallowCopy` array itself would not appear in the `types` array (meaning element assignment, which really is what he showed above despite saying "deep copy"). If this suits your needs, it will have the best performance.
```
MyType[] shallowCopy = (MyType[])types.Clone();
```
He also mentions a "deep copy" which would be different for mutable types that are not recursive value-type aggregates of primitives. If the `MyType` implements `ICloneable`, this works great for a deep copy:
```
MyType[] deepCopy = (MyType[])Array.ConvertAll(element => (MyType)element.Clone());
``` | C# Copy Array by Value | [
"",
"c#",
"arrays",
""
] |
I am trying implement the [Data transformation using Reflection](https://web.archive.org/web/20210122135227/http://geekswithblogs.net/shahed/archive/2008/07/24/123998.aspx)1 example in my code.
The `GetSourceValue` function has a switch comparing various types, but I want to remove these types and properties and have `GetSourceValue` get the value of the property using only a single string as the parameter. I want to pass a class and property in the string and resolve the value of the property.
Is this possible?
1 [Web Archive version of original blog post](https://web.archive.org/web/20130815002453/http://msmvps.com/blogs/shahed/archive/2008/07/24/c-reflection-tips-data-transformation-using-reflection.aspx) | ```
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
```
Of course, you will want to add validation and whatnot, but that is the gist of it. | How about something like this:
```
public static Object GetPropValue(this Object obj, String name) {
foreach (String part in name.Split('.')) {
if (obj == null) { return null; }
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
public static T GetPropValue<T>(this Object obj, String name) {
Object retval = GetPropValue(obj, name);
if (retval == null) { return default(T); }
// throws InvalidCastException if types are incompatible
return (T) retval;
}
```
This will allow you to descend into properties using a single string, like this:
```
DateTime now = DateTime.Now;
int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
int hrs = now.GetPropValue<int>("TimeOfDay.Hours");
```
You can either use these methods as static methods or extensions. | Get property value from string using reflection | [
"",
"c#",
"reflection",
"properties",
""
] |
In my "native" programming language (RPG), I can write a loop and just leave the loop or force an iteration. It is kind of like a GOTO.
```
dow (x < 999);
read file;
if (%eof);
leave; // Leave the loop
endif;
if (field <> fileField);
iter; // Iterate to the next record
endif;
enddo;
```
My question is if there is a similar option is C#. In my case, I am working with a foreach loop. | ```
continue; // Goto the next iteration
break; // Exit the loop
``` | [Break](http://msdn.microsoft.com/en-us/library/adbctzc4(VS.80).aspx) will exit the loop.
[Continue](http://msdn.microsoft.com/en-us/library/923ahwt1(VS.80).aspx) will jump to the next iteration. | Force an iteration of a loop | [
"",
"c#",
"loops",
"foreach",
""
] |
I am trying to perform a migration from cvs to svn on my our new XServe server which is running OS X Server. There is a known conflict between the cvs2svn and dbm libraries that come pre-installed with OS X. The error is:
> ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <http://python.org/doc/current/lib/module-anydbm.html> for more information.
I followed all the prescribed steps in the [cvs2svn FAQ](http://cvs2svn.tigris.org/faq.html#osxsetup) but the error still persists. Does anyone know of an alternative way to accomplish this task, or another website that offer a different solution to this seemingly common problem? | Since CVS and Subversion repositories are really just collections of files, one way to work around this problem might be to copy your CVS repository to a machine where cvs2svn can run successfully, run it to convert to Subversion, and then copy the new repository back to your server. The added benefit of this method is that you won't run the risk of accidentally messing up your server configuration while doing this conversion step. | cvs2svn itself is available in MacPorts so, instead of just the dbm libraries, you could install cvs2svn using MacPorts:
```
port install cvs2svn
```
If not already installed, it will also install the MacPorts version of python2.5 and other dependencies. There's no harm in that but it will take a little time and a little extra space. The advantage is that you should have a working, supported version without having to fight further dependency problems. | Alternative to cvs2svn for performing cvs to svn migration | [
"",
"python",
"macos",
"xserver",
"cvs2svn",
"gdbm",
""
] |
I've written a class that should allow me to easily read and write values in app settings:
```
public static class SettingsManager
{
public static string ComplexValidationsString
{
get { return (string)Properties.Settings.Default["ComplexValidations"]; }
set
{
Properties.Settings.Default["ComplexValidations"] = value;
Properties.Settings.Default.Save();
}
}
```
the problem is the value isn't really saved, I mean it is not changed when I exit the application and run it again. What can I do to ensure that the saved value persists between closing and opening again? | You should check
```
Properties.Settings.Default.Properties["ComplexValidations"].IsReadOnly
```
It is probably true, this is what Roland means with "Application Scope". Save will fail silently. Take a look at Project|Properties|Settings, 3rd column. | settings scope must be user not application | How to change application settings (Settings) while app is open? | [
"",
"c#",
".net",
"application-settings",
""
] |
I have a need to record XML fragments in a SQL Server 2005 database for logging purposes (SOAP messages, in this case). Is there any reason to use the XML datatype over a simple varchar or nvarchar column?
I can see instances already where being able to use XPath to get into the data in the XML would be rather nice, and I haven't been able to find any real downsides in some brief research.
Are there any pitfalls that need to be watched out for or is there a better way to approach this? | [Here](http://social.msdn.microsoft.com/Forums/en-US/sqlxml/thread/19af2f3c-3558-4e71-95cb-4085f9f37042)'s a great forum post on the topic. In general, use XML datatypes if you forsee needing the XML manipulation and typing functionality. | Depending upon the size of xml and the ability of extracting particular information from within the xml, it can become a drawback. Did you consider storing the xml on the file system and just having the path in the database? | Downsides (If any) With SQL Server 2005 XML Datatype | [
"",
"sql",
"sql-server",
"xml",
""
] |
I've found loads of practical examples of this, and understand the practical output when overriding or hiding methods, but I'm looking for some under the covers info on why this is and why C# allows it when according to the rules of polymorphism, this shouldn't be allowed - at least, insofar as my understanding of polymorphism goes (which seems to coincide with the standard definitions found on Wikipedia/Webopedia).
```
Class Base
{
public virtual void PrintName()
{
Console.WriteLine("BaseClass");
}
}
Class FirstDerived : Base
{
public override void PrintName()
{
Console.WriteLine("FirstDerived");
}
}
Class SecondDerived : Base
{
public new void PrintName()
{
Console.WriteLine("SecondDerived");
}
}
```
Using the following code:
```
FirstDerived b = new FirstDerived();
BaseClass a = b;
b.PrintName();
a.PrintName();
```
I get:
FirstDerived
FirstDerived
Okay, I get that, makes sense.
```
SecondDerived c = new SecondDerived();
BaseClass a = c;
c.PrintName();
a.PrintName();
```
I get:
```
SecondDerived
BaseClass
```
Okay, that makes sense, too, instance a can't see c.PrintName() so it's using its own method to print its own name, however I can cast my instance to its true type using:
```
((SecondDerived)a).PrintName();
```
or
```
(a as SecondDerived).PrintName();
```
to get the output I would expect:
```
SecondDerived
```
So what is going on under the covers and what does this mean in terms of polymorphism? I'm told that this facility "breaks polymorphism" - and I guess according to the definition, it does. Is that right? Would an "object oriented" langage like C# really allow you to break one of the core principles of OOP? | (This answers the "why is it allowed" which I *think* is really the central point of your question. How it works in terms of the IL is less interesting to my mind... let me know if you want me to go into that though. Basically it's just a case of specifying the method to call with a different type token.)
It allows base classes to evolve without breaking derived classes.
Suppose `Base` didn't originally have the `PrintName` method. The only way to get at `SecondDerived.PrintName` would be to have an expression with a static type of `SecondDerived`, and call it on that. You ship your product, everything is fine.
Now fast forward to `Base` introducing a `PrintName` method. This may or may not have the same semantics of `SecondDerived.PrintName` - it's safest to assume that it doesn't.
Any callers of `Base.PrintName` know that they're calling the new method - they couldn't have called it before. Any callers which were previously using `SecondDerived.PrintName` *still* want to use it though - they don't want to suddenly end up calling `Base.PrintName` which could do something entirely different.
The difficulty is *new* callers of `SecondDerived.PrintName`, who may or may not appreciate that this *isn't* an override of `Base.PrintName`. They may be able to notice this from the documentation of course, but it may not be obvious. However, at least we haven't broken *existing* code.
When `SecondDerived` is recompiled though, the authors will be made aware that there's now a `Base.PrintName` class through a warning. They can either stick to their existing non-virtual scheme by adding the `new` modifier, or make it override the `Base.PrintName` method. Until they make that decision, they'll keep getting a warning.
Versioning and compatibility isn't usually mentioned in OO theory in my experience, but C# has been designed to try to avoid compatibility nightmares. It doesn't solve the problem completely, but it does a pretty good job. | I answer "how" it works. Jon has answered the "Why" part.
Calls to `virtual` methods are resolved a bit differently to those of non-`virtual` ones. Basically, a `virtual` method declaration introduces a "virtual method slot" in the base class. The slot will hold a pointer to the actual method definition (and the contents will point to an overridden version in the derived classes and no new slot will be created). When the *compiler* generates code for a virtual method call, it uses the `callvirt` IL instruction, specifying the method slot to call. The *runtime* will dispatch the call to the appropriate method. On the other hand, a non-virtual method is called with a `call` IL instruction, which will be statically resolved to the actual method by the compiler, at compile time (only with the knowledge of the compile-time type of the variable). `new` modifier does nothing in the compiled code. It essentially tells the C# compiler "Dude, shut up! I'm sure I'm doing the right thing" and turns off the compiler warning.
A `new` method (actually, any method without an `override` modifier) will introduce a completely separate chain of methods (new method slot). Note that a `new` method can be `virtual` itself. The compiler will look at the static type of the variable when it wants to resolve the *method chain* and the run time will choose the *actual method* in that specific chain. | What's really happening with new and override under the covers? | [
"",
"c#",
"oop",
"polymorphism",
""
] |
We have an API that handles event timers. This API says that it uses OS callbacks to handle timed events (using select(), apparently).
The api claims this order of execution as well:
readable events
writable events
timer events
This works by creating a point to a Timer object, but passing the create function a function callback:
Something along these lines:
```
Timer* theTimer = Timer::Event::create(timeInterval,&Thisclass::FunctionName);
```
I was wondering how this worked?
The operating system is handling the timer itself, and when it sees it fired how does it actually invoke the callback? Does the callback run in a seperate thread of execution?
When I put a pthread\_self() call inside the callback function (Thisclass::FunctionName) it appears to have the same thread id as the thread where theTimer is created itself! (Very confused by this)
Also: What does that priority list above mean? What is a writable event vs a readable event vs a timer event?
Any explanation of the use of select() in this scenario is also appreciated.
Thanks! | This looks like a simple wrapper around `select(2)`. The class keeps a list of callbacks, I guess separate for read, write, and timer expiration. Then there's something like a `dispatch` or `wait` call somewhere there that packs given file descriptors into sets, calculates minimum timeout, and invokes `select` with these arguments. When `select` returns, the wrapper probably goes over read set first, invoking read callback, then write set, then looks if any of the timers have expired and invokes those callbacks. This all might happen on the same thread, or on separate threads depending on the implementation of the wrapper.
You should read up on `select` and `poll` - they are very handy.
The general term is **IO demultiplexing**. | A readable event means that data is available for reading on a particular file descriptor without blocking, and a writable event means that you can write to a particular file descriptor without blocking. These are most often used with sockets and pipes. See the [`select()`](http://www.opengroup.org/onlinepubs/9699919799/functions/pselect.html) manual page for details on these.
A timer event means that a previously created timer has expired. If the library is using `select()` or `poll()`, the library itself has to keep track of timers since these functions accept a single timeout. The library must calculate the time remaining until the first timer expires, and use that for the timeout parameter. Another approach is to use [`timer_create()`](http://www.opengroup.org/onlinepubs/9699919799/functions/timer_create.html), or an older variant like [`setitimer()`](http://www.opengroup.org/onlinepubs/9699919799/functions/setitimer.html) or [`alarm()`](http://www.opengroup.org/onlinepubs/9699919799/functions/alarm.html) to receive notification via a signal.
You can determine which mechanism is being used at the OS layer using a tool like [`strace`](http://linux.die.net/man/1/strace) (Linux) or [`truss`](http://docs.oracle.com/cd/E23824_01/html/821-1461/truss-1.html#scrolltoc) (Solaris). These tools trace the actual system calls that are being made by the program. | C++ Timers in Unix | [
"",
"c++",
"unix",
"timer",
""
] |
I'd like to write to file in a processor smart card that accepts APDU commands.
Do you know any examples in C# or smartcard sdk?
Has anyone used <http://code.google.com/p/pcsc-sharp/>? | First, you need to create a managed wrapper for WinScard dll. WinScard is Microsoft's implementation of PC/SC. You will need this dll to send and receive APDUs from the card.
Next, you need to know what is the OS of the smart card you are going to use. You must have the API documentation of the smart card. This will help you construct the correct APDUs for writing a file. In the smart card world, there is no single, generic way to create a file. It all depends on the card's OS. | Subsembly is what we use. We don't do much with it, but it should get you started.
<http://www.smartcard-api.com/> | How to write files on smart cards in C# | [
"",
"c#",
"smartcard",
"apdu",
""
] |
I'm a relative novice at C# and am thoroughly stuck! For a school assignment I need to make a sliding puzzle where numbered tiles are to be rearranged in order by using a blank space, i.e.
```
[1] [2] [3]
[4] [5] [6]
[7] [8] [ ]
```
I have no idea where to start. | Regardless on how the application will be used (Winforms UI, Console, Web or whatever) you need to focus on how to build such an application. So start by considering what you will need to do:
You'll need
* an engine that manages the state of the puzzle
+ the engine must be able to reset the puzzle
+ the engine must be able to scramble the puzzle without going into an unsolvable state
+ the engine must be able to perform moves
+ the engine must be able to detect whether the puzzle is solved
* a user interface (Console, Web or Desktop) that
+ fetches the state from the engine and displays it
+ offers the user to start over
+ offers the user to perform a move
+ shows wheter the puzzle is solved (and congratulates the user if so).
At beginner level I'd start with the engine. You will want to write a C# class that holds the data. Consult a C# tutorial on info how to use the language, I'll focus on the problem here:
The enigne needs to hold the puzzle. We have 9 fields and 8 tiles. So we might just use a fixed array of length 9. Each entry in the array is a number that describes a tile. 1 is tile one, 2 is tile two and so on up to tile 8. We use 0 to describe the empty tile.
Then you need to implement methods for the moves. At any time you can try to move tile into the empty slot from up, right, bottom or left. Which one is the empty tile? The entry in our array that contains 0.
So let's write four methods up, down, left, right to implement the moves. Let's focus on "up" that moves a tile from the upper slot into the empty slot. We can assume our array maps to the puzzle as follows:
0 1 2
3 4 5
6 7 8
So if the array contains "7 6 5 3 0 1 2 4 8" the puzzle would look
7 6 5
3 \_ 1
2 4 8
The up methods now needs to find the "0" in the array and exchange it with the value in the row above:
If the "0" is in the upper row (array index 0, index 1 or index 2) there is no upper row and "up" throws an exception. It can't work.
If "0" is on another index i the index "above" i will be index i-3. So we exchange the values of index i and index i-3 in the array.
You'd implement the "left", "right" and "bottom" methods similarily. Have a look at so called "unit-testing" software on how to write test cases for your software. ([Nunit](http://www.nunit.org), [MBUnit](http://www.mbunit.com))
At last build a method or property in your puzzle class that checks whether the contents of the array are in the correct order "1 2 3 4 5 6 7 8 0" when it is solved.
Now you have a puzzle class that implements the logic.
As a last (but nevertheless big step) you now need to read a Winforms or WPF tutorial on how to build a UI. But now you SHOULD have learned enough about C# to find & read a tutorial and follow it through. | I'd approach this using Domain-Driven Design. Concentrate on designing some classes which represent the entities in the problem domain - so I'd probably have Puzzle, Tile and EmptySpace classes, and maybe a Wall or Block class. When you can push the tiles around using unit tests then look at putting a GUI on the top. | Sliding Puzzle assignment | [
"",
"c#",
""
] |
I'd like for a single console application to spawn other console windows and output to different ones at different times inside of a C# console application. Preferably within one console application, I spawn some other consoles, write to them, and close them during the finally block of the original console application.
What's the ideal way to do this in C#? | I don't believe you can do this with a regular console application. The closest you could come would be to create a your own form in WinForms/WPF which behaved in roughly the same was as a normal console window.
I *suppose* you could spawn extra processes which each had their own console, and write to them via network connections or named pipes etc... it would be pretty ugly though. | You can do this with Auto/Manual [EventWaitHandles](http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.aspx) in C# combined with countless other techniques. However, you should probably step back and see what you are trying to accomplish and see if a winform app would be a better fit. Maybe post more details and ask for ideas. | c# console application sub windows | [
"",
"c#",
""
] |
Almost every article I read told me that you can't have **chdir** in Java. The accepted answer to [this question](https://stackoverflow.com/questions/840190/changing-the-current-working-directory-in-java) says you can't do it in Java.
However, here's some of the stuff I tried:
```
geo@codebox:~$ java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode, sharing)
```
Here's a test class I'm using:
```
import java.io.*;
public class Ch {
public static void main(String[] args) {
System.out.println(new File(".").getAbsolutePath());
System.setProperty("user.dir","/media");
System.out.println(new File(".").getAbsolutePath());
}
}
```
```
geo@codebox:~$ pwd
/home/geo
geo@codebox:~$ java Ch
/home/geo/.
/media/.
```
Please explain why this worked. Can I use this from now on and expect it to work the same way on all platforms? | Just because `new File(".")` gives the desired answer doesn't mean it's doing what you want it to.
For example, try:
```
new FileOutputStream("foo.txt").close();
```
Where does that end up? On my Windows box, even though `new File(".").getAbsolutePath()` moves around based on `user.dir`, `foo.txt` is always created in the original working directory. It strikes me that setting `user.dir` such that `new File(".")` *doesn't* refer to the current working directory is just asking for trouble. | Quote:
> The user.dir property is set at VM startup to be the working directory. You should not change this property or set it on the command-line. If you do, then you will see some inconsistent behaviour as there places in the implementation that assumes that the user.dir is the working directory and that it doesn't change during the lifetime of the VM.
The discussion is [here](http://www.java.net/node/654577) | Why is the user.dir system property working in Java? | [
"",
"java",
"filesystems",
"chdir",
""
] |
I have several strongly typed datasets throughout my application. Writing methods to update the data is getting tedious as each has several tables. I want to create one generic function that I can update all of the tables easily. I don't mind if I have to create one of these for each DataSet but if one function could handle all of them, that would be amazing!
There will be any number of new, updated, or deleted records and each row should be flagged properly. This function should just be handling the actual saving. Here is what I have so far:
```
private bool SaveData(object oTableAdaptor, object ds)
{
try
{
Type oType = oTableAdaptor.GetType();
MethodInfo[] oMethodInfoArray = oType.GetMethods();
foreach (MethodInfo oMI in oMethodInfoArray)
{
if (oMI.Name == "Update")
{
ParameterInfo[] oParamaterInfoArray = oMI.GetParameters();
foreach (ParameterInfo oPI in oParamaterInfoArray)
{
Type DsType = null;
if (oPI.ParameterType.Name == "NameOfDataSet")
{
DsType = typeof(MyDataSet);
// get a list of the changed tables???
}
if (((DataSet)ds).HasChanges() == true)
{
if (oPI.ParameterType == DsType)
{
object[] values = { ds };
try
{
oMI.Invoke(oTableAdaptor, values);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(oTableAdaptor.GetType().Name + Environment.NewLine + ex.Message);
}
}
}
}
}
}
}
catch (Exception Exp)
{
System.Diagnostics.Debug.WriteLine(Exp.Message);
if (Exp.InnerException != null) System.Diagnostics.Debug.WriteLine(Exp.InnerException.Message);
return false;
}
return true;
```
I have adapted this from another bit of code another developer has in a different application. The main difference thus far is he is passing in an array (of type object) of dataadaptors and has each of the three DataSets (globally instantiated) set up as individual if blocks inside the foreach (ParameterInfo oPI in oParamaterInfoArray) block (where my 'NameOfDataSet' would be one of the datasets)
Can anybody give me a little push (or a shove?) in the direction of finishing this function up? I know I am right there but it feels like I am over looking something. This code does compile without error. | Can't you just treat them as their base classes, DbDataAdapter, DataSet and DataTable?
You can access the table by name by doing DataSet.Tables["name"]. This returns a DataTable object that you can pass to the DbDataAdapters update method.
Or if your TableAdapter updates all the tables in your DataSet then you can pass the entire DataSet to the update method directly.
With that said I would suggest you rethink the use of typed data sets if you have the chance to do so. In my experience they end up being a hassle to maintain and use and have found the general DataTable, DataSet and DbDataAdapter classes to be much easier to use directly. | I've been using this. It would need some optimizations though. This also takes care of updating the tables in correct order depending on the relations in dataset (in case there are no self-references, which can be handled by sorting the rows, but for simplicity I'm not posting it here).
```
public static void Save(DataSet data, SqlConnection connection)
{
/// Dictionary for associating adapters to tables.
Dictionary<DataTable, SqlDataAdapter> adapters = new Dictionary<DataTable, SqlDataAdapter>();
foreach (DataTable table in data.Tables)
{
/// Find the table adapter using Reflection.
Type adapterType = GetTableAdapterType(table);
SqlDataAdapter adapter = SetupTableAdapter(adapterType, connection, validityEnd);
adapters.Add(table, adapter);
}
/// Save the data.
Save(data, adapters);
}
static Type GetTableAdapterType(DataTable table)
{
/// Find the adapter type for the table using the namespace conventions generated by dataset code generator.
string nameSpace = table.GetType().Namespace;
string adapterTypeName = nameSpace + "." + table.DataSet.DataSetName + "TableAdapters." + table.TableName + "TableAdapter";
Type adapterType = Type.GetType(adapterTypeName);
return adapterType;
}
static SqlDataAdapter SetupTableAdapter(Type adapterType, SqlConnection connection)
{
/// Set connection to TableAdapter and extract SqlDataAdapter (which is private anyway).
object adapterObj = Activator.CreateInstance(adapterType);
SqlDataAdapter sqlAdapter = (SqlDataAdapter)GetPropertyValue(adapterType, adapterObj, "Adapter");
SetPropertyValue(adapterType, adapterObj, "Connection", connection);
return sqlAdapter;
}
static object GetPropertyValue(Type type, object instance, string propertyName)
{
return type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance).GetValue(instance, null);
}
static void SetPropertyValue(Type type, object instance, string propertyName, object propertyValue)
{
type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance).SetValue(instance, propertyValue, null);
}
static void Save(DataSet data, Dictionary<DataTable, SqlDataAdapter> adapters)
{
if (data == null)
throw new ArgumentNullException("data");
if (adapters == null)
throw new ArgumentNullException("adapters");
Dictionary<DataTable, bool> procesedTables = new Dictionary<DataTable, bool>();
List<DataTable> sortedTables = new List<DataTable>();
while (true)
{
DataTable rootTable = GetRootTable(data, procesedTables);
if (rootTable == null)
break;
sortedTables.Add(rootTable);
}
/// Updating Deleted rows in Child -> Parent order.
for (int i = sortedTables.Count - 1; i >= 0; i--)
{
Update(adapters, sortedTables[i], DataViewRowState.Deleted);
}
/// Updating Added / Modified rows in Parent -> Child order.
for (int i = 0; i < sortedTables.Count; i++)
{
Update(adapters, sortedTables[i], DataViewRowState.Added | DataViewRowState.ModifiedCurrent);
}
}
static void Update(Dictionary<DataTable, SqlDataAdapter> adapters, DataTable table, DataViewRowState states)
{
SqlDataAdapter adapter = null;
if (adapters.ContainsKey(table))
adapter = adapters[table];
if (adapter != null)
{
DataRow[] rowsToUpdate = table.Select("", "", states);
if (rowsToUpdate.Length > 0)
adapter.Update(rowsToUpdate);
}
}
static DataTable GetRootTable(DataSet data, Dictionary<DataTable, bool> procesedTables)
{
foreach (DataTable table in data.Tables)
{
if (!procesedTables.ContainsKey(table))
{
if (IsRootTable(table, procesedTables))
{
procesedTables.Add(table, false);
return table;
}
}
}
return null;
}
static bool IsRootTable(DataTable table, Dictionary<DataTable, bool> procesedTables)
{
foreach (DataRelation relation in table.ParentRelations)
{
DataTable parentTable = relation.ParentTable;
if (parentTable != table && !procesedTables.ContainsKey(parentTable))
return false;
}
return true;
}
``` | Generic DataTable & TableAdaptor updates with Reflection (C#) | [
"",
"c#",
"reflection",
"datatable",
"generics",
"tableadapter",
""
] |
How can I best prevent these libraries from flooding my own apps log4j bus? I do not want to set everything to ERROR, but at this rate the vendor library is flooding up the log file at a rate of about a gig/day. I do not want it to log anything to this file... | As suggested by [Jon Skeet´s answer](https://stackoverflow.com/questions/1235229/junk-from-vendor-libraries-flooding-log4j/1235247#1235247), you should configure log4j to ignore the classes from the vendor library. Usually there is a file named `log4j.xml` that one can put the package names and the threshold category to print like this:
```
<category name="httpclient.wire">
<priority value="INFO"/>
</category>
<category name="org.apache.commons.httpclient">
<priority value="WARN"/>
</category>
<category name="org.hibernate">
<priority value="DEBUG"/>
</category>
<category name="net.sf.jasperreports">
<priority value="ERROR"/>
</category>
```
Take a look at [the manual](http://logging.apache.org/log4j/1.2/manual.html) for details. | Is the vendor using categories reasonably? If so, set *just their root category* to ERROR and leave everything else as normal. That way you should be able to filter out their non-error messages but still see your own info/debug/etc.
That's most of the point of categories :) | Junk from vendor libraries flooding log4j | [
"",
"java",
"logging",
"jakarta-ee",
"log4j",
""
] |
I already have quite a bit of js on my site, so I want to have a function that grabs the domain name of the current url as efficiently as possible.
Example:
input : <https://stackoverflow.com/questions/ask>
result : stackoverflow.com
input : <http://test.stackoverflow.com/questions/ask>
result : test.stackoverflow.com
I guess the best way to start is with document.location, but I'm at odds what to do from there. | Try `document.location.hostname` | It depends on what you are going to use the domain name for and specifically whether or not you care about a specified port number. If you URL includes a port number like:
<http://stackoverflow.com:80/question/ask>
`document.location.hostname` will return "stackoverflow.com"
while, `document.location.host` will return "stackoverflow.com:80"
Which is better depends on your use case.
If you happen to be examining the domain name to know whether or not a script will be able to access a script/DOM in another frame/window, then note that the port number is significant. Browsers will not permit cross domain script access across frames/windows. For the purpose of comparing domain names, different port numbers can be considered different domains. | Fastest way to grab domain/host name using javascript | [
"",
"javascript",
""
] |
I have the following table:
```
tickername | tickerbbname | tickertype
------------+---------------+------------
USDZAR | USDZAR Curncy | C
EURCZK | EURCZK Curncy | C
EURPLN | EURPLN Curncy | C
USDBRL | USDBRL Curncy | C
USDTRY | USDTRY Curncy | C
EURHUF | EURHUF Curncy | C
USDRUB | USDRUB Curncy | C
```
I don't want there to ever be more than one column for any given `tickername`/`tickerbbname` pair. I've already created the table and have lots of data in it (which I have already ensured meets the unique criteria). As it gets larger, though, room for error creeps in.
Is there any way to add a `UNIQUE` constraint at this point? | `psql`'s inline help:
```
\h ALTER TABLE
```
Also documented in the [postgres docs](https://www.postgresql.org/docs/current/ddl-alter.html#DDL-ALTER-ADDING-A-CONSTRAINT) (an excellent resource, plus easy to read, too).
```
ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);
``` | Yes, you can. But if you have non-unique entries in your table, it will fail. Here is the how to add a unique constraint to your table in PostgreSQL 9.x:
```
CREATE UNIQUE INDEX constraint_name ON table_name (columns);
``` | Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created? | [
"",
"sql",
"database",
"postgresql",
"indexing",
"unique-constraint",
""
] |
Is there anyway for me to make it work so anyone who presses F5 or any refresh button will be moved to a different page, instead of it refreshing the page the user wants?
Something like :
```
If (refresh){
goto "link to hopme page"
}
```
If not is there anyway for me to not allow refreshing on a certain page?
I have some people that are are just refreshing non stop and it is killing my bandwidth. It is a game site so I don't want to ban the ip's. | ```
session_start();
if($_SESSION['hasbeenhere'] == 1)
{
// Page refreshed
}
else
{
$_SESSION['hasbeenhere'] = 1;
}
```
If the person doesn't have cookies enabled, this will fail. If someone goes to another page and comes back, it will shown as refreshed.
Overall, you can't do this in a way that is surefire, but this is 1 way to prevent someone from seeing the same page twice.
Because of your comment, if you want to stop people from pressing F5 200 times, try this.
```
$page = $_SERVER['REQUEST_URI'];
// Defaults
if(!isset($_SESSION[$page]['count']))
{
$_SESSION[$page]['count'] = 1;
$_SESSION[$page]['first_hit'] = time();
$_SESSION[$page]['banned'] = false;
}
else
{
$_SESSION[$page]['count']++; // Increase the counter
}
// If person is banned, end script
if($_SESSION[$page]['banned'] == true)
{
die();
}
if($_SESSION[$page]['first_hit'] < time() - 30)
{
$_SESSION[$page]['count'] = 1; // Reset every 30 seconds
}
if($_SESSION[$page]['count'] > 100)
{
$_SESSION[$page]['banned'] = true;
// Ban if they hit over 100 times in 30 seconds.
}
``` | Perhaps you should be focusing your effort instead on reducing the bandwidth your page is using. Explore the areas of image compression, page optimization and caching. | Stop people from refreshing the page | [
"",
"php",
"refresh",
"html",
""
] |
In Java is there a way to find out if first character of a string is a number?
One way is
```
string.startsWith("1")
```
and do the above all the way till 9, but that seems very inefficient. | ```
Character.isDigit(string.charAt(0))
```
Note that [this will allow *any* Unicode digit](http://java.sun.com/javase/6/docs/api/java/lang/Character.html#isDigit(char)), not just 0-9. You might prefer:
```
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
```
Or the slower regex solutions:
```
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
```
However, with any of these methods, you must first be sure that the string isn't empty. If it is, `charAt(0)` and `substring(0, 1)` will throw a `StringIndexOutOfBoundsException`. `startsWith` does not have this problem.
To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
```
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
```
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable. | Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:
```
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
``` | How do I find out if first character of a string is a number? | [
"",
"java",
"string",
""
] |
Im trying to connect a "Information" object to many "Customers" (see code below)
When one Information object is updated, I want to send email to each Customer that is connected to the Information.
However, when I log the sold\_to field that the signal recieves I always get what the data is like BEFORE the save.
I'm guessing this is because its ManyToManyField and the data is stored in a separate table, but shouldn't the post\_save signal be called after all relations have been updated?
Anyone got a suggestion for a solution?
```
class Customer
name = models.CharField(max_length=200)
category = models.ManyToManyField('Category',symmetrical=False)
contact = models.EmailField()
class Information
name = models.CharField(max_length=200)
email = models.EmailField(max_length=200)
mod_date = models.DateTimeField(auto_now=True)
sold_to = models.ManyToManyField(Customer, null=True, blank=True)
def send_admin_email(sender, instance, signal, *args, **kwargs):
from myapp import settings
for cust in instance.sold_to.all():
settings.debug(cust.name)
post_save.connect(send_admin_email, sender=Information)
```
Edit: apollo13 in #django alerted me to this:
"Related items (the things being saved into the many-to-many relation)
are not saved as part of a model's save method, as you have discovered." - <http://groups.google.com/group/django-users/msg/2b734c153537f970>
But since its from Jul 9 2006 I really really hope there is a solution for this. | There's an open ticket for the issue you are facing [here](http://code.djangoproject.com/ticket/5390). You could either keep an eye on that for when it makes it into a release, or you could try applying the patch that it provides and see if that helps. | This is my solution, after applying the patch from code.djangoproject.com mentioned above.
Added this in models.py:
```
from django.db.models.signals import m2m_changed
m2m_changed.connect(send_admin_email, sender=Information)
```
And the send\_admin\_email function:
```
def send_customer_email(sender, instance, action, model, field_name, reverse, objects, **kwargs):
if ("add" == action):
# do stuff
``` | Why does Django post_save signal give me pre_save data? | [
"",
"python",
"django",
"django-signals",
""
] |
I was looking at some sample code and in it they used a `ListDictionary` object to store a small amount of data (around 5-10 objects or so, but this number could change over time). The only issue I have with using this class is that, unlike everything else I've been doing, it's not generic. This means, and correct me if I'm wrong here, that every time I get an object out of here or enumerate over it that there's casting going on. Is there enough overhead in the larger `Dictionary<T>` object to justify the overhead of a non-generic `ListDictionary`?
The code that will be using this object will be enumerated over on each page load which I'm guessing is why the `ListDictionary` class was used over one of the other alternatives. This is also why I would like the most performance out of this list of data. | Unfortunately there is no generic equivalent of ListDictionary.
However it shouldn't be terribly difficult to implement one. ListDictionary essentially works by keeping a linked list of Key/Value pairs and iterating over them for lookup operations. You could build a `ListDictionary<TKey,TValue>` by wrapping a `LinkedList<T>` with some very simple LINQ expressions.
For example
```
public class LinkedDictionary<TKey,TValue> {
private LinkedList<KeyValuePair<TKey,TValue>> _list = new LinkedList<KeyValuePair<TKey,TValue>>();
private IEqualityComparer<TKey> _comp = EqualityComparer<TKey>.Default;
public void Add(TKey key, TValue value) {
_list.Add(new KeyValuePair<TKey,TValue>(key,value));
}
public TValue Get(TKey key) {
return _list.Where(x => _comp.Equals(x.Key,key)).First().Value;
}
...
}
``` | There is no generic equivalent of `ListDictionary`.
If your use of this small dictionary isn't dominated by `Add` and `Remove`, you might consider [`SortedList<TKey, TValue>`](https://msdn.microsoft.com/en-us/library/ms132319%28v=vs.110%29.aspx) which, despite its name, implements `IDictionary<TKey, TValue>`. Unlike `ListDictionary` which is backed by a singly-linked list, `SortedList` is backed by an array of sorted keys and an array values. | Is there a generic alternative to the ListDictionary class? | [
"",
"c#",
".net",
"performance",
"generics",
""
] |
I am confused on DataTable.DefaultView.Sort. Here is the segment of the code I want to use it in.
```
actionLogDT.DefaultView.Sort = "StartDate";
foreach (CustomerService.ActionLogStartEndRow logRow in actionLogDT)
{
// code here
}
```
The samples I have seen don't use the foreach loop and thus is confusing me on how to process this. It isn't sorting as I thought it should be.
I see that .DefaultView returns a view, and .Table gives a compile error. | I had to take a slightly different approach. [This post](http://forums.asp.net/p/425620/425629.aspx) was the closest I could find to get my code to work. Here is the working result:
```
actionLogDT.DefaultView.Sort = "StartDate";
DataView dv = actionLogDT.DefaultView;
foreach (DataRowView logRow in dv) { . . . }
```
From there I just have to cast the value back into it's proper type.
```
(string)logRow["Status"].ToString()
``` | ```
actionLogDT.DefaultView.Sort = "StartDate";
actionLogDT = actionLogDT.DefaultView.ToTable();
``` | DataTable.DefaultView.Sort Doesn't Sort | [
"",
"c#",
"datatable",
"sorting",
""
] |
I'm using PDO and MySQL, for some reason when getting values from the database that are int type, the PDOStatement is returning a string representation of the number and not a value of numeric type. How do I prevent this from happening?
I noticed there is a attribute of the PDO class: `PDO::ATTR_STRINGIFY_FETCHES` that is supposed to take care of this but, when trying to modify it, it throws an error saying the attribute is not valid for MySQL driver.
Is it normal to get strings instead of numbers when consulting a database? | I don't think having "numbers" can be done in PHP 5.2 **:-(**
In PHP 5.3, it becomes possible, if I remember correctly, when you are using the new *(new as in PHP >= 5.3)* mysql**nd** *(MySQL Native Driver)* driver.
Well, after more digging through my bookmarks I found this article about mysqlnd : [`PDO_MYSQLND: The new features of PDO_MYSQL in PHP 5.3`](http://blog.ulf-wendel.de/2008/pdo_mysqlnd-the-new-features-of-pdo_mysql/)
It says this (quote) :
> **Advantages of using mysqlnd for PDO**
>
> mysqlnd returns native data types when
> using Server-side Prepared Statements,
> for example an INT column is returned
> as an integer variable not as a
> string. That means fewer data
> conversions internally.
But this is PHP 5.3 only (provided your version of PHP 5.3 is compiled with mysqlnd (*and not old libmysql)*), and seems to only be the case for prepared statements :-(
Sorry...
A solution would be to have, on the PHP-side, a mapping-system *(like an ORM -- see [Doctrine](http://www.doctrine-project.org/) ; just as an example of ORM : I don't know if it does what you're asking)* to convert results coming from the DB to PHP datatypes...
And yes, this is bad if you want to use operators like `===` and `!==`, which are type-sensitive... | To answer your last question first, "yes," unfortunately it's normal to receive numbers as strings. As the manual quoted by Pascal says, mysqlnd (PHP 5.3) will return native data types from prepared statements, provided you turn off the prepared statement emulation from PDO.
```
new PDO($dsn, $user, $pass, array(
PDO::ATTR_EMULATE_PREPARES => false
))
```
PDO::ATTR\_STRINGIFY\_FETCHES is unrelated to MySQL.
If you look at the bright side, it's good practice to use prepared statements anyway, so... ;) | How to get numeric types from MySQL using PDO? | [
"",
"php",
"mysql",
"pdo",
""
] |
So, I'm very tempted to rewrite my application using a php framework, as I think it'll make it easier for folks to get involved, as well as improving the design of the app.
CakePHP looks like the best of the PHP web frameworks. Does anyone have any experiences of it? What are the caveats I should consider going from handcoded PHP to using a framework? | Not depending on the framework you'll chose, the first thing you have to know is that :
* it'll take some time for you to know it
* you'll do crapping things, during that time ^^
* so, take into account the fact it'll take some time before you are fully operational **:-)**
I think those points are the most under-estimated points : using a framework takes not much time... Using it well and to the full extend of its abilities takes... Well, a couple of months, maybe... Which means, when you are at the end of your project you'll say "I should rewrite that with all the stuff I learned while re-writing it the first time" :-D
What it means is : **learn what the framework can do, learn how to use it, and use it for a while on small applications, before starting rewriting your big one !**
Then, there is probably no "best framework" : one framework may be very well suited for one project, and another one may be best for a second, different project.
I've never worked with CakePHP ; I really like [Zend Framework](http://framework.zend.com/). But that is a personal opinion, and O know people who really like [symfony](http://www.symfony-project.org/) ; they are not wrong : symfony is great -- and I am not wrong either ^^
Still, we sometimes agree on some things ; like the fact that [Doctrine](http://www.doctrine-project.org/) (default ORM layer of symfony) is really great stuff, and we tend to use in both symfony and ZF-based projects...
If motivated, you can take a look at many posts on SO, about frameworks... Here are a couple of those :
* [What PHP framework would you choose for a new application and why?](https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why)
* [Is Symfony a good framework to learn?](https://stackoverflow.com/questions/133701/is-symfony-a-good-framework-to-learn)
* [What, in your mind, is the best PHP MVC framework?](https://stackoverflow.com/questions/75882/what-in-your-mind-is-the-best-php-mvc-framework)
* [Is Symfony a better choice than Zend for a web development shop (10+) because it is a full stack framework?](https://stackoverflow.com/questions/392980/is-symfony-a-better-choice-than-zend-for-a-web-development-shop-10-because-it)
* [Best PHP framework for an experienced PHP developer?](https://stackoverflow.com/questions/257212/best-php-framework-for-an-experienced-php-developer)
Good luck with those ^^
*("Which framework" is a quite pationnating -- and subjective -- question ^^ )* | CakePHP has it's good parts but there is no "best" framework. [Here's a thread](https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why) with some clues about what's good in most popular PHP frameworks.
If you never used MVC frameworks before (and Cake is MVC framework) I think you should first familiaze yourself with [MVC architecture](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller). | Rewriting a php app in CakePHP | [
"",
"php",
"cakephp",
""
] |
Consider the following code in a class called Worker
```
FileSystemWatcher watcher = new FileSystemWatcher();
public void Run()
{
watcher.Path = @"c:\queue";
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.EnableRaisingEvents = true;
}
```
Now here's what I would like to do wih the Worker, but obviouly this doesn't fly.
```
Worker worker = new Worker();
Thread thread = new Thread(worker.Run);
thread.Start();
Console.ReadLine(); // something else more interesting would go here.
```
The reason being that the Run method ends rather than going into some sort of event loop. How do I get an event loop going. (I think I"m looking for something like Application.Run) | Not tested, but your "event" loop, if you're wanting it to run on the thread, would look something like this:
```
private bool running = true;
private AutoResetEvent waiter = new AutoResetEvent(false);
public void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher("C:\\");
FileSystemEventArgs changes = null;
watcher.Changed +=
(object sender, FileSystemEventArgs e) => {
changes = e;
waiter.Set();
};
watcher.EnableRaisingEvents = true;
while (running)
{
waiter.WaitOne();
if (!running) break;
Console.WriteLine("Path: {0}, Type: {1}",
changes.FullPath, changes.ChangeType);
}
Console.WriteLine("Thread complete");
}
public void Stop()
{
running = false;
waiter.Set();
}
```
You would place this code in a class and run it on a separate thread (if you wish). If you want to have your main thread wait on the thread you create finishing (although why bother creating a thread in that case?) then you can use the [Thread.Join](http://www.google.com/search?client=opera&rls=en&q=Thread.Join&sourceid=opera&ie=utf-8&oe=utf-8) method. | Pulled from [MSDN](http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx)
```
Worker worker = new Worker();
Thread thread = new ThreadStart(worker.Run);
thread.Start();
// Not sure if you need this while
while (!oThread.IsAlive);
oThread.Join();
Console.ReadLine();
``` | How to wait on events on a second thread | [
"",
"c#",
"multithreading",
"events",
""
] |
Suppose I have some serially numbered items that are 1-n units wide, that need to be displayed in rows. Each row is m units wide. I need some pseudo-code that will output the rows, for me, so that the m-width limit is kept. This is not a knapsack problem, as the items must remain in serial number order - empty spaces at the end of rows are fine.
I've been chasing my tail over this, partly because I need it in both PHP and jQuery/javascript, hence the request for pseudo-code.... | ```
while (!items.isEmpty()) {
rowRemain = m;
rowContents = [];
while (!items.isEmpty() && rowRemain > items[0].width) {
i = items.shift();
rowRemain -= i.width
rowContents.push(i);
}
rows.push(rowContents);
}
```
Running time is Θ(number of items) | Modulus is your friend. I would do something like:
```
$items = array(/* Your list of stuff */);
$count = 0;
$maxUnitsPerRow = 4; // Your "m" above
while ($item = $items[$count]) {
if ($count % $maxUnitsPerRow == 0) {
$row = new row();
}
$row->addItemToRow($item);
$count++;
}
``` | Pseudo-code for shelf-stacking | [
"",
"php",
"jquery",
"algorithm",
"pseudocode",
""
] |
I'm writing a Java program which uses a lot of CPU because of the nature of what it does. However, lots of it can run in parallel, and I have made my program multi-threaded. When I run it, it only seems to use one CPU until it needs more then it uses another CPU - is there anything I can do in Java to force different threads to run on different cores/CPUs? | > When I run it, it only seems to use
> one CPU until it needs more then it
> uses another CPU - is there anything I
> can do in Java to force different
> threads to run on different
> cores/CPUs?
I interpret this part of your question as meaning that you have already addressed the problem of making your application multi-thread capable. And despite that, it doesn't immediately start using multiple cores.
The answer to "is there any way to force ..." is (AFAIK) not directly. Your JVM and/or the host OS decide how many 'native' threads to use, and how those threads are mapped to physical processors. You do have some options for tuning. For example, I found [this page](http://java.sun.com/docs/hotspot/threads/threads.html) which talks about how to tune Java threading on Solaris. And [this page](http://java.sun.com/docs/hotspot/HotSpotFAQ.html#perf_scaling) talks about other things that can slow down a multi-threaded application. | There are two basic ways to multi-thread in Java. Each logical task you create with these methods should run on a fresh core when needed and available.
**Method one:** define a Runnable or Thread object (which can take a Runnable in the constructor) and start it running with the Thread.start() method. It will execute on whatever core the OS gives it -- generally the less loaded one.
Tutorial: [Defining and Starting Threads](http://java.sun.com/docs/books/tutorial/essential/concurrency/runthread.html)
**Method two:** define objects implementing the Runnable (if they don't return values) or Callable (if they do) interface, which contain your processing code. Pass these as tasks to an ExecutorService from the java.util.concurrent package. The java.util.concurrent.Executors class has a bunch of methods to create standard, useful kinds of ExecutorServices. [Link](http://java.sun.com/docs/books/tutorial/essential/concurrency/exinter.html) to Executors tutorial.
From personal experience, the Executors fixed & cached thread pools are very good, although you'll want to tweak thread counts. Runtime.getRuntime().availableProcessors() can be used at run-time to count available cores. You'll need to shut down thread pools when your application is done, otherwise the application won't exit because the ThreadPool threads stay running.
**Getting good multicore performance is sometimes tricky, and full of gotchas:**
* Disk I/O slows down a LOT when run in
parallel. Only one thread should do disk read/write at a time.
* Synchronization of objects provides safety to multi-threaded operations, but slows down work.
* If tasks are too
trivial (small work bits, execute
fast) the overhead of managing them
in an ExecutorService costs more than
you gain from multiple cores.
* Creating new Thread objects is slow. The ExecutorServices will try to re-use existing threads if possible.
* All sorts of crazy stuff can happen when multiple threads work on something. Keep your system simple and try to make tasks logically distinct and non-interacting.
One other problem: controlling work is hard! A good practice is to have one manager thread that creates and submits tasks, and then a couple working threads with work queues (using an ExecutorService).
I'm just touching on key points here -- multithreaded programming is considered one of the hardest programming subjects by many experts. It's non-intuitive, complex, and the abstractions are often weak.
---
**Edit -- Example using ExecutorService:**
```
public class TaskThreader {
class DoStuff implements Callable {
Object in;
public Object call(){
in = doStep1(in);
in = doStep2(in);
in = doStep3(in);
return in;
}
public DoStuff(Object input){
in = input;
}
}
public abstract Object doStep1(Object input);
public abstract Object doStep2(Object input);
public abstract Object doStep3(Object input);
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
ArrayList<Callable> tasks = new ArrayList<Callable>();
for(Object input : inputs){
tasks.add(new DoStuff(input));
}
List<Future> results = exec.invokeAll(tasks);
exec.shutdown();
for(Future f : results) {
write(f.get());
}
}
}
``` | Forcing multiple threads to use multiple CPUs when they are available | [
"",
"java",
"concurrency",
"multithreading",
"multicore",
""
] |
I have a page which has a style like this in a css file:
```
body
{
background: #000000 url(images/back_all.gif) repeat-x top;
font: 12px Tahoma, Arial, Helvetica, sans-serif;
color: #666666;
}
```
and I have either a javascript which is loaded after window.onload and causes page to be expand vertically and so the rest of my page will become black.
how can I apply the background image to my page again after the javascript code is completed? | **jQuery:**
`$('body').css('backgroundImage', 'url(something.gif)');`
---
**Non-jQuery:**
Assign Body an ID: `<body id="the_body">`
`document.getElementById('the_body').style.backgroundImage = "something.gif"`
or as John mentioned
`document.body.style.backgroundImage = "something.gif";`
and furthermore, a T POPs Mentioned, make sure it goes at the end:
```
<html>
<body>
..... Data ........
<script type="text/javascript">
.... Code ........
</script>
</body>
</html>
``` | i think inserting this at the end of a document could work:
```
<script type="text/javascript">
var obj= document.getElementByName("body");
obj.style.background = "#000000 url(images/myimage.gif) repeat-x top";
// change color, image and settings
</script>
```
regards | how to change html background dynamically | [
"",
"javascript",
"html",
""
] |
I am creating a file like so
```
try {
File file = new File(workingDir, obj.getName() + ".xls");
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
```
And I am getting
```
java.io.FileNotFoundException: ..\a\relative\path\obj_name.xls (The parameter is incorrect)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
```
What does "the parameter is incorrect" mean? The pathname I validated exists; shouldn't it just create the file name? This is on a windows machine. The code works without this error on unix based systems.
---
**Update**
Verified that the file exists that the output stream is attempting to write to. Also verified that the file is writable. After much fussing, I removed the actual path and just passed in the file name (not desired) and that works. So the issue has something to do with the path. Do I need to escape the characters in the path? | This looks like a [reported bug](https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6262148) on Windows machines.
Under normal situations, something like a path that has a colon (:) in it which does not refer to a drive letter would cause this message. | It appears to be an issue with the path you're using. Try using file.getPath() before you open it to debug what is going on with your path.
```
File file = new File(workingDir, obj.getName() + ".xls");
System.out.println("Path="+file.getPath());
outputStream = new FileOutputStream(file);
``` | Typically, what does it mean when java returns a "The parameter is incorrect" | [
"",
"java",
"filenotfoundexception",
""
] |
I am working on a small PHP website. I need a MySql database access class that is easy to configure and work with.
Does not need to be a full framework, I only need a max. few classes. | [ADODb](http://adodb.sourceforge.net/) is pretty easy to work with and worth considering. Some illustrative samples:
```
//connect
$dsn = 'mysql://user:pwd@localhost/mydb';
$db = ADONewConnection($dsn);
//get a single value
$value=$db->GetOne("select foo from bar where x=?", array($x));
//get a row
$row=$db->GetRow("select * from bar where x=?", array($x));
//easy insert example
$record=array("id"=>1, "foo"=>"bar");
$db->AutoExecute("table", $record, "INSERT");
``` | PDO works great for me, even tho it's not a fully blown library like PEAR::MDB2.
PDO is a compiled extension of PHP5, so there's a small performance benefit as well. | Useful PHP database class | [
"",
"php",
"mysql",
"database",
""
] |
I am in the process of refactoring my existing code. It actually works fine, but it is a bit cluttered with multiple if-else conditionals checking the value of one variable and change the value of a second variable to an updated value taken from a fixed enumeration structure.
```
else if (var1 == 'valueX')
{
if (var2 == MyEnum.A)
var2 = MyEnum.B;
else if (var2 == MyEnum.B)
var2 = MyEnum.C;
else if (var2 == MyEnum.C)
var2 = MyEnum.D;
else if (var2 == MyEnum.D)
var2 = MyEnum.A;
}
else if (....)
{
..similar block of conditionals
}
```
I am a bit confused as to what is the best way to refactor and clean-up this code. Would you suggest the use of a switch perhaps? Or something more elegant?
Thanks in advance! | At least with J2SE 1.5 forward, you can give enums extra attributes. This means you might be able to replace that entire string of if-else with something that looks like
```
var2 = var1.getNextInSequence();
```
Now, in this case, it looks like you would want the attribute to be a reference to another enum, which adds some wrinkles, for example you can't forward reference enums when you initialize them, but there might be a workable solution for you this way.
When the attributes aren't other instances of the same enum, this kind of thing will work:
```
public enum Animal {
FOX(4),
CHICKEN(2),
WORM(0);
private int countLegs;
Animal(int n) {
countLegs = n;
}
public int getLegCount() {
return countLegs;
}
// .. more getters setters etc
}
```
But when the enum is self-referential, you have to be careful about the order of declaration of your instances. I.e., this will have some issues:
```
public enum Animal {
FOX(4, CHICKEN), // 'CHICKEN' doesn't exist yet
WORM(0, null),
CHICKEN(2, WORM); // this actually will compile
private int countLegs;
private Animal eatsWhat;
Animal(int n, Animal dinner) {
countLegs = n;
eatsWhat = dinner;
}
public int getLegCount() {
return countLegs;
}
// .. getters, setters, etc
}
```
So if you had need of a circular set of references among the enums, you'd have to work something else out, but if not, you *could* use this technique, though you may have to order your enum instances just so to make it work. | The classic answer to refactoring conditionals is [Replace Conditional With Polymorphism](http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html). In this case, if each of MyEnum knew what its successor was, you could simply say (in the 'valuex' case: var2 = var2.successor. For var1 - if it could be an object that implemented an interface that knew how to handle whatever you're doing inside the loop, and each implementing class knew what it, specifically, should do... Well, you'd be done.
**Update:**
And here's a dandy little successor function in a test case:
```
public class EnumTest extends TestCase {
private enum X {
A, B, C;
public X successor() {
return values()[(ordinal() + 1) % values().length];
}
};
public void testSuccessor() throws Exception {
assertEquals(X.B, X.A.successor());
assertEquals(X.C, X.B.successor());
assertEquals(X.A, X.C.successor());
}
}
``` | refactoring multiple if-else conditionals in a method | [
"",
"java",
"refactoring",
"conditional-statements",
""
] |
I have an application that works with XML file. It works great if the xml file is present, however there is also a requirement, that the project generates a blank XML file and then writes to it in case the output file is not present.
The xml file has a quite complicated schema, something like the following:
```
<?xml version="1.0" encoding="UTF-8"?>
<Results>
<Result>
<WorkorderId>45</WorkorderId>
<WorkerId>13</WorkerId>
<DeviceId>38954178</DeviceId>
<Latitude>45.234</Latitude>
<Longitude>19.54</Longitude>
<Note>[all is good]</Note>
<Operations>
<Operation>
<OperationId>23</OperationId>
<Result>Success</Result>
<ParsedInformation>
<Info>parsed data</Info>
<Info>more parsed data</Info>
</ParsedInformation>
</Operation>
<!-- more operations ... -->
</Operations>
</Result>
<!-- more results ... -->
</Results>
```
I am wondering how would I create a XmlDocument like this, so I can write the results to it? Is there a "best practice" about hard coding the schema somewhere in the project, etc?
Please note that I am new to Xml so any additional information/literature would be very welcome. | To my knowledge you have to build the document node by node. Perhaps you can save an empty tree as template. | I would usually create a set of classes that would contain the data and tag them with appropriate XmlSerializer attributes to make sure they get serialized to the format you are expecting. This is a pretty good resource: <http://msdn.microsoft.com/en-us/library/2baksw0z(VS.85).aspx>
In your case you would have the following classes (untested):
```
[XmlRoot("Results")]
public class Results
{
List<Result> results = new List<Result>();
[XmlElement("Result")]
List<Result> Results {get{return results;}}
}
public class Result
{
List<Operation> operations = new List<Operation>();
int WorkorderId {get; set;}
.... other fields
string Note{get;set;}
List<Operation> Operations {get{return operations;}}
}
public class Operation
{
List<string> parsedInformation = new List<string>();
int OperationId {get;set;}
....
[XmlArray("ParsedInformation")]
[XmlArrayItem("Info")]
List<string> ParsedInformation{get{return parsedInformation;}}
}
```
Later you use XmlSerializer class to serialize it to xml:
```
XmlSerializer serializer = new XmlSerializer(typeof(Results));
StringBuilder sb = new StringBuilder(); //this will contain the xml
serializer.Serialize(new TextWriter(sb), resultsObj);
```
Obviously you can also deserialize data from string to object.
Please note that if you have a XSD schema for your xml, you can use xsd.exe tool to generate the code for you. | Creating a XmlDocument with hardcoded schema C# | [
"",
"c#",
"xml",
"xml-generation",
""
] |
I was just about to implement an override of ToString() on a particular business class in order to produce an Excel-friendly format to write to an output file, which will be picked up later and processed. Here's what the data is supposed to look like:
```
5555555 "LASTN SR, FIRSTN" 5555555555 13956 STREET RD TOWNSVILLE MI 48890 25.88 01-003-06-0934
```
It's no big deal for me to just make a format string and override `ToString()`, but that will change the behavior of `ToString()` for any objects I decide to serialize this way, making the implementation of `ToString()` all ragged across the library.
Now, I've been reading up on [IFormatProvider](http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx), and a class implementing it sounds like a good idea, but I'm still a little confused about where all this logic should reside and how to build the formatter class.
What do you guys do when you need to make a CSV, tab-delimited or some other non-XML arbitrary string out of an object? | Here is a generic fashion for creating CSV from a list of objects, using reflection:
```
public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
Type t = typeof(T);
FieldInfo[] fields = t.GetFields();
string header = String.Join(separator, fields.Select(f => f.Name).ToArray());
StringBuilder csvdata = new StringBuilder();
csvdata.AppendLine(header);
foreach (var o in objectlist)
csvdata.AppendLine(ToCsvFields(separator, fields, o));
return csvdata.ToString();
}
public static string ToCsvFields(string separator, FieldInfo[] fields, object o)
{
StringBuilder linie = new StringBuilder();
foreach (var f in fields)
{
if (linie.Length > 0)
linie.Append(separator);
var x = f.GetValue(o);
if (x != null)
linie.Append(x.ToString());
}
return linie.ToString();
}
```
Many variations can be made, such as writing out directly to a file in ToCsv(), or replacing the StringBuilder with an IEnumerable and yield statements. | Here is a simplified version of Per Hejndorf's CSV idea (without the memory overhead as it yields each line in turn). Due to popular demand it also supports both fields and simple properties by use of `Concat`.
## Update 18 May 2017
This example was never intended to be a complete solution, just advancing the original idea posted by Per Hejndorf. To generate valid CSV you need to replace any text delimiter characters, within the text, with a sequence of 2 delimiter characters. e.g. a simple `.Replace("\"", "\"\"")`.
## Update 12 Feb 2016
After using my own code again in a project today, I realised I should not have taken anything for granted when I started from the example of `@Per Hejndorf`. It makes more sense to assume a default delimiter of "," (comma) and make the delimiter the second, *optional*, parameter. My own library version also provides a 3rd `header` parameter that controls whether a header row should be returned as sometimes you only want the data.
## e.g.
```
public static IEnumerable<string> ToCsv<T>(IEnumerable<T> objectlist, string separator = ",", bool header = true)
{
FieldInfo[] fields = typeof(T).GetFields();
PropertyInfo[] properties = typeof(T).GetProperties();
if (header)
{
yield return String.Join(separator, fields.Select(f => f.Name).Concat(properties.Select(p=>p.Name)).ToArray());
}
foreach (var o in objectlist)
{
yield return string.Join(separator, fields.Select(f=>(f.GetValue(o) ?? "").ToString())
.Concat(properties.Select(p=>(p.GetValue(o,null) ?? "").ToString())).ToArray());
}
}
```
**so you then use it like this for comma delimited:**
```
foreach (var line in ToCsv(objects))
{
Console.WriteLine(line);
}
```
**or like this for another delimiter (e.g. TAB):**
```
foreach (var line in ToCsv(objects, "\t"))
{
Console.WriteLine(line);
}
```
## Practical examples
**write list to a comma-delimited CSV file**
```
using (TextWriter tw = File.CreateText("C:\testoutput.csv"))
{
foreach (var line in ToCsv(objects))
{
tw.WriteLine(line);
}
}
```
**or write it tab-delimited**
```
using (TextWriter tw = File.CreateText("C:\testoutput.txt"))
{
foreach (var line in ToCsv(objects, "\t"))
{
tw.WriteLine(line);
}
}
```
*If you have complex fields/properties you will need to filter them out of the select clauses.*
---
## Previous versions and details below:
Here is a simplified version of Per Hejndorf's CSV idea (without the memory overhead as it yields each line in turn) **and has only 4 lines of code :)**
```
public static IEnumerable<string> ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
FieldInfo[] fields = typeof(T).GetFields();
yield return String.Join(separator, fields.Select(f => f.Name).ToArray());
foreach (var o in objectlist)
{
yield return string.Join(separator, fields.Select(f=>(f.GetValue(o) ?? "").ToString()).ToArray());
}
}
```
**You can iterate it like this:**
```
foreach (var line in ToCsv(",", objects))
{
Console.WriteLine(line);
}
```
where `objects` is a strongly typed list of objects.
## This variation includes both public fields and simple public properties:
```
public static IEnumerable<string> ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
FieldInfo[] fields = typeof(T).GetFields();
PropertyInfo[] properties = typeof(T).GetProperties();
yield return String.Join(separator, fields.Select(f => f.Name).Concat(properties.Select(p=>p.Name)).ToArray());
foreach (var o in objectlist)
{
yield return string.Join(separator, fields.Select(f=>(f.GetValue(o) ?? "").ToString())
.Concat(properties.Select(p=>(p.GetValue(o,null) ?? "").ToString())).ToArray());
}
}
``` | Best practices for serializing objects to a custom string format for use in an output file | [
"",
"c#",
"serialization",
"formatprovider",
""
] |
My memory is failing me. I have a simple audit log table based on a trigger:
`ID``int (identity, PK)`
`CustomerID``int`
`Name``varchar(255)`
`Address``varchar(255)`
`AuditDateTime``datetime`
`AuditCode``char(1)`
It has data like this:
`ID``CustomerID``Name``Address``AuditDateTime``AuditCode`
`1``123``Bob``123 Internet Way``2009-07-17 13:18:06.353``I`
`2``123``Bob``123 Internet Way``2009-07-17 13:19:02.117``D`
`3``123``Jerry``123 Internet Way``2009-07-17 13:36:03.517``I`
`4``123``Bob``123 My Edited Way``2009-07-17 13:36:08.050``U`
`5``100``Arnold``100 SkyNet Way``2009-07-17 13:36:18.607``I`
`6``100``Nicky``100 Star Way``2009-07-17 13:36:25.920``U`
`7``110``Blondie``110 Another Way``2009-07-17 13:36:42.313``I`
`8``113``Sally``113 Yet another Way``2009-07-17 13:36:57.627``I`
**What would be the efficient select statement be to get all most current records between a start and end time?** FYI: I for insert, D for delete, and U for update.
Am I missing anything in the audit table? My next step is to create an audit table that only records changes, yet you can extract the most recent records for the given time frame. For the life of me I cannot find it on any search engine easily. Links would work too. Thanks for the help. | Another (better?) method to keep audit history is to use a 'startDate' and 'endDate' column rather than an auditDateTime and AuditCode column. This is often the approach in tracking Type 2 changes (new versions of a row) in data warehouses.
This lets you more directly select the current rows (WHERE endDate is NULL), and you will not need to treat updates differently than inserts or deletes. You simply have three cases:
* Insert: copy the full row along with a start date and NULL end date
* Delete: set the End Date of the existing current row (endDate is NULL)
* Update: do a Delete then Insert
Your select would simply be:
```
select * from AuditTable where endDate is NULL
```
Anyway, here's my query for your existing schema:
```
declare @from datetime
declare @to datetime
select b.* from (
select
customerId
max(auditdatetime) 'auditDateTime'
from
AuditTable
where
auditcode in ('I', 'U')
and auditdatetime between @from and @to
group by customerId
having
/* rely on "current" being defined as INSERTS > DELETES */
sum(case when auditcode = 'I' then 1 else 0 end) >
sum(case when auditcode = 'D' then 1 else 0 end)
) a
cross apply(
select top 1 customerId, name, address, auditdateTime
from AuditTable
where auditdatetime = a.auditdatetime and customerId = a.customerId
) b
```
**References**
A [cribsheet for data warehouses](http://www.simple-talk.com/sql/sql-training/sql-server-data-warehouse-cribsheet/), but has a good section on type 2 changes (what you want to track)
MSDN page on [data warehousing](http://msdn.microsoft.com/en-us/library/aa902672(SQL.80).aspx#sql_dwdesign_topic4) | Ok, a couple of things for audit log tables.
**For most applications, we want audit tables to be extremely quick on insertion.**
If the audit log is truly for diagnostic or for very irregular audit reasons, then the quickest insertion criteria is to make the table physically ordered upon insertion time.
And this means to put the audit time as the first column of the clustered index, e.g.
```
create unique clustered index idx_mytable on mytable(AuditDateTime, ID)
```
This will allow for extremely efficient select queries upon AuditDateTime O(log n), and O(1) insertions.
If you wish to look up your audit table on a per CustomerID basis, then you will need to compromise.
You may add a nonclustered index upon (CustomerID, AuditDateTime), which will allow for O(log n) lookup of per-customer audit history, however the cost will be the maintenance of that nonclustered index upon insertion - that maintenance will be O(log n) conversely.
However that insertion time penalty may be preferable to the table scan (that is, O(n) time complexity cost) that you will need to pay if you don't have an index on CustomerID and this is a regular query that is performed.
An O(n) lookup which locks the table for the writing process for an irregular query may block up writers, so it is sometimes in writers' interests to be slightly slower if it guarantees that readers aren't going to be blocking their commits, because readers need to table scan because of a lack of a good index to support them....
---
Addition: if you are looking to restrict to a given timeframe, the most important thing first of all is the index upon AuditDateTime. And make it clustered as you are inserting in AuditDateTime order. This is the biggest thing you can do to make your query efficient from the start.
Next, if you are looking for the most recent update for all CustomerID's within a given timespan, well thereafter a full scan of the data, restricted by insertion date, is required.
You will need to do a subquery upon your audit table, between the range,
```
select CustomerID, max(AuditDateTime) MaxAuditDateTime
from AuditTrail
where AuditDateTime >= @begin and Audit DateTime <= @end
```
and then incorporate that into your select query proper, eg.
```
select AuditTrail.* from AuditTrail
inner join
(select CustomerID, max(AuditDateTime) MaxAuditDateTime
from AuditTrail
where AuditDateTime >= @begin and Audit DateTime <= @end
) filtration
on filtration.CustomerID = AuditTrail.CustomerID and
filtration.AuditDateTime = AuditTrail.AuditDateTime
``` | SQL standard select current records from an audit log question | [
"",
"sql",
"logging",
"select",
"audit",
""
] |
I know about Redgate's Ants Profiler which I hear is awesome but it's also $400. Any cheaper alternatives out there that will at least point me to where I might need to optimize my code? | [Dottrace](http://www.jetbrains.com/profiler/) is about half the price of Ants, and it's really good. Made by the same people that do ReSharper.
If you're just looking for a one-off optimization of your code, then you should go for Ants anyway, since it has a full-featured 15-day free trial, which should be enough to get a lot of optimization done. | [EQATEC Profiler](http://www.eqatec.com/tools/profiler/) is free.
I haven't tried it myself, but it sounds ok and there are some positive testimonials on their site.
I'd be interested to hear the opinion of anyone who has actually used it. | Free or inexpensive options for profiling / performance analysis for C# asp.net? | [
"",
"c#",
"asp.net",
"performance",
"profiler",
""
] |
I have a script named `test1.py` which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call `test1.py` from the script running as a service.
For example:
File **`test1.py`**:
```
print "I am a test"
print "see! I do nothing productive."
```
File **`service.py`**:
```
# Lots of stuff here
test1.py # do whatever is in test1.py
``` | The usual way to do this is something like the following.
test1.py
```
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
```
service.py
```
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
``` | This is possible in Python 2 using [`execfile`](https://docs.python.org/2/library/functions.html#execfile):
```
execfile("test2.py")
```
In Python 3, this is possible using [`exec`](https://docs.python.org/3/library/functions.html#exec):
```
exec(open("test2.py").read())
```
See the documentation for the handling of namespaces, if important in your case.
However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean. | How to call a script from another script? | [
"",
"python",
""
] |
I'm writing a program where I typically start five threads. The threads return in a non-determinate order. Each thread is calling a method which returns a List.
I'm doing this:
```
var masterList = List<string>();
foreach (var threadParam in threadParams)
{
var expression = threadParam ;
ThreadStart sub = () => MyMethod(expressions);
var thread = new Thread(sub)
{
Name = expression
};
listThreads.Add(thread);
thread.Start();
}
var abort = true;
while (abort) //Wait until all threads finish
{
var count = 0;
foreach (var list in listThreads)
{
if (!list.IsAlive)
{
count++;
}
}
if (count == listThreads.Count)
{
abort = false;
}
}
```
So here is the problem:
Each thread when it terminates returns a list I would like to append the masterList declared earlier.
How would one go about this?
Also I KNOW there must be a better way than below to wait for all threads to finish
```
var abort = true;
while (abort) //Wait until all threads finish
{
var count = 0;
foreach (var list in listThreads)
{
if (!list.IsAlive)
{
count++;
}
}
if (count == listThreads.Count)
{
abort = false;
}
}
``` | Use a [`WaitHandle`](http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx)
---
Here's an example:
```
using System;
using System.Threading;
class ThreadSleeper
{
int seconds;
AutoResetEvent napDone = new AutoResetEvent(false);
private ThreadSleeper(int seconds)
{
this.seconds = seconds;
}
public void Nap()
{
Console.WriteLine("Napping {0} seconds", seconds);
Thread.Sleep(seconds * 1000);
Console.WriteLine("{0} second nap finished", seconds);
napDone.Set();
}
public static WaitHandle DoSleep(int seconds)
{
ThreadSleeper ts = new ThreadSleeper(seconds);
Thread thread = new Thread(new ThreadStart(ts.Nap));
thread.Start();
return(ts.napDone);
}
}
public class OperationsThreadsWaitingwithWaitHandle
{
public static void Main()
{
WaitHandle[] waits = new WaitHandle[2];
waits[0] = ThreadSleeper.DoSleep(8);
waits[1] = ThreadSleeper.DoSleep(4);
Console.WriteLine("Waiting for threads to finish");
WaitHandle.WaitAll(waits);
Console.WriteLine("Threads finished");
}
}
```
---
**Links to check out**:
* [Threads:Waiting with WaitHandle](http://www.java2s.com/Code/CSharp/Thread/ThreadsWaitingwithWaitHandle.htm)
* [Jon Skeet's post](http://www.yoda.arachsys.com/csharp/threads/waithandles.shtml)
* [Difference between Barrier in C# 4.0 and WaitHandle in C# 3.0?](https://stackoverflow.com/questions/990970/difference-between-barrier-in-c-4-0-and-waithandle-in-c-3-0)
* [Novice C# threading: WaitHandles](http://bojordan.com/log/?p=258)
* [WaitHandle Exceptions and Work Arounds](http://www.codeproject.com/KB/recipes/WaitHandleExceptions.aspx?display=Print)
* [Multithreading with C#](http://ondotnet.com/pub/a/dotnet/2001/08/06/csharp.html?page=4&x-maxdepth=0)
* [WaitHandle, AutoResetEvent and ManualResetEvent Classes in VB.Net](http://www.developerfusion.com/article/5184/multithreading-in-vbnet/3/) | The best way would be to make each thread it's own object. Don't have any intermingling with other objects, all you do is construct it (passing in the variables), add yourself as a listener and start it.
When it's done, it stores the values in a member variable and notifies your listener.
Your listener can retrieve the values at leisure.
The obvious shortcut, returning the values directly to the listener, works but you may find this version more flexible later (and really not much more code) | Threads that return data in .NET | [
"",
"c#",
"multithreading",
""
] |
I'm trying out the [solution](https://stackoverflow.com/questions/1162401/is-it-possible-to-access-values-of-non-type-template-parameters-in-specialized-te/1162910#1162910) to a [question about specialized template classes](https://stackoverflow.com/questions/1162401/is-it-possible-to-access-values-of-non-type-template-parameters-in-specialized-te).
This code with a compiles fine in g++, but throws up linker errors when compiled with gcc. What's the cause of these errors ?
```
$ g++ traits2.cpp
$ gcc traits2.cpp
/tmp/ccI7CNCY.o: In function `__static_initialization_and_destruction_0(int, int)':
traits2.cpp:(.text+0x36): undefined reference to `std::ios_base::Init::Init()'
traits2.cpp:(.text+0x3b): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccI7CNCY.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
```
The traits2.ccp file contains the aforementioned [solution](https://stackoverflow.com/questions/1162401/is-it-possible-to-access-values-of-non-type-template-parameters-in-specialized-te/1162910#1162910) with an emtpy main() function:
```
#include <iostream>
using namespace std;
// A default Traits class has no information
template<class T> struct Traits
{
};
// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
return Traits<T>();
}
template <int major, int minor> struct A
{
void f()
{
cout << major << endl;
}
};
// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
enum { major = N1, minor = N2 };
};
template <> struct A<4,0>
{
void f()
{
cout << "Specialized:" << GetTraits(*this).major << endl;
}
};
int main(int argc, char * argv[] )
{
/*
A<4,0> p;
A<1,2> p2;
p.f();
p2.f();
*/
return 1;
}
``` | When you compile with gcc, the C++ libraries are not linked in by default. Always build C++ code with g++. | If you want to see the difference for yourself, try both versions with the -v flag
```
$ g++ -v traits2.cpp
$ gcc -v traits2.cpp
```
This will show you each of the steps from code top executable, including the libraries that are added. | Programs compiles in g++ but exits with linker errors in gcc | [
"",
"c++",
"templates",
"gcc",
"g++",
""
] |
```
for($x=0; $x<12; $x++)
{
$month = mktime(0, 0, 0, date("m")+$x, date("d"), date("Y"));
$key = date('m', $month);
$monthname = date('F', $month);
$months[$key] = $monthname;
}
```
I know for sure I'm doing the math incorrectly for the 4th parameter of mktime. I'm starting with the current month number ( 7 being July ) and adding 1 for each next month, sometimes it ends up being that the same month is returned twice, maybe because I'm not setting it to the beginning of the month? How would you improve/recode this?
Result is that $months would result in an array where 07 = July 08 = August, 09 = September. Right now it populates October twice. I think it has to do with today being the 31st and it incorrectly adds and reaches the next month. | Just fixed your code slightly, this should work pretty well:
```
$months = array();
$currentMonth = (int)date('m');
for ($x = $currentMonth; $x < $currentMonth + 12; $x++) {
$months[] = date('F', mktime(0, 0, 0, $x, 1));
}
```
Note that I took out the array key, as I think it's unnecessary, but you can change that of course if you need it. | An alternative would be to use [`strtotime`](http://php.net/strtotime):
```
for ($x=0; $x < 12; $x++) {
$time = strtotime('+' . $x . ' months', strtotime(date('Y-M' . '-01')));
$key = date('m', $time);
$name = date('F', $time);
$months[$key] = $name;
}
```
In my opinion this code is easier to read. | PHP: Populating an array with the names of the next 12 months | [
"",
"php",
""
] |
I'm trying to move from Prototype to jQuery and there's one last thing I can't figure out how to do in the new library.
Here's what I used to do with Prototype:
```
MyClass = Class.create();
MyClass.prototype = {
initialize: function(options) {
}
}
```
Then I could create a new `MyClass` with:
```
var mc = new MyClass({});
```
Does jQuery have anything like Prototype's `Class.create()`? And if not, how do I get the same kind of thing without a library? | I use the jquery [extend](http://docs.jquery.com/Utilities/jQuery.extend) function to extend a class prototype.
For example:
```
MyWidget = function(name_var) {
this.init(name_var);
}
$.extend(MyWidget.prototype, {
// object variables
widget_name: '',
init: function(widget_name) {
// do initialization here
this.widget_name = widget_name;
},
doSomething: function() {
// an example object method
alert('my name is '+this.widget_name);
}
});
// example of using the class built above
var widget1 = new MyWidget('widget one');
widget1.doSomething();
```
Note: I asked a [related question](https://stackoverflow.com/questions/84716/is-there-a-better-way-to-create-an-object-oriented-class-with-jquery) about this same topic. | jQuery uses the standard javascript functionality for creating new classes.
There are some fine examples on the web, but I would recommend looking at David Flanagan's books Javascript: The Definitive Guide.
[Object-Oriented JavaScript](http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/)
[JavaScript and Object Oriented Programming (OOP)](http://www.javascriptkit.com/javatutors/oopjs.shtml)
---
I apologize, I completely misunderstood your original post. I'm guessing that you actually want to know how to extend the jQuery $ object. This is easily doable, there are a large number of plugins out there for doing so. There is a tutorial on the jQuery site for doing this: [Getting Started With jQuery](http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Plug_me:_Writing_your_own_plugins)
Essentially, though, you use
```
jQuery.fn.foobar = function() {
// do something
};
``` | How can I get class-based objects in JavaScript with jQuery? | [
"",
"javascript",
"jquery",
"class",
""
] |
I've got a project that consists of two processes and I need to pass some data between them in a fast and efficent manner.
I'm aware that I could use sockets to do this using TCP, even though both processes will always exist on the same computer, however this does not seem to be a very efficient solution.
I see lots of information about using "pipes" on Linux. However I primarily want this for Windows and Linux (preferably via a cross platform library), ideally in a type safe,
non-blocking manner.
Another important thing is I need to support multiple instances of the whole application (i.e. both processes), each with their own independent copy of the communication objects.
Also is there a cross platform way to spawn a new process? | For IPC, [Windows supports named pipes](http://msdn.microsoft.com/en-us/library/aa365590%28VS.85%29.aspx) just like [Linux does](http://tldp.org/LDP/lpg/node15.html), except that the pipe names follow a different format, owing to the difference in path formats between the two operating systems. This is something that you could overcome with simple preprocessor defines. Both operating systems also support non-blocking IO on pipes and IO multiplexing with select(). | Take a look at [Boost.Interprocess](http://www.boost.org/doc/libs/1_40_0/doc/html/interprocess.html)
> **Boost.Interprocess** simplifies the use of common interprocess communication and synchronization mechanisms and offers a wide range of them:
>
> * Shared memory.
> * Memory-mapped files.
> * Semaphores, mutexes, condition variables and upgradable mutex types to place them in shared memory and memory mapped files.
> * Named versions of those synchronization objects, similar to UNIX/Windows sem\_open/CreateSemaphore API.
> * File locking.
> * Relative pointers.
> * Message queues.
>
> **Boost.Interprocess** also offers higher-level interprocess mechanisms to allocate dynamically portions of a shared memory or a memory mapped file (in general, to allocate portions of a fixed size memory segment). Using these mechanisms, Boost.Interprocess offers useful tools to construct C++ objects, including STL-like containers, in shared memory and memory mapped files:
>
> * Dynamic creation of anonymous and named objects in a shared memory or memory mapped file.
> * STL-like containers compatible with shared memory/memory-mapped files.
> * STL-like allocators ready for shared memory/memory-mapped files implementing several memory allocation patterns (like pooling).
>
> **Boost.Interprocess** has been tested in the following compilers/platforms:
>
> * Visual 7.1 Windows XP
> * Visual 8.0 Windows XP
> * GCC 4.1.1 MinGW
> * GCC 3.4.4 Cygwin
> * Intel 9.1 Windows XP
> * GCC 4.1.2 Linux
> * GCC 3.4.3 Solaris 11
> * GCC 4.0 MacOs 10.4.1 | C++ multiple processes? | [
"",
"c++",
"multithreading",
"concurrency",
"ipc",
""
] |
My `TableModel` implementations typically sit on an `ArrayList` to allow for efficient random access performance. However, `ArrayList`'s `remove(int)` implementation looks fairly inefficient as it involves making a `System.arrayCopy(...)` call to shift all subsequent elements back by 1.
What approaches to people take to implementing `TableModel`s? Is there a better data structure I should be considering? ... perhaps a 3rd party library?
Some more information: My table data can shrink and grow so any fixed-size buffer implementation isn't going to work.
Thanks in advance. | Your question reeks of "Premature Optimization".
On my computer, `System.arrayCopy()` can copy [1 million elements of data in roughly 13ms](http://blog.pdark.de/2009/01/23/another-lesson-on-performance-2/). So I suggest to measure whether this is really an issue. In the general case, ArrayList is faster and has a better memory performance than any other similar data structure.
Using a `LinkedList` would make all operations on the list (including `remove()`) slower since you will now have to traverse half of all list elements for each operation (on average). So most operations would go from O(1) to O(N/2). | When implementing a TableModel you need to consider 2 things
1) creating and manipulating the model
2) rendering your table
The first is alot less important performance wise then the second.
You typicaly create your model once and do a tiny amount of manipulation, the rendering engine behind the table continuosly queries your tablemodel.
This means that the retrieval of the information from a model has to be optimal, any action taken to speed up model manipulation at cost of model query is therefore to be avoided.
In my case i need both, heavy manipulation and fast rendering. So the choice i did was a sort of LinkedList implemenation for all manipulation combined with an array, both are kept synchronous , all inserting, manipulation deletion is being done through the linkedlist structure, all rendering with the array structure | Efficient TableModel implementation | [
"",
"java",
"swing",
"data-structures",
""
] |
Would
```
WHERE substr(my_field,1,6) = 'search'
```
or
```
WHERE my_field LIKE 'search%'
```
be faster in Oracle, or would there be no difference? | Assuming maximum performance is the goal, I would ideally choose `SUBSTR(my_field,1,6)` and create a function-based index to support the query.
```
CREATE INDEX my_substr_idx
ON my_table( substr( my_field,1,6 ) );
```
As others point out, `SUBSTR(my_field,1,6)` would not be able to use a regular index on `MY_FIELD`. The LIKE version might use the index, but the optimizer's cardinality estimates in that case are generally rather poor so it is quite likely to either not use an index when it would be helpful or to use an index when a table scan would be preferable. Indexing the actual expression will give the optimizer far more information to work with so it is much more likely to pick the index correctly. Someone smarter than I am may be able to suggest a way to use statistics on virtual columns in 11g to give the optimizer better information for the LIKE query.
If 6 is a variable (i.e. you sometimes want to search the first 6 characters and sometimes want to search a different number), you probably won't be able to come up with a function-based index to support that query. In that case, you're probably better off with the vagaries of the optimizer's decisions with the LIKE formulation. | Of the two options provided, definitely LIKE. The substring method will have to be executed against all rows in the table. Using LIKE will allow the use of indexes.
To check my answer, just profile the results. It should be clear as day. | Is substr or LIKE faster in Oracle? | [
"",
"sql",
"oracle",
""
] |
I have a query like this:
```
SELECT lesson.id, p1.first_name, p1.surname, start_time, instrument.name
FROM lesson, person AS p1, person AS p2, instrument, invoice_lesson
WHERE lesson.student = p1.id
AND lesson.teacher = p2.id
AND instrument.id = lesson.instrument_id
ORDER BY surname
```
However, I would like to modify it so that it only shows results where `lesson.id` is not in the table `invoice_lesson.lesson_id`. Is this a correlated query? How do I do this? | You can do this with an outer join:
```
SELECT lesson.id, p1.first_name, p1.surname, start_time, instrument.name
FROM lesson l JOIN person p1 ON l.student = p1.id
JOIN person p2 ON l.teacher = p2.id
JOIN instrument i ON i.id = l.instrument_id
LEFT JOIN invoice_lesson il ON l.id = il.lesson_id
WHERE il.lesson_id IS NULL
ORDER BY surname
```
This approach will be much faster than the correlated subquery approach. | The easiest way:
```
SELECT lesson.id, p1.first_name, p1.surname, start_time, instrument.name
FROM lesson, person AS p1, person AS p2, instrument, invoice_lesson
WHERE lesson.student = p1.id
AND lesson.teacher = p2.id
AND instrument.id = lesson.instrument_id
AND lesson.id NOT IN (SELECT lesson_id FROM invoice_lesson)
ORDER BY surname
```
Might not exactly be the quickest one :)
Tomasz Kopczuk | MySQL query - show results that are not in another table | [
"",
"sql",
"mysql",
""
] |
I am writing a method which needs to check some parameters and if they are validated return an IEnumerable. E.g.
```
public static IEnumerable<double> GetEnum(int param)
{
if (!IsValidParameter(param))
{
throw new Exception();
}
while(true)
{
yield return 5.0;
}
}
```
However, I believe because of lazy evaluation, when I run my unit tests with bad parameters, but don't call any of the IEnumerable methods yet, the Exception is not thrown.
```
[Test]
[ExpectedException(typeof(Exception))]
void Test()
{
var ie = GetEnum(bad_param);
}
```
I can fix things by building the IEnumerable in another function (say Foo), then check parameters in GetEnum and call Foo but is there a solution without having to create multiple functions?
Cheers, Jurgen | Due to how iterator blocks are defined, you currently need two methods to achieve this:
```
public static IEnumerable<double> GetEnum(int param) {
if (!IsValidParameter(param)) {
throw new Exception();
}
return GetEnumCore(param);
}
private static IEnumerable<double> GetEnumCore(int param) {
while(true) {
yield return 5.0;
}
}
```
Only the iterator block (`GetEnumCore`) is deferred; `GetEnum` runs immediately, performing your checks. | Could you maybe just initiate the iteration using the underlying enumerator?
```
[Test]
[ExpectedException(typeof(Exception))]
void Test()
{
var ie = GetEnum(bad_param);
var en = ie.GetEnumerator();
en.MoveNext();
}
``` | Named Iterator & Exceptions | [
"",
"c#",
"exception",
"iterator",
""
] |
How could you match 12 hour time in a regex-- in other words match 12:30 but not 14:74?
Thanks! | This should work:
```
([1-9]|1[012]):[0-5][0-9]
``` | This is an example of a problem where "hey I know, I'll use regular expressions!" is the wrong solution. You can use a regular expression to check that your input format is digit-digit-colon-digit-digit, then use programming logic to ensure that the values are within the range you expect. For example:
```
/(\d\d?):(\d\d)/
if ($1 >= 1 && $1 <= 12 && $2 < 60) {
// result is valid 12-hour time
}
```
This is much easier to read and understand than some of the obfuscated regex examples you see in other answers here. | How do you match 12 hour time hh:mm in a regex? | [
"",
"php",
"regex",
"datetime",
"time",
""
] |
So I am working on a jsp/servlet that came to me and I'm looking at the jsp file and it is just a jungle of jstl tags, java code and html thrown together. At first it looked like someone ran the standard eclipse formatter on it and had the page width set to 40 so alot of stuff is broken up, I tried to format it with a larger page width but that seemed to make it worse to the point of not being able to tell what is going on without formatting parts of it first.
Anyone have any luck with any jsp/code formatter? | Are you using [Eclipse WTP](http://www.eclipse.org/webtools/) plugin? If not, take a look at it - it has quite a few ways to customize formatting of JSP.
If you are, JSP formatting can be customized under Window -> Preferences; Web -> JSP Files -> Editor; note that there are two separate links there - for XML and HTML JSP. | Netbeans does a **decent** job at formatting my jsp code. You could download Netbeans 6.5.1 and format the files in there. | Code Formatter: cleaning up horribly formatted jsp code | [
"",
"java",
"jsp",
"code-formatting",
"code-cleanup",
""
] |
we a phonenumber field in our database and I would like to do a simple lookup query like:
```
SELECT * FROM TABLE WHERE Phonenumber = '555123456'
```
But since the phonenumbers are entered by users and are not normalized, we don't really know what they look like.
Could be:
* +555-123456
or
* (555) 123 456
or
* 555-12-34-56
or something complety different.
The only thing certain is that the all the given numbers should be there in the correct order. Is it possible to construct a query around that? | Since I don't know what RDBMS you're looking for, I'll give the most generic way:
```
phonenumber like '%5%5%5%1%2%3%4%5%6%'
```
This assumes that all phone numbers are at least equal length (in digits). | IF you can alter the table (assuming it's **SQL Server 2005** and up), you could add a computed column to your table, and persist it. This column could hold a "cleaned up" representation of your "phonenumber" field.
Something like this:
```
create function dbo.CleanPhone(@phone varchar(100))
returns varchar(100)
with schemabinding
as begin
return
replace(replace(replace(replace(replace(replace(@phone, ' ', ''),
'-', ''), '(', ''), ')', ''), '-', ''), '+', '')
end
```
and then:
```
alter table (yourtable)
add cleanedPhone as dbo.CleanPhone(Phone) persisted
```
Now, your "CleanedPhone" column would always contained a "cleaned up" version of your phone number - always something like: 555123456.
Since it's a PERSISTED field, you don't incur a performance penalty when querying, either - the value is created and stored in your table, and is available as a normal column.
On this, you could now query quite easily.
Marc | SQL - Query Phonenumber that are stored inconsistently | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I'm dealing with two tables which have 2 columns, as listed under.
Table 1: table\_snapshot
account\_no | balance\_due
Table 2: table\_ paid
account\_no | post\_balance | delta\_balance
I added a third column to table2 with the following command:
```
ALTER TABLE table_paid ADD delta_balance number(18);
```
I'm trying to use the following query, to update the new column ( delta\_balance ) with the difference in balances between 1 and 2.
FYI, table\_paid is a subset of table\_snapshot. i,e., table 2 has only a few accounts present in table 1. I get an error saying : SQL Statement not properly ended. the query i'm using is:
```
UPDATE table_paid
SET table_paid.delta_balance = table_paid.post_balance - table_snapshot.balance_due
from table_paid, table_snapshot
WHERE table_paid.account_no = table_snapshot.account_no;
```
Appreciate if someone can correct my query.
Many thanks.
novice. | Oracle doesn't have the UPDATE ... FROM syntax that you're using from MS Sql Server (which, I believe, isn't ANSI anyway). Instead, when you need to do an update on a result set, Oracle has you create the resultset as a kind of inline view, then you update through the view, like so:
```
UPDATE ( SELECT tp.delta_balance
, tp.post_balance
, ts.balance_due
FROM table_paid tp
JOIN table_snapshot ts
ON tp.account_no = ts.account_no
)
SET delta_balance = post_balance - balance_due;
```
This is more "correct" than the answers supplied by Babar and palindrom, as their queries will update every row in table\_paid, even if there are no corresponding rows in table\_snapshot. If there is a 1-1 correspondance, you don't need to worry, but it's safer to do it with the inline view.
It's unclear from your example which table is the parent table, or (as I'm guessing) neither is the parent table and account\_no is pointing to the primary key of another table (presumably account, or "table\_account" by your naming conventions). In any case, it's clear that there is not a 1-1 correspondence in your table - 15K in one, millions in the other.
This could mean 2 things: either there are many rows in table\_snapshot that have no corresponding row in table\_paid, or there are many rows in table\_snapshot for each row in table\_paid. If the latter is true, your query is impossible - you will have multiple updates for each row in table\_paid, and the result will be unpredictable; how will you know which of the "post\_balance - balance\_due" expressions will ultimately determine the value of a given delta\_balance?
If you run my query, you will find this out quickly enough - you will get an error message that says, "ORA-01779: cannot modify a column which maps to a non key-preserved table". This error will appear based not on the data in the table (it may be okay), but based on the primary keys you have defined on the two tables. If the join condition you specify doesn't unambiguously result in a 1-1 relationship between the updated table and the rest of the join, based on the defined keys, you will get this error. It's Oracle's way of telling you, "You're about to screw up your data".
In the other answers here, you will only get an error (in that case, ORA-01427: single-row subquery returns more than one row) if you actually have data that would cause a problem; my version is more strict, so it may turn out that you will need to use the other versions.
And, as the others have said, you'll definitely want an index on account\_no for the table\_snapshot table. One on the table\_paid wouldn't hurt either. | Try this
```
UPDATE table_paid
SET table_paid.delta_balance = table_paid.post_balance -
(SELECT table_snapshot.balance_due from table_snapshot WHERE table_paid.account_no =
table_snapshot.account_no);
``` | Update all rows of a single column | [
"",
"sql",
"oracle",
"oracle10g",
""
] |
I have a list thumbnails that lead to larger counterparts when clicked. I'd like to show the image title in a div, at the bottom edge of the thumbnail. Also, when a mouse is moved over the thumbnail, it shows a 2nd div (containing text) over the entire thing.
Whats the best way of doing that? If a js library is required, jquery is preferred. | If you are ready to go with [jQuery](http://www.jquery.com) then here is a fantastic post by [Sam Dunn](http://buildinternet.com/2009/03/sliding-boxes-and-captions-with-jquery/). | I wrote a small plugin some time ago that allows you to do what you need, and with an animation on hover. It was originally made to add hover background animations but I guess it should be able to do what you need.
```
/*
* jQuery Animate Background (v0.2)
* Copyright (c) 2009 Mario "Kuroir" Ricalde ( http://twitter.com/exolimpo )
* Usage:
* $("h1").animateBg();
* Con Campos Opcionales:
* $("div").animateBg({time:130,add:"span"});
*/
(function($){
$.fn.animateBg = function(opciones){
$.fn.animateBg.defecto = {
time : "fast", add : "span"
};
var config = $.extend({}, $.fn.animateBg.defecto, opciones);
this.each(function(){
var c = config;
var title = $(this).attr("title");
$(this).append("<"+ c.add +">" + title + "</"+ c.add +">").hover(function(){
$(this).children(c.add).fadeIn(c.time);
},function(){
$(this).children(c.add).fadeOut(c.time);
});
});
}
})(jQuery);
$(document).ready(function(){
$("#thumb-list p img").animateBg();
});
<div id="thumb-list">
<p><img src="lol.jpg" title="My title" /></p>
</div>
```
Sorry if the code doesn't work.. I couldn't test since I'm not at home. | How do you overlay a div over an img, and show another div onmouseover? | [
"",
"javascript",
"jquery",
"html",
"css",
""
] |
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.
```
if(condition here){
include "myFile.php?id='$someVar'";
}
```
Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.
Can someone please tell me how to achieve this?
Thanks. | Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables). | You could do something like this to achieve the effect you are after:
```
$_GET['id']=$somevar;
include('myFile.php');
```
However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).
In this case, why not turn it into a regular function, included once and called multiple times? | PHP - include a php file and also send query parameters | [
"",
"php",
"parameters",
"include",
""
] |
I'm looking for a java library or some help to write my own interpolation function. That is I have two arrays of doubles which are potentially different sizes, but are ordered. I need to be able to make an estimate of intermediate values, and insert so that both arrays become the same size. In fact the total number of points appearing in the interpolation is the sum of the 2 array sizes minus 1. The range of each array must stay the same however, so there is no extrapolation needed.
eg. a1 = [1, 4, 9, 16, 25, 36] and a2 = [6, 9, 14, 30]
the results could be eg.
a1 = [1, 2.25, 4, 6.25, 9, 12.25, 16, 25, 36]
and
a2 = [6, 6.5625, 7.25, 9, 10.0625, 11.25, 14, 25.25, 30]
these examples are `f(x) = x^2 and g(x) = x^2 + 5`, however could easily have been any polynomial - the point is to be able to estimate/approximate the function from the dataset well enough to provide decent enough interpolation. Here the x value is just the index of the input array. In the output only the y values are important. | The other answers give you linear interpolations -- these don't really work for complex, nonlinear data. **You want a [spline fit](http://en.wikipedia.org/wiki/Interpolation#Spline_interpolation), (spline interpolation) I believe.**
Spline fits describe regions of the data using a set of control points from the data, then apply a polynomial interpolation between control points. More control points gives you a more accurate fit, less a more general fit. Splines are much more accurate than linear fits, faster to use than a general regression fit, better than a high-order polynomial because it won't do crazy things between control points.
I can't remember names off the top of my head, but there are some excellent fitting libraries in Java -- I suggest you look for one rather than writing your own function.
---
\*\*EDIT: Libraries that might be useful: \*\*
* [JMSL](http://www.vni.com/products/imsl/jmsl/jmsl.php)
* [JSpline+](http://www.brothersoft.com/jspline+-1718.html)
* [Curfitting library](http://curvefitting.sourceforge.net/) (hope you can read German)
\*\* Theory/code that may be useful: \*\*
* Spline applets with code: [link](http://www.cse.unsw.edu.au/~lambert/splines/)
* [Arkan](http://arkan.pixmart-llc.qarchive.org/) spline fitting for poly-lines to bezier splines
* [Theory](http://www.tinaja.com/cubic01.asp) of splines, and some math for fitting. More math, less code, might help if the libraries don't. | Designed for ONE Dimension data array
```
import java.util.ArrayList;
public class Interpolator {
public static Float CosineInterpolate(Float y1,Float y2,Float mu)
{
double mu2;
mu2 = (1.0f-Math.cos(mu*Math.PI))/2.0f;
Float f_mu2 = new Float(mu2);
return(y1*(1.0f-f_mu2)+y2*f_mu2);
}
public static Float LinearInterpolate(Float y1,Float y2,Float mu)
{
return(y1*(1-mu)+y2*mu);
}
public static Float[] Interpolate(Float[] a, String mode) {
// Check that have at least the very first and very last values non-null
if (!(a[0] != null && a[a.length-1] != null)) return null;
ArrayList<Integer> non_null_idx = new ArrayList<Integer>();
ArrayList<Integer> steps = new ArrayList<Integer>();
int step_cnt = 0;
for (int i=0; i<a.length; i++)
{
if (a[i] != null)
{
non_null_idx.add(i);
if (step_cnt != 0) {
steps.add(step_cnt);
System.err.println("aDDed step >> " + step_cnt);
}
step_cnt = 0;
}
else
{
step_cnt++;
}
}
Float f_start = null;
Float f_end = null;
Float f_step = null;
Float f_mu = null;
int i = 0;
while (i < a.length - 1) // Don't do anything for the very last element (which should never be null)
{
if (a[i] != null && non_null_idx.size() > 1 && steps.size() > 0)
{
f_start = a[non_null_idx.get(0)];
f_end = a[non_null_idx.get(1)];
f_step = new Float(1.0) / new Float(steps.get(0) + 1);
f_mu = f_step;
non_null_idx.remove(0);
steps.remove(0);
}
else if (a[i] == null)
{
if (mode.equalsIgnoreCase("cosine"))
a[i] = CosineInterpolate(f_start, f_end, f_mu);
else
a[i] = LinearInterpolate(f_start, f_end, f_mu);
f_mu += f_step;
}
i++;
}
return a;
}
}
```
Don't know if it helps...
It is very fast coded, so if anyone has a nicer / more performing way to do the same, thank for contributing.
USAGE:
```
input : Float[] a = {1.0f, null, null, 2.0f, null, null, null, 15.0f};
call : Interpolator.Interpolate(a, "Linear");
output : 1.0|1.3333333|1.6666667|2.0|5.25|8.5|11.75|15.0
``` | Interpolation over an array (or two) | [
"",
"java",
"dataset",
"interpolation",
""
] |
I have been developing a GUI for reading continuous data from a serial port. After reading the data, some calculations are made and the results will be plotted and refreshed (aka dynamic plotting). I use the wx backend provided in the matplotlib for this purposes. To do this, I basically use an array to store my results, in which I keep appending it to, after each calculation, and replot the whole graph. To make it "dynamic", I just set the x-axis lower and upper limits for each iteration. Something like found in:
<http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/>
The problem, however, is that since the data is continuous, and if I keep plotting it, eventually the system memory will run out and system will crash. Is there any other way I can plot my result continuously? | > To do this, I basically use an array
> to store my results, in which I keep
> appending it to
Try limiting the size of this array, either by deleting old data or by deleting every n-th entry (the screen resolution will prevent all entries to be displayed anyway). I assume you write all the data to disk so you won't lose anything.
Also, analise your code for memory leaks. Stuff you use and don't need anymore but that doesn't get garbage-collected because you still have a reference to it. | I have created such a component with pythons Tkinter. The source is [here](http://code.google.com/p/asuro-syd/source/browse/lib/pysyd/SydPlot.py).
Basically, you have to keep the plotted data *somewhere*. You cannot keep an infinite amount of data points in memory, so you either have to save it to disk or you have to overwrite old data points. | dynamic plotting in wxpython | [
"",
"python",
"wxpython",
"matplotlib",
""
] |
I'd like to build a function in Django that iterates over a set of objects in a queryset and does something based on the value of an arbitrary attribute. The type of the objects is fixed; let's say they're guaranteed to be from the Comment model, which looks like this:
```
class Comment(models.Model):
name = models.CharField(max_length=255)
text = models.TextField()
email = models.EmailField()
```
Sometimes I'll want to do run the function over the `name`s, but other times the `email`s. I'd like to know how to write and call a function that looks like this:
```
def do_something(attribute, objects):
for object in objects:
# do something with the object based on object.attribute
return results
``` | ```
def do_something(attribute, objects):
results = []
for object in objects:
if hasattr(object, attribute):
results.append(getattr(object, attribute))
return results
```
Or, more succinctly,
```
def do_something(attribute, objects):
return [getattr(o, attribute) for o in objects if hasattr(o, attribute)]
``` | If you're only doing stuff with a single attribute, you can use .values\_list(), which is more performant since you're not instantiating whole objects, and you're only pulling the specific value you're using from the database.
```
>>> def do_something(values):
... for value in values:
... print value
... return something
...
>>> emails = Comment.objects.values_list('email', flat=True)
>>> names = Comment.objects.values_list('name', flat=True)
>>> do_something(emails) # Prints all email addresses
>>> do_something(names) # Prints all names
``` | Passing a Django model attribute name to a function | [
"",
"python",
"django",
""
] |
In the following code, the Type of our Dictionary is `<int, Customer>`, but how do I know what's the type of Customer? It seems like Customer is a string here since we're Customer cust1 = new Customer(1, "Cust 1"); .... im confused...
```
public class Customer
{
public Customer(int id, string name)
{
ID = id;
Name = name;
}
private int m_id;
public int ID
{
get { return m_id; }
set { m_id = value; }
}
private string m_name;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
}
Dictionary<int, Customer> customers = new Dictionary<int, Customer>();
Customer cust1 = new Customer(1, "Cust 1");
Customer cust2 = new Customer(2, "Cust 2");
Customer cust3 = new Customer(3, "Cust 3");
customers.Add(cust1.ID, cust1);
customers.Add(cust2.ID, cust2);
customers.Add(cust3.ID, cust3);
foreach (KeyValuePair<int, Customer> custKeyVal in customers)
{
Console.WriteLine(
"Customer ID: {0}, Name: {1}",
custKeyVal.Key,
custKeyVal.Value.Name);
}
``` | A `Customer` object is type `Customer` even though it consists of an `int` and a `string`. When you are calling `Customer cust1 = new Customer(1, "Cust 1");` that is really saying "make me an object of type `Customer` which consists of the integer 1 and string Cust 1" | The type of `Customer` is `Customer`. A `class` is a user-defined type that can store other types in named fields (the other such kind of type is a `struct`).
The place where a string is passed is called a constructor - a special method that sets up a new object. Here it accepts a string and stores it as the customer's name. | Question on C# Generic Collection | [
"",
"c#",
"generics",
""
] |
I have a problem with the following implementation of `hook_cron` in Drupal 6.1.3.
The script below runs exactly as expected: it sends a welcome letter to new members, and updates a hidden field in their profile to designate that the letter has been sent. There are no errors in the letter, all new members are accounted for, etc.
The problem is that the last line -- updating the profile -- doesn't seem to work when Drupal cron is invoked by the 'real' cron on the server.
When I run cron manually (such as via `/admin/reports/status/run-cron`) the profile fields get updated as expected.
Any suggestions as to what might be causing this?
(Note, since someone will suggest it: members join by means outside of Drupal, and are uploaded to Drupal nightly, so Drupal's built-in welcome letters won't work (I think).)
```
<?php
function foo_cron() {
// Find users who have not received the new member letter,
// and send them a welcome email
// Get users who have not recd a message, as per the profile value setting
$pending_count_sql = "SELECT COUNT(*) FROM {profile_values} v
WHERE (v.value = 0) AND (v.fid = 7)"; //fid 7 is the profile field for profile_intro_email_sent
if (db_result(db_query($pending_count_sql))) {
// Load the message template, since we
// know we have users to feed into it.
$email_template_file = "/home/foo/public_html/drupal/" .
drupal_get_path('module', 'foo') .
"/emails/foo-new-member-email-template.txt";
$email_template_data = file_get_contents($email_template_file);
fclose($email_template_fh);
//We'll just pull the uid, since we have to run user_load anyway
$query = "SELECT v.uid FROM {profile_values} v
WHERE (v.value = 0) AND (v.fid = 7)";
$result = db_query(($query));
// Loop through the uids, loading profiles so as to access string replacement variables
while ($item = db_fetch_object($result)) {
$new_member = user_load($item->uid);
$translation_key = array(
// ... code that generates the string replacement array ...
);
// Compose the email component of the message, and send to user
$email_text = t($email_template_data, $translation_key);
$language = user_preferred_language($new_member); // use member's language preference
$params['subject'] = 'New Member Benefits - Welcome to FOO!';
$params['content-type'] = 'text/plain; charset=UTF-8; format=flowed;';
$params['content'] = $email_text;
drupal_mail('foo', 'welcome_letter', $new_member->mail, $language, $params, 'webmaster@foo.org');
// Mark the user's profile to indicate that the message was sent
$change = array(
// Rebuild all of the profile fields in this category,
// since they'll be deleted otherwise
'profile_first_name' => $new_member->profile_first_name,
'profile_last_name' => $new_member->profile_last_name,
'profile_intro_email_sent' => 1);
profile_save_profile($change, $new_member, "Membership Data");
}
}
}
``` | To safely switch users
<http://api.drupal.org/api/function/session_save_session/6>
```
<?php
global $user;
$original_user = $user;
session_save_session(FALSE); // D7: use drupal_save_session(FALSE);
$user = user_load(array('uid' => 1)); // D7: use user_load(1);
// Take your action here where you pretend to be the user with UID = 1 (typically the admin user on a site)
// If your code fails, it's not a problem because the session will not be saved
$user = $original_user;
session_save_session(TRUE); // // D7: use drupal_save_session(TRUE);
// From here on the $user is back to normal so it's OK for the session to be saved
?>
```
Taken from here:
drupal dot org/node/218104 | Not quite a random guess ... but close ...
When "real" cron runs code, it runs it as a particular user.
Similarly, when you run the Drupal cron code manually, the code will also be running as a particular user.
My suspicion is that the two users are different, with different permissions, and that's causing the failure.
Does the cron job's user have access to write the database, or read only?
Are there any log files generated by the cron job?
**Update**: By 'user' above, I'm referring to the user accounts on the host server, not Drupal accounts. For example, on a sandbox system I use for testing Drupal changes, Apache runs under the `noone` account. | Drupal's profile_save_profile Doesn't Work in hook_cron, When Run by the Server's cron | [
"",
"php",
"drupal",
""
] |
I would like to run my own internal PyPI server, for [egg](https://stackoverflow.com/questions/2051192) distribution within my organization.
I have found a few projects, such as:
* *[EggBasket](http://pypi.python.org/pypi/EggBasket/)*
* <http://plone.org/products/plonesoftwarecenter>
As I understand it, pypi.python.org uses software called Cheese Shop.
My questions:
1. Why can't I use Cheese Shop itself? (I can't find it and am not sure it exists)
2. How do other people solve this problem? (Currently we use *blush* [SVN](https://en.wikipedia.org/wiki/Apache_Subversion) to distribute 'eggs')
This seems canonical: *[The Python Wiki](http://wiki.python.org/moin/)*, *[Python Implementations](https://wiki.python.org/moin/PythonImplementations)*. Still, I'm interested in feedback.
How can I roll my own PyPI? | **Update: PyPi is now powered by [Warehouse](https://github.com/pypa/warehouse), which is the replacement for Cheese Shop.**
The source to Cheese Shop can be downloaded from <https://bitbucket.org/pypa/pypi/src>. There is also an example, from the page you linked to, of using Apache as a "dumb" Python package repository:
```
# Mount pypi repositories into URI space
Alias /pypi /var/pypi
# /pypi/dev: Redirect for unknown packages (fallback to pypi)
RewriteCond /var/pypi/dev/$1 !-d
RewriteCond /var/pypi/dev/$1 !-f
RewriteRule ^/pypi/dev/([^/]+)/?$ http://pypi.python.org/pypi/$1/ [R,L]
RewriteCond /var/pypi/dev/$1/$2 !-f
RewriteRule ^/pypi/dev/([^/]+)/([^/]+)$ http://pypi.python.org/pypi/$1/$2 [R,L]
# /pypi/stable: Redirect for unknown packages (fallback to pypi)
RewriteCond /var/pypi/stable/$1 !-d
RewriteCond /var/pypi/stable/$1 !-f
RewriteRule ^/pypi/stable/([^/]+)/?$ http://pypi.python.org/pypi/$1/ [R,L]
RewriteCond /var/pypi/stable/$1/$2 !-f
RewriteRule ^/pypi/stable/([^/]+)/([^/]+)$ http://pypi.python.org/pypi/$1/$2 [R,L]
``` | For a lightweight solution, use [pypiserver](http://pypi.python.org/pypi/pypiserver). | How can I roll my own PyPI? For example, for 'egg' distribution | [
"",
"python",
"pypi",
""
] |
In an article <http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html>, it says the followings:
> There are numerous advantages to using prepared statements in your applications, both for ***security*** and performance reasons.
>
> Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack.
>
> Normally when you are dealing with an ad hoc query, you need to be very careful when handling the data that you received from the user. ***This entails using functions that escape all of the necessary trouble characters, such as the single quote, double quote, and backslash characters.***
>
> ***This is unnecessary when dealing with prepared statements***. The separation of the data allows MySQL to automatically take into account these characters and they do not need to be escaped using any special function.
Does this mean I don't need `htmlentities()` or `htmlspecialchars()`?
But I assume I need to add `strip_tags()` to user input data?
Am I right? | [`htmlentities`](http://php.net/htmlentities) and [`htmlspecialchars`](http://www.php.net/htmlspecialchars) are used to generate the **HTML output** that is sent to the browser.
Prepared statements are used to generate/send queries to the **Database engine**.
Both allow escaping of data; but they don't escape for the same usage.
So, no, prepared statements *(for SQL queries)* don't prevent you from properly using `htmlspecialchars`/`htmlentities` *(for HTML generation)*
About `strip_tags`: it will remove tags from a string, where `htmlspecialchars` will transform them to HTML entities.
Those two functions don't do the same thing; you should choose which one to use depending on your needs / what you want to get.
For instance, with this piece of code:
```
$str = 'this is a <strong>test</strong>';
var_dump(strip_tags($str));
var_dump(htmlspecialchars($str));
```
You'll get this kind of output:
```
string 'this is a test' (length=14)
string 'this is a <strong>test</strong>' (length=43)
```
In the first case, no tag; in the second, properly escaped ones.
And, with an HTML output:
```
$str = 'this is a <strong>test</strong>';
echo strip_tags($str);
echo '<br />';
echo htmlspecialchars($str);
```
You'll get:
```
this is a test
this is a <strong>test</strong>
```
Which one of those do you want? **That** is the important question **;-)** | Nothing changes for `htmlspecialchars()`, because that's for HTML, not SQL. You still need to escape HTML properly, and it's best to do it when you actually generate the HTML, rather than tying it to the database somehow.
If you use prepared statements, then you don't need `mysql_[real_]escape_string()` anymore (assuming you stick to prepared statements' placeholders and resist temptation to bypass it with string manipulation).
If you want to get rid of `htmlspecialchars()`, then there are HTML templating engines that work similarily to prepared statements in SQL and free you from escaping everything manually, for example [PHPTAL](http://phptal.org). | Do I need htmlentities() or htmlspecialchars() in prepared statements? | [
"",
"php",
"mysql",
""
] |
After some events in a tab, I would like to reload it. I need to send a parameter to the page that loads into the tab.
The following reloads the page: $("#tabs").tabs( 'load' , 6);
But, how can I send a parameter with it? | ```
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
```
Then you can grab the url variables and adjust your tab accordingly (i just did this on a project no more than an hour ago!!)
Code taken from snipplr.com | You can do something like this:
```
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected');
var newurl = "ajax/tab3.html?extraparm=4";
$tabs.tabs( 'url' , selected , newurl );
$tabs.tabs( 'load' , selected);
```
The jquery ui tabs plugin doens't have a easy function to get the url of the currently selected tab but if you do something like this you can get it:
```
$tabs.find('.ui-tabs-selected a').data('href.tabs');
```
This will let you modify the url all you want.
You can also do something like:
```
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected');
var extraData = {extraparm:4,otherparm:'foo'};
$tabs.tabs('option', 'ajaxOptions', { data: extraData });
$tabs.tabs( 'load' , selected);
$tabs.tabs('option', 'ajaxOptions', { data: {} });
```
This uses the ajaxOptions to set the extra data to send, selects the tab again and then sets the data back to a blank object. | Jquery tab reload with a parameter | [
"",
"javascript",
"jquery-ui",
"jquery",
""
] |
I need to iterate a list of assemblies and determine their version numbers. I've made use of System.Reflection.Assembly.GetExecutingAssembly().GetName().Version before, but in this case I'm working with assemblies that have not yet been loaded. I understand I can use System.Reflection.Assembly.ReflectionOnlyLoadFrom("assembly.dll") but I've read that this can eat memory unless I load the assemblies in their own application domain and then unload them. Is this true of ReflectionOnlyLoadFrom() or just LoadFrom()?
Alternatively, is there a way of obtaining the version info without loading the assembly? | Take a look at [System.Reflection.AssemblyName](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.aspx). You can do
```
AssemblyName.GetAssemblyName("foo.dll").Version
```
which returns [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) object where you can get major, minor, minor revison, and revision information. According to the [Msdn article](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.getassemblyname.aspx) on GetAssemblyName method:
> This will work if the file contains an
> assembly manifest. This method causes
> the file to be opened and closed, but
> the assembly is not added to this
> domain. | You could use the [Cecil](http://www.mono-project.com/Cecil)-library of the Mono-project. | Suggestions needed on most efficient way to retrieve an assembly version from an external assembly | [
"",
"c#",
".net",
"reflection",
""
] |
I'm trying to run code that will copy fields into a new table, moving them from a `_New` table to the original table. The VBA code that does this works as such:
```
SQLStatement = CStr("INSERT INTO " & TName & " SELECT * FROM " & TName & "_New")
Log.WriteLine "Running query with string """ & SQLStatement & """ "
QueryTimer = Timer
DoCmd.RunSQL SQLStatement
Log.WriteLine "Query time: " & (Timer - QueryTimer)
```
The log is just a handful of procedures in a class module I threw together. Its output on the error is
```
@142921: Running query with string "INSERT INTO Records SELECT * FROM Records_New"
@142941: Error Date/Time: 7/21/2009 2:29:40 PM
@142941: Error # & Description: 3162, You tried to assign the Null value to a variable that is not a Variant data type.
```
I can confirm that `TName` and `SQLStatement` are both valid strings at the time the SQL operation is run, and that the sources (Records and Records\_New) are both valid. `Option Explicit` is set elsewhere in the file to avoid any confusion from typos. The error is thrown on the `DoCmd` line.
Why would this have a `Null` value, even though `DoCmd.RunSQL` doesn't return a value? | Can you post the table descriptions for Records and Records\_New tables?
I would wager that you are trying to insert a NULL value into one of the columns of the "Records" table (and the column description is NOT NULL).
Hope this helps. | I think it will help if you also change the insert statement to be more specific about which columns it is inserting/selecting. You are asking for bugs by being so non-specific.
This may seem like it is non-responsive to your answer, but I suspect that the columns in the select table and destination table are either not lined up, or there is a field in the destination table that disallows null.
Try this:
In a new Query (in SQL view) paste your query "INSERT INTO Records SELECT \* FROM Records\_New" in and try to run it manually. I bet you get a more specific error and can troubleshoot the query there before running it with the added complexity of the code around it. | "Null" value in Queries | [
"",
"sql",
"ms-access",
"ms-access-2007",
"vba",
""
] |
Its been a while since i've needed to do this so i was looking at the old school methods of writing XMLDocument from code down to a File.
In my application i am writing alot to an XMLdocument with new elements and values and periodically saving it down to disc and also reading from the file and depending on the data i am doing things.
I am using methods like File.Exists(...) \_xmldoc.LoadFile(..) etc...
Im wondering probably now a days there are better methods for this with regards
* Parsing the XML
* Checking its format for saving down
* rather then the data being saved down being treated as text but as XML
maybe what i am doing is fine but its been a while and wondered if there are other methods :)
thanks | Have you looked at the Save method of your XmlDocument? It will save whatever is in your XmlDocument as a valid formatted file.
If your program is able to use the XmlDocument class, the XmlDocument class will be able to save your file. You won't need to worry about validating before saving, and you can give it whatever file extension you want. As to your third point... an XML file is really just a text file. It won't matter how the OS sees it. | Well there's [LINQ to XML](http://msdn.microsoft.com/en-us/library/bb387098.aspx) which is a *really* nice XML API introduced in .NET 3.5. I don't think the existing `XMLDocument` API has changed much, beyond some nicer ways of creating `XmlReader`s and `XmlWriter`s (`XmlReader.Create`/`XmlWriter.Create`).
I'm not sure what you really mean by your second and third bullets though. What exactly are you doing in code which feels awkward? | xml and files on disc interaction | [
"",
"c#",
"file",
"xmldocument",
""
] |
Say I've got stored proc 1, that returns some data. how can I execute that stored proc and set some parameters within another stored proc based on the results of that stored proc.
For example:
Table:
```
UserInfo (UserID [int], Name [varchar], DateOfBirth [datetime] )
```
Stored Proc 1:
```
CREATE Procedure StoredProc1
@Name [varchar]
AS
SELECT UserID, Name, DateOfBirth FROM UserInfo WHERE Name = @Name
```
Stored Proc 2:
```
CREATE Procedure StoredProc2
@AmountOfNames [int] OUT
SELECT @AmountOfNames=COUNT(EXEC StoredProc1 @Name='Irwin')
```
I know that Stored Proc 2 is not how it should be built but that is what I want to do, set the count based on the last set of results.
I can't modify stored proc 1 | you can catch the results of your first stored proc in a temp table or table variable...
```
DECLARE @MyResults TABLE(UserID int, Name varchar(30), DateOfBirth datetime)
INSERT @MyResults
EXEC StoredProc1 'Scott'
-- do what you want with the table here...
```
Or - you can use the @@ROWCOUNT variable to grab the count of the results from your first proc. This may or may not work depending on what comes after the select statement in your first stored proc...
```
DECLARE @Count int
EXEC StoredProc1 'Scott'
SET @Count = @@ROWCOUNT
-- do whatever you want with the count here...
```
If you don't have control over StoredProc1, the temp table might be your best option since you can't guarantee the results of @@ROWCOUNT getting reset by code after the select statement in your StoredProc1 proc. | If you know the schema of the return of SP1, you can do this:
```
CREATE SP2
AS
BEGIN
CREATE TABLE #Results1 (
UserID VARCHAR(50),
Name VARCHAR(100),
DateOfBirth DATETIME
)
INSERT INTO #Results1
EXEC sp1 @Param1, @Param2
SELECT COUNT(UserID) FROM #Results1
END
``` | Trying to access the results/result-set of a SQL server EXEC statement | [
"",
"sql",
"stored-procedures",
""
] |
Can someone please explain to me what is going on with python in ubuntu 9.04?
I'm trying to spin up `virtualenv`, and the `--no-site-packages` flag seems to do nothing with ubuntu. I installed `virtualenv 1.3.3` with `easy_install` (which I've upgraded to `setuptools 0.6c9`) and everything seems to be installed to `/usr/local/lib/python2.6/dist-packages`
I *assume* that when installing a package using apt-get, it's placed in `/usr/lib/python2.6/dist-packages/` ?
The issue is, there is a `/usr/local/lib/python2.6/site-packages` as well that just sits there being empty. It would seem (by looking at the `path` in a `virtualenv`) that this is the folder virtualenv uses as backup. Thus even thought I omit `--no-site-packages`, I cant access my local systems packages from any of my virtualenv's.
So my questions are:
1. How do I get `virtualenv` to point to one of the `dist-packages`?
2. *Which* dist-packages should I point it to? `/usr/lib/python2.6/dist-packages` or `/usr/local/lib/python2.6/dist-packages/`
3. What is the point of `/usr/lib/python2.6/site-packages`? There's nothing in there!
4. Is it first come first serve on the path? If I have a newer version of package XYZ installed in `/usr/local/lib/python2.6/dist-packages/` and and older one (from ubuntu repos/apt-get) in `/usr/lib/python2.6/dist-packages`, which one gets imported when I `import xyz`? I'm assuming this is based on the path list, yes?
5. Why the hell is this so confusing? Is there something I'm missing here?
6. Where is it defined that `easy_install` should install to `/usr/local/lib/python2.6/dist-packages`?
7. Will this affect `pip` as well?
Thanks to anyone who can clear this up! | I'd be tempted to hack it by making site-packages a link to dist-packages, but I guess this might affect other cases where you want to install some extension other than from the ubuntu dist. I can't think of another answer to 1 except tweaking virtualenv's sources (with both ubuntu and virtualenv being so popular I wouldn't be surprised to find tweaked versions already exist).
Re 2, if you're using /usr/local/bin/python you should use the /usr/local version of the lib (including site-packages) and conversely if you're using /usr/bin/python.
Re 3, there will be something there if you ever install an extension for /usr/bin/python from sources (not via easy\_install or from ubuntu's distro).
Re 4, yes, earlier entries on the path take precedence.
Re 5, easy\_install is easy only in its name -- it does so much dark magic that it's been carefully kept out of the standard python library despite its convenience because the consensus among us python committers is that deep dark magic for convenience is "easy" only on the surface.
Re 6, I think that's an ubuntu modification to easy\_install -- if that's right then it's defined wherever Canonical or other ubuntu maintainers make their collective decisions.
Re 7, sorry, no idea -- I have no reasonably recent ubuntu at hand to check. | I believe Mike Orr's answer from [the virtual-env mailing list](http://groups.google.com/group/python-virtualenv/browse_thread/thread/1412994580f0a2c6/17271fcd6a6e747e?lnk=gst&q=ubuntu+virtualenv#17271fcd6a6e747e) seems to be the best. Note the OP published this question in both places.
**Original content of mail:**
Years ago Debian created /usr/local/lib/pythonVERSION/site-packages,
and compiled the Python binary to include it in the default search
path. Ubuntu followed Debian's lead as it normally does. The Python
developers did not like this because you'd get interference with a
locally-installed /usr/local/bin/python using the same site-packages
directory. Ubuntu finally decided to abandon site-packages and use
dist-packages instead, a name which they invented so it wouldn't
interfere with anything. The loing story is out there somewhere if
you google it, somewhere in the Python bug tracker or distutils SIG or
such.
The system works, at least if you use the Ubuntu virtualenv package.
Some people have had problems using a locally-installed virtualenv on
Ubuntu because the magic sys.path entries weren't being added or
something. I'm not sure about --no-site-packages because I never use
that option: I run PIL and mysqldb from the Ubuntu packages because it
can be hard to compile their C dependencies sometimes. (Need the
right header files, Python is ignoring the header files, etc.)
So Ubuntu Python packages go into
/usr/lib/pythonVERSION/dist-packages. Or that python-support
directory for some reason. Locally-installed Python packages go into
/usr/local/lib/pythonVERSION/dist-packages by default. Whenever I
install an Ubuntu 9.04 system I run:
$ sudo apt-get install python-setuptools (6.0c9)
$ sudo apt-get install python-virtualenv (1.3.3)
$ sudo easy\_install pip
$ sudo pip install virtualenvwrapper
The virtualenvs work fine this way, although I haven't tried --no-site-packages.
> I'm trying to spin up virtualenv, and the --no-site-packages flag
> seems to do nothing with ubuntu. I installed virtualenv 1.3.3 with
> easy\_install (which I've upgraded to setuptools 0.6c9)
These versions are both in Ubuntu 9.04, so you're making it harder on
yourself by installing them locally.
> and everything
> seems to be installed to /usr/local/lib/python2.6/dist-packages
Yes
> I assume that when installing a package using apt-get, it's placed in /
> usr/lib/python2.6/dist-packages/ ?
Yes
> 4. Is it first come first serve on the path? If I have a newer
> version of package XYZ installed in /usr/local/lib/python2.6/dist-
> packages/ and and older one (from ubuntu repos/apt-get) in /usr/lib/
> python2.6/dist-packages, which one gets imported when I import xyz?
> I'm assuming this is based on the path list, yes?
sys.path is scanned in order. The only funny thing is that .pth eggs
get put earlier or later in the path than some people expect. But if
you're using pip for everything it can do (i.e. except to install pip
itself, precompiled eggs, and a snapshot of a local directory that's a
copy rather than an egg link), you won't have many .pth eggs anyway.
> 5. Why the hell is this so confusing? Is there something I'm
> missing here?
It's not well documented. I figured it out by scanning the web.
> 7. Will this affect pip as well?
Yes, pip will automatically install to
/usr/local/lib/pythonVERSION/site-packages. Use "pip install -E
$VIRTUAL\_ENV packagename" to install into a virtualenv. | Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages | [
"",
"python",
"ubuntu",
"setuptools",
"virtualenv",
""
] |
Getting started with TDD and the repository pattern, I'm wondering if it makes any sense testing this...
Using the repository pattern, I have this interface:
```
public interface ICustomerRepository
{
IList<Customer> List();
Customer Get(int id);
}
```
I have like 50 different entities, so 50 different repository interfaces/implementations.
My question is if it's correct to test each repository, by mocking up the interface, like:
```
[TestMethod]
public void List_Should_Return_Two_Customers()
{
// Arrange
var customerr = new List<Customer>();
customer.Add(new Customer());
customer.Add(new Customer());
var repository = new Mock<ICustomerRepository>();
repository.Setup(r => r.List()).Returns(customer);
// Assert
Assert.AreEqual(2, repository.Object.List().Count);
}
[TestMethod]
public void Get_Should_Return_One_Customer()
{
// Arrange
var customer = new List<Customer>();
customerr.Add(new Customer() { Id = 1 });
customerr.Add(new Customer() { Id = 2 });
var repository = new Mock<ICustomerRepository>();
repository.Setup(r => r.Get(1)).Returns(customer.Where(w => w.Id == 1).First());
// Assert
Assert.IsTrue(repository.Object.Get(1).Id == 1);
}
```
Does it make any sense testing a fake implementation of these interfaces? To me it does not. | **No, it does not make sense**. Obviously you should test only implementations, not interfaces. There is nothing to test in an interface.
The only things being tested in your examples are the mocking framework, the .NET list and some LINQ extension methods. There is no need to test those, somebody else already takes care of that.
Maybe the intention was to provide unit tests for the fact that the interface exists and has certain methods? In that case, the tests are still unnecessary. This is implicitly tested by the tests for other code that relies on the interface declaration.
You should only create an `ICustomerRepository` mock when you need a fake implementation in order to test other code. | Yes, it is "correct" to test each Repository. Repositories exist to abstract your database away from the code, and should be verified that they are working correctly. Your data access layer is arguably one of the most important components to test. | Does it make any sense testing this? (Repository pattern) | [
"",
"c#",
"unit-testing",
"repository",
""
] |
I'd like to write my own memory manager. The target language is C++ and the goal of the memory manager is mainly to help debugging. It should detect double frees, memory overwrite and so on. And of course - I'd like to learn about memory management.
Can someone give me a hint so resources where I can learn how to write such a memory manager?
Thank you for your help. | I think this is a very interesting project that you might learn a lot from. Here's a little bit of reading material on the subject of memory management. It goes over some of the basics of memory management, leads into a simple malloc implementation, then touches on a couple more advanced topics.
[Inside memory management](http://www.ibm.com/developerworks/linux/library/l-memory/)
Also, since you mention that you want to make a memory manager that is useful for debugging, you may want to consider reading this paper by the developers of Memcheck/Valgrind (A wonderful memory debugger for Linux). It details how they track all the the metadata (whether or not a particular byte is defined, intialized, etc.) in memchck. It's a bit detailed, but it's good reading on how to make a scalable and efficient dynamic memory checker.
[How to Shadow Every Byte of Memory Used by a Program](http://valgrind.org/docs/shadow-memory2007.pdf "Memcheck paper") | Dave Hanson's [C Interfaces and Implementations](http://www.cs.princeton.edu/software/cii/) presents first a standard memory manager and then a memory manager with a few debugging features. This would be a great starting point to learn from and extend.
Of course, if you actually want to diagnose memory problems in a running C or C++ program, you should use [`valgrind`](http://www.valgrind.org/). | Write your own memory manager | [
"",
"c++",
"memory-management",
""
] |
So I have a set of unit/integration tests and a set of selenium rc tests as part of my suite. When I run them together using PHPUnit I get a Segmentation fault error message at the very end of the run when, during normal operation, it starts to generate log files. The interesting part is, if I run just the unit tests, or just the selenium rc tests everything works fine. I'm reasonably certain it's not a problem with my code-base because I can visually see all my tests passing. As I said, the error occurs during the results generation phase.
I'm using code-coverage for the unit tests but NOT for the selenium tests (by leaving the $coverageScriptUrl property empty in my selenium objects).
I'm really grasping at straws here because I've never had to diagnose an error with no file or line number. Is there some place I check for some more information? Can someone point me in the right direction? The php error log is empty.
Any ideas? | I've run into the same kind of trouble, at work, with a colleague : one day, we started having a segfault, with apparently no reason, as the same code was running fine on another machine :-(
We ended up removing code coverage *(as it was not that useful to us ; was too low anyway)*
Couple of things you could try :
* try with the latest version of Xdebug (sometimes, those are supposed to correct stuff like that)
* try with an older version Xdebug (why not ? )
* think about splitting your test suite in two executions on PHPUnit :
+ one execution with code coverage, for unit-tests
+ one execution without code coverage (as you don't use it anyway), for functional-tests
Another thng might be to try with a CVS version of Xdebug 2.1, instead of the the stable 2.0.x ; but not sure that'll help (see <http://www.phpunit.de/ticket/513> for instance)
There are a couple of bug reports related to segfaults on Xdebug's Mantis BT ; some of those are not solved.
For instance :
* <http://bugs.xdebug.org/view.php?id=402>
* <http://bugs.xdebug.org/view.php?id=321>
* <http://bugs.xdebug.org/view.php?id=176>
Anyway, good luck...
*<(And if you ever find what was causing the problem, I'm interested ;-) )* | Segfaults in PHP can definitely be tricky.
As a wild guess, are you running PHPUnit 3.4? It looks like [there's a bug](http://www.phpunit.de/ticket/809) reported with Selenium integration just a few weeks ago when using the `$this->selectWindow()` call and a `null` parameter. | Selenium RC Tests + Unit Tests using PHPUnit throws a Seg Fault | [
"",
"php",
"testing",
"selenium",
"phpunit",
""
] |
I want to know more about OOP in PHP 5.2.
Can anybody help me with a link to advanced OOP tutorials in PHP?
I know about `static`, `public` and `private` class member attributes, but I need more info about basic and advanced OO techniques. I hope somebody can help. :) | Have you checked out the [OOP WikiBook entry](http://en.wikibooks.org/wiki/Object_oriented_programming)? | In order to first understand OOP with PHP, you must understand the core concepts behind OOP. Tutorials won't help you correctly grasps things like abstraction, inheritance, encapsulation, and polymorphism.
Grab a book about Object Oriented Programming, that is the best way to learn. One of my favorites is:
# Design Patterns: Elements of Reusable Object-Oriented Software
[](https://rads.stackoverflow.com/amzn/click/com/0201633612)
If you want something more PHP oriented, I heard nothing but good things about:
# PHP 5 Objects, Patterns, and Practice
[PHP 5 Objects, Patterns, and Practice http://ecx.images-amazon.com/images/I/51BF7MF03NL.\_BO2,204,203,200\_PIsitb-sticker-arrow-click,TopRight,35,-76\_AA240\_SH20\_OU01\_.jpg](http://www.amazon.com/)
Both are available at [Amazon.com](https://rads.stackoverflow.com/amzn/click/com/1590593804)
I don't understand why so many young/new programmers have a total aversion for books when they start learning. | Advanced OOP in PHP5? | [
"",
"php",
"oop",
"class",
""
] |
I have a number of methods in C# which return various collections which I wish to test. I would like to use as few test APIs as possible - performance is not important. A typical example is:
```
HashSet<string> actualSet = MyCreateSet();
string[] expectedArray = new string[]{"a", "c", "b"};
MyAssertAreEqual(expectedArray, actualSet);
```
//...
```
void MyAssertAreEqual(string[] expected, HashSet<string> actual)
{
HashSet<string> expectedSet = new HashSet<string>();
foreach {string e in expected)
{
expectedSet.Add(e);
}
Assert.IsTrue(expectedSet.Equals(actualSet));
}
```
I am having to write a number of signatures according to whether the collections are arrays, Lists, ICollections, etc. Are there transformations which simplify this (e.g. for converting an array to a Set?).
I also need to do this for my own classes. I have implemented HashCode and Equals for them. They are (mainly) subclassed from (say) MySuperClass. Is it possible to implement the functionality:
```
void MyAssertAreEqual(IEnumerable<MySuperClass> expected,
IEnumerable<MySuperClass> actual);
```
such that I can call:
```
IEnumerable<MyClassA> expected = ...;
IEnumerable<MyClassA> actual = ...;
MyAssertAreEqual(expected, actual);
```
rather than writing this for every class | Both NUnit and MSTest (probably the other ones as well) have a CollectionAssert class
* [CollectionAssert (NUnit 2.5)](http://www.nunit.org/index.php?p=collectionAssert&r=2.5.1)
* [CollectionAssert for MSTest](http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.aspx) | If you are using .NET 3.5 you can use the Enumerable.SequenceEqual method.
```
Assert.IsTrue(seqA.SequenceEqual(seqB));
```
You should use OrderBy on both sequences prior to calling SequenceEqual if you only care about the elements being equal and not the order. | How can I create unit tests involving collections in c#? | [
"",
"c#",
"unit-testing",
"collections",
""
] |
I have an input string and I want to verify that it contains:
* Only letters or
* Only letters and numbers or
* Only letters, numbers or underscore
To clarify, I have 3 different cases in the code, each calling for different validation. What's the simplest way to achieve this in C#? | Only letters:
```
Regex.IsMatch(input, @"^[a-zA-Z]+$");
```
Only letters and numbers:
```
Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");
```
Only letters, numbers and underscore:
```
Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");
``` | ```
bool result = input.All(Char.IsLetter);
bool result = input.All(Char.IsLetterOrDigit);
bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');
``` | Verifying that a string contains only letters in C# | [
"",
"c#",
"string",
""
] |
What is the difference between [`PDOStatement::bindParam()`](http://www.php.net/manual/en/pdostatement.bindparam.php) and [`PDOStatement::bindValue()`](http://www.php.net/manual/en/pdostatement.bindvalue.php)? | The answer is in the documentation for [`bindParam`](http://www.php.net/manual/en/pdostatement.bindparam.php):
> Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
And [`execute`](http://php.net/manual/en/pdostatement.execute.php)
> call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers
Example:
```
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindParam(':baz', $value); // use bindParam to bind the variable
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foobarbaz'
```
or
```
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindValue(':baz', $value); // use bindValue to bind the variable's value
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foo'
``` | From [the manual entry for `PDOStatement::bindParam`](http://php.net/manual/en/pdostatement.bindparam.php):
> [With `bindParam`] Unlike `PDOStatement::bindValue()`, the variable is bound as a reference and will only be evaluated at the time that `PDOStatement::execute()` is called.
So, for example:
```
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindParam(':sex', $sex); // use bindParam to bind the variable
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'female'
```
or
```
$sex = 'male';
$s = $dbh->prepare('SELECT name FROM students WHERE sex = :sex');
$s->bindValue(':sex', $sex); // use bindValue to bind the variable's value
$sex = 'female';
$s->execute(); // executed with WHERE sex = 'male'
``` | What is the difference between bindParam and bindValue? | [
"",
"php",
"pdo",
"bindparam",
"bindvalue",
""
] |
I've got this header (redone from a boost asio example):
```
#ifndef MSGSRV_H_
#define MSGSRV_H_
#include <asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/system/error_code.hpp>
namespace msgSrv {
class msgSrv {
private:
asio::ip::udp::socket *asioSocket;
asio::io_service *asioIoService;
int listenPort;
boost::array<char,1> rcvBuff;
asio::ip::udp::endpoint lastRcvdPcktEndp;
public:
msgSrv(int listenPort);
virtual ~msgSrv();
void start();
void pckRcvd( boost::system::error_code &, std::size_t);
};
}
```
and the .cpp:
```
#include "msgSrv.h"
namespace msgSrv {
msgSrv::msgSrv(int listenPort) {
// TODO Auto-generated constructor stub
this->listenPort = listenPort;
try{
asioIoService = new asio::io_service();
asioSocket = new asio::ip::udp::socket(*asioIoService, asio::ip::udp::endpoint(asio::ip::udp::v4(), listenPort)); //new asio::ip::udp::socket_(*asioIoService, udp::endpoint(udp::v4(), listenPort));
}catch(std::exception &e){
std::cerr << "Error initializing ioservice or socket:" << e.what();
}
}
msgSrv::~msgSrv() {
// TODO Auto-generated destructor stub
delete asioIoService;
delete asioSocket;
}
void msgSrv::start(){
asioSocket->async_receive_from(
asio::buffer(rcvBuff), lastRcvdPcktEndp,
boost::bind(&msgSrv::pckRcvd, this,
asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
void msgSrv::pckRcvd( boost::system::error_code &error, std::size_t bytesRcvd){
std::cout << "Rcvd!\n";
}
}
```
Now, it refuses to compile, giving un-intelligible results:
```
> make all
Building file: ../src/msgSrv/msgSrv.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/msgSrv/msgSrv.d" -MT"src/msgSrv/msgSrv.d" -o"src/msgSrv/msgSrv.o" "../src/msgSrv/msgSrv.cpp"
/usr/include/boost/bind.hpp: In member function ‘void boost::_bi::list3<A1, A2, A3>::operator()(boost::_bi::type<void>, F&, A&, int) [with F = boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, A = boost::_bi::list2<asio::error::basic_errors&, int&>, A1 = boost::_bi::value<msgSrv::msgSrv*>, A2 = boost::arg<1> (*)(), A3 = boost::arg<2> (*)()]’:
/usr/include/boost/bind/bind_template.hpp:61: instantiated from ‘typename boost::_bi::result_traits<R, F>::type boost::_bi::bind_t<R, F, L>::operator()(A1&, A2&) [with A1 = asio::error::basic_errors, A2 = int, R = void, F = boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, L = boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()>]’
/usr/include/asio/detail/bind_handler.hpp:95: instantiated from ‘void asio::detail::binder2<Handler, Arg1, Arg2>::operator()() [with Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Arg1 = asio::error::basic_errors, Arg2 = int]’
/usr/include/asio/handler_invoke_hook.hpp:62: instantiated from ‘void asio::asio_handler_invoke(Function, ...) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>]’
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ‘void asio_handler_invoke_helpers::invoke(const Function&, Context*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>, Context = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >]’
/usr/include/asio/detail/bind_handler.hpp:129: instantiated from ‘void asio::detail::asio_handler_invoke(const Function&, asio::detail::binder2<Handler, Arg1, Arg2>*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>, Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Arg1 = asio::error::basic_errors, Arg2 = int]’
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ‘void asio_handler_invoke_helpers::invoke(const Function&, Context*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>, Context = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>]’
/usr/include/asio/detail/handler_queue.hpp:191: instantiated from ‘static void asio::detail::handler_queue::handler_wrapper<Handler>::do_call(asio::detail::handler_queue::handler*) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>]’
/usr/include/asio/detail/handler_queue.hpp:171: instantiated from ‘asio::detail::handler_queue::handler_wrapper<Handler>::handler_wrapper(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>]’
/usr/include/asio/detail/handler_alloc_helpers.hpp:137: instantiated from ‘asio::detail::handler_ptr<Alloc_Traits>::handler_ptr(asio::detail::raw_handler_ptr<Alloc_Traits>&, Arg1&) [with Arg1 = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>, Alloc_Traits = asio::detail::handler_alloc_traits<asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>, asio::detail::handler_queue::handler_wrapper<asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int> > >]’
/usr/include/asio/detail/handler_queue.hpp:116: instantiated from ‘static asio::detail::handler_queue::handler* asio::detail::handler_queue::wrap(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>]’
/usr/include/asio/detail/task_io_service.hpp:190: instantiated from ‘void asio::detail::task_io_service<Task>::post(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>, Task = asio::detail::epoll_reactor<false>]’
/usr/include/asio/impl/io_service.ipp:125: instantiated from ‘void asio::io_service::post(Handler) [with CompletionHandler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error::basic_errors, int>]’
/usr/include/asio/detail/reactive_socket_service.hpp:1376: instantiated from ‘void asio::detail::reactive_socket_service<Protocol, Reactor>::async_receive_from(asio::detail::reactive_socket_service<Protocol, Reactor>::implementation_type&, const MutableBufferSequence&, typename Protocol::endpoint&, int, Handler) [with MutableBufferSequence = asio::mutable_buffers_1, Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Protocol = asio::ip::udp, Reactor = asio::detail::epoll_reactor<false>]’
/usr/include/asio/datagram_socket_service.hpp:310: instantiated from ‘void asio::datagram_socket_service<Protocol>::async_receive_from(typename asio::detail::reactive_socket_service<Protocol, asio::detail::epoll_reactor<false> >::implementation_type&, const MutableBufferSequence&, typename Protocol::endpoint&, int, ReadHandler) [with MutableBufferSequence = asio::mutable_buffers_1, ReadHandler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Protocol = asio::ip::udp]’
/usr/include/asio/basic_datagram_socket.hpp:756: instantiated from ‘void asio::basic_datagram_socket<Protocol, DatagramSocketService>::async_receive_from(const MutableBufferSequence&, typename Protocol::endpoint&, ReadHandler) [with MutableBufferSequence = asio::mutable_buffers_1, ReadHandler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Protocol = asio::ip::udp, DatagramSocketService = asio::datagram_socket_service<asio::ip::udp>]’
../src/msgSrv/msgSrv.cpp:37: instantiated from here
/usr/include/boost/bind.hpp:348: error: no match for call to ‘(boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>) (msgSrv::msgSrv*&, asio::error::basic_errors&, int&)’
/usr/include/boost/bind/mem_fn_template.hpp:272: note: candidates are: R boost::_mfi::mf2<R, T, A1, A2>::operator()(T*, A1, A2) const [with R = void, T = msgSrv::msgSrv, A1 = boost::system::error_code&, A2 = unsigned int]
/usr/include/boost/bind/mem_fn_template.hpp:291: note: R boost::_mfi::mf2<R, T, A1, A2>::operator()(T&, A1, A2) const [with R = void, T = msgSrv::msgSrv, A1 = boost::system::error_code&, A2 = unsigned int]
/usr/include/boost/bind.hpp: In member function ‘void boost::_bi::list3<A1, A2, A3>::operator()(boost::_bi::type<void>, F&, A&, int) [with F = boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, A = boost::_bi::list2<asio::error_code&, int&>, A1 = boost::_bi::value<msgSrv::msgSrv*>, A2 = boost::arg<1> (*)(), A3 = boost::arg<2> (*)()]’:
/usr/include/boost/bind/bind_template.hpp:61: instantiated from ‘typename boost::_bi::result_traits<R, F>::type boost::_bi::bind_t<R, F, L>::operator()(A1&, A2&) [with A1 = asio::error_code, A2 = int, R = void, F = boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, L = boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()>]’
/usr/include/asio/detail/bind_handler.hpp:95: instantiated from ‘void asio::detail::binder2<Handler, Arg1, Arg2>::operator()() [with Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Arg1 = asio::error_code, Arg2 = int]’
/usr/include/asio/handler_invoke_hook.hpp:62: instantiated from ‘void asio::asio_handler_invoke(Function, ...) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>]’
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ‘void asio_handler_invoke_helpers::invoke(const Function&, Context*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>, Context = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >]’
/usr/include/asio/detail/bind_handler.hpp:129: instantiated from ‘void asio::detail::asio_handler_invoke(const Function&, asio::detail::binder2<Handler, Arg1, Arg2>*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>, Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Arg1 = asio::error_code, Arg2 = int]’
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ‘void asio_handler_invoke_helpers::invoke(const Function&, Context*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>, Context = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>]’
/usr/include/asio/detail/handler_queue.hpp:191: instantiated from ‘static void asio::detail::handler_queue::handler_wrapper<Handler>::do_call(asio::detail::handler_queue::handler*) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>]’
/usr/include/asio/detail/handler_queue.hpp:171: instantiated from ‘asio::detail::handler_queue::handler_wrapper<Handler>::handler_wrapper(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>]’
/usr/include/asio/detail/handler_alloc_helpers.hpp:137: instantiated from ‘asio::detail::handler_ptr<Alloc_Traits>::handler_ptr(asio::detail::raw_handler_ptr<Alloc_Traits>&, Arg1&) [with Arg1 = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>, Alloc_Traits = asio::detail::handler_alloc_traits<asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>, asio::detail::handler_queue::handler_wrapper<asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int> > >]’
/usr/include/asio/detail/handler_queue.hpp:116: instantiated from ‘static asio::detail::handler_queue::handler* asio::detail::handler_queue::wrap(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>]’
/usr/include/asio/detail/task_io_service.hpp:190: instantiated from ‘void asio::detail::task_io_service<Task>::post(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>, Task = asio::detail::epoll_reactor<false>]’
/usr/include/asio/impl/io_service.ipp:125: instantiated from ‘void asio::io_service::post(Handler) [with CompletionHandler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, int>]’
/usr/include/asio/detail/reactive_socket_service.hpp:1390: instantiated from ‘void asio::detail::reactive_socket_service<Protocol, Reactor>::async_receive_from(asio::detail::reactive_socket_service<Protocol, Reactor>::implementation_type&, const MutableBufferSequence&, typename Protocol::endpoint&, int, Handler) [with MutableBufferSequence = asio::mutable_buffers_1, Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Protocol = asio::ip::udp, Reactor = asio::detail::epoll_reactor<false>]’
/usr/include/asio/datagram_socket_service.hpp:310: instantiated from ‘void asio::datagram_socket_service<Protocol>::async_receive_from(typename asio::detail::reactive_socket_service<Protocol, asio::detail::epoll_reactor<false> >::implementation_type&, const MutableBufferSequence&, typename Protocol::endpoint&, int, ReadHandler) [with MutableBufferSequence = asio::mutable_buffers_1, ReadHandler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Protocol = asio::ip::udp]’
/usr/include/asio/basic_datagram_socket.hpp:756: instantiated from ‘void asio::basic_datagram_socket<Protocol, DatagramSocketService>::async_receive_from(const MutableBufferSequence&, typename Protocol::endpoint&, ReadHandler) [with MutableBufferSequence = asio::mutable_buffers_1, ReadHandler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Protocol = asio::ip::udp, DatagramSocketService = asio::datagram_socket_service<asio::ip::udp>]’
../src/msgSrv/msgSrv.cpp:37: instantiated from here
/usr/include/boost/bind.hpp:348: error: no match for call to ‘(boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>) (msgSrv::msgSrv*&, asio::error_code&, int&)’
/usr/include/boost/bind/mem_fn_template.hpp:272: note: candidates are: R boost::_mfi::mf2<R, T, A1, A2>::operator()(T*, A1, A2) const [with R = void, T = msgSrv::msgSrv, A1 = boost::system::error_code&, A2 = unsigned int]
/usr/include/boost/bind/mem_fn_template.hpp:291: note: R boost::_mfi::mf2<R, T, A1, A2>::operator()(T&, A1, A2) const [with R = void, T = msgSrv::msgSrv, A1 = boost::system::error_code&, A2 = unsigned int]
/usr/include/boost/bind.hpp: In member function ‘void boost::_bi::list3<A1, A2, A3>::operator()(boost::_bi::type<void>, F&, A&, int) [with F = boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, A = boost::_bi::list2<asio::error_code&, unsigned int&>, A1 = boost::_bi::value<msgSrv::msgSrv*>, A2 = boost::arg<1> (*)(), A3 = boost::arg<2> (*)()]’:
/usr/include/boost/bind/bind_template.hpp:61: instantiated from ‘typename boost::_bi::result_traits<R, F>::type boost::_bi::bind_t<R, F, L>::operator()(A1&, A2&) [with A1 = asio::error_code, A2 = unsigned int, R = void, F = boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, L = boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()>]’
/usr/include/asio/detail/bind_handler.hpp:95: instantiated from ‘void asio::detail::binder2<Handler, Arg1, Arg2>::operator()() [with Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Arg1 = asio::error_code, Arg2 = unsigned int]’
/usr/include/asio/handler_invoke_hook.hpp:62: instantiated from ‘void asio::asio_handler_invoke(Function, ...) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>]’
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ‘void asio_handler_invoke_helpers::invoke(const Function&, Context*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>, Context = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >]’
/usr/include/asio/detail/bind_handler.hpp:129: instantiated from ‘void asio::detail::asio_handler_invoke(const Function&, asio::detail::binder2<Handler, Arg1, Arg2>*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>, Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, Arg1 = asio::error_code, Arg2 = unsigned int]’
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ‘void asio_handler_invoke_helpers::invoke(const Function&, Context*) [with Function = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>, Context = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>]’
/usr/include/asio/detail/handler_queue.hpp:191: instantiated from ‘static void asio::detail::handler_queue::handler_wrapper<Handler>::do_call(asio::detail::handler_queue::handler*) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>]’
/usr/include/asio/detail/handler_queue.hpp:171: instantiated from ‘asio::detail::handler_queue::handler_wrapper<Handler>::handler_wrapper(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>]’
/usr/include/asio/detail/handler_alloc_helpers.hpp:137: instantiated from ‘asio::detail::handler_ptr<Alloc_Traits>::handler_ptr(asio::detail::raw_handler_ptr<Alloc_Traits>&, Arg1&) [with Arg1 = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>, Alloc_Traits = asio::detail::handler_alloc_traits<asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>, asio::detail::handler_queue::handler_wrapper<asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int> > >]’
/usr/include/asio/detail/handler_queue.hpp:116: instantiated from ‘static asio::detail::handler_queue::handler* asio::detail::handler_queue::wrap(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>]’
/usr/include/asio/detail/task_io_service.hpp:190: instantiated from ‘void asio::detail::task_io_service<Task>::post(Handler) [with Handler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>, Task = asio::detail::epoll_reactor<false>]’
/usr/include/asio/impl/io_service.ipp:125: instantiated from ‘void asio::io_service::post(Handler) [with CompletionHandler = asio::detail::binder2<boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(), boost::arg<2> (*)()> >, asio::error_code, unsigned int>]’
/usr/include/asio/detail/reactive_socket_service.hpp:1353: instantiated from ‘void asio::detail::reactive_socket_service<Protocol, Reactor>::receive_from_operation<MutableBufferSequence, Handler>::complete(const asio::error_code&, size_t) [with MutableBufferSequence = asio::mutable_buffers_1, Handler = boost::_bi::bind_t<void, boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>, boost::_bi::list3<boost::_bi::value<msgSrv::msgSrv*>, boost::arg<1> (*)(),
```
...and so on. I really don't know what to do since I can't understand what the error is about! | Due to the large number of templates instantiated, the error messages are quite long, but most of it is giving what could be helpful context. I've taken the first error and snipped the excessively long lines.
First the compiler says where the error is, and what sequence of template instantiations resulted in the particular template instance the resulted in the error to be instantiated.
```
/usr/include/boost/bind.hpp: In member function ‘void boost::_bi::list3<A1, A2, A3>::operator()(boost::_bi::type<void>, F&, A&, int) ...
/usr/include/boost/bind/bind_template.hpp:61: instantiated from ...
/usr/include/asio/detail/bind_handler.hpp:95: instantiated from ...
/usr/include/asio/handler_invoke_hook.hpp:62: instantiated from ...
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ...
/usr/include/asio/detail/bind_handler.hpp:129: instantiated from ...
/usr/include/asio/detail/handler_invoke_helpers.hpp:39: instantiated from ...
/usr/include/asio/detail/handler_queue.hpp:191: instantiated from ...
/usr/include/asio/detail/handler_queue.hpp:171: instantiated from ...
/usr/include/asio/detail/handler_alloc_helpers.hpp:137: instantiated from ...
/usr/include/asio/detail/handler_queue.hpp:116: instantiated from ...
/usr/include/asio/detail/task_io_service.hpp:190: instantiated from ...
/usr/include/asio/impl/io_service.ipp:125: instantiated from ...
/usr/include/asio/detail/reactive_socket_service.hpp:1376: instantiated from ...
/usr/include/asio/datagram_socket_service.hpp:310: instantiated from ...
/usr/include/asio/basic_datagram_socket.hpp:756: instantiated from ...
```
And here is the line of your code that resulted in all that happening:
```
../src/msgSrv/msgSrv.cpp:37: instantiated from here
```
And here is the real error:
```
/usr/include/boost/bind.hpp:348: error: no match for call to ‘(boost::_mfi::mf2<void, msgSrv::msgSrv, boost::system::error_code&, unsigned int>) (msgSrv::msgSrv*&, asio::error::basic_errors&, int&)’
/usr/include/boost/bind/mem_fn_template.hpp:272: note: candidates are: R boost::_mfi::mf2<R, T, A1, A2>::operator()(T*, A1, A2) const [with R = void, T = msgSrv::msgSrv, A1 = boost::system::error_code&, A2 = unsigned int]
/usr/include/boost/bind/mem_fn_template.hpp:291: note: R boost::_mfi::mf2<R, T, A1, A2>::operator()(T&, A1, A2) const [with R = void, T = msgSrv::msgSrv, A1 = boost::system::error_code&, A2 = unsigned int]
```
For the purposes of argument passing, `msgSrv::msgSrv*&` will convert to `msgSrv::msgSrv*`, but the `A1` parameter is a reference and `boost::system::error_code` and `asio::error::basic_errors` are not *reference-compatible*.
**Edit:**
If you read the type requirements for a [read handler](http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio/reference/ReadHandler.html), you'll see that the handler has work with a first parameter that is *l-value* of type `const error_code`. This means that your first parameter has to be either `const boost::system::error_code&` (i.e. a const reference) or `boost::system::error_code`, a non-reference parameter. | Try out the [STL Error Decryptor](http://www.bdsoft.com/tools/stlfilt.html) for assistance in understanding error messages from templated code. | Boost beginner, boost::bind nightmare | [
"",
"c++",
"boost",
"bind",
""
] |
I am developing a client-server application - the server being an ASP .NET web app.
The client (a desktop app) needs to send data contained in a text file to my asp .net web app.
Data would be approximately 100 KB, in multi-line textual form.
What is the best approach to POST this data to the server, given that I need to do it once every 10 minutes or so? | If the file is small enough that you can easily fit it in memory (which you would want it to be if you're sending it via POST) then you can simply do the following:
```
string textFileContents = System.IO.File.ReadAllText( @"C:\MyFolder\MyFile.txt" );
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://www.myserver.com/myurl.aspx" );
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "fileContents=" + System.Web.HttpUtility.UrlEncode( textFileContents );
byte[] data = encoding.GetBytes( postData );
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write( data, 0, data.Length );
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// do something with the response if required
```
As far as reading the text server side you can just use the Page.Request.Form[ "fileContents" ] | I'm confused; you say you want it as a POST param, but then you read it from a header...? That would be the Form for typical post fields, or just the request body for raw data...
For sending form fields:
```
NameValueCollection fields = new NameValueCollection();
fields.Add("name1","some text");
fields.Add("name2","some more text");
using (var client = new WebClient())
{
byte[] resp = client.UploadValues(address, fields);
// use Encoding to get resp as a string if needed
}
```
For sending a raw file (not as a form; just the text itself), use `UploadFile`; and for headers, use `.Headers.Add`. | POST data from a text file (read by a desktop client) to an ASP .NET based server | [
"",
"c#",
".net",
"post",
"upload",
""
] |
Yesterday I asked about C++ context sensitivity, see [here](https://stackoverflow.com/questions/1172939/is-any-part-of-c-syntax-context-sensitive). Among many excellent answers, [here](https://stackoverflow.com/questions/1172939/is-any-part-of-c-syntax-context-sensitive/1173004#1173004) is the accepted one, by [dmckee](https://stackoverflow.com/users/2509/dmckee).
However, I still think there's something to be said about this (maybe some terminological confusion?). The question amounts to: what part of compilation deals with the ambiguity?
To clarify my terminology: A CFG is a grammar that has only one non-terminal symbol on the left-hand-side of the rule (eg. `A->zC`), a CSG is one that has a terminal (plus a non-terminal) on the left-hand-side (`aAv->QT`), where uppercase letters are nonterminals and lowercase are terminals.
Is any representation like the latter in the **grammar** parsing C++ source code?
Thank you, and sorry to push the issue. | No C++ front end (parser, name/type resolver) that I know of
([including the one we built](http://www.semanticdesigns.com/Products/FrontEnds/CppFrontEnd.html)) implements a context sensitive parser using CSG grammar rules as you defined it. Pretty much they operate explicitly or implicitly with a context free grammar which still has ambiguities.
Many of them use a combination of top-down parsing and interwoven collection of type information to distinguish between the ambiguous cases.
Weaving the parsing and type collection together makes building a parser this way really messy and hard, producing the folk theorem "C++ is hard to parse".
Like many such "theorems", it isn't true, unless you also insist on parsing with one hand tied behind your back (e.g., recursive descent, LL(k), LALR [e.g., YACC]). If you use a parsing technology that can handle ambiguities, the C++ grammar is actually not so hard. We (and others, such as the
[Elsa](http://www.cs.berkeley.edu/~smcpeak/elkhound/sources/elsa) C++ parser) use GLR parsing technology for this reason. (We go a bit further and capture macro definitions, uses and preprocessor conditionals in the C++ grammer because we are interested in transforming the code before the processor has ruined it; normally preprocessor directives are treated completely separately in an independent preprocessor).
Elsa I think still interleaves the ambiguity resolution into the parsing process, but because the parsing is so clean this is easier to do. Our front end builds an AST with ambiguity nodes, and after the tree is built, we walk the tree using an attribute grammar evaluator to collect names, and types, and eliminate those branches of ambiguities that are type inconsistent. The latter is a really beautiful scheme, and completely decouples parsing and name resolution.
What *is* hard is actually doing the name resolution. C++ has a pretty arcane scheme for looking things up, and its spread across the 600 pages of the standard, as well as bent in various ways by various dialects. Keeping name resolution separate from parsing makes this ugliness more manageable, but the folk theorem should be "C++ is hard to name resolve". | First there is the difference between the language and the grammar. A
language is a set of strings. A grammar is a way of describing a set of
strings (one often say that a grammar "generates" the strings). A given
language may be described by several grammars.
The most well known kind of grammar are the production based one. Those
where classified by Chomsky in
* unrestricted grammars, where there can be anything on the two sides of the
productions
* monotonic grammar, where the left hand side is at most as long as the
right hand side
* context-sensitive, where only one non-terminal is expanded
* context-free, where the left hand side of productions consist only of one
non terminal
* regular grammars, where the left hand side of productions consist only of
one non terminal and right hand side of production may have only one
non-terminal, as the latest element.
Monotonic and context-sensitive grammars are also called type 1 grammars.
They are able to generate the same languages. They are less powerfull than
type 0 grammars. AFAIK, while I've seen proofs that there are languages
which have a type 0 grammar but no type 1 one, I know of no example.
Context-free grammars are called type 2 grammars. They are less
powerfull than type 1 grammar. The standard example of language for which
there is no type 2 grammar but a type 1 grammar is the set of strings
consisting of an equal number of a, b and c, with the a before the b and
the b before the c.
Regular grammar are also called type 3 grammars. They are less powerfull
than type 2 grammars. The standard example of a language for which there
is no type 3 grammar but a type 2 grammar is the set of strings with
correctly matching parenthesis.
Ambiguity in grammars is something outside that hierarchy. A grammar is
ambiguous if a given string can generated in several ways. There are
unambigous type 1 grammars, and there are ambiguous type 3 grammars.
Then there are other kinds of grammars, which aren't part on Chomsky
classification (two levels grammars, attribute grammars, tree adjoining
grammars, ...) even if they are based on productions. Some of these are
even able to describe the semantic of programming languages.
Then there are parsing algorithms. Those often are based on CFG and impose
more restrictions to get better parsing speed (parsing a CSG needs
exponential time, a CFG needs cubic time, common algorithms only linear
time). Those restrictions introduce other classes of grammars.
CSG and monotonic grammars are in fact of little use to describe or compile
a programming language: their global behaviour isn't apparent and is
synthesised from local properties, so they are difficult to understand and
attaching semantic to production is problematic, parsing them is costly --
in general exponential -- and error handling is difficult. The non Chomsky
grammars were introduced to solve these issues.
Back to C++. The standard describes the C++ language with a context-free
grammar but
* there are ambiguities (the famous "most vexing parse"). So a compiler
has to recognize the ambiguities and use the right interpretation (i.e.
`C x();` is a function declaration, not an object definition).
* the grammar is not LR(1) (one of the most well known subset of CFG for
which a linear parsing algorithm exist). Other algorithms (potentially
more costly in time or space) are used, either based on a more general
theory or by tweeking linear one to adapt them to C++ rules. Simplifying
the grammar and rejecting the incorrectly accepted programs in the
semantic analysis is also a possibility.
* the correspondance between strings of characters and terminals is
modified (mainly by type and template declarations, the need to take that
into account in template definition has been solved with the use of
`typename` and `template` for dependent names). This is solved by having
the lexing phase query the symbol table so that a given string will give
a terminal or another depending on the context.
* there are additional constraints (need to declarare some identifiers,
type checking, ...) described in a more of less formal variant of
english. This is usually considered semantic even if some more powerfull
grammar descriptions could handle them. | Where does context sensitivity get resolved in the C++ compilation process? | [
"",
"c++",
"parsing",
"compiler-construction",
""
] |
I want to send data to an emailaddress and save it into a MySQL database (PHP).
What is the easiest way to do this? (no form post, no curl etc., just email) | If your server doesn't have imap but you have an outside system which does have cron you can write a page that checks the email account and loads the data into MySQL then set up a script on a machine that does have cron to wget the mysql page once every X minutes where X is how frequently you want to load data.
Alternately if you know the emails will load quickly you can set up small one field table in your DB with a time stamp. Each time your PHP script runs it checks the time stamp and if it's more than 5 minutes old it calls the email loading script before loading the web page. | there are a few ways.
* use a postfix alias script, basically, postfix receives your mail, and then runs it through a script of your choosing. The contents of the mail appear in STDIN - then you can do as you please with the contents of the mail.
* Use a custom mail server like apache james, that is designed to process mail, and 'do something with it'
{A good one I found recently was in the google labs - <http://freshmeat.net/projects/subethasmtp>} - looked really good.
pls bear in mind that email is not a guaranteed protocol, if you are trying to do app-to-app messaging, then there are probably better ways!
Hope this helps., ace | Mail to MySQL Database | [
"",
"php",
"mysql",
"email",
""
] |
Is there a C library version of the C++ std::map in a standard library? | `std::map` is not a hash table. Therefore, my suggestion: [Red-Black Tree C Code](http://www.mit.edu/~emin/source_code/red_black_tree/index.html)
> The following C files implement balanced binary trees using the red-black paradigm. I have written these functions in a very general manner so that the key can be anything at all. Each node of the balanced binary tree must contain a key and a pointer to info. The user defines what data-type the key is and provides a comparison function for the keys. The info can also be any kind of data type.
(Disclaimer: haven't tried it myself.) | The C standard library does not support such an equivalent. However, a commonly used C library is [GLib](http://library.gnome.org/devel/glib/stable/) from the GNOME project. In particular, the [GLib Hash Tables](http://library.gnome.org/devel/glib/stable/glib-Hash-Tables.html) may be what you're looking for. | C version of C++ std::map | [
"",
"c++",
"c",
""
] |
Installed the Google App Engine SDK.Python 2.6 perfect.
Wanted to go into images, and test locally.Installed PIL
Installed Python, then ran the PIL install, worked this time.
Things seemed good, but trying to do localhost image manipulation
gives:
```
"NotImplementedError: Unable to find the Python PIL library. Please
view the SDK documentation for details about installing PIL on your system."
```
System : winxp | We're probably going to need more information, so here are some questions and things to try.
How are you trying to access the PIL? Are you trying to use the google.appengine.api.images module, or PIL directly? It sounds like the former, but it's not clear.
Did you follow [the App Engine instructions](http://code.google.com/appengine/docs/python/images/)?
Post code, if you can.
Perhaps the most important thing to try: see if you can use PIL from a non-App Engine script. Just write a quick Python script that accesses it and see how that goes. Something like:
```
import Image
im = Image.open('filename.png')
im.show()
```
If that doesn't work, it's not surprising that Google App Engine wouldn't work with PIL. | I took a while to get PIL working. Mainly because I forgot to tell app engine to load it in the yaml file:
```
libraries:
- name: PIL
version: 1.1.7
```
Maybe this step is obvious, but I did not see it documented well on google documentation and I found all kinds of messages here stating that PIL was not available on app engine. I want to confirm that PIL is running on app engine. | Unable to find the Python PIL library.Google App Engine | [
"",
"python",
"google-app-engine",
"python-imaging-library",
""
] |
for some reason, whenever I *dynamically load a swf* on a $(document).ready() by writing to a div, I am unable to make javascript calls to the browser. Specifically, all calls to the browser return "null". This does not occur when embedding the swf normally on the page load, but I would like to prevent loading of the swf until a specified point in time.
What the heck is going on here? Is there something special about dynamically embedding a swf that prevents the swf from talking to the browser? The methods ARE called (I've proven such by showing alerts), but all return values to *any* function, regardless of type returned, shows as null when it gets to flash.
Is this a bug with flex, or am I missing something entirely? This has been a major headache for me. | Switching to swfobject2.2 to embed the swf alleviated the problem magically. | I assume you're using ExternalInterface.call (or maybe .addcallback)? Can you post some code (especially from the JS side)? | Unable to communicate with Javascript from Flex after dymanically loading a swf | [
"",
"javascript",
"jquery",
"apache-flex",
"actionscript-3",
""
] |
What's your opinion in handling exceptions within a thread's execution? More specifically, what if the exception is thrown inside catch block of an try-catch clause? And what happen to the thread if the exception is unhandled? | *What's your opinion in handling exceptions within a thread's execution?*
You should handle exceptions whenever possible and whenever you expect exceptions.
Clarification: I totally agree with John that you should not handle exceptions everywhere - only where you can do something about them. However, you should never let an exception go unhandled in a thread as this will cause serious problems. Have a root exception handler and let your thread die gracefully (after logging the problem etc...)
*More specifically, what if the thread is thrown inside catch block of an try-catch clause?*
Did you mean: What if the exception is thrown within the catch block? Well, then it goes unhandled by the current try-catch block. It's best not to put too much processing in a catch block to avoid this situation as much as possible.
*And what happen to the thread if the the the thread is unhandled?*
Did you mean: What happens to the thread if the exception is unhandled? It dies.
And as Ben mentioned:
> An uncaught exception in a thread
> triggers an UnhandledException in the
> thread's AppDomain. You can watch for
> these by adding an event handler:
>
> ```
> AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
> ``` | I have to disagree with ren, or at least with what it sounds like he meant.
Only handle exceptions if you can actually *handle* them. Only if you can do something about what went wrong, or add information. Don't handle them just because you can.
```
try {
// ..
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
```
The above is very bad. First, you don't display the entire exception, but only the Message. Second, you let things continue, and you don't know what state the process is in. | Best practice to handle exception, that is thrown within catch block, in a thread. (.NET) | [
"",
"c#",
".net",
"multithreading",
"exception",
""
] |
I'm building a simple interpreter of a language that i'm developing, but how i can do a *cout* of something that is after a word and in rounded by "", like this:
```
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main( int argc, char* argv[] )
{
if(argc != 2)
{
cout << "Error syntax is incorrect!\nSyntax: " << argv[ 0 ] << " <file>\n";
return 0;
}
ifstream file(argv[ 1 ]);
if (!file.good()) {
cout << "File " << argv[1] << " does not exist.\n";
return 0;
}
string linha;
while(!file.eof())
{
getline(file, linha);
if(linha == "print")
{
cout << text after print;
}
}
return 0;
}
```
And how i can remove the "" when printing the text. Here is the file example:
> print "Hello, World"
**Read my post in the middle of the answers!**
Thanks | I'm assuming what you want is to identify quoted strings in the file, and print them without the quotes. If so, the below snippet should do the trick.
This goes in your `while(!file.eof())` loop:
```
string linha;
while(!file.eof())
{
getline(file, linha);
string::size_type idx = linha.find("\""); //find the first quote on the line
while ( idx != string::npos ) {
string::size_type idx_end = linha.find("\"",idx+1); //end of quote
string quotes;
quotes.assign(linha,idx,idx_end-idx+1);
// do not print the start and end " strings
cout << "quotes:" << quotes.substr(1,quotes.length()-2) << endl;
//check for another quote on the same line
idx = linha.find("\"",idx_end+1);
}
}
``` | I hope this simple example would help.
```
std::string code = " print \" hi \" ";
std::string::size_type beg = code.find("\"");
std::string::size_type end = code.find("\"", beg+1);
// end-beg-1 = the length of the string between ""
std::cout << code.substr(beg+1, end-beg-1);
```
This code finds the first occurnce of `".` Then finds the next occurrence of it *after* the first one. Finally, it extracts the desired string between `""` and prints it. | Read Something After a Word in C++ | [
"",
"c++",
"file-io",
"interpreter",
""
] |
I'm using Subversion for one of my PHP projects. I have two questions/issues:
1. How are file permissions handled with Subversion? If I have a file that I CHMOD to 755, and I check that file into the repository, will it have the same permissions when it's checked out into other working copies? If it does not copy, do I really need to change the permissions with every checkout?
2. I have a .htaccess file that I don't want to check into the repository. If I do an update on a working copy that contains a .htaccess (but the repository doesn't have that file), will the file be deleted or will the update leave it alone? | 1. The only permission Subversion knows about, is the executable bit, which is stored as a special "svn:executable" property. If this property is defined, the file is checked out with the exec bit set. For the rw flags, it depends on your umask. If your umask is for example 0022, a file without the svn:executable bit will be checked out with permission 0644. If your umask is 0002, the permission will be 0664. If svn:executable is set, the exec bit is set for the owner, group and everyone else.
2. If you don't mark the .htaccess for addition (svn add), svn will leave the file alone. It will not go into the repo when committing, and it will not be deleted when you run svn update. You will see a "?" in front of it when you run "svn status". | For #2 you can simply add .htaccess to svn:ignore property. Here's a good take on what that does and how that work <http://blog.bogojoker.com/2008/07/command-line-svnignore-a-file/>
Permission-wise if you check out file it gets read/write permissions unless it's executable which should have svn:executable permissions and will be checked out as such. The file can also be explicitly marked with svn:needs-lock which then makes it read-only when you checkout | How does Subversion handle file permissions and a .htaccess file? | [
"",
"php",
"svn",
"apache",
""
] |
I'm making an [AIR](https://en.wikipedia.org/wiki/Adobe_Integrated_Runtime) application (so the download time doesn't have a huge impact). Does combining and minifing all the JavaScript files affect the performance? How would obfuscating affect the performance? | Minifying improves performance for your page overall by decreasing the load time (even if only slightly).
Neither minifying nor obfuscating alter the execution time by any perceivable amount **for the vast majority of JavaScript code out there.**
I do recommend minifying for those reasons and more. Minifying multiple scripts together (like jQuery and its plugins) can yield even greater savings.
As pointed out, on constrained devices and/or with very *large* codebases minifying could yield a noticeable result. | ### Minification
Minification does improve performance for two reasons:
* Reduced file-size (because it removes comments and unnecessary white spaces), so your script loads faster. Even if it is embedded into the `<head>`.
* It is parsed faster, since comments and white spaces don't have to be explicitly ignored (since they're not there).
### Combining
I've written quite a few HTML/JavaScript AIR applications, and from personal experience, combining files won't make a difference. In fact, it's good practice to separate the script based on certain criteria (classes, global functions, SQL functions, etc.). It helps keep them organised when the project becomes too big.
### Obfuscation
Obfuscating is usually a combination of minification and renaming variables. It involves using `eval` to blow up the code again. This reduces performance for obvious reasons, but it depends on the size of your code.
I'd suggest running tests to understand this best for your specific situation. | Does minified JavaScript code improve performance? | [
"",
"javascript",
""
] |
I've been working with ASP.NET MVC and Javascript/jQuery a lot lately and I seem to be heading in a direction where I'm always needing to pass some dynamic value "to" my javascript. When the script is right in the page, I've done something like this:
```
var isEditable = <%=ViewData["editable"]%>
```
I like how this is quick & easy and just like I'd inject a value into HTML. But this smells. Really, really bad. And it breaks Visual Studio's intellisense and code formatting, making my scripts hard to read and understand.
It has occurred to me another solution would be to pass my data to a hidden field, and have the Javascript reference that...
```
<input type="hidden" id="editable" value="<%=ViewData["editable"]%>" />
var isEditable = $("#editable").attr("value");
```
This is probably much better as it keeps the script intact and would allow me to move it to an external .js file. But something about this solution doesn't seem ideal either. Or is it just me?
Can anyone recommend solutions & best practices for passing data into your scripts? Am I headed down the wrong path if my scripts end up heavily relying the viewdata from my controllers in the first place? | I sometimes pass data to my pages by writing a config object to the page via a JSON serializer:
```
var pageConfig = <%= ServerConfig.ToJson() %>;
```
Where you need to write the ToJson method yourself. This keeps the page state nicely contained, so that there is only one place where you inject server values. Everything from here on out is pure javascript. In your example, you could then do:
```
var isEditable = pageConfig.isEditable;
```
even in an external js file, if `pageConfig` is global. In that case, though, you should properly namespace it: `MY_APP.pageConfig` perhaps. | You are going to inject that information one way or another. And IMO, your first example aren't really different from the second one.
Another solution is to have a JS class (or prototype?) that will accept an options object. Though admittedly, it's not really different than the examples you've given. But still, maybe you'd want to go this way.
```
$(function () {
myClass.init({ isEditable: <%=ViewData["editable"]%>,
another: '<%=ViewData["another"]%>' });
});
``` | Best practices for passing data from asp.net-mvc to javascript | [
"",
"javascript",
"jquery",
"asp.net-mvc",
""
] |
I want to have a class with a private static data member:
```
class C {
// read-only, can also be static const
// should be filled with all characters from 'a' to 'z'
static std::vector<char> alphabet;
public:
C() { /* ... */ }
};
```
In Java or C#, I can just make a "static constructor" that will run before I make any instances of the class, and sets up the static data members of the class. It only gets run once (as the variables are read only and only need to be set once) and since it's a function of the class it can access its private members.
I could add code in the `C()` constructor that checks to see if the vector is initialized, and initialize it if it's not, but that introduces many necessary checks and doesn't seem like the optimal solution to the problem.
The member is read-only, so it can be `static const` and I can define it outside the class, but that seems like an ugly hack.
**Is it possible to have private static data members in a class if I don't want to initialize them in the instance constructor?** | To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.
```
class StaticStuff
{
std::vector<char> letters_;
public:
StaticStuff()
{
for (char c = 'a'; c <= 'z'; c++)
letters_.push_back(c);
}
// provide some way to get at letters_
};
class Elsewhere
{
static StaticStuff staticStuff; // constructor runs once, single instance
};
``` | Well you can have
```
class MyClass
{
public:
static vector<char> a;
static class _init
{
public:
_init() { for(char i='a'; i<='z'; i++) a.push_back(i); }
} _initializer;
};
```
Don't forget (in the .cpp) this:
```
vector<char> MyClass::a;
MyClass::_init MyClass::_initializer;
```
The program will still link without the second line, but the initializer will not be executed. | How do you initialize static data members, similar to static constructors? | [
"",
"c++",
"static",
"private",
"initializer",
"static-constructor",
""
] |
I am currently using [similar\_text](https://www.php.net/manual/en/function.similar-text.php) to compare a string against a list of ~50,000 which works although due to the number of comparisons it's very slow. It takes around 11 minutes to compare ~500 unique strings.
Before running this I do check the databases to see whether it has been processed in the past so everytime after the inital run it's close to instant.
I'm sure using [levenshtein](https://www.php.net/manual/en/function.levenshtein.php) would be slightly faster and the LevenshteinDistance function someone posted in the manual looks interesting. Am I missing something that could make this significantly faster? | In the end, both `levenshtein` and `similar_text` were both too slow with the number of strings it had to go through, even with lots of checks and only using them one of them as a last resort.
As an experiment, I ported some of the code to C# to see how much faster it would be over interperated code. It ran in about 3 minutes with the same dataset.
Next I added an extra field to the table and used the double metaphone PECL extension to generate keys for each row. The results were good although since some included numbers this caused duplicates. I guess I could then have run each one through the above functions but decided not to.
In the end I opted for the simplest approach, MySQLs full text which worked very well. Occasionally there are mistakes although they are easy to detect and correct. Also it runs very fast, in around 3-4 seconds. | Perhaps you could 'short-circuit' some checks by first comparing your string for an exact match (and by first comparing if length identical), and if it is skip the more expensive `similar_text` call.
As @jason noted, an O(N^3) algorithm is never going to be a good choice. | Speeding up levenshtein / similar_text in PHP | [
"",
"php",
"levenshtein-distance",
"similarity",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.